<commit_before>package main

import (
	"bytes"
	"github.com/franela/goblin"
	"github.com/stretchr/testify/assert"
	"io/ioutil"
	"net/http"
	"os"
	"testing"
)

type FakeResponseBodyGenerator struct {
	use string
}

func (instance *FakeResponseBodyGenerator) Generate() string {
	return instance.use
}

func (instance *FakeResponseBodyGenerator) UseString(value string) {
	instance.use = value
}

func NewFakeResponseBodyGenerator() *FakeResponseBodyGenerator {
	return &FakeResponseBodyGenerator{""}
}

var fakeResponseBodyGenerator *FakeResponseBodyGenerator
var enanosHttpHandlerFactory *DefaultEnanosHttpHandlerFactory

func TestMain(m *testing.M) {
	fakeResponseBodyGenerator = NewFakeResponseBodyGenerator()
	enanosHttpHandlerFactory = NewDefaultEnanosHttpHandlerFactory(fakeResponseBodyGenerator)
	go func() {
		StartEnanos(fakeResponseBodyGenerator, enanosHttpHandlerFactory)
	}()
	os.Exit(m.Run())
}

func Test_ResponseBodyGenerator(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("Default Response Body Generator", func() {
		g.It("generates a string of the defined lenth", func() {
			maxLength := 5
			generator := NewDefaultResponseBodyGenerator(maxLength)
			value := generator.Generate()
			assert.Equal(t, maxLength, len(value))
		})
	})

	g.Describe("Random Response Body Generator", func() {
		g.It("generates a string of length between the defined min length and the defined max length", func() {
			minLength := 50
			maxLength := 500
			generator := NewRandomResponseBodyGenerator(minLength, maxLength)
			value := generator.Generate()
			assert.True(t, len(value) >= minLength && len(value) <= maxLength)
		})
	})
}

func SendHelloWorldByHttpMethod(method string, url string) (resp *http.Response, err error) {
	var jsonStr = []byte(`{"message":"hello world"}`)
	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return
}

func Test_Enanos(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("Enanos Server:", func() {

		url := func(path string) (fullPath string) {
			fullPath = "http://localhost:8000" + path
			return
		}

		g.Describe("Happy :", func() {
			var happyUrl string
			g.Before(func() {
				happyUrl = url("/default/happy")
			})
			g.It("GET returns 200", func() {
				resp, _ := http.Get(happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("POST returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("POST", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("PUT returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("PUT", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("DELETE returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("DELETE", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})
		})

		g.Describe("Grumpy :", func() {
			var grumpyUrl string
			g.Before(func() {
				grumpyUrl = url("/default/grumpy")
			})
			g.It("GET returns 500", func() {
				resp, _ := http.Get(grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("POST returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("POST", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("PUT returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("PUT", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("DELETE returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("DELETE", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})
		})

		g.Describe("Sneezy :", func() {
			g.It("GET returns 200", func() {
				resp, _ := http.Get(url("/default/sneezy"))
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("GET returns random response body", func() {
				sample := "foobar"
				fakeResponseBodyGenerator.UseString(sample)
				resp, _ := http.Get(url("/default/sneezy"))
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				assert.Equal(t, sample, string(body))
			})
		})
	})
}
<commit_msg>testing Grumpy and happy for any random verb returns 500 and 200 respectivley<commit_after>package main

import (
	"bytes"
	"github.com/franela/goblin"
	"github.com/stretchr/testify/assert"
	"io/ioutil"
	"net/http"
	"os"
	"testing"
)

type FakeResponseBodyGenerator struct {
	use string
}

func (instance *FakeResponseBodyGenerator) Generate() string {
	return instance.use
}

func (instance *FakeResponseBodyGenerator) UseString(value string) {
	instance.use = value
}

func NewFakeResponseBodyGenerator() *FakeResponseBodyGenerator {
	return &FakeResponseBodyGenerator{""}
}

var fakeResponseBodyGenerator *FakeResponseBodyGenerator
var enanosHttpHandlerFactory *DefaultEnanosHttpHandlerFactory

func TestMain(m *testing.M) {
	fakeResponseBodyGenerator = NewFakeResponseBodyGenerator()
	enanosHttpHandlerFactory = NewDefaultEnanosHttpHandlerFactory(fakeResponseBodyGenerator)
	go func() {
		StartEnanos(fakeResponseBodyGenerator, enanosHttpHandlerFactory)
	}()
	os.Exit(m.Run())
}

func Test_ResponseBodyGenerator(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("Default Response Body Generator", func() {
		g.It("generates a string of the defined lenth", func() {
			maxLength := 5
			generator := NewDefaultResponseBodyGenerator(maxLength)
			value := generator.Generate()
			assert.Equal(t, maxLength, len(value))
		})
	})

	g.Describe("Random Response Body Generator", func() {
		g.It("generates a string of length between the defined min length and the defined max length", func() {
			minLength := 50
			maxLength := 500
			generator := NewRandomResponseBodyGenerator(minLength, maxLength)
			value := generator.Generate()
			assert.True(t, len(value) >= minLength && len(value) <= maxLength)
		})
	})
}

func SendHelloWorldByHttpMethod(method string, url string) (resp *http.Response, err error) {
	var jsonStr = []byte(`{"message":"hello world"}`)
	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr))
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return
}

func Test_Enanos(t *testing.T) {
	g := goblin.Goblin(t)
	g.Describe("Enanos Server:", func() {

		url := func(path string) (fullPath string) {
			fullPath = "http://localhost:8000" + path
			return
		}

		g.Describe("Happy :", func() {
			var happyUrl string
			g.Before(func() {
				happyUrl = url("/default/happy")
			})
			g.It("GET returns 200", func() {
				resp, _ := http.Get(happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("POST returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("POST", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("PUT returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("PUT", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("DELETE returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("DELETE", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("Any Random Verb returns 200", func() {
				resp, _ := SendHelloWorldByHttpMethod("TALULA", happyUrl)
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})
		})

		g.Describe("Grumpy :", func() {
			var grumpyUrl string
			g.Before(func() {
				grumpyUrl = url("/default/grumpy")
			})
			g.It("GET returns 500", func() {
				resp, _ := http.Get(grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("POST returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("POST", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("PUT returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("PUT", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("DELETE returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("DELETE", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})

			g.It("Any Random Verb returns 500", func() {
				resp, _ := SendHelloWorldByHttpMethod("TALULA", grumpyUrl)
				assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
			})
		})

		g.Describe("Sneezy :", func() {
			g.It("GET returns 200", func() {
				resp, _ := http.Get(url("/default/sneezy"))
				assert.Equal(t, http.StatusOK, resp.StatusCode)
			})

			g.It("GET returns random response body", func() {
				sample := "foobar"
				fakeResponseBodyGenerator.UseString(sample)
				resp, _ := http.Get(url("/default/sneezy"))
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				assert.Equal(t, sample, string(body))
			})
		})
	})
}
<|endoftext|>


<commit_before>// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package wrappy

import (
	"fmt"
	"log"
	"strings"

	"sigs.k8s.io/kustomize/api/ifc"
	"sigs.k8s.io/kustomize/api/resid"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

// WNode implements ifc.Kunstructured using yaml.RNode.
//
// It exists only to help manage a switch from
// kunstruct.UnstructAdapter to yaml.RNode as the core
// representation of KRM objects in kustomize.
//
// It's got a silly name because we don't want it around for long,
// and want its use to be obvious.
type WNode struct {
	node *yaml.RNode
}

var _ ifc.Kunstructured = (*WNode)(nil)

func NewWNode() *WNode {
	return FromRNode(yaml.NewRNode(nil))
}

func FromMap(m map[string]interface{}) (*WNode, error) {
	n, err := yaml.FromMap(m)
	if err != nil {
		return nil, err
	}
	return FromRNode(n), nil
}

func FromRNode(node *yaml.RNode) *WNode {
	return &WNode{node: node}
}

func (wn *WNode) demandMetaData(label string) yaml.ResourceMeta {
	meta, err := wn.node.GetMeta()
	if err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("for %s', expected valid resource: %v", label, err)
	}
	return meta
}

// Copy implements ifc.Kunstructured.
func (wn *WNode) Copy() ifc.Kunstructured {
	return &WNode{node: wn.node.Copy()}
}

// GetAnnotations implements ifc.Kunstructured.
func (wn *WNode) GetAnnotations() map[string]string {
	return wn.demandMetaData("GetAnnotations").Annotations
}

// GetFieldValue implements ifc.Kunstructured.
func (wn *WNode) GetFieldValue(path string) (interface{}, error) {
	fields := strings.Split(path, ".")
	rn, err := wn.node.Pipe(yaml.Lookup(fields...))
	if err != nil {
		return nil, err
	}
	if rn == nil {
		return nil, NoFieldError{path}
	}
	yn := rn.YNode()

	// If this is an alias node, resolve it
	if yn.Kind == yaml.AliasNode {
		yn = yn.Alias
	}

	// Return value as map for DocumentNode and MappingNode kinds
	if yn.Kind == yaml.DocumentNode || yn.Kind == yaml.MappingNode {
		var result map[string]interface{}
		if err := yn.Decode(&result); err != nil {
			return nil, err
		}
		return result, err
	}

	// Return value as slice for SequenceNode kind
	if yn.Kind == yaml.SequenceNode {
		var result []interface{}
		for _, node := range yn.Content {
			result = append(result, node.Value)
		}
		return result, nil
	}

	// Return value value directly for all other (ScalarNode) kinds
	return yn.Value, nil
}

// GetGvk implements ifc.Kunstructured.
func (wn *WNode) GetGvk() resid.Gvk {
	meta := wn.demandMetaData("GetGvk")
	g, v := resid.ParseGroupVersion(meta.APIVersion)
	return resid.Gvk{Group: g, Version: v, Kind: meta.Kind}
}

// GetKind implements ifc.Kunstructured.
func (wn *WNode) GetKind() string {
	return wn.demandMetaData("GetKind").Kind
}

// GetLabels implements ifc.Kunstructured.
func (wn *WNode) GetLabels() map[string]string {
	return wn.demandMetaData("GetLabels").Labels
}

// GetName implements ifc.Kunstructured.
func (wn *WNode) GetName() string {
	return wn.demandMetaData("GetName").Name
}

// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetSlice(path string) ([]interface{}, error) {
	value, err := wn.GetFieldValue(path)
	if err != nil {
		return nil, err
	}
	if sliceValue, ok := value.([]interface{}); ok {
		return sliceValue, nil
	}
	return nil, fmt.Errorf("node %s is not a slice", path)
}

// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetString(path string) (string, error) {
	value, err := wn.GetFieldValue(path)
	if err != nil {
		return "", err
	}
	if v, ok := value.(string); ok {
		return v, nil
	}
	return "", fmt.Errorf("node %s is not a string: %v", path, value)
}

// Map implements ifc.Kunstructured.
func (wn *WNode) Map() map[string]interface{} {
	var result map[string]interface{}
	if err := wn.node.YNode().Decode(&result); err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("failed to decode ynode: %v", err)
	}
	return result
}

// MarshalJSON implements ifc.Kunstructured.
func (wn *WNode) MarshalJSON() ([]byte, error) {
	return wn.node.MarshalJSON()
}

// MatchesAnnotationSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesAnnotationSelector(string) (bool, error) {
	panic("TODO(#WNode) MatchesAnnotationSelector; implement or drop from API")
}

// MatchesLabelSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesLabelSelector(string) (bool, error) {
	panic("TODO(#WNode) MatchesLabelSelector; implement or drop from API")
}

// SetAnnotations implements ifc.Kunstructured.
func (wn *WNode) SetAnnotations(annotations map[string]string) {
	if err := wn.node.SetAnnotations(annotations); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

// SetGvk implements ifc.Kunstructured.
func (wn *WNode) SetGvk(gvk resid.Gvk) {
	wn.setMapField(yaml.NewScalarRNode(gvk.Kind), yaml.KindField)
	wn.setMapField(
		yaml.NewScalarRNode(
			fmt.Sprintf("%s/%s", gvk.Group, gvk.Version)), yaml.APIVersionField)
}

// SetLabels implements ifc.Kunstructured.
func (wn *WNode) SetLabels(labels map[string]string) {
	if err := wn.node.SetLabels(labels); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

// SetName implements ifc.Kunstructured.
func (wn *WNode) SetName(name string) {
	wn.setMapField(yaml.NewScalarRNode(name), yaml.MetadataField, yaml.NameField)
}

// SetNamespace implements ifc.Kunstructured.
func (wn *WNode) SetNamespace(ns string) {
	if err := wn.node.SetNamespace(ns); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

func (wn *WNode) setMapField(value *yaml.RNode, path ...string) {
	if err := wn.node.SetMapField(value, path...); err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("failed to set field %v: %v", path, err)
	}
}

// UnmarshalJSON implements ifc.Kunstructured.
func (wn *WNode) UnmarshalJSON(data []byte) error {
	return wn.node.UnmarshalJSON(data)
}

type NoFieldError struct {
	Field string
}

func (e NoFieldError) Error() string {
	return fmt.Sprintf("no field named '%s'", e.Field)
}
<commit_msg>Complete WNode implementation.<commit_after>// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package wrappy

import (
	"fmt"
	"log"
	"strings"

	"sigs.k8s.io/kustomize/api/ifc"
	"sigs.k8s.io/kustomize/api/resid"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

// WNode implements ifc.Kunstructured using yaml.RNode.
//
// It exists only to help manage a switch from
// kunstruct.UnstructAdapter to yaml.RNode as the core
// representation of KRM objects in kustomize.
//
// It's got a silly name because we don't want it around for long,
// and want its use to be obvious.
type WNode struct {
	node *yaml.RNode
}

var _ ifc.Kunstructured = (*WNode)(nil)

func NewWNode() *WNode {
	return FromRNode(yaml.NewRNode(nil))
}

func FromMap(m map[string]interface{}) (*WNode, error) {
	n, err := yaml.FromMap(m)
	if err != nil {
		return nil, err
	}
	return FromRNode(n), nil
}

func FromRNode(node *yaml.RNode) *WNode {
	return &WNode{node: node}
}

func (wn *WNode) demandMetaData(label string) yaml.ResourceMeta {
	meta, err := wn.node.GetMeta()
	if err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("for %s', expected valid resource: %v", label, err)
	}
	return meta
}

// Copy implements ifc.Kunstructured.
func (wn *WNode) Copy() ifc.Kunstructured {
	return &WNode{node: wn.node.Copy()}
}

// GetAnnotations implements ifc.Kunstructured.
func (wn *WNode) GetAnnotations() map[string]string {
	return wn.demandMetaData("GetAnnotations").Annotations
}

// GetFieldValue implements ifc.Kunstructured.
func (wn *WNode) GetFieldValue(path string) (interface{}, error) {
	fields := strings.Split(path, ".")
	rn, err := wn.node.Pipe(yaml.Lookup(fields...))
	if err != nil {
		return nil, err
	}
	if rn == nil {
		return nil, NoFieldError{path}
	}
	yn := rn.YNode()

	// If this is an alias node, resolve it
	if yn.Kind == yaml.AliasNode {
		yn = yn.Alias
	}

	// Return value as map for DocumentNode and MappingNode kinds
	if yn.Kind == yaml.DocumentNode || yn.Kind == yaml.MappingNode {
		var result map[string]interface{}
		if err := yn.Decode(&result); err != nil {
			return nil, err
		}
		return result, err
	}

	// Return value as slice for SequenceNode kind
	if yn.Kind == yaml.SequenceNode {
		var result []interface{}
		for _, node := range yn.Content {
			result = append(result, node.Value)
		}
		return result, nil
	}

	// Return value value directly for all other (ScalarNode) kinds
	return yn.Value, nil
}

// GetGvk implements ifc.Kunstructured.
func (wn *WNode) GetGvk() resid.Gvk {
	meta := wn.demandMetaData("GetGvk")
	g, v := resid.ParseGroupVersion(meta.APIVersion)
	return resid.Gvk{Group: g, Version: v, Kind: meta.Kind}
}

// GetKind implements ifc.Kunstructured.
func (wn *WNode) GetKind() string {
	return wn.demandMetaData("GetKind").Kind
}

// GetLabels implements ifc.Kunstructured.
func (wn *WNode) GetLabels() map[string]string {
	return wn.demandMetaData("GetLabels").Labels
}

// GetName implements ifc.Kunstructured.
func (wn *WNode) GetName() string {
	return wn.demandMetaData("GetName").Name
}

// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetSlice(path string) ([]interface{}, error) {
	value, err := wn.GetFieldValue(path)
	if err != nil {
		return nil, err
	}
	if sliceValue, ok := value.([]interface{}); ok {
		return sliceValue, nil
	}
	return nil, fmt.Errorf("node %s is not a slice", path)
}

// GetSlice implements ifc.Kunstructured.
func (wn *WNode) GetString(path string) (string, error) {
	value, err := wn.GetFieldValue(path)
	if err != nil {
		return "", err
	}
	if v, ok := value.(string); ok {
		return v, nil
	}
	return "", fmt.Errorf("node %s is not a string: %v", path, value)
}

// Map implements ifc.Kunstructured.
func (wn *WNode) Map() map[string]interface{} {
	var result map[string]interface{}
	if err := wn.node.YNode().Decode(&result); err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("failed to decode ynode: %v", err)
	}
	return result
}

// MarshalJSON implements ifc.Kunstructured.
func (wn *WNode) MarshalJSON() ([]byte, error) {
	return wn.node.MarshalJSON()
}

// MatchesAnnotationSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesAnnotationSelector(selector string) (bool, error) {
	return wn.node.MatchesAnnotationSelector(selector)
}

// MatchesLabelSelector implements ifc.Kunstructured.
func (wn *WNode) MatchesLabelSelector(selector string) (bool, error) {
	return wn.node.MatchesLabelSelector(selector)
}

// SetAnnotations implements ifc.Kunstructured.
func (wn *WNode) SetAnnotations(annotations map[string]string) {
	if err := wn.node.SetAnnotations(annotations); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

// SetGvk implements ifc.Kunstructured.
func (wn *WNode) SetGvk(gvk resid.Gvk) {
	wn.setMapField(yaml.NewScalarRNode(gvk.Kind), yaml.KindField)
	wn.setMapField(
		yaml.NewScalarRNode(
			fmt.Sprintf("%s/%s", gvk.Group, gvk.Version)), yaml.APIVersionField)
}

// SetLabels implements ifc.Kunstructured.
func (wn *WNode) SetLabels(labels map[string]string) {
	if err := wn.node.SetLabels(labels); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

// SetName implements ifc.Kunstructured.
func (wn *WNode) SetName(name string) {
	wn.setMapField(yaml.NewScalarRNode(name), yaml.MetadataField, yaml.NameField)
}

// SetNamespace implements ifc.Kunstructured.
func (wn *WNode) SetNamespace(ns string) {
	if err := wn.node.SetNamespace(ns); err != nil {
		log.Fatal(err) // interface doesn't allow error.
	}
}

func (wn *WNode) setMapField(value *yaml.RNode, path ...string) {
	if err := wn.node.SetMapField(value, path...); err != nil {
		// Log and die since interface doesn't allow error.
		log.Fatalf("failed to set field %v: %v", path, err)
	}
}

// UnmarshalJSON implements ifc.Kunstructured.
func (wn *WNode) UnmarshalJSON(data []byte) error {
	return wn.node.UnmarshalJSON(data)
}

type NoFieldError struct {
	Field string
}

func (e NoFieldError) Error() string {
	return fmt.Sprintf("no field named '%s'", e.Field)
}
<|endoftext|>


<commit_before>package requests

import (
	"errors"
	"testing"

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

func TestInputErrors(t *testing.T) {
	assert := assert.New(t)
	errs := make(InputErrors)
	assert.Implements((*error)(nil), errs)
	assert.False(errs.HasErrors())
	assert.True(errs.Errors() == nil)
	emptyMessage := errs.Error()

	errs.Set("test", nil)
	assert.False(errs.HasErrors())
	assert.NotEqual(errs, errs.Errors())
	assert.Equal(emptyMessage, errs.Error())

	errs = make(InputErrors)
	errs.Set("test", errors.New("Test error"))
	assert.True(errs.HasErrors())
	assert.Equal(errs, errs.Errors())
	assert.NotEqual(emptyMessage, errs.Error())

	errs.Set("test2", errors.New("Second test error"))
	newErrs := InputErrors{
		"test":  errors.New("Overriding test error"),
		"test3": errors.New("New error"),
	}
	errs = errs.Merge(newErrs)
	assert.True(errs.HasErrors())
	assert.Equal(3, len(errs))
	assert.Equal("Overriding test error", errs["test"].Error())
	assert.NotEqual(emptyMessage, errs.Error())
}
<commit_msg>test InputErrors(nil).Merge(nonNilInputErrors) == nonNilInputErrors<commit_after>package requests

import (
	"errors"
	"testing"

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

func TestInputErrors(t *testing.T) {
	assert := assert.New(t)
	errs := make(InputErrors)
	assert.Implements((*error)(nil), errs)
	assert.False(errs.HasErrors())
	assert.True(errs.Errors() == nil)
	emptyMessage := errs.Error()

	errs.Set("test", nil)
	assert.False(errs.HasErrors())
	assert.NotEqual(errs, errs.Errors())
	assert.Equal(emptyMessage, errs.Error())

	errs = make(InputErrors)
	errs.Set("test", errors.New("Test error"))
	assert.True(errs.HasErrors())
	assert.Equal(errs, errs.Errors())
	assert.NotEqual(emptyMessage, errs.Error())

	errs.Set("test2", errors.New("Second test error"))
	newErrs := InputErrors{
		"test":  errors.New("Overriding test error"),
		"test3": errors.New("New error"),
	}
	errs = errs.Merge(newErrs)
	assert.True(errs.HasErrors())
	assert.Equal(3, len(errs))
	assert.Equal("Overriding test error", errs["test"].Error())
	assert.NotEqual(emptyMessage, errs.Error())

	errs = nil
	assert.Equal(newErrs, errs.Merge(newErrs))
}
<|endoftext|>


<commit_before>package jsonptr

import (
	"testing"
)

func checkEscape(t *testing.T, in, expected string) {
	got := Escape(in)
	if got != expected {
		t.Errorf("in: %#v\n    got: %#v\nexpected: %#v\n", in, got, expected)
	} else {
		t.Logf("%#v => %#v\n", in, got)
	}
}

func TestEscape(t *testing.T) {
	checkEscape(t, "", "")
	checkEscape(t, "a", "a")
	checkEscape(t, "a~", "a~0")
	checkEscape(t, "~a", "~0a")
	checkEscape(t, "a~b", "a~0b")
	checkEscape(t, "a/", "a~1")
	checkEscape(t, "/a", "~1a")
	checkEscape(t, "a/b", "a~1b")
	checkEscape(t, "a/~b", "a~1~0b")
	checkEscape(t, "a~/b", "a~0~1b")
	checkEscape(t, "a~~~b", "a~0~0~0b")
	checkEscape(t, "a///b", "a~1~1~1b")
	checkEscape(t, "a/b/c/d", "a~1b~1c~1d")
	checkEscape(t, "é~é", "é~0é")
	checkEscape(t, "é~", "é~0")
	checkEscape(t, "~é", "~0é")
}

func TestUnescape(t *testing.T) {
	for _, test := range []struct {
		in, out string
		err     error
	}{
		{"", "", nil},
		{"x", "x", nil},
		{"~0", "~", nil},
		{"~1", "/", nil},
		{"~0~1", "~/", nil},
		{"~1~0", "/~", nil},
		{"x~1~0", "x/~", nil},
		{"x~1y~0", "x/y~", nil},
		{"~", "", ErrSyntax},
		{"~~", "", ErrSyntax},
		{"~a", "", ErrSyntax},
		{"~a ", "", ErrSyntax},
		{"a ~", "", ErrSyntax},
		{"a ~ x", "", ErrSyntax},
		{"a ~0 ~x", "", ErrSyntax},
	} {
		t.Logf("%s => %s", test.in, test.out)
		got, err := Unescape(test.in)
		if err != test.err {
			t.Logf("got: %s, expected: %s", err, test.err)
			t.Fail()
		} else if test.err != nil && got != test.out {
			t.Logf("got: %s, expected: %s", got, test.out)
			t.Fail()
		}
	}
}
<commit_msg>Refactor TestEscape<commit_after>package jsonptr

import (
	"testing"
)

func checkEscape(t *testing.T, in, expected string) {
}

func TestEscape(t *testing.T) {
	for _, tc := range []struct {
		in, expected string
	}{
		{"", ""},
		{"a", "a"},
		{"a~", "a~0"},
		{"~a", "~0a"},
		{"a~b", "a~0b"},
		{"a/", "a~1"},
		{"/a", "~1a"},
		{"a/b", "a~1b"},
		{"a/~b", "a~1~0b"},
		{"a~/b", "a~0~1b"},
		{"a~~~b", "a~0~0~0b"},
		{"a///b", "a~1~1~1b"},
		{"a/b/c/d", "a~1b~1c~1d"},
		{"é~é", "é~0é"},
		{"é~", "é~0"},
		{"~é", "~0é"},
	} {
		t.Logf("%#v => %#v\n", tc.in, tc.expected)
		got := Escape(tc.in)
		if got != tc.expected {
			t.Errorf("got: %#v\n", got)
		}
	}
}

func TestUnescape(t *testing.T) {
	for _, test := range []struct {
		in, out string
		err     error
	}{
		{"", "", nil},
		{"x", "x", nil},
		{"~0", "~", nil},
		{"~1", "/", nil},
		{"~0~1", "~/", nil},
		{"~1~0", "/~", nil},
		{"x~1~0", "x/~", nil},
		{"x~1y~0", "x/y~", nil},
		{"~", "", ErrSyntax},
		{"~~", "", ErrSyntax},
		{"~a", "", ErrSyntax},
		{"~a ", "", ErrSyntax},
		{"a ~", "", ErrSyntax},
		{"a ~ x", "", ErrSyntax},
		{"a ~0 ~x", "", ErrSyntax},
	} {
		t.Logf("%s => %s", test.in, test.out)
		got, err := Unescape(test.in)
		if err != test.err {
			t.Logf("got: %s, expected: %s", err, test.err)
			t.Fail()
		} else if test.err != nil && got != test.out {
			t.Logf("got: %s, expected: %s", got, test.out)
			t.Fail()
		}
	}
}
<|endoftext|>


<commit_before>package hwio

// A driver for BeagleBone's running Linux kernel 3.8 or higher, which use device trees instead
// of the old driver.
//
// Notable differences between this driver and the other BeagleBone driver:
// - this uses the file system for everything.
// - will only work on linux kernel 3.8 and higher, irrespective of the board version.
// - memory mapping is no longer used, as it was unsupported anyway.
// - this will probably not have the raw performance of the memory map technique (this is yet to be measured)
// - this driver will likely support alot more functions, as it's leveraging drivers that already exist.
//
// This driver shares some information from the other driver, since the pin configuration information is essentially the same.
//
// Articles used in building this driver:
// GPIO:
// - http://www.avrfreaks.net/wiki/index.php/Documentation:Linux/GPIO#Example_of_GPIO_access_from_within_a_C_program
// Analog:
// - http://hipstercircuits.com/reading-analog-adc-values-on-beaglebone-black/
// Background on changes in linux kernal 3.8:
// - https://docs.google.com/document/d/17P54kZkZO_-JtTjrFuVz-Cp_RMMg7GB_8W9JK9sLKfA/edit?hl=en&forcehl=1#heading=h.mfjmczsbv38r

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

const ()

// var beaglePins []*BeaglePin
// var bbGpioProfile []Capability
// var bbAnalogInProfile []Capability
// var bbUsrLedProfile []Capability

type BeagleBoneFSOpenPin struct {
	pin          Pin
	gpioLogical  int
	gpioBaseName string
	valueFile    *os.File
}

// Write a string to a file and close it again.
func writeStringToFile(filename string, value string) error {
	f, e := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, 0666)
	if e != nil {
		return e
	}
	defer f.Close()

	f.WriteString(value)
	return nil
}

// Needs to be called to allocate the GPIO pin
func (op *BeagleBoneFSOpenPin) gpioExport() error {
	s := strconv.FormatInt(int64(op.gpioLogical), 10)
	e := writeStringToFile("/sys/class/gpio/export", s)
	if e != nil {
		return e
	}

	// calculate the base name for the gpio pin
	op.gpioBaseName = "/sys/class/gpio/gpio" + strconv.Itoa(op.gpioLogical)
	return nil
}

// Once exported, the direction of a GPIO can be set
func (op *BeagleBoneFSOpenPin) gpioDirection(dir string) error {
	if dir != "in" && dir != "out" {
		return errors.New("direction must be in or out")
	}
	f := op.gpioBaseName + "/direction"
	e := writeStringToFile(f, dir)

	mode := os.O_WRONLY | os.O_TRUNC
	if dir == "in" {
		mode = os.O_RDONLY
	}

	// @todo open the value file with the correct mode. Put that file in 'op'
	op.valueFile, e = os.OpenFile(op.gpioBaseName+"/"+strconv.Itoa(op.gpioLogical), mode, 0666)
	if e != nil {
		return e
	}

	return e
}

// Get the value. Will return HIGH or LOW
func (op *BeagleBoneFSOpenPin) gpioGetValue() (int, error) {
	var b []byte
	b = make([]byte, 1)
	n, e := op.valueFile.ReadAt(b, 0)
	value := 0
	if n > 0 {
		if b[0] == '1' {
			value = HIGH
		} else {
			value = LOW
		}
	}
	return value, e
}

// Set the value, Expects HIGH or LOW
func (op *BeagleBoneFSOpenPin) gpioSetValue(value int) error {
	_, e := op.valueFile.Seek(0, 0)
	if e != nil {
		return e
	}

	if value == 0 {
		op.valueFile.WriteString("0")
	} else {
		op.valueFile.WriteString("1")
	}
	return nil
}

type BeagleBoneFSDriver struct {
	openPins map[Pin]*BeagleBoneFSOpenPin
}

func (d *BeagleBoneFSDriver) Init() error {
	d.openPins = make(map[Pin]*BeagleBoneFSOpenPin)
	return nil
}

func (d *BeagleBoneFSDriver) Close() {
	// @todo call unexport on all open pins
}

// create an openPin object and put it in the map.
func (d *BeagleBoneFSDriver) makeOpenPin(pin Pin, gpioLogicalPin int) *BeagleBoneFSOpenPin {
	result := &BeagleBoneFSOpenPin{pin: pin, gpioLogical: gpioLogicalPin}
	d.openPins[pin] = result
	return result
}

// For GPIO:
// - write GPIO pin to /sys/class/gpio/export. This is the port number plus pin on that port. Ports 0, 32, 64, 96.
// - write direction to /sys/class/gpio/gpio{nn}/direction. Values are 'in' and 'out'

func (d *BeagleBoneFSDriver) PinMode(pin Pin, mode PinIOMode) error {
	p := beaglePins[pin]

	// handle analog first, they are simplest from PinMode perspective
	if p.isAnalogPin() {
		if mode != INPUT {
			return errors.New(fmt.Sprintf("Pin %d is an analog pin, and the mode must be INPUT", p))
		}
		// @todo set up the analog pin
		return nil // nothing to set up
	}

	// Create an open pin object
	openPin := d.makeOpenPin(pin, p.gpioLogical)
	e := openPin.gpioExport()
	if e != nil {
		return e
	}

	if mode == OUTPUT {
		e = openPin.gpioDirection("out")
		if e != nil {
			return e
		}
	} else {
		e = openPin.gpioDirection("in")
		// pull := BB_CONF_PULL_DISABLE
		// // note: pull up/down modes assume that CONF_PULLDOWN resets the pull disable bit
		// if mode == INPUT_PULLUP {
		// 	pull = BB_CONF_PULLUP
		// } else if mode == INPUT_PULLDOWN {
		// 	pull = BB_CONF_PULLDOWN
		// }

		if e != nil {
			return e
		}
	}
	return nil
}

func (d *BeagleBoneFSDriver) pinMux(mux string, mode uint) error {
	// Uses kernel omap_mux files to set pin modes.
	// There's no simple way to write the control module registers from a
	// user-level process because it lacks the proper privileges, but it's
	// easy enough to just use the built-in file-based system and let the
	// kernel do the work.
	f, e := os.OpenFile(BB_PINMUX_PATH+mux, os.O_WRONLY|os.O_TRUNC, 0666)
	if e != nil {
		return e
	}

	s := strconv.FormatInt(int64(mode), 16)
	//	fmt.Printf("Writing mode %s to mux file %s\n", s, PINMUX_PATH+mux)
	f.WriteString(s)
	return nil
}

func (d *BeagleBoneFSDriver) DigitalWrite(pin Pin, value int) (e error) {
	openPin := d.openPins[pin]
	openPin.gpioSetValue(value)
	return nil
}

func (d *BeagleBoneFSDriver) DigitalRead(pin Pin) (value int, e error) {
	openPin := d.openPins[pin]
	return openPin.gpioGetValue()
}

func (d *BeagleBoneFSDriver) AnalogWrite(pin Pin, value int) (e error) {
	return nil
}

func (d *BeagleBoneFSDriver) AnalogRead(pin Pin) (value int, e error) {
	return 0, nil
}

func (d *BeagleBoneFSDriver) PinMap() (pinMap HardwarePinMap) {
	pinMap = make(HardwarePinMap)

	for i, hw := range beaglePins {
		names := []string{hw.hwPin}
		if hw.hwPin != hw.gpioName {
			names = append(names, hw.gpioName)
		}
		pinMap.add(Pin(i), names, hw.profile)
	}

	return
}
<commit_msg>clean up in BB FS driver<commit_after>package hwio

// A driver for BeagleBone's running Linux kernel 3.8 or higher, which use device trees instead
// of the old driver.
//
// Notable differences between this driver and the other BeagleBone driver:
// - this uses the file system for everything.
// - will only work on linux kernel 3.8 and higher, irrespective of the board version.
// - memory mapping is no longer used, as it was unsupported anyway.
// - this will probably not have the raw performance of the memory map technique (this is yet to be measured)
// - this driver will likely support alot more functions, as it's leveraging drivers that already exist.
//
// This driver shares some information from the other driver, since the pin configuration information is essentially the same.
//
// Articles used in building this driver:
// GPIO:
// - http://www.avrfreaks.net/wiki/index.php/Documentation:Linux/GPIO#Example_of_GPIO_access_from_within_a_C_program
// Analog:
// - http://hipstercircuits.com/reading-analog-adc-values-on-beaglebone-black/
// Background on changes in linux kernal 3.8:
// - https://docs.google.com/document/d/17P54kZkZO_-JtTjrFuVz-Cp_RMMg7GB_8W9JK9sLKfA/edit?hl=en&forcehl=1#heading=h.mfjmczsbv38r

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

type BeagleBoneFSOpenPin struct {
	pin          Pin
	gpioLogical  int
	gpioBaseName string
	valueFile    *os.File
}

// Write a string to a file and close it again.
func writeStringToFile(filename string, value string) error {
	//	fmt.Printf("writing %s to file %s\n", value, filename)
	f, e := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, 0666)
	if e != nil {
		return e
	}
	defer f.Close()

	f.WriteString(value)
	return nil
}

// Needs to be called to allocate the GPIO pin
func (op *BeagleBoneFSOpenPin) gpioExport() error {
	s := strconv.FormatInt(int64(op.gpioLogical), 10)
	e := writeStringToFile("/sys/class/gpio/export", s)
	if e != nil {
		return e
	}

	// calculate the base name for the gpio pin
	op.gpioBaseName = "/sys/class/gpio/gpio" + strconv.Itoa(op.gpioLogical)
	return nil
}

// Once exported, the direction of a GPIO can be set
func (op *BeagleBoneFSOpenPin) gpioDirection(dir string) error {
	if dir != "in" && dir != "out" {
		return errors.New("direction must be in or out")
	}
	f := op.gpioBaseName + "/direction"
	e := writeStringToFile(f, dir)

	mode := os.O_WRONLY | os.O_TRUNC
	if dir == "in" {
		mode = os.O_RDONLY
	}

	// open the value file with the correct mode. Put that file in 'op'. Note that we keep this file open
	// continuously for performance.
	// Preliminary tests on 200,000 DigitalWrites indicate an order of magnitude improvement when we don't have
	// to re-open the file each time. Re-seeking and writing a new value suffices.
	op.valueFile, e = os.OpenFile(op.gpioBaseName+"/value", mode, 0666)

	return e
}

// Get the value. Will return HIGH or LOW
func (op *BeagleBoneFSOpenPin) gpioGetValue() (int, error) {
	var b []byte
	b = make([]byte, 1)
	n, e := op.valueFile.ReadAt(b, 0)
	value := 0
	if n > 0 {
		if b[0] == '1' {
			value = HIGH
		} else {
			value = LOW
		}
	}
	return value, e
}

// Set the value, Expects HIGH or LOW
func (op *BeagleBoneFSOpenPin) gpioSetValue(value int) error {
	_, e := op.valueFile.Seek(0, 0)
	if e != nil {
		return e
	}

	if value == 0 {
		op.valueFile.WriteString("0")
	} else {
		op.valueFile.WriteString("1")
	}
	return nil
}

type BeagleBoneFSDriver struct {
	openPins map[Pin]*BeagleBoneFSOpenPin
}

func (d *BeagleBoneFSDriver) Init() error {
	d.openPins = make(map[Pin]*BeagleBoneFSOpenPin)
	return nil
}

func (d *BeagleBoneFSDriver) Close() {
	// @todo call unexport on all open pins
}

// create an openPin object and put it in the map.
func (d *BeagleBoneFSDriver) makeOpenPin(pin Pin, gpioLogicalPin int) *BeagleBoneFSOpenPin {
	result := &BeagleBoneFSOpenPin{pin: pin, gpioLogical: gpioLogicalPin}
	d.openPins[pin] = result
	return result
}

// For GPIO:
// - write GPIO pin to /sys/class/gpio/export. This is the port number plus pin on that port. Ports 0, 32, 64, 96.
// - write direction to /sys/class/gpio/gpio{nn}/direction. Values are 'in' and 'out'

func (d *BeagleBoneFSDriver) PinMode(pin Pin, mode PinIOMode) error {
	p := beaglePins[pin]

	// handle analog first, they are simplest from PinMode perspective
	if p.isAnalogPin() {
		if mode != INPUT {
			return errors.New(fmt.Sprintf("Pin %d is an analog pin, and the mode must be INPUT", p))
		}
		// @todo set up the analog pin
		return nil // nothing to set up
	}

	// Create an open pin object
	openPin := d.makeOpenPin(pin, p.gpioLogical)
	e := openPin.gpioExport()
	if e != nil {
		return e
	}

	if mode == OUTPUT {
		fmt.Printf("about to set pin %d to output\n", pin)
		e = openPin.gpioDirection("out")
		if e != nil {
			return e
		}
	} else {
		e = openPin.gpioDirection("in")
		// pull := BB_CONF_PULL_DISABLE
		// // note: pull up/down modes assume that CONF_PULLDOWN resets the pull disable bit
		// if mode == INPUT_PULLUP {
		// 	pull = BB_CONF_PULLUP
		// } else if mode == INPUT_PULLDOWN {
		// 	pull = BB_CONF_PULLDOWN
		// }

		if e != nil {
			return e
		}
	}
	return nil
}

func (d *BeagleBoneFSDriver) DigitalWrite(pin Pin, value int) (e error) {
	openPin := d.openPins[pin]
	if openPin == nil {
		return errors.New("Pin is being written but has not been opened")
	}
	openPin.gpioSetValue(value)
	return nil
}

func (d *BeagleBoneFSDriver) DigitalRead(pin Pin) (value int, e error) {
	openPin := d.openPins[pin]
	return openPin.gpioGetValue()
}

func (d *BeagleBoneFSDriver) AnalogWrite(pin Pin, value int) (e error) {
	return nil
}

func (d *BeagleBoneFSDriver) AnalogRead(pin Pin) (value int, e error) {
	return 0, nil
}

func (d *BeagleBoneFSDriver) PinMap() (pinMap HardwarePinMap) {
	pinMap = make(HardwarePinMap)

	for i, hw := range beaglePins {
		names := []string{hw.hwPin}
		if hw.hwPin != hw.gpioName {
			names = append(names, hw.gpioName)
		}
		pinMap.add(Pin(i), names, hw.profile)
	}

	return
}
<|endoftext|>


<commit_before>package dual

import (
	"fmt"
	"testing"
)

var (
	zero = New(0, 0)
	e0   = New(1, 0)
	e1   = New(0, 1)
)

func TestEquals(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want bool
	}{
		{zero, zero, true},
		{e0, e0, true},
		{e1, e1, true},
		{e0, e1, false},
		{e1, e0, false},
		{New(2.03, 3), New(2.0299999999, 3), true},
		{New(1, 2), New(3, 4), false},
	}
	for _, test := range tests {
		if got := test.x.Equals(test.y); got != test.want {
			t.Errorf("Equals(%v, %v) = %v", test.x, test.y, got)
		}
	}
}

func TestCopy(t *testing.T) {
	var tests = []struct {
		x    *Dual
		want *Dual
	}{
		{zero, zero},
		{New(1, 2), New(1, 2)},
	}
	for _, test := range tests {
		if got := new(Dual).Copy(test.x); !got.Equals(test.want) {
			t.Errorf("Copy(%v) = %v, want %v", test.x, got, test.want)
		}
	}
}

func TestString(t *testing.T) {
	var tests = []struct {
		x    *Dual
		want string
	}{
		{zero, "(0+0ε)"},
		{e0, "(1+0ε)"},
		{e1, "(0+1ε)"},
		{New(1, 1), "(1+1ε)"},
		{New(1, -1), "(1-1ε)"},
		{New(-1, 1), "(-1+1ε)"},
		{New(-1, -1), "(-1-1ε)"},
	}
	for _, test := range tests {
		if got := test.x.String(); got != test.want {
			t.Errorf("String(%v) = %v, want %v", test.x, got, test.want)
		}
	}
}

func ExampleNew() {
	fmt.Println(New(1, 0))
	fmt.Println(New(0, 1))
	fmt.Println(New(2, -3))
	fmt.Println(New(-4, 5))
	// Output:
	// (1+0ε)
	// (0+1ε)
	// (2-3ε)
	// (-4+5ε)
}

func TestScal(t *testing.T) {}

func TestNeg(t *testing.T) {}

func TestConj(t *testing.T) {}

func TestAdd(t *testing.T) {}

func TestSub(t *testing.T) {}

func TestMul(t *testing.T) {}

func TestQuad(t *testing.T) {}

func TestIsZeroDiv(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want bool
	}{
		{zero, true},
		{e0, false},
		{e1, true},
	}
	for _, test := range tests {
		if got := test.z.IsZeroDiv(); got != test.want {
			t.Errorf("IsZeroDiv(%v) = %v", test.z, got)
		}
	}
}

func TestInv(t *testing.T) {}

func TestQuo(t *testing.T) {}
<commit_msg>Add tests<commit_after>package dual

import (
	"fmt"
	"math"
	"testing"
)

var (
	zero = New(0, 0)
	e0   = New(1, 0)
	e1   = New(0, 1)
)

func TestString(t *testing.T) {
	var tests = []struct {
		x    *Dual
		want string
	}{
		{zero, "(0+0ε)"},
		{e0, "(1+0ε)"},
		{e1, "(0+1ε)"},
		{New(1, 1), "(1+1ε)"},
		{New(1, -1), "(1-1ε)"},
		{New(-1, 1), "(-1+1ε)"},
		{New(-1, -1), "(-1-1ε)"},
	}
	for _, test := range tests {
		if got := test.x.String(); got != test.want {
			t.Errorf("String(%v) = %v, want %v", test.x, got, test.want)
		}
	}
}

func TestEquals(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want bool
	}{
		{zero, zero, true},
		{e0, e0, true},
		{e1, e1, true},
		{e0, e1, false},
		{e1, e0, false},
		{New(2.03, 3), New(2.0299999999, 3), true},
		{New(1, 2), New(3, 4), false},
	}
	for _, test := range tests {
		if got := test.x.Equals(test.y); got != test.want {
			t.Errorf("Equals(%v, %v) = %v", test.x, test.y, got)
		}
	}
}

func TestCopy(t *testing.T) {
	var tests = []struct {
		x    *Dual
		want *Dual
	}{
		{zero, zero},
		{New(1, 2), New(1, 2)},
	}
	for _, test := range tests {
		if got := new(Dual).Copy(test.x); !got.Equals(test.want) {
			t.Errorf("Copy(%v) = %v, want %v", test.x, got, test.want)
		}
	}
}

func ExampleNew() {
	fmt.Println(New(1, 0))
	fmt.Println(New(0, 1))
	fmt.Println(New(2, -3))
	fmt.Println(New(-4, 5))
	// Output:
	// (1+0ε)
	// (0+1ε)
	// (2-3ε)
	// (-4+5ε)
}

func TestScal(t *testing.T) {
	var tests = []struct {
		z    *Dual
		a    float64
		want *Dual
	}{
		{zero, 1, zero},
		{New(1, 2), 3, New(3, 6)},
		{New(1, 2), 0, zero},
	}
	for _, test := range tests {
		if got := new(Dual).Scal(test.z, test.a); !got.Equals(test.want) {
			t.Errorf("Scal(%v, %v) = %v, want %v",
				test.z, test.a, got, test.want)
		}
	}
}

func TestNeg(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want *Dual
	}{
		{zero, zero},
		{e0, New(-1, 0)},
		{e1, New(0, -1)},
		{New(3, 4), New(-3, -4)},
	}
	for _, test := range tests {
		if got := new(Dual).Neg(test.z); !got.Equals(test.want) {
			t.Errorf("Neg(%v) = %v, want %v",
				test.z, got, test.want)
		}
	}
}

func TestConj(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want *Dual
	}{
		{zero, zero},
		{e0, e0},
		{e1, New(0, -1)},
		{New(3, 4), New(3, -4)},
	}
	for _, test := range tests {
		if got := new(Dual).Conj(test.z); !got.Equals(test.want) {
			t.Errorf("Conj(%v) = %v, want %v",
				test.z, got, test.want)
		}
	}
}

func TestAdd(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want *Dual
	}{
		{zero, zero, zero},
		{e0, e0, New(2, 0)},
		{e1, e1, New(0, 2)},
		{e0, e1, New(1, 1)},
		{e1, e0, New(1, 1)},
	}
	for _, test := range tests {
		if got := new(Dual).Add(test.x, test.y); !got.Equals(test.want) {
			t.Errorf("Add(%v, %v) = %v, want %v",
				test.x, test.y, got, test.want)
		}
	}
}

func TestSub(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want *Dual
	}{
		{zero, zero, zero},
		{e0, e0, zero},
		{e1, e1, zero},
		{e0, e1, New(1, -1)},
		{e1, e0, New(-1, 1)},
	}
	for _, test := range tests {
		if got := new(Dual).Sub(test.x, test.y); !got.Equals(test.want) {
			t.Errorf("Sub(%v, %v) = %v, want %v",
				test.x, test.y, got, test.want)
		}
	}
}

func TestMul(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want *Dual
	}{
		{zero, zero, zero},
		{e0, e0, e0},
		{e1, e1, zero},
		{e0, e1, e1},
		{e1, e0, e1},
	}
	for _, test := range tests {
		if got := new(Dual).Mul(test.x, test.y); !got.Equals(test.want) {
			t.Errorf("Mul(%v, %v) = %v, want %v",
				test.x, test.y, got, test.want)
		}
	}
}

func TestQuad(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want float64
	}{
		{zero, 0},
		{e0, 1},
		{e1, 0},
		{New(-2, 1), 4},
	}
	for _, test := range tests {
		if got := test.z.Quad(); notEquals(got, test.want) {
			t.Errorf("Quad(%v) = %v, want %v",
				test.z, got, test.want)
		}
	}
}

func TestIsZeroDiv(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want bool
	}{
		{zero, true},
		{e0, false},
		{e1, true},
	}
	for _, test := range tests {
		if got := test.z.IsZeroDiv(); got != test.want {
			t.Errorf("IsZeroDiv(%v) = %v", test.z, got)
		}
	}
}

func TestInv(t *testing.T) {
	var tests = []struct {
		x    *Dual
		want *Dual
	}{
		{e0, e0},
		{New(2, 0), New(0.5, 0)},
	}
	for _, test := range tests {
		if got := new(Dual).Inv(test.x); !got.Equals(test.want) {
			t.Errorf("Inv(%v) = %v, want %v",
				test.x, got, test.want)
		}
	}
}

func TestQuo(t *testing.T) {
	var tests = []struct {
		x    *Dual
		y    *Dual
		want *Dual
	}{
		{e0, e0, e0},
		{New(0.5, 0), New(2, 0), New(0.25, 0)},
	}
	for _, test := range tests {
		if got := new(Dual).Quo(test.x, test.y); !got.Equals(test.want) {
			t.Errorf("Quo(%v, %v) = %v, want %v",
				test.x, test.y, got, test.want)
		}
	}
}

func TestIsInf(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want bool
	}{
		{zero, false},
		{e0, false},
		{e1, false},
		{New(math.Inf(0), 4), true},
	}
	for _, test := range tests {
		if got := test.z.IsInf(); got != test.want {
			t.Errorf("IsInf(%v) = %v", test.z, got)
		}
	}
}

func ExampleInf() {
	fmt.Println(Inf(+1, +1))
	fmt.Println(Inf(+1, -1))
	fmt.Println(Inf(-1, +1))
	fmt.Println(Inf(-1, -1))
	// Output:
	// (+Inf+Infε)
	// (+Inf-Infε)
	// (-Inf+Infε)
	// (-Inf-Infε)
}

func TestIsNaN(t *testing.T) {
	var tests = []struct {
		z    *Dual
		want bool
	}{
		{zero, false},
		{e0, false},
		{e1, false},
		{New(math.NaN(), 4), true},
		{New(math.Inf(0), math.NaN()), false},
	}
	for _, test := range tests {
		if got := test.z.IsNaN(); got != test.want {
			t.Errorf("IsNaN(%v) = %v", test.z, got)
		}
	}
}

func ExampleNaN() {
	fmt.Println(NaN())
	// Output:
	// (NaN+NaNε)
}
<|endoftext|>


<commit_before>// Package easyvk provides you simple way
// to work with VK API.
package easyvk

import (
	"net/url"
	"net/http"
	"io/ioutil"
	"fmt"
	"encoding/json"
)

const apiURL = "https://api.vk.com/method/"

// VK defines a set of functions for
// working with VK API.
type VK struct {
	AccessToken string
	Version     string
	Account     Account
	Fave        Fave
	Photos      Photos
	Status      Status
	Upload      Upload
	Wall        Wall
}

// WithToken helps to initialize your
// VK object with token.
func WithToken(token string) VK {
	vk := VK{}
	vk.AccessToken = token
	vk.Version = "5.63"
	vk.Account = Account{&vk }
	vk.Fave = Fave{&vk }
	vk.Photos = Photos{&vk }
	vk.Status = Status{&vk }
	vk.Upload = Upload{}
	vk.Wall = Wall{&vk }
	return vk
}

// Request provides access to VK API methods.
func (vk *VK) Request(method string, params map[string]string) ([]byte, error) {
	u, err := url.Parse(apiURL + method)
	if err != nil {
		return nil, err
	}

	query := url.Values{}
	for k, v := range params {
		query.Set(k, v)
	}
	query.Set("access_token", vk.AccessToken)
	query.Set("v", vk.Version)
	u.RawQuery = query.Encode()

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

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if string(body[2:7]) == "error" {
		var e VKError
		err = json.Unmarshal(body, &e)
		return nil, fmt.Errorf("Code %d: %s", e.Error.Code, e.Error.Message)
	}

	return body, nil
}

type response struct {
	Response int `json:"response"`
}
<commit_msg>First step to auth<commit_after>// Package easyvk provides you simple way
// to work with VK API.
package easyvk

import (
	"net/url"
	"net/http"
	"io/ioutil"
	"fmt"
	"encoding/json"
)

const version = "5.63"
const apiURL = "https://api.vk.com/method/"
const authURL = "https://oauth.vk.com/authorize?" +
	"client_id=%s" +
	"&scope=%s" +
	"&redirect_uri=https://oauth.vk.com/blank.html" +
	"&display=wap" +
	"&v=%s" +
	"&response_type=token"

// VK defines a set of functions for
// working with VK API.
type VK struct {
	AccessToken string
	Version     string
	Account     Account
	Fave        Fave
	Photos      Photos
	Status      Status
	Upload      Upload
	Wall        Wall
}

// WithToken helps to initialize your
// VK object with token.
func WithToken(token string) VK {
	vk := VK{}
	vk.AccessToken = token
	vk.Version = version
	vk.Account = Account{&vk }
	vk.Fave = Fave{&vk }
	vk.Photos = Photos{&vk }
	vk.Status = Status{&vk }
	vk.Upload = Upload{}
	vk.Wall = Wall{&vk }
	return vk
}

func WithAuth(login, password, clientID, scope string) {
	u := fmt.Sprintf(authURL, clientID, scope, version)
	client := &http.Client{}

	resp, err := client.Get(u)
	if err != nil {

	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {

	}
	fmt.Println(string(body))
}

// Request provides access to VK API methods.
func (vk *VK) Request(method string, params map[string]string) ([]byte, error) {
	u, err := url.Parse(apiURL + method)
	if err != nil {
		return nil, err
	}

	query := url.Values{}
	for k, v := range params {
		query.Set(k, v)
	}
	query.Set("access_token", vk.AccessToken)
	query.Set("v", vk.Version)
	u.RawQuery = query.Encode()

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

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if string(body[2:7]) == "error" {
		var e VKError
		err = json.Unmarshal(body, &e)
		return nil, fmt.Errorf("Code %d: %s", e.Error.Code, e.Error.Message)
	}

	return body, nil
}

type response struct {
	Response int `json:"response"`
}
<|endoftext|>


<commit_before>/*
   Copyright 2010-2014 gtalent2@gmail.com

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

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

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

import (
	"flag"
	"github.com/hoisie/web"
	"github.com/russross/blackfriday"
	"io/ioutil"
	"log"
	"strings"
)

func docLinks() string {
	out := "
"
	list, err := ioutil.ReadDir(".")
	if err == nil {
		for _, v := range list {
			name := v.Name()
			if name[len(name)-3:] == ".md" {
				out += "
" + name + "
"
			}
		}
	} else {
		log.Println("error:", err)
	}
	out += "
"
	return out
}

func mkServer(contextDir string, format bool) func(*web.Context, string) string {
	return func(params *web.Context, val string) string {
		if len(val) == 0 || (len(val) == 1 && val == "/") {
			val = "index.md"
		}
		file, err := ioutil.ReadFile(contextDir + val)
		if err != nil {
			if val != "index.md" {
				return "404: File not found: " + val
			} else {
				return `

		<title>Directory Listing</title>

Docs

` + docLinks() + `

`

			}
		}
		if strings.HasSuffix(val, ".md") {
			var text string
			if format {
				text = string(blackfriday.MarkdownBasic(file))
			} else {
				text = string(file)
			}
			return `

		<title>` + val + `</title>

` + text + `

`
		}
		return string(file)
	}
}

func main() {
	var contextDir = ""
	global := flag.Bool("global", false, "Allow the server to access any files that the user running it has access to.")
	remote := flag.Bool("remote", false, "Allow the remote clients to access the server.")
	port := "15448"
	flag.Parse()
	//read the context from the input and override whats in the settings file if something was there
	if flag.NArg() != 0 {
		contextDir = flag.Arg(0)
	}
	//make sure the context is a directory
	if len(contextDir) != 0 && !strings.HasSuffix(contextDir, "/") {
		contextDir += "/"
	}

	contextServe := mkServer(contextDir, true)
	rawServe := mkServer(contextDir, false)
	globalServe := mkServer("", true)
	web.Get("/doc/(.*)", contextServe)
	web.Get("/doc", contextServe)
	web.Get("/raw/(.*)", rawServe)
	web.Get("/raw", rawServe)
	if *global {
		web.Get("/doc-g/(.*)", globalServe)
		web.Get("/doc-g", globalServe)
	}
	if *remote {
		web.Run("0.0.0.0:" + port)
	} else {
		web.Run("127.0.0.1:" + port)
	}
}
<commit_msg>Cleaned up directory list code.<commit_after>/*
   Copyright 2010-2014 gtalent2@gmail.com

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

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

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

import (
	"flag"
	"github.com/hoisie/web"
	"github.com/russross/blackfriday"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func dirList() string {
	out := `

		<title>Directory Listing</title>

Docs

`
	list, err := ioutil.ReadDir(".")
	if err == nil {
		for _, v := range list {
			name := v.Name()
			if name[len(name)-3:] == ".md" {
				out += "
" + name + "
"
			}
		}
	} else {
		log.Println("error:", err)
		return "404: Not Found"
	}
	out += `

`
	return out
}

func mkServer(contextDir string, format bool) func(*web.Context, string) string {
	return func(params *web.Context, val string) string {
		if len(val) == 0 || (len(val) == 1 && val == "/") {
			val = "."
		}
		if fi, err := os.Stat(contextDir + val); fi.IsDir() {
			return dirList()
		} else if err != nil {
			log.Println("error:", err)
			return "404: File not found: " + val
		} else {
			file, err := ioutil.ReadFile(contextDir + val)
			if err != nil {
				log.Println("error:", err)
				return "404: File not found: " + val
			} else if strings.HasSuffix(val, ".md") {
				var text string
				if format {
					text = string(blackfriday.MarkdownBasic(file))
				} else {
					text = string(file)
				}
				return `

		<title>` + val + `</title>

` + text + `

`
			}
			return string(file)
		}
	}
}

func main() {
	var contextDir = ""
	global := flag.Bool("global", false, "Allow the server to access any files that the user running it has access to.")
	remote := flag.Bool("remote", false, "Allow the remote clients to access the server.")
	port := "15448"
	flag.Parse()
	//read the context from the input and override whats in the settings file if something was there
	if flag.NArg() != 0 {
		contextDir = flag.Arg(0)
	}
	//make sure the context is a directory
	if len(contextDir) != 0 && !strings.HasSuffix(contextDir, "/") {
		contextDir += "/"
	}

	contextServe := mkServer(contextDir, true)
	rawServe := mkServer(contextDir, false)
	globalServe := mkServer("", true)
	web.Get("/doc/(.*)", contextServe)
	web.Get("/doc", contextServe)
	web.Get("/raw/(.*)", rawServe)
	web.Get("/raw", rawServe)
	if *global {
		web.Get("/doc-g/(.*)", globalServe)
		web.Get("/doc-g", globalServe)
	}
	if *remote {
		web.Run("0.0.0.0:" + port)
	} else {
		web.Run("127.0.0.1:" + port)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
    "fmt"
    "os"
    "io"
    "io/ioutil"
)

func main() {
	var md []byte
	var dir, calc string

	list := make(map[string]bool)

	if len(os.Args) > 1 {
		dir = os.Args[1]
	} else {
		dir = "./test"
	}

	fmt.Printf("Reading %s\n", dir)

    files, _ := ioutil.ReadDir(dir)

    for _, f := range files {

		md,_ = ComputeMd5(dir + "/" + f.Name())

		calc = string(md[:])

        fmt.Printf("File: %s, md5: %x\n", f.Name(), md)

        if list[calc] {
        	fmt.Printf("Possible duplicate: %s\n", f.Name())
        }

        list[calc] = true
    }
}

func ComputeMd5(filePath string) ([]byte, error) {
  var result []byte
  file, err := os.Open(filePath)
  if err != nil {
    return result, err
  }
  defer file.Close()

  hash := md5.New()
  if _, err := io.Copy(hash, file); err != nil {
    return result, err
  }

  return hash.Sum(result), nil
}
<commit_msg>updated and commented version<commit_after>package main

import (
	"crypto/md5"
    "fmt"
    "os"
    "io"
    "io/ioutil"
    "strings"
)

func main() {
	var md []byte
	var dir, path, calc string

	// create map for existing files
	list := make(map[string]bool)

	// see of args
	if len(os.Args) > 1 {
		dir = os.Args[1]
	} else {
		dir = "./test"
	}

	// display name of parsed directory
	fmt.Printf("Reading %s\n", dir)

	// get list of files
    files, _ := ioutil.ReadDir(dir)

    // iterate
    for _, f := range files {

		// create path to file (dir + name)
		path = dir + "/" + f.Name()

		// check if it's not directory
		if info, err := os.Stat(path); err == nil && !info.IsDir() {

			// calc md5
       		md,_ = ComputeMd5(dir + "/" + f.Name())

			// create string to use in map
			calc = string(md[:])

       		// show name and md5 of file
        	fmt.Printf("File: %s, md5: %x\n", f.Name(), md)

        	// if file is already on the list, mark as a duplicate
        	if list[calc] {

        		fmt.Printf("Possible duplicate: %s\n", f.Name())

        		// check if is not already .duplicate
        		if !strings.HasSuffix(path, ".duplicate") {
        			os.Rename(path, path + ".duplicate")
        		}
       		} else {
				list[calc] = true
			}

   	 	} else {
   	 		fmt.Printf("Dir: %s - skipped\n", path)
   	 	} // end if

    } // end for
 }

func ComputeMd5(filePath string) ([]byte, error) {
  var result []byte
  file, err := os.Open(filePath)
  if err != nil {
    return result, err
  }
  defer file.Close()

  hash := md5.New()
  if _, err := io.Copy(hash, file); err != nil {
    return result, err
  }

  return hash.Sum(result), nil
}
<|endoftext|>


<commit_before>package model

import (
	"time"

	"github.com/mjibson/goon"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
	"google.golang.org/appengine/datastore"
)

type LineUser struct {
	Id        string `datastore:"-" goon:"id"`
	CreatedAt time.Time
}

func NewLineUser(id string) *LineUser {
	return &LineUser{Id: id}
}

func (u *LineUser) Put(ctx context.Context) error {
	g := goon.FromContext(ctx)

	// check for cached item
	if g.Get(u) == nil {
		return errors.Errorf("LineUser already exists.")
	}

	return g.RunInTransaction(func(g *goon.Goon) error {
		err := g.Get(u)
		if err != nil && err != datastore.ErrNoSuchEntity {
			return err
		}

		jst, err := time.LoadLocation("Asia/Tokyo")
		if err != nil {
			return err
		}
		u.CreatedAt = time.Now().In(jst)

		_, err = g.Put(u)
		return err
	}, nil)
}

type LineUserQuery struct {
	context context.Context
	cursor  datastore.Cursor
	Limit   int
}

func NewLineUserQuery(ctx context.Context) *LineUserQuery {
	return &LineUserQuery{context: ctx, Limit: 100}
}

func (u *LineUserQuery) GetIds() ([]string, error) {
	q := datastore.NewQuery("LineUser").KeysOnly().Limit(u.Limit)
	if u.cursor.String() != "" {
		q = q.Start(u.cursor)
	}

	ids := []string{}
	t := q.Run(u.context)
	for {
		k, err := t.Next(nil)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		ids = append(ids, k.StringID())
	}

	var err error
	u.cursor, err = t.Cursor()
	if err != nil {
		return nil, err
	}
	return ids, nil
}
<commit_msg>Add Enabled column to LineUser<commit_after>package model

import (
	"time"

	"github.com/mjibson/goon"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
	"google.golang.org/appengine/datastore"
)

type LineUser struct {
	Id        string `datastore:"-" goon:"id"`
	Enabled   bool
	CreatedAt time.Time
}

func NewLineUser(id string) *LineUser {
	return &LineUser{Id: id, Enabled: true}
}

func (u *LineUser) Put(ctx context.Context) error {
	g := goon.FromContext(ctx)

	// check for cached item
	if g.Get(u) == nil {
		return errors.Errorf("LineUser already exists.")
	}

	return g.RunInTransaction(func(g *goon.Goon) error {
		err := g.Get(u)
		if err != nil && err != datastore.ErrNoSuchEntity {
			return err
		}

		jst, err := time.LoadLocation("Asia/Tokyo")
		if err != nil {
			return err
		}
		u.CreatedAt = time.Now().In(jst)

		_, err = g.Put(u)
		return err
	}, nil)
}

type LineUserQuery struct {
	context context.Context
	cursor  datastore.Cursor
	Limit   int
}

func NewLineUserQuery(ctx context.Context) *LineUserQuery {
	return &LineUserQuery{context: ctx, Limit: 100}
}

func (u *LineUserQuery) GetIds() ([]string, error) {
	q := datastore.NewQuery("LineUser").Filter("Enabled =", true).KeysOnly().Limit(u.Limit)
	if u.cursor.String() != "" {
		q = q.Start(u.cursor)
	}

	ids := []string{}
	t := q.Run(u.context)
	for {
		k, err := t.Next(nil)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		ids = append(ids, k.StringID())
	}

	var err error
	u.cursor, err = t.Cursor()
	if err != nil {
		return nil, err
	}
	return ids, nil
}
<|endoftext|>


<commit_before>package network

import (
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	inet "github.com/jbenet/go-ipfs/net"
	peer "github.com/jbenet/go-ipfs/peer"
	util "github.com/jbenet/go-ipfs/util"
)

var log = util.Logger("bitswap_network")

// NewFromIpfsNetwork returns a BitSwapNetwork supported by underlying IPFS
// Dialer & Service
func NewFromIpfsNetwork(n inet.Network) BitSwapNetwork {
	bitswapNetwork := impl{
		network: n,
	}
	n.SetHandler(inet.ProtocolBitswap, bitswapNetwork.handleNewStream)
	return &bitswapNetwork
}

// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
type impl struct {
	network inet.Network

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
}

// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {

	if bsnet.receiver == nil {
		return
	}

	go func() {
		defer s.Close()

		received, err := bsmsg.FromNet(s)
		if err != nil {
			go bsnet.receiver.ReceiveError(err)
			return
		}

		p := s.Conn().RemotePeer()
		ctx := context.Background()
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}()

}

func (bsnet *impl) DialPeer(ctx context.Context, p peer.ID) error {
	return bsnet.network.DialPeer(ctx, p)
}

func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
	if err != nil {
		return err
	}
	defer s.Close()

	return outgoing.ToNet(s)
}

func (bsnet *impl) SendRequest(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
	if err != nil {
		return nil, err
	}
	defer s.Close()

	if err := outgoing.ToNet(s); err != nil {
		return nil, err
	}

	return bsmsg.FromNet(s)
}

func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
}
<commit_msg>style(bitswap) public methods at top<commit_after>package network

import (
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	inet "github.com/jbenet/go-ipfs/net"
	peer "github.com/jbenet/go-ipfs/peer"
	util "github.com/jbenet/go-ipfs/util"
)

var log = util.Logger("bitswap_network")

// NewFromIpfsNetwork returns a BitSwapNetwork supported by underlying IPFS
// Dialer & Service
func NewFromIpfsNetwork(n inet.Network) BitSwapNetwork {
	bitswapNetwork := impl{
		network: n,
	}
	n.SetHandler(inet.ProtocolBitswap, bitswapNetwork.handleNewStream)
	return &bitswapNetwork
}

// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
type impl struct {
	network inet.Network

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
}

func (bsnet *impl) DialPeer(ctx context.Context, p peer.ID) error {
	return bsnet.network.DialPeer(ctx, p)
}

func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
	if err != nil {
		return err
	}
	defer s.Close()

	return outgoing.ToNet(s)
}

func (bsnet *impl) SendRequest(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

	s, err := bsnet.network.NewStream(inet.ProtocolBitswap, p)
	if err != nil {
		return nil, err
	}
	defer s.Close()

	if err := outgoing.ToNet(s); err != nil {
		return nil, err
	}

	return bsmsg.FromNet(s)
}

func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
}

// handleNewStream receives a new stream from the network.
func (bsnet *impl) handleNewStream(s inet.Stream) {

	if bsnet.receiver == nil {
		return
	}

	go func() {
		defer s.Close()

		received, err := bsmsg.FromNet(s)
		if err != nil {
			go bsnet.receiver.ReceiveError(err)
			return
		}

		p := s.Conn().RemotePeer()
		ctx := context.Background()
		bsnet.receiver.ReceiveMessage(ctx, p, received)
	}()

}
<|endoftext|>


<commit_before>package e2e

import (
	"context"
	"strings"

	. "github.com/onsi/gomega" // nolint
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/test/e2e/framework"
	e2elog "k8s.io/kubernetes/test/e2e/framework/log"
)

var (
	vaultExamplePath = "../examples/kms/vault/"
	vaultServicePath = "vault.yaml"
	vaultPSPPath     = "vault-psp.yaml"
	vaultRBACPath    = "csi-vaulttokenreview-rbac.yaml"
	vaultConfigPath  = "kms-config.yaml"
)

func deployVault(c kubernetes.Interface, deployTimeout int) {
	// hack to make helm E2E pass as helm charts creates this configmap as part
	// of cephcsi deployment
	_, err := framework.RunKubectl(cephCSINamespace, "delete", "cm", "ceph-csi-encryption-kms-config", "--namespace", cephCSINamespace, "--ignore-not-found=true")
	Expect(err).Should(BeNil())

	createORDeleteVault("create")
	opt := metav1.ListOptions{
		LabelSelector: "app=vault",
	}

	pods, err := c.CoreV1().Pods(cephCSINamespace).List(context.TODO(), opt)
	Expect(err).Should(BeNil())
	Expect(len(pods.Items)).Should(Equal(1))
	name := pods.Items[0].Name
	err = waitForPodInRunningState(name, cephCSINamespace, c, deployTimeout, noError)
	Expect(err).Should(BeNil())
}

func deleteVault() {
	createORDeleteVault("delete")
}

func createORDeleteVault(action string) {
	data, err := replaceNamespaceInTemplate(vaultExamplePath + vaultServicePath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultServicePath, err)
	}

	data = strings.ReplaceAll(data, "vault.default", "vault."+cephCSINamespace)

	data = strings.ReplaceAll(data, "value: default", "value: "+cephCSINamespace)
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault statefulset %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultRBACPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultRBACPath, err)
	}
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault statefulset %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultConfigPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultConfigPath, err)
	}
	data = strings.ReplaceAll(data, "default", cephCSINamespace)
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault configmap %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultPSPPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultPSPPath, err)
	}
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault psp %v", action, err)
	}
}
<commit_msg>e2e: reformat long lines in this package to 120 chars<commit_after>package e2e

import (
	"context"
	"strings"

	. "github.com/onsi/gomega" // nolint
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/test/e2e/framework"
	e2elog "k8s.io/kubernetes/test/e2e/framework/log"
)

var (
	vaultExamplePath = "../examples/kms/vault/"
	vaultServicePath = "vault.yaml"
	vaultPSPPath     = "vault-psp.yaml"
	vaultRBACPath    = "csi-vaulttokenreview-rbac.yaml"
	vaultConfigPath  = "kms-config.yaml"
)

func deployVault(c kubernetes.Interface, deployTimeout int) {
	// hack to make helm E2E pass as helm charts creates this configmap as part
	// of cephcsi deployment
	_, err := framework.RunKubectl(
		cephCSINamespace,
		"delete",
		"cm",
		"ceph-csi-encryption-kms-config",
		"--namespace",
		cephCSINamespace,
		"--ignore-not-found=true")
	Expect(err).Should(BeNil())

	createORDeleteVault("create")
	opt := metav1.ListOptions{
		LabelSelector: "app=vault",
	}

	pods, err := c.CoreV1().Pods(cephCSINamespace).List(context.TODO(), opt)
	Expect(err).Should(BeNil())
	Expect(len(pods.Items)).Should(Equal(1))
	name := pods.Items[0].Name
	err = waitForPodInRunningState(name, cephCSINamespace, c, deployTimeout, noError)
	Expect(err).Should(BeNil())
}

func deleteVault() {
	createORDeleteVault("delete")
}

func createORDeleteVault(action string) {
	data, err := replaceNamespaceInTemplate(vaultExamplePath + vaultServicePath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultServicePath, err)
	}

	data = strings.ReplaceAll(data, "vault.default", "vault."+cephCSINamespace)

	data = strings.ReplaceAll(data, "value: default", "value: "+cephCSINamespace)
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault statefulset %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultRBACPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultRBACPath, err)
	}
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault statefulset %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultConfigPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultConfigPath, err)
	}
	data = strings.ReplaceAll(data, "default", cephCSINamespace)
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault configmap %v", action, err)
	}

	data, err = replaceNamespaceInTemplate(vaultExamplePath + vaultPSPPath)
	if err != nil {
		e2elog.Failf("failed to read content from %s %v", vaultExamplePath+vaultPSPPath, err)
	}
	_, err = framework.RunKubectlInput(cephCSINamespace, data, action, ns, "-f", "-")
	if err != nil {
		e2elog.Failf("failed to %s vault psp %v", action, err)
	}
}
<|endoftext|>


<commit_before>package emit

import (
	"bufio"
	"fmt"
	"strings"
	"github.com/andrewchambers/g/parse"
)

type emitter struct {
    curscope *scope
    out *bufio.Writer

    curFuncType *GFunc
}

type exprValue struct {
    llvmVal string
    lval bool
    gType GType
}

func newEmitter(out *bufio.Writer) *emitter {
    ret := &emitter{}
    ret.curscope = newScope(nil)
    ret.out = out
    return ret
}

func (e *emitter) pushScope() {
    e.curscope = newScope(e.curscope)
}

func (e *emitter) popScope() {
    e.curscope = e.curscope.parent
}

func (e *emitter) emit(s string,args ...interface{}) {
    fmt.Fprintf(e.out,s,args...)
}

func (e *emitter) emiti(s string,args ...interface{}) {
    e.emit("    "+s,args...)
}

func EmitModule(out *bufio.Writer, file *parse.File) error {
    e := newEmitter(out)
    err := e.collectGlobalSymbols(file)
    if err != nil {
        return err
    }
    for _, fd := range file.FuncDecls {
        err = e.emitFuncDecl(fd)
        if err != nil {
            return err
        }
    }
    out.Flush()
    return nil
}

func (e *emitter) collectGlobalSymbols(file *parse.File) error {
    for _, imp := range file.Imports {
        impdef := imp.Val[1:len(imp.Val) - 1]
        impdef = strings.Split(impdef,"/")[0]
        sym := newSymbol(imp.Span.Start)
        err := e.curscope.declareSym(impdef,sym)
        if err != nil {
           return fmt.Errorf("bad import: %s %s:%v",err , imp.Span.Path, imp.Span.Start)
        }
    }
    for _, fd := range file.FuncDecls {
        sym := newSymbol(fd.Span.Start)
        err := e.curscope.declareSym(fd.Name,sym)
        if err != nil {
            return fmt.Errorf("bad func decl: %s %s:%v",err , fd.Span.Path, fd.Span.Start)
        }
    }
    for _,vd := range file.VarDecls {
        sym := newSymbol(vd.Span.Start)
        err := e.curscope.declareSym(vd.Name,sym)
        if err != nil {
            return fmt.Errorf("bad var decl: %s %s:%v",err , vd.Span.Path, vd.Span.Start)
        }
    }
    return nil
}

func (e *emitter) emitFuncDecl(f *parse.FuncDecl) error {
	//Emit function start
	ft,err := e.funcDeclToGType(f)
	if err != nil {
	    return err
	}
	e.curFuncType = ft
	e.emit("define %s @%s() {\n","i32", f.Name)
	for _,stmt := range f.Body {
	    e.emitStatement(stmt)
	}
	e.emit("}\n")
	return nil
}

func (e *emitter) emitStatement(stmt parse.Node) {
    switch stmt := stmt.(type) {
        case *parse.Return:
            e.emitReturn(stmt)
        default:
            panic("unhandled Statement type...")
    }
}

func (e *emitter) emitReturn(r *parse.Return) {
    v := e.emitExpression(r.Expr)
    //XXX type check
    e.emiti("ret %s\n",v.llvmVal)
}

func (e *emitter) emitExpression(expr parse.Node) *exprValue {
    switch expr := expr.(type) {
        case *parse.Constant:
            v := &exprValue{}
            v.llvmVal = fmt.Sprintf("i32 %s",expr.Val)
            v.gType = NewGInt(32,true)
            return v
        default:
            panic("unhandled...")
    }
}

func (e *emitter) funcDeclToGType(f *parse.FuncDecl) (*GFunc,error) {
    ret := &GFunc{}
    for _,t := range f.ArgTypes {
        gty,err := e.parseNodeToGType(t)
        if err == nil {
            return nil,err
        }
        ret.ArgTypes = append(ret.ArgTypes,gty)
    }
    if f.RetType != nil {
        t,err := e.parseNodeToGType(f.RetType)
        if err != nil {
            return nil,err
        }
        ret.RetType = t
    }

    return ret,nil
}

func (e *emitter) parseNodeToGType(n parse.Node) (GType,error) {
    span := n.GetSpan()
    var err error
    var ret GType
    switch n := n.(type) {
        case *parse.TypeAlias:
            ret,err = e.curscope.lookupType(n.Name)
    }
    if err != nil {
        return nil,fmt.Errorf("expected type (%s) at %s:%v.",err ,span.Path,span.Start)
    }
    return ret,nil
}

<commit_msg>more emission code<commit_after>package emit

import (
	"bufio"
	"fmt"
	"strings"
	"github.com/andrewchambers/g/parse"
)

type emitter struct {
    curscope *scope
    out *bufio.Writer

    curFuncType *GFunc
}

type exprValue struct {
    llvmVal string
    lval bool
    gType GType
}

func newEmitter(out *bufio.Writer) *emitter {
    ret := &emitter{}
    ret.curscope = newScope(nil)
    ret.out = out
    return ret
}

func (e *emitter) pushScope() {
    e.curscope = newScope(e.curscope)
}

func (e *emitter) popScope() {
    e.curscope = e.curscope.parent
}

func (e *emitter) emit(s string,args ...interface{}) {
    fmt.Fprintf(e.out,s,args...)
}

func (e *emitter) emiti(s string,args ...interface{}) {
    e.emit("    "+s,args...)
}

func EmitModule(out *bufio.Writer, file *parse.File) error {
    e := newEmitter(out)
    err := e.collectGlobalSymbols(file)
    if err != nil {
        return err
    }
    for _, fd := range file.FuncDecls {
        err = e.emitFuncDecl(fd)
        if err != nil {
            return err
        }
    }
    out.Flush()
    return nil
}

func (e *emitter) collectGlobalSymbols(file *parse.File) error {
    for _, imp := range file.Imports {
        impdef := imp.Val[1:len(imp.Val) - 1]
        impdef = strings.Split(impdef,"/")[0]
        sym := newSymbol(imp.Span.Start)
        err := e.curscope.declareSym(impdef,sym)
        if err != nil {
           return fmt.Errorf("bad import: %s %s:%v",err , imp.Span.Path, imp.Span.Start)
        }
    }
    for _, fd := range file.FuncDecls {
        sym := newSymbol(fd.Span.Start)
        err := e.curscope.declareSym(fd.Name,sym)
        if err != nil {
            return fmt.Errorf("bad func decl: %s %s:%v",err , fd.Span.Path, fd.Span.Start)
        }
    }
    for _,vd := range file.VarDecls {
        sym := newSymbol(vd.Span.Start)
        err := e.curscope.declareSym(vd.Name,sym)
        if err != nil {
            return fmt.Errorf("bad var decl: %s %s:%v",err , vd.Span.Path, vd.Span.Start)
        }
    }
    return nil
}

func (e *emitter) emitFuncDecl(f *parse.FuncDecl) error {
	//Emit function start
	ft,err := e.funcDeclToGType(f)
	if err != nil {
	    return err
	}
	e.curFuncType = ft
	e.emit("define %s @%s() {\n","i32", f.Name)
	for _,stmt := range f.Body {
	    e.emitStatement(stmt)
	}
	e.emit("}\n")
	return nil
}

func (e *emitter) emitStatement(stmt parse.Node) {
    switch stmt := stmt.(type) {
        case *parse.Return:
            e.emitReturn(stmt)
        default:
            panic("unhandled Statement type...")
    }
}

func (e *emitter) emitReturn(r *parse.Return) {
    v := e.emitExpression(r.Expr)
    //XXX type check
    e.emiti("ret %s\n",v.llvmVal)
}

func (e *emitter) emitExpression(expr parse.Node) *exprValue {
    switch expr := expr.(type) {
        case *parse.Constant:
            v := &exprValue{}
            v.llvmVal = fmt.Sprintf("i32 %s",expr.Val)
            v.gType = NewGInt(32,true)
            return v
        default:
            panic("unhandled...")
    }
}

func (e *emitter) funcDeclToGType(f *parse.FuncDecl) (*GFunc,error) {
    ret := &GFunc{}
    for _,t := range f.ArgTypes {
        gty,err := e.parseNodeToGType(t)
        if err != nil {
            return nil,err
        }
        ret.ArgTypes = append(ret.ArgTypes,gty)
    }
    if f.RetType != nil {
        t,err := e.parseNodeToGType(f.RetType)
        if err != nil {
            return nil,err
        }
        ret.RetType = t
    }

    return ret,nil
}

func (e *emitter) parseNodeToGType(n parse.Node) (GType,error) {
    span := n.GetSpan()
    var err error
    var ret GType
    switch n := n.(type) {
        case *parse.TypeAlias:
            ret,err = e.curscope.lookupType(n.Name)
    }
    if err != nil {
        return nil,fmt.Errorf("expected type (%s) at %s:%v.",err ,span.Path,span.Start)
    }
    return ret,nil
}

<|endoftext|>


<commit_before>// Written in 2014 by Philipp Stephani <p.stephani2@gmail.com>.
//
// To the extent possible under law, the author has dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software.  If not, see http://creativecommons.org/publicdomain/zero/1.0/.

package main

import (
	"flag"
	"os"

	"github.com/golang/glog"

	"github.com/phst/dupremove/dup"
	"github.com/phst/dupremove/filter"
	"github.com/phst/dupremove/rdfind"
)

var dryRun = flag.Bool("n", false, "dry-run mode: don't remove any files")

func main() {
	flag.Parse()
	keep := []string{}
	dirs := []string{}
	mode := ""
	for _, arg := range flag.Args() {
		if arg == "keep" || arg == "remove" {
			mode = arg
		} else {
			if mode == "" {
				glog.Fatalf("command line arguments need to start with 'keep' or 'remove'")
			} else {
				dirs = append(dirs, arg)
				if mode == "keep" {
					keep = append(keep, arg)
				}
			}
		}
	}
	if len(dirs) == 0 {
		glog.Fatalf("no directories specified")
	}

	groups, err := rdfind.Run(dirs)
	if err != nil {
		glog.Fatalf("error running rdfind: %s", err)
	}
	glog.Infof("found %d file groups", len(groups))

	removed := 0
	for _, group := range groups {
		files := filter.RemovableFiles(group, keep)
		for _, file := range files {
			if err := remove(file); err != nil {
				glog.Errorf("could not remove file %s: %s", file, err)
			} else {
				glog.V(1).Infof("removed file %s", file)
				removed++
			}
		}
	}
	glog.Infof("removed %d files", removed)
}

func remove(f dup.FileName) error {
	if *dryRun {
		return nil
	}
	return os.Remove(string(f))
}
<commit_msg>Don't use formatting log functions when unneeded<commit_after>// Written in 2014 by Philipp Stephani <p.stephani2@gmail.com>.
//
// To the extent possible under law, the author has dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software.  If not, see http://creativecommons.org/publicdomain/zero/1.0/.

package main

import (
	"flag"
	"os"

	"github.com/golang/glog"

	"github.com/phst/dupremove/dup"
	"github.com/phst/dupremove/filter"
	"github.com/phst/dupremove/rdfind"
)

var dryRun = flag.Bool("n", false, "dry-run mode: don't remove any files")

func main() {
	flag.Parse()
	keep := []string{}
	dirs := []string{}
	mode := ""
	for _, arg := range flag.Args() {
		if arg == "keep" || arg == "remove" {
			mode = arg
		} else {
			if mode == "" {
				glog.Fatal("command line arguments need to start with 'keep' or 'remove'")
			} else {
				dirs = append(dirs, arg)
				if mode == "keep" {
					keep = append(keep, arg)
				}
			}
		}
	}
	if len(dirs) == 0 {
		glog.Fatal("no directories specified")
	}

	groups, err := rdfind.Run(dirs)
	if err != nil {
		glog.Fatalf("error running rdfind: %s", err)
	}
	glog.Infof("found %d file groups", len(groups))

	removed := 0
	for _, group := range groups {
		files := filter.RemovableFiles(group, keep)
		for _, file := range files {
			if err := remove(file); err != nil {
				glog.Errorf("could not remove file %s: %s", file, err)
			} else {
				glog.V(1).Infof("removed file %s", file)
				removed++
			}
		}
	}
	glog.Infof("removed %d files", removed)
}

func remove(f dup.FileName) error {
	if *dryRun {
		return nil
	}
	return os.Remove(string(f))
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"net/http"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type todo struct {
	ID    uint64 `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	e.GET("/", func(ctx echo.Context) error {
		return ctx.String(200, "Hello World")
	})

	e.GET("/panic", func(ctx echo.Context) error {
		panic("Panic")
	})

	e.GET("/error", func(ctx echo.Context) error {
		return echo.NewHTTPError(http.StatusInternalServerError)
	})

	e.GET("/genericError", func(ctx echo.Context) error {
		return errors.New("Some error")
	})

	e.GET("/unauthorized", func(ctx echo.Context) error {
		return echo.ErrUnauthorized
	})

	e.GET("/todos", func(ctx echo.Context) error {
		todos := []todo{
			{
				ID:    1,
				Title: "Example",
				Done:  false,
			},
		}
		ctx.Response().Header().Set("Link", "<http://www.google.com>; rel=\"next\"")
		return ctx.JSON(http.StatusOK, todos)
	})

	e.GET("/map", func(ctx echo.Context) error {
		return ctx.JSON(http.StatusOK, echo.Map{
			"Hello": "World",
			"One":   1,
		})
	})

	e.GET("/hello/:name", func(ctx echo.Context) error {
		return ctx.JSON(http.StatusOK, ctx.Param("name"))
	})

	e.Start(":9000")
}
<commit_msg>Decode from query<commit_after>package main

import (
	"errors"
	"net/http"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type todo struct {
	ID    uint64 `query:"id"    json:"id"`
	Title string `query:"title" json:"title"`
	Done  bool   `query:"done"  json:"done"`
}

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	e.GET("/", func(ctx echo.Context) error {
		return ctx.String(200, "Hello World")
	})

	e.GET("/panic", func(ctx echo.Context) error {
		panic("Panic")
	})

	e.GET("/error", func(ctx echo.Context) error {
		return echo.NewHTTPError(http.StatusInternalServerError)
	})

	e.GET("/genericError", func(ctx echo.Context) error {
		return errors.New("Some error")
	})

	e.GET("/unauthorized", func(ctx echo.Context) error {
		return echo.ErrUnauthorized
	})

	e.GET("/todos", func(ctx echo.Context) error {
		todos := []todo{
			{
				ID:    1,
				Title: "Example",
				Done:  false,
			},
		}
		ctx.Response().Header().Set("Link", "<http://www.google.com>; rel=\"next\"")
		return ctx.JSON(http.StatusOK, todos)
	})

	e.GET("/map", func(ctx echo.Context) error {
		return ctx.JSON(http.StatusOK, echo.Map{
			"Hello": "World",
			"One":   1,
		})
	})

	e.GET("/hello/:name", func(ctx echo.Context) error {
		return ctx.JSON(http.StatusOK, ctx.Param("name"))
	})

	e.GET("/query", func(ctx echo.Context) error {
		var todo todo

		if err := ctx.Bind(&todo); err != nil {
			return err
		}

		return ctx.JSON(http.StatusOK, todo)
	})

	e.Start(":9000")
}
<|endoftext|>