<commit_before>package lists

import (
	"strconv"
	"testing"
)

func TestLinkedListEmpty(t *testing.T) {
	var lst LinkedList

	if !lst.IsEmpty() {
		t.Error("list is not empty")
	}

	if lst.Size() != 0 {
		t.Errorf("list size is supposed to be 0 but is %d instead", lst.Size())
	}

	if lst.Front() != nil {
		t.Error("list.Front() != nil")
	}
}

func TestLinkedListNewList(t *testing.T) {
	var lst LinkedList

	if lst.Size() != 0 {
		t.Errorf("list size is supposed to be 0 but is %d instead", lst.Size())
	}

	lst.Append(1)
	if lst.Size() != 1 {
		t.Errorf("list size is supposed to be 1 but is %d instead", lst.Size())
	}

	lst.Append(2)
	if lst.Size() != 2 {
		t.Errorf("list size is supposed to be 2 but is %d instead", lst.Size())
	}

	if val, err := lst.Get(0); err != nil || val != 1 {
		t.Error("list[0] != 1")
	}

	if val, err := lst.Get(1); err != nil || val != 2 {
		t.Error("list[1] != 2")
	}

	if _, err := lst.Get(2); err == nil {
		t.Errorf("accessing list[2] didn't raise any error")
	}
}

func TestLinkedListClearList(t *testing.T) {
	var lst LinkedList

	lst.Append(1)
	lst.Append(2)
	lst.Append(3)
	lst.Append(4)
	lst.Append(5)
	if lst.Size() != 5 {
		t.Fatalf("list has unexpected size %d", lst.Size())
	}

	lst.Clear()
	if lst.Size() != 0 {
		t.Fatal("list is not empty after Clear()")
	}
}

func TestLinkedListIteration(t *testing.T) {
	var lst LinkedList
	var i int = 1

	for i <= 10 {
		lst.Append(i)
		i++
	}

	i = 1
	for e := lst.Front(); e != nil; e = e.Next() {
		if e.Value() != i {
			t.Errorf("expected value '%d', found: '%d'", i, e.Value())
		}
		i++
	}
}

func TestLinkedListInsertBefore(t *testing.T) {
	var lst LinkedList

	node := lst.Append(1)
	lst.InsertBefore(3, lst.InsertBefore(4, node))

	if lst.Size() != 3 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 3 {
		t.Errorf("list[0] != 3")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}

	if val, _ := lst.Get(2); val != 1 {
		t.Errorf("list[2] != 1")
	}
}

func TestLinkedListInsertAfter(t *testing.T) {
	var lst LinkedList

	node := lst.Append(1)
	lst.InsertAfter(3, lst.InsertAfter(4, node))

	if lst.Size() != 3 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 1 {
		t.Errorf("list[0] != 1")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}
	if val, _ := lst.Get(2); val != 3 {
		t.Errorf("list[2] != 3")
	}
}

func TestLinkedListRemove(t *testing.T) {
	var lst LinkedList

	node1 := lst.Append(1)
	lst.Append(2)
	node3 := lst.Append(3)
	lst.Append(4)
	node5 := lst.Append(5)

	if lst.Size() != 5 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	lst.Remove(node3)
	if lst.Size() != 4 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	lst.Remove(node1)
	lst.Remove(node5)
	if lst.Size() != 2 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 2 {
		t.Errorf("list[0] != 2")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}
}

func TestLinkedListStrings(t *testing.T) {
	lst := NewLinkedList()

	for i := 1; i <= 100; i++ {
		lst.Append("item " + strconv.Itoa(i))
	}

	if lst.Size() != 100 {
		t.Fatalf("lists contains %d items (expected: 100)", lst.Size())
	}

	i := 1
	for head := lst.Front(); head != nil; head = head.Next() {
		expected := "item " + strconv.Itoa(i)
		if head.Value() != expected {
			t.Fatalf("unexpected item in list: %s (expected: %s)", head.Value(), expected)
		}
		i++
	}
}

func TestLinkedListGeneric(t *testing.T) {
	lst := NewLinkedList()

	values := []interface{}{
		uint8(1),
		uint16(2),
		int64(30000000),
		"hello world",
		complex(17, 4),
		float64(12.2),
		lst,
	}

	for v := range values {
		lst.Append(values[v])
	}

	if lst.Size() != len(values) {
		t.Fatal("expected %d items, found: %d", len(values), lst.Size())
	}

	i := 0
	for head := lst.Front(); head != nil; head = head.Next() {
		if head.Value() != values[i] {
			t.Fatalf("expected %s but found %s", values[i], head.Value())
		}
		i++
	}
}
<commit_msg>Added some benchmarks for the linked list implementation<commit_after>package lists

import (
	"strconv"
	"testing"
)

func TestLinkedListEmpty(t *testing.T) {
	var lst LinkedList

	if !lst.IsEmpty() {
		t.Error("list is not empty")
	}

	if lst.Size() != 0 {
		t.Errorf("list size is supposed to be 0 but is %d instead", lst.Size())
	}

	if lst.Front() != nil {
		t.Error("list.Front() != nil")
	}
}

func TestLinkedListNewList(t *testing.T) {
	var lst LinkedList

	if lst.Size() != 0 {
		t.Errorf("list size is supposed to be 0 but is %d instead", lst.Size())
	}

	lst.Append(1)
	if lst.Size() != 1 {
		t.Errorf("list size is supposed to be 1 but is %d instead", lst.Size())
	}

	lst.Append(2)
	if lst.Size() != 2 {
		t.Errorf("list size is supposed to be 2 but is %d instead", lst.Size())
	}

	if val, err := lst.Get(0); err != nil || val != 1 {
		t.Error("list[0] != 1")
	}

	if val, err := lst.Get(1); err != nil || val != 2 {
		t.Error("list[1] != 2")
	}

	if _, err := lst.Get(2); err == nil {
		t.Errorf("accessing list[2] didn't raise any error")
	}
}

func TestLinkedListClearList(t *testing.T) {
	var lst LinkedList

	lst.Append(1)
	lst.Append(2)
	lst.Append(3)
	lst.Append(4)
	lst.Append(5)
	if lst.Size() != 5 {
		t.Fatalf("list has unexpected size %d", lst.Size())
	}

	lst.Clear()
	if lst.Size() != 0 {
		t.Fatal("list is not empty after Clear()")
	}
}

func TestLinkedListIteration(t *testing.T) {
	var lst LinkedList
	var i int = 1

	for i <= 10 {
		lst.Append(i)
		i++
	}

	i = 1
	for e := lst.Front(); e != nil; e = e.Next() {
		if e.Value() != i {
			t.Errorf("expected value '%d', found: '%d'", i, e.Value())
		}
		i++
	}
}

func TestLinkedListInsertBefore(t *testing.T) {
	var lst LinkedList

	node := lst.Append(1)
	lst.InsertBefore(3, lst.InsertBefore(4, node))

	if lst.Size() != 3 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 3 {
		t.Errorf("list[0] != 3")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}

	if val, _ := lst.Get(2); val != 1 {
		t.Errorf("list[2] != 1")
	}
}

func TestLinkedListInsertAfter(t *testing.T) {
	var lst LinkedList

	node := lst.Append(1)
	lst.InsertAfter(3, lst.InsertAfter(4, node))

	if lst.Size() != 3 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 1 {
		t.Errorf("list[0] != 1")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}
	if val, _ := lst.Get(2); val != 3 {
		t.Errorf("list[2] != 3")
	}
}

func TestLinkedListRemove(t *testing.T) {
	var lst LinkedList

	node1 := lst.Append(1)
	lst.Append(2)
	node3 := lst.Append(3)
	lst.Append(4)
	node5 := lst.Append(5)

	if lst.Size() != 5 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	lst.Remove(node3)
	if lst.Size() != 4 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	lst.Remove(node1)
	lst.Remove(node5)
	if lst.Size() != 2 {
		t.Fatalf("list contains unexpected number of items: %d", lst.Size())
	}

	if val, _ := lst.Get(0); val != 2 {
		t.Errorf("list[0] != 2")
	}

	if val, _ := lst.Get(1); val != 4 {
		t.Errorf("list[1] != 4")
	}
}

func TestLinkedListStrings(t *testing.T) {
	lst := NewLinkedList()

	for i := 1; i <= 100; i++ {
		lst.Append("item " + strconv.Itoa(i))
	}

	if lst.Size() != 100 {
		t.Fatalf("lists contains %d items (expected: 100)", lst.Size())
	}

	i := 1
	for head := lst.Front(); head != nil; head = head.Next() {
		expected := "item " + strconv.Itoa(i)
		if head.Value() != expected {
			t.Fatalf("unexpected item in list: %s (expected: %s)", head.Value(), expected)
		}
		i++
	}
}

func TestLinkedListGeneric(t *testing.T) {
	lst := NewLinkedList()

	values := []interface{}{
		uint8(1),
		uint16(2),
		int64(30000000),
		"hello world",
		complex(17, 4),
		float64(12.2),
		lst,
	}

	for v := range values {
		lst.Append(values[v])
	}

	if lst.Size() != len(values) {
		t.Fatal("expected %d items, found: %d", len(values), lst.Size())
	}

	i := 0
	for head := lst.Front(); head != nil; head = head.Next() {
		if head.Value() != values[i] {
			t.Fatalf("expected %s but found %s", values[i], head.Value())
		}
		i++
	}
}

func BenchmarkLinkedListAppend(b *testing.B) {
	lst := NewLinkedList()

	for i := 0; i < b.N; i++ {
		lst.Append(i)
	}
}

func BenchmarkLinkedListInsertAtBeginning(b *testing.B) {
	lst := NewLinkedList()

	for i := 0; i < b.N; i++ {
		lst.InsertBefore(i, lst.Front())
	}
}

func BenchmarkLinkedListAppendAndRemove(b *testing.B) {
	lst := NewLinkedList()

	for i := 0; i < b.N; i++ {
		lst.Append(i)
	}
	for i := 0; i < b.N; i++ {
		lst.Remove(lst.Front())
	}
}
<|endoftext|>


<commit_before>// Code generated by "go run gen_schema.go"; DO NOT EDIT

package taskname

var SCHEMA_FROM_GIT = map[string][]string{
	"Build":       {"os", "compiler", "target_arch", "configuration"},
	"Calmbench":   {"os"},
	"Canary":      {"project", "os", "compiler", "target_arch", "configuration"},
	"Housekeeper": {"frequency"},
	"Infra":       {"frequency"},
	"Perf":        {"os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration", "test_filter"},
	"Test":        {"os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration", "test_filter"},
	"Upload":      {"orig_role", "os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration"},
}

var SEPARATOR_FROM_GIT = "-"
<commit_msg>Update task_name_schema<commit_after>// Code generated by "go run gen_schema.go"; DO NOT EDIT

package taskname

var SCHEMA_FROM_GIT = map[string][]string{
	"Build":       {"os", "compiler", "target_arch", "configuration"},
	"Calmbench":   {"os", "compiler", "target_arch", "configuration"},
	"Canary":      {"project", "os", "compiler", "target_arch", "configuration"},
	"Housekeeper": {"frequency"},
	"Infra":       {"frequency"},
	"Perf":        {"os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration", "test_filter"},
	"Test":        {"os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration", "test_filter"},
	"Upload":      {"orig_role", "os", "compiler", "model", "cpu_or_gpu", "cpu_or_gpu_value", "arch", "configuration"},
}

var SEPARATOR_FROM_GIT = "-"
<|endoftext|>


<commit_before>package trace

import (
	"context"
	"errors"
	"testing"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/plugin/pkg/dnstest"
	"github.com/coredns/coredns/plugin/pkg/rcode"
	"github.com/coredns/coredns/plugin/test"
	"github.com/coredns/coredns/request"

	"github.com/miekg/dns"
	"github.com/opentracing/opentracing-go/mocktracer"
)

func TestStartup(t *testing.T) {
	m, err := traceParse(caddy.NewTestController("dns", `trace`))
	if err != nil {
		t.Errorf("Error parsing test input: %s", err)
		return
	}
	if m.Name() != "trace" {
		t.Errorf("Wrong name from GetName: %s", m.Name())
	}
	err = m.OnStartup()
	if err != nil {
		t.Errorf("Error starting tracing plugin: %s", err)
		return
	}

	if m.tagSet != tagByProvider["default"] {
		t.Errorf("TagSet by proviser hasn't been corectly initialized")
	}

	if m.Tracer() == nil {
		t.Errorf("Error, no tracer created")
	}
}

func TestTrace(t *testing.T) {
	cases := []struct {
		name     string
		rcode    int
		question *dns.Msg
		server   string
		err    error
	}{
		{
			name:     "NXDOMAIN",
			rcode:    dns.RcodeNameError,
			question: new(dns.Msg).SetQuestion("example.org.", dns.TypeA),
		},
		{
			name:     "NOERROR",
			rcode:    dns.RcodeSuccess,
			question: new(dns.Msg).SetQuestion("example.net.", dns.TypeCNAME),
		},
		{
			name:     "SERVFAIL",
			rcode:    dns.RcodeServerFailure,
			question: new(dns.Msg).SetQuestion("example.net.", dns.TypeA),
			err:      errors.New("test error"),
		},
	}
	defaultTagSet := tagByProvider["default"]
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			w := dnstest.NewRecorder(&test.ResponseWriter{})
			m := mocktracer.New()
			tr := &trace{
				Next: test.HandlerFunc(func(_ context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
					m := new(dns.Msg)
					m.SetRcode(r, tc.rcode)
					w.WriteMsg(m)
					if tc.err != nil {
						return tc.rcode, tc.err
					}
					return tc.rcode, nil
				}),
				every:  1,
				tracer: m,
				tagSet: defaultTagSet,
			}
			ctx := context.TODO()
			if _, err := tr.ServeDNS(ctx, w, tc.question); err != nil && tc.err == nil {
				t.Fatalf("Error during tr.ServeDNS(ctx, w, %v): %v", tc.question, err)
			}

			fs := m.FinishedSpans()
			// Each trace consists of two spans; the root and the Next function.
			if len(fs) != 2 {
				t.Fatalf("Unexpected span count: len(fs): want 2, got %v", len(fs))
			}

			rootSpan := fs[1]
			req := request.Request{W: w, Req: tc.question}
			if rootSpan.OperationName != defaultTopLevelSpanName {
				t.Errorf("Unexpected span name: rootSpan.Name: want %v, got %v", defaultTopLevelSpanName, rootSpan.OperationName)
			}

			if rootSpan.Tag(defaultTagSet.Name) != req.Name() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Name, req.Name(), rootSpan.Tag(defaultTagSet.Name))
			}
			if rootSpan.Tag(defaultTagSet.Type) != req.Type() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Type, req.Type(), rootSpan.Tag(defaultTagSet.Type))
			}
			if rootSpan.Tag(defaultTagSet.Proto) != req.Proto() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Proto, req.Proto(), rootSpan.Tag(defaultTagSet.Proto))
			}
			if rootSpan.Tag(defaultTagSet.Remote) != req.IP() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Remote, req.IP(), rootSpan.Tag(defaultTagSet.Remote))
			}
			if rootSpan.Tag(defaultTagSet.Rcode) != rcode.ToString(tc.rcode) {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Rcode, rcode.ToString(tc.rcode), rootSpan.Tag(defaultTagSet.Rcode))
			}
			if tc.err != nil && rootSpan.Tag("error") != true {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", "error", true, rootSpan.Tag("error"))
			}
		})
	}
}
<commit_msg>auto go fmt<commit_after>package trace

import (
	"context"
	"errors"
	"testing"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/plugin/pkg/dnstest"
	"github.com/coredns/coredns/plugin/pkg/rcode"
	"github.com/coredns/coredns/plugin/test"
	"github.com/coredns/coredns/request"

	"github.com/miekg/dns"
	"github.com/opentracing/opentracing-go/mocktracer"
)

func TestStartup(t *testing.T) {
	m, err := traceParse(caddy.NewTestController("dns", `trace`))
	if err != nil {
		t.Errorf("Error parsing test input: %s", err)
		return
	}
	if m.Name() != "trace" {
		t.Errorf("Wrong name from GetName: %s", m.Name())
	}
	err = m.OnStartup()
	if err != nil {
		t.Errorf("Error starting tracing plugin: %s", err)
		return
	}

	if m.tagSet != tagByProvider["default"] {
		t.Errorf("TagSet by proviser hasn't been corectly initialized")
	}

	if m.Tracer() == nil {
		t.Errorf("Error, no tracer created")
	}
}

func TestTrace(t *testing.T) {
	cases := []struct {
		name     string
		rcode    int
		question *dns.Msg
		server   string
		err      error
	}{
		{
			name:     "NXDOMAIN",
			rcode:    dns.RcodeNameError,
			question: new(dns.Msg).SetQuestion("example.org.", dns.TypeA),
		},
		{
			name:     "NOERROR",
			rcode:    dns.RcodeSuccess,
			question: new(dns.Msg).SetQuestion("example.net.", dns.TypeCNAME),
		},
		{
			name:     "SERVFAIL",
			rcode:    dns.RcodeServerFailure,
			question: new(dns.Msg).SetQuestion("example.net.", dns.TypeA),
			err:      errors.New("test error"),
		},
	}
	defaultTagSet := tagByProvider["default"]
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			w := dnstest.NewRecorder(&test.ResponseWriter{})
			m := mocktracer.New()
			tr := &trace{
				Next: test.HandlerFunc(func(_ context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
					m := new(dns.Msg)
					m.SetRcode(r, tc.rcode)
					w.WriteMsg(m)
					if tc.err != nil {
						return tc.rcode, tc.err
					}
					return tc.rcode, nil
				}),
				every:  1,
				tracer: m,
				tagSet: defaultTagSet,
			}
			ctx := context.TODO()
			if _, err := tr.ServeDNS(ctx, w, tc.question); err != nil && tc.err == nil {
				t.Fatalf("Error during tr.ServeDNS(ctx, w, %v): %v", tc.question, err)
			}

			fs := m.FinishedSpans()
			// Each trace consists of two spans; the root and the Next function.
			if len(fs) != 2 {
				t.Fatalf("Unexpected span count: len(fs): want 2, got %v", len(fs))
			}

			rootSpan := fs[1]
			req := request.Request{W: w, Req: tc.question}
			if rootSpan.OperationName != defaultTopLevelSpanName {
				t.Errorf("Unexpected span name: rootSpan.Name: want %v, got %v", defaultTopLevelSpanName, rootSpan.OperationName)
			}

			if rootSpan.Tag(defaultTagSet.Name) != req.Name() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Name, req.Name(), rootSpan.Tag(defaultTagSet.Name))
			}
			if rootSpan.Tag(defaultTagSet.Type) != req.Type() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Type, req.Type(), rootSpan.Tag(defaultTagSet.Type))
			}
			if rootSpan.Tag(defaultTagSet.Proto) != req.Proto() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Proto, req.Proto(), rootSpan.Tag(defaultTagSet.Proto))
			}
			if rootSpan.Tag(defaultTagSet.Remote) != req.IP() {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Remote, req.IP(), rootSpan.Tag(defaultTagSet.Remote))
			}
			if rootSpan.Tag(defaultTagSet.Rcode) != rcode.ToString(tc.rcode) {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", defaultTagSet.Rcode, rcode.ToString(tc.rcode), rootSpan.Tag(defaultTagSet.Rcode))
			}
			if tc.err != nil && rootSpan.Tag("error") != true {
				t.Errorf("Unexpected span tag: rootSpan.Tag(%v): want %v, got %v", "error", true, rootSpan.Tag("error"))
			}
		})
	}
}
<|endoftext|>


<commit_before>package librariesio

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"testing"
	"time"
)

const APIKey string = "1234"

func startNewServer() (*httptest.Server, *http.ServeMux, *url.URL) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	url, _ := url.Parse(server.URL)
	return server, mux, url
}

func checkHeader(t *testing.T, req *http.Request, header string, want string) {
	if got := req.Header.Get(header); got != want {
		t.Errorf("Header.Get(%q) returned %q, want %q", header, got, want)
	}
}

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

	if got, want := c.apiKey, APIKey; got != want {
		t.Errorf("NewClient baseURL is %v, want %v", got, want)
	}

	if got, want := c.BaseURL.String(), "https://libraries.io/api/"; got != want {
		t.Errorf("NewClient baseURL is %v, want %v", got, want)
	}

	if got, want := c.UserAgent, "go-librariesio/1"; got != want {
		t.Errorf("NewClient userAgent is %v, want %v", got, want)
	}

	if got, want := c.client.Timeout, time.Second*10; got != want {
		t.Errorf("NewClient timeout is %v, want %v", got, want)
	}
}

func TestNewRequest_badURL(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", ":", nil)

	if err == nil {
		t.Fatalf("NewRequest did not return error")
	}
	if req != nil {
		t.Fatalf("did not expect non-nil request, got %+v", req)
	}
}

func TestNewRequest_noPayload(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", "pypi/cookiecutter", nil)

	if err != nil {
		t.Fatalf("NewRequest returned error: %v", err)
	}

	if req.Body != nil {
		t.Fatalf("request contains a non-nil Body\n%v", req.Body)
	}
}

func TestNewRequest_invalidJSON(t *testing.T) {
	client := NewClient(APIKey)

	foo := make(map[interface{}]interface{})

	_, err := client.NewRequest("GET", "pypi/cookiecutter", foo)

	if err == nil {
		t.Error("Expected error to be returned")
	}
	if err, ok := err.(*json.UnsupportedTypeError); !ok {
		t.Errorf("Expected a JSON error, got %#v", err)
	}
}

func TestNewRequest_auth(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", "pypi/cookiecutter", nil)

	if err != nil {
		t.Fatalf("NewRequest returned error: %v", err)
	}

	query := req.URL.Query()
	if got, want := query.Get("api_key"), APIKey; got != want {
		t.Fatalf("did not set query param to %v, got %v", want, got)
	}
}

func TestNewRequest_headers(t *testing.T) {
	testCases := []struct {
		name    string
		body    interface{}
		headers map[string]string
	}{
		{
			name: "No Content-Type without body",
			body: nil,
			headers: map[string]string{
				"Accept":     "application/json",
				"User-Agent": "go-librariesio/" + libraryVersion,
			},
		},
		{
			name: "Content-Type with body",
			body: "hello world",
			headers: map[string]string{
				"Accept":       "application/json",
				"Content-Type": "application/json",
				"User-Agent":   "go-librariesio/" + libraryVersion,
			},
		},
	}

	client := NewClient(APIKey)

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			req, err := client.NewRequest("GET", "pypi/cookiecutter", testCase.body)
			if err != nil {
				t.Fatal("unexpected error")
			}

			for key, value := range testCase.headers {
				checkHeader(t, req, key, value)
			}
		})
	}
}

func TestCheckResponse(t *testing.T) {
	response := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusBadRequest,
		Body:       ioutil.NopCloser(strings.NewReader(`{"error":"Nope Nope Nope"}`)),
	}
	errResponse, ok := CheckResponse(response).(*ErrorResponse)

	if !ok {
		t.Errorf("Expected ErrorResponse, got %v", errResponse)
	}

	want := &ErrorResponse{
		Response: response,
		Message:  "Nope Nope Nope",
	}
	if !reflect.DeepEqual(errResponse, want) {
		t.Errorf("\nExpected %#v\nGot %#v", want, errResponse)
	}
}

func TestErrorResponse(t *testing.T) {
	client := NewClient(APIKey)
	request, _ := client.NewRequest("GET", "pypi/poyo", nil)
	response := &http.Response{
		Request:    request,
		StatusCode: http.StatusBadRequest,
	}

	err := &ErrorResponse{Response: response, Message: "nope"}
	want := `GET https://libraries.io/api/pypi/poyo?api_key=REDACTED: 400 "nope"`

	if got := err.Error(); got != want {
		t.Fatalf("\nExpected %q\nGot %q", want, got)
	}
}

func TestDo_httpClientError(t *testing.T) {
	server, _, url := startNewServer()
	client := NewClient(APIKey)
	client.BaseURL = url
	defer server.Close()

	_, err := client.Do(&http.Request{}, nil)
	if err == nil {
		t.Fatalf("Expected error to be returned")
	}
}
<commit_msg>Remove helper function for checking headers<commit_after>package librariesio

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"testing"
	"time"
)

const APIKey string = "1234"

func startNewServer() (*httptest.Server, *http.ServeMux, *url.URL) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	url, _ := url.Parse(server.URL)
	return server, mux, url
}

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

	if got, want := c.apiKey, APIKey; got != want {
		t.Errorf("NewClient baseURL is %v, want %v", got, want)
	}

	if got, want := c.BaseURL.String(), "https://libraries.io/api/"; got != want {
		t.Errorf("NewClient baseURL is %v, want %v", got, want)
	}

	if got, want := c.UserAgent, "go-librariesio/1"; got != want {
		t.Errorf("NewClient userAgent is %v, want %v", got, want)
	}

	if got, want := c.client.Timeout, time.Second*10; got != want {
		t.Errorf("NewClient timeout is %v, want %v", got, want)
	}
}

func TestNewRequest_badURL(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", ":", nil)

	if err == nil {
		t.Fatalf("NewRequest did not return error")
	}
	if req != nil {
		t.Fatalf("did not expect non-nil request, got %+v", req)
	}
}

func TestNewRequest_noPayload(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", "pypi/cookiecutter", nil)

	if err != nil {
		t.Fatalf("NewRequest returned error: %v", err)
	}

	if req.Body != nil {
		t.Fatalf("request contains a non-nil Body\n%v", req.Body)
	}
}

func TestNewRequest_invalidJSON(t *testing.T) {
	client := NewClient(APIKey)

	foo := make(map[interface{}]interface{})

	_, err := client.NewRequest("GET", "pypi/cookiecutter", foo)

	if err == nil {
		t.Error("Expected error to be returned")
	}
	if err, ok := err.(*json.UnsupportedTypeError); !ok {
		t.Errorf("Expected a JSON error, got %#v", err)
	}
}

func TestNewRequest_auth(t *testing.T) {
	client := NewClient(APIKey)
	req, err := client.NewRequest("GET", "pypi/cookiecutter", nil)

	if err != nil {
		t.Fatalf("NewRequest returned error: %v", err)
	}

	query := req.URL.Query()
	if got, want := query.Get("api_key"), APIKey; got != want {
		t.Fatalf("did not set query param to %v, got %v", want, got)
	}
}

func TestNewRequest_headers(t *testing.T) {
	testCases := []struct {
		name    string
		body    interface{}
		headers map[string]string
	}{
		{
			name: "No Content-Type without body",
			body: nil,
			headers: map[string]string{
				"Accept":     "application/json",
				"User-Agent": "go-librariesio/" + libraryVersion,
			},
		},
		{
			name: "Content-Type with body",
			body: "hello world",
			headers: map[string]string{
				"Accept":       "application/json",
				"Content-Type": "application/json",
				"User-Agent":   "go-librariesio/" + libraryVersion,
			},
		},
	}

	client := NewClient(APIKey)

	for _, testCase := range testCases {
		t.Run(testCase.name, func(t *testing.T) {
			req, err := client.NewRequest("GET", "pypi/cookiecutter", testCase.body)
			if err != nil {
				t.Fatal("unexpected error")
			}

			for header, want := range testCase.headers {
				if got := req.Header.Get(header); got != want {
					t.Errorf("Header.Get(%q) returned %q, want %q", header, got, want)
				}
			}
		})
	}
}

func TestCheckResponse(t *testing.T) {
	response := &http.Response{
		Request:    &http.Request{},
		StatusCode: http.StatusBadRequest,
		Body:       ioutil.NopCloser(strings.NewReader(`{"error":"Nope Nope Nope"}`)),
	}
	errResponse, ok := CheckResponse(response).(*ErrorResponse)

	if !ok {
		t.Errorf("Expected ErrorResponse, got %v", errResponse)
	}

	want := &ErrorResponse{
		Response: response,
		Message:  "Nope Nope Nope",
	}
	if !reflect.DeepEqual(errResponse, want) {
		t.Errorf("\nExpected %#v\nGot %#v", want, errResponse)
	}
}

func TestErrorResponse(t *testing.T) {
	client := NewClient(APIKey)
	request, _ := client.NewRequest("GET", "pypi/poyo", nil)
	response := &http.Response{
		Request:    request,
		StatusCode: http.StatusBadRequest,
	}

	err := &ErrorResponse{Response: response, Message: "nope"}
	want := `GET https://libraries.io/api/pypi/poyo?api_key=REDACTED: 400 "nope"`

	if got := err.Error(); got != want {
		t.Fatalf("\nExpected %q\nGot %q", want, got)
	}
}

func TestDo_httpClientError(t *testing.T) {
	server, _, url := startNewServer()
	client := NewClient(APIKey)
	client.BaseURL = url
	defer server.Close()

	_, err := client.Do(&http.Request{}, nil)
	if err == nil {
		t.Fatalf("Expected error to be returned")
	}
}
<|endoftext|>


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

package sparc64

import "cmd/internal/obj"

func ri(rd, imm22 int) uint32 {
	return uint32(rd&31<<25 | imm22&(1<<23-1))
}

func d22(a, disp22 int) uint32 {
	return uint32(a&1<<29 | disp22&(1<<23-1))
}

func d19(a, cc1, cc0, p, disp19 int) uint32 {
	return uint32(a&1<<29 | cc1&1<<21 | cc0&1<<20 | p&1<<19 | disp19&(1<<20-1))
}

func d30(disp30 int) uint32 {
	return uint32(disp30 & (1<<31 - 1))
}

func rrr(rd, rs1, imm_asi, rs2 int) uint32 {
	return uint32(rd&31<<25 | rs1&31<<14 | imm_asi&255<<5 | rs2&31)
}

func rrs(rd, rs1, simm13 int) uint32 {
	return uint32(rd&31<<25 | rs1&31<<14 | 1<<13 | simm13&(1<<14-1))
}

func op(op int) uint32 {
	return uint32(op << 30)
}

func op3(op, op3 int) uint32 {
	return uint32(op<<30 | op3<<19)
}

func op2(op2 int) uint32 {
	return uint32(op2 << 22)
}

func cond(cond int) uint32 {
	return uint32(cond << 25)
}

func opf(opf int) uint32 {
	return uint32(opf << 5)
}

func opcode(a int) uint32 {
	switch a {
	// Add.
	case AADD:
		return op3(2, 0)
	case AADDCC:
		return op3(2, 16)
	case AADDC:
		return op3(2, 8)
	case AADDCCC:
		return op3(2, 24)

	// AND logical operation.
	case AAND:
		return op3(2, 1)
	case AANDCC:
		return op3(2, 17)
	case AANDN:
		return op3(2, 5)
	case AANDNCC:
		return op3(2, 21)

	// Branch on integer condition codes with prediction (BPcc).
	case obj.AJMP:
		return cond(8) | op2(1)
	case ABN:
		return cond(0) | op2(1)
	case ABNE:
		return cond(9) | op2(1)
	case ABE:
		return cond(1) | op2(1)
	case ABG:
		return cond(10) | op2(1)
	case ABLE:
		return cond(2) | op2(1)
	case ABGE:
		return cond(11) | op2(1)
	case ABL:
		return cond(3) | op2(1)
	case ABGU:
		return cond(12) | op2(1)
	case ABLEU:
		return cond(4) | op2(1)
	case ABCC:
		return cond(13) | op2(1)
	case ABCS:
		return cond(5) | op2(1)
	case ABPOS:
		return cond(14) | op2(1)
	case ABNEG:
		return cond(6) | op2(1)
	case ABVC:
		return cond(15) | op2(1)
	case ABVS:
		return cond(7) | op2(1)

	// Branch on integer register with prediction (BPr).
	case ABRZ:
		return cond(1) | op2(3)
	case ABRLEZ:
		return cond(2) | op2(3)
	case ABRLZ:
		return cond(3) | op2(3)
	case ABRNZ:
		return cond(5) | op2(3)
	case ABRGZ:
		return cond(6) | op2(3)
	case ABRGEZ:
		return cond(7) | op2(3)

	// Call and link
	case obj.ACALL:
		return op(1)

	case ACASAW:
		return op3(3, 0x3C)
	case ACASA:
		return op3(3, 0x3E)

	case AFABSS:
		return op3(2, 0x34) | opf(9)
	case AFABSD:
		return op3(2, 0x34) | opf(10)

	case AFADDS:
		return op3(2, 0x34) | opf(0x41)
	case AFADDD:
		return op3(2, 0x34) | opf(0x42)

	// Branch on floating-point condition codes (FBfcc).
	case AFBA:
		return cond(8) | op2(6)
	case AFBN:
		return cond(0) | op2(6)
	case AFBU:
		return cond(7) | op2(6)
	case AFBG:
		return cond(6) | op2(6)
	case AFBUG:
		return cond(5) | op2(6)
	case AFBL:
		return cond(4) | op2(6)
	case AFBUL:
		return cond(3) | op2(6)
	case AFBLG:
		return cond(2) | op2(6)
	case AFBNE:
		return cond(1) | op2(6)
	case AFBE:
		return cond(9) | op2(6)
	case AFBUE:
		return cond(10) | op2(6)
	case AFBGE:
		return cond(11) | op2(6)
	case AFBUGE:
		return cond(12) | op2(6)
	case AFBLE:
		return cond(13) | op2(6)
	case AFBULE:
		return cond(14) | op2(6)
	case AFBO:
		return cond(15) | op2(6)

	// Floating-point compare.
	case AFCMPS:
		return op3(2, 0x35) | opf(0x51)
	case AFCMPD:
		return op3(2, 0x35) | opf(0x52)

	// Floating-point divide.
	case AFDIVS:
		return op3(2, 0x34) | opf(0x4D)
	case AFDIVD:
		return op3(2, 0x34) | opf(0x4E)

	// Convert 32-bit integer to floating point.
	case AFWTOS:
		return op3(2, 0x34) | opf(0xC4)
	case AFWTOD:
		return op3(2, 0x34) | opf(0xC8)

	case AFLUSH:
		return op3(2, 0x3B)

	// Floating-point move.
	case AFMOVS:
		return op3(2, 0x34) | opf(1)
	case AFMOVD:
		return op3(2, 0x34) | opf(2)

	// Floating-point multiply.
	case AFMULS:
		return op3(2, 0x34) | opf(0x49)
	case AFMULD:
		return op3(2, 0x34) | opf(0x4A)
	case AFSMULD:
		return op3(2, 0x34) | opf(0x69)

	// Floating-point negate.
	case AFNEGS:
		return op3(2, 0x34) | opf(5)
	case AFNEGD:
		return op3(2, 0x34) | opf(6)

	// Floating-point square root.
	case AFSQRTS:
		return op3(2, 0x34) | opf(0x29)
	case AFSQRTD:
		return op3(2, 0x34) | opf(0x2A)

	// Convert floating-point to integer.
	case AFSTOXD:
		return op3(2, 0x34) | opf(0x81)
	case AFDTOXD:
		return op3(2, 0x34) | opf(0x82)
	case AFSTOXW:
		return op3(2, 0x34) | opf(0xD1)
	case AFDTOXW:
		return op3(2, 0x34) | opf(0xD2)

	// Convert between floating-point formats.
	case AFSTOD:
		return op3(2, 0x34) | opf(0xC9)
	case AFDTOS:
		return op3(2, 0x34) | opf(0xC6)

	// Floating-point subtract.
	case AFSUBS:
		return op3(2, 0x34) | opf(0x45)
	case AFSUBD:
		return op3(2, 0x34) | opf(0x46)

	// Convert 64-bit integer to floating point.
	case AFXTOS:
		return op3(2, 0x34) | opf(0x84)
	case AFXTOD:
		return op3(2, 0x34) | opf(0x88)

	// Jump and link.
	case AJMPL:
		return op3(2, 0x38)

	// Load integer.
	case ALDSB:
		return op3(3, 9)
	case ALDSH:
		return op3(3, 10)
	case ALDSW:
		return op3(3, 8)
	case ALDUB:
		return op3(3, 1)
	case ALDUH:
		return op3(3, 2)
	case ALDUW:
		return op3(3, 0)
	case ALDD:
		return op3(3, 11)

	// Load floating-point register.
	case ALDSF:
		return op3(3, 0x20)
	case ALDDF:
		return op3(3, 0x23)

	// Memory Barrier.
	case AMEMBAR:
		return op3(2, 0x28) | 0xF<<14

	// Multiply and divide.
	case AMULD:
		return op3(2, 9)
	case ASDIVD:
		return op3(2, 0x2D)
	case AUDIVD:
		return op3(2, 0xD)

	// OR logical operation.
	case AOR:
		return op3(2, 2)
	case AORCC:
		return op3(2, 18)
	case AORN:
		return op3(2, 6)
	case AORNCC:
		return op3(2, 22)

	// Read ancillary state register.
	case ARDCCR:
		return op3(2, 0x28) | 2<<14
	case ARDTICK:
		return op3(2, 0x28) | 4<<14
	case ARDPC:
		return op3(2, 0x28) | 5<<14

	case ASETHI:
		return op2(4)

	// Shift.
	case ASLLW:
		return op3(2, 0x25)
	case ASRLW:
		return op3(2, 0x26)
	case ASRAW:
		return op3(2, 0x27)
	case ASLLD:
		return op3(2, 0x25) | 1<<12
	case ASRLD:
		return op3(2, 0x26) | 1<<12
	case ASRAD:
		return op3(2, 0x27) | 1<<12

	// Store Integer.
	case ASTB:
		return op3(3, 5)
	case ASTH:
		return op3(3, 6)
	case ASTW:
		return op3(3, 4)
	case ASTD:
		return op3(3, 14)

	// Store floating-point.
	case ASTSF:
		return op3(3, 0x24)
	case ASTDF:
		return op3(3, 0x27)

	// Subtract.
	case ASUB:
		return op3(2, 4)
	case ASUBCC:
		return op3(2, 20)
	case ASUBC:
		return op3(2, 12)
	case ASUBCCC:
		return op3(2, 28)

	// XOR logical operation.
	case AXOR:
		return op3(2, 3)
	case AXORCC:
		return op3(2, 19)
	case AXNOR:
		return op3(2, 7)
	case AXNORCC:
		return op3(2, 23)

	default:
		panic("unknown instruction: " + obj.Aconv(a))
	}
}

func rclass(r int16) int {
	switch {
	case r == RegZero:
		return ClassZero
	case REG_R1 <= r && r <= REG_R31:
		return ClassReg
	case REG_F0 <= r && r <= REG_F31:
		return ClassFloatReg
	case r == REG_BSP || r == REG_BFP:
		return ClassBiased
	}
	return ClassUnknown
}
<commit_msg>cmd/internal/obj/sparc64: order args in layout functions to match Plan 9<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package sparc64

import "cmd/internal/obj"

func ir(imm22, rd int) uint32 {
	return uint32(rd&31<<25 | imm22&(1<<23-1))
}

func d22(a, disp22 int) uint32 {
	return uint32(a&1<<29 | disp22&(1<<23-1))
}

func d19(a, cc1, cc0, p, disp19 int) uint32 {
	return uint32(a&1<<29 | cc1&1<<21 | cc0&1<<20 | p&1<<19 | disp19&(1<<20-1))
}

func d30(disp30 int) uint32 {
	return uint32(disp30 & (1<<31 - 1))
}

func rrr(rs1, imm_asi, rs2, rd int) uint32 {
	return uint32(rd&31<<25 | rs1&31<<14 | imm_asi&255<<5 | rs2&31)
}

func rsr(rs1, simm13, rd int) uint32 {
	return uint32(rd&31<<25 | rs1&31<<14 | 1<<13 | simm13&(1<<14-1))
}

func op(op int) uint32 {
	return uint32(op << 30)
}

func op3(op, op3 int) uint32 {
	return uint32(op<<30 | op3<<19)
}

func op2(op2 int) uint32 {
	return uint32(op2 << 22)
}

func cond(cond int) uint32 {
	return uint32(cond << 25)
}

func opf(opf int) uint32 {
	return uint32(opf << 5)
}

func opcode(a int) uint32 {
	switch a {
	// Add.
	case AADD:
		return op3(2, 0)
	case AADDCC:
		return op3(2, 16)
	case AADDC:
		return op3(2, 8)
	case AADDCCC:
		return op3(2, 24)

	// AND logical operation.
	case AAND:
		return op3(2, 1)
	case AANDCC:
		return op3(2, 17)
	case AANDN:
		return op3(2, 5)
	case AANDNCC:
		return op3(2, 21)

	// Branch on integer condition codes with prediction (BPcc).
	case obj.AJMP:
		return cond(8) | op2(1)
	case ABN:
		return cond(0) | op2(1)
	case ABNE:
		return cond(9) | op2(1)
	case ABE:
		return cond(1) | op2(1)
	case ABG:
		return cond(10) | op2(1)
	case ABLE:
		return cond(2) | op2(1)
	case ABGE:
		return cond(11) | op2(1)
	case ABL:
		return cond(3) | op2(1)
	case ABGU:
		return cond(12) | op2(1)
	case ABLEU:
		return cond(4) | op2(1)
	case ABCC:
		return cond(13) | op2(1)
	case ABCS:
		return cond(5) | op2(1)
	case ABPOS:
		return cond(14) | op2(1)
	case ABNEG:
		return cond(6) | op2(1)
	case ABVC:
		return cond(15) | op2(1)
	case ABVS:
		return cond(7) | op2(1)

	// Branch on integer register with prediction (BPr).
	case ABRZ:
		return cond(1) | op2(3)
	case ABRLEZ:
		return cond(2) | op2(3)
	case ABRLZ:
		return cond(3) | op2(3)
	case ABRNZ:
		return cond(5) | op2(3)
	case ABRGZ:
		return cond(6) | op2(3)
	case ABRGEZ:
		return cond(7) | op2(3)

	// Call and link
	case obj.ACALL:
		return op(1)

	case ACASAW:
		return op3(3, 0x3C)
	case ACASA:
		return op3(3, 0x3E)

	case AFABSS:
		return op3(2, 0x34) | opf(9)
	case AFABSD:
		return op3(2, 0x34) | opf(10)

	case AFADDS:
		return op3(2, 0x34) | opf(0x41)
	case AFADDD:
		return op3(2, 0x34) | opf(0x42)

	// Branch on floating-point condition codes (FBfcc).
	case AFBA:
		return cond(8) | op2(6)
	case AFBN:
		return cond(0) | op2(6)
	case AFBU:
		return cond(7) | op2(6)
	case AFBG:
		return cond(6) | op2(6)
	case AFBUG:
		return cond(5) | op2(6)
	case AFBL:
		return cond(4) | op2(6)
	case AFBUL:
		return cond(3) | op2(6)
	case AFBLG:
		return cond(2) | op2(6)
	case AFBNE:
		return cond(1) | op2(6)
	case AFBE:
		return cond(9) | op2(6)
	case AFBUE:
		return cond(10) | op2(6)
	case AFBGE:
		return cond(11) | op2(6)
	case AFBUGE:
		return cond(12) | op2(6)
	case AFBLE:
		return cond(13) | op2(6)
	case AFBULE:
		return cond(14) | op2(6)
	case AFBO:
		return cond(15) | op2(6)

	// Floating-point compare.
	case AFCMPS:
		return op3(2, 0x35) | opf(0x51)
	case AFCMPD:
		return op3(2, 0x35) | opf(0x52)

	// Floating-point divide.
	case AFDIVS:
		return op3(2, 0x34) | opf(0x4D)
	case AFDIVD:
		return op3(2, 0x34) | opf(0x4E)

	// Convert 32-bit integer to floating point.
	case AFWTOS:
		return op3(2, 0x34) | opf(0xC4)
	case AFWTOD:
		return op3(2, 0x34) | opf(0xC8)

	case AFLUSH:
		return op3(2, 0x3B)

	// Floating-point move.
	case AFMOVS:
		return op3(2, 0x34) | opf(1)
	case AFMOVD:
		return op3(2, 0x34) | opf(2)

	// Floating-point multiply.
	case AFMULS:
		return op3(2, 0x34) | opf(0x49)
	case AFMULD:
		return op3(2, 0x34) | opf(0x4A)
	case AFSMULD:
		return op3(2, 0x34) | opf(0x69)

	// Floating-point negate.
	case AFNEGS:
		return op3(2, 0x34) | opf(5)
	case AFNEGD:
		return op3(2, 0x34) | opf(6)

	// Floating-point square root.
	case AFSQRTS:
		return op3(2, 0x34) | opf(0x29)
	case AFSQRTD:
		return op3(2, 0x34) | opf(0x2A)

	// Convert floating-point to integer.
	case AFSTOXD:
		return op3(2, 0x34) | opf(0x81)
	case AFDTOXD:
		return op3(2, 0x34) | opf(0x82)
	case AFSTOXW:
		return op3(2, 0x34) | opf(0xD1)
	case AFDTOXW:
		return op3(2, 0x34) | opf(0xD2)

	// Convert between floating-point formats.
	case AFSTOD:
		return op3(2, 0x34) | opf(0xC9)
	case AFDTOS:
		return op3(2, 0x34) | opf(0xC6)

	// Floating-point subtract.
	case AFSUBS:
		return op3(2, 0x34) | opf(0x45)
	case AFSUBD:
		return op3(2, 0x34) | opf(0x46)

	// Convert 64-bit integer to floating point.
	case AFXTOS:
		return op3(2, 0x34) | opf(0x84)
	case AFXTOD:
		return op3(2, 0x34) | opf(0x88)

	// Jump and link.
	case AJMPL:
		return op3(2, 0x38)

	// Load integer.
	case ALDSB:
		return op3(3, 9)
	case ALDSH:
		return op3(3, 10)
	case ALDSW:
		return op3(3, 8)
	case ALDUB:
		return op3(3, 1)
	case ALDUH:
		return op3(3, 2)
	case ALDUW:
		return op3(3, 0)
	case ALDD:
		return op3(3, 11)

	// Load floating-point register.
	case ALDSF:
		return op3(3, 0x20)
	case ALDDF:
		return op3(3, 0x23)

	// Memory Barrier.
	case AMEMBAR:
		return op3(2, 0x28) | 0xF<<14

	// Multiply and divide.
	case AMULD:
		return op3(2, 9)
	case ASDIVD:
		return op3(2, 0x2D)
	case AUDIVD:
		return op3(2, 0xD)

	// OR logical operation.
	case AOR:
		return op3(2, 2)
	case AORCC:
		return op3(2, 18)
	case AORN:
		return op3(2, 6)
	case AORNCC:
		return op3(2, 22)

	// Read ancillary state register.
	case ARDCCR:
		return op3(2, 0x28) | 2<<14
	case ARDTICK:
		return op3(2, 0x28) | 4<<14
	case ARDPC:
		return op3(2, 0x28) | 5<<14

	case ASETHI:
		return op2(4)

	// Shift.
	case ASLLW:
		return op3(2, 0x25)
	case ASRLW:
		return op3(2, 0x26)
	case ASRAW:
		return op3(2, 0x27)
	case ASLLD:
		return op3(2, 0x25) | 1<<12
	case ASRLD:
		return op3(2, 0x26) | 1<<12
	case ASRAD:
		return op3(2, 0x27) | 1<<12

	// Store Integer.
	case ASTB:
		return op3(3, 5)
	case ASTH:
		return op3(3, 6)
	case ASTW:
		return op3(3, 4)
	case ASTD:
		return op3(3, 14)

	// Store floating-point.
	case ASTSF:
		return op3(3, 0x24)
	case ASTDF:
		return op3(3, 0x27)

	// Subtract.
	case ASUB:
		return op3(2, 4)
	case ASUBCC:
		return op3(2, 20)
	case ASUBC:
		return op3(2, 12)
	case ASUBCCC:
		return op3(2, 28)

	// XOR logical operation.
	case AXOR:
		return op3(2, 3)
	case AXORCC:
		return op3(2, 19)
	case AXNOR:
		return op3(2, 7)
	case AXNORCC:
		return op3(2, 23)

	default:
		panic("unknown instruction: " + obj.Aconv(a))
	}
}

func rclass(r int16) int {
	switch {
	case r == RegZero:
		return ClassZero
	case REG_R1 <= r && r <= REG_R31:
		return ClassReg
	case REG_F0 <= r && r <= REG_F31:
		return ClassFloatReg
	case r == REG_BSP || r == REG_BFP:
		return ClassBiased
	}
	return ClassUnknown
}
<|endoftext|>


<commit_before>package trace

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/trace"
	"net/http"
)

type traceError gin.Error

// add custom stringer method to gin error type
func (e traceError) String() string {
	return fmt.Sprintf("Error: %s\nMeta: %s", e.Err, e.Meta)
}

// Trace will gather information from the request and also add the trace methods to handlers
func Trace() gin.HandlerFunc {
	return func(c *gin.Context) {

		if gin.IsDebugging() {
			// a new trace
			tr := trace.New(c.HandlerName(), c.Request.URL.Path)

			c.Next()

			if len(c.Errors) != 0 {
				// loop through errors
				for _, err := range c.Errors {
					tr.LazyLog(traceError(*err), false)
				}
				tr.SetError()
			}

			// finish the trace
			tr.Finish()

			return
		}

		c.Next()

	}
}

// TraceController returns the default trace requests page
// example handler: r.GET("/debug/requests", trace.TraceController)
func TraceController(c *gin.Context) {

	if gin.IsDebugging() {
		// render the requests page
		trace.Render(c.Writer, c.Request, false)
	}

	c.String(http.StatusNotFound, "Not found")

	return
}
<commit_msg>add errors and gin debug flag check<commit_after>package trace

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/trace"
	"net/http"
)

type traceError gin.Error

// add custom stringer method to gin error type
func (e traceError) String() string {
	return fmt.Sprintf("Error: %s\nMeta: %s", e.Err, e.Meta)
}

// Trace will gather information from the request and also add the trace methods to handlers
func Trace() gin.HandlerFunc {
	return func(c *gin.Context) {

		if gin.IsDebugging() {
			// a new trace
			tr := trace.New(c.HandlerName(), c.Request.URL.Path)

			c.Next()

			if len(c.Errors) != 0 {
				// loop through errors
				for _, err := range c.Errors {
					tr.LazyLog(traceError(*err), false)
				}
				tr.SetError()
			}

			// finish the trace
			tr.Finish()

			return
		}

		c.Next()

	}
}

// TraceController returns the default trace requests page
// example handler: r.GET("/debug/requests", trace.TraceController)
func TraceController(c *gin.Context) {

	if gin.IsDebugging() {
		// render the requests page
		trace.Render(c.Writer, c.Request, false)
		return
	}

	c.String(http.StatusNotFound, "Not found")
	return
}
<|endoftext|>


<commit_before>package gocr

import (
	"encoding/csv"
	"encoding/gob"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"os"

	"github.com/anthonynsimon/bild/segment"
)

// Read image in path
func ReadImage(path string) image.Image {
	// Read the file
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer file.Close()

	// Decode the file to image (will decode any type of image .png, .jpg, .gif)
	src, _, err := image.Decode(file)
	if err != nil {
		panic(err)
	}

	return src
}

//Convert image to grayscale 2D array
func ImageToGraysclaeArray(src image.Image) [][]uint8 {
	// Convert the image to Grayscale
	bounds := src.Bounds()
	w, h := bounds.Max.X, bounds.Max.Y
	gray := image.NewGray(image.Rect(0, 0, w, h))
	for x := 0; x < w; x++ {
		for y := 0; y < h; y++ {
			oldColor := src.At(x, y)
			grayColor := gray.ColorModel().Convert(oldColor)
			gray.Set(x, y, grayColor)
		}
	}

	// Initialize 2D array for the gray value of the image (row first)
	imageArr := make([][]uint8, gray.Bounds().Max.X)

	for x := 0; x < gray.Bounds().Max.X; x++ {
		// Intialize the column
		imageArr[x] = make([]uint8, gray.Bounds().Max.Y)
		for y := 0; y < gray.Bounds().Max.Y; y++ {
			imageArr[x][y] = gray.GrayAt(x, y).Y
		}
	}

	// Return the 2D array
	return imageArr
}

func ImageToBinaryArray(src image.Image) [][]uint8 {
	// FIXME: still finding the best Threshold
	gray := segment.Threshold(src, 128)

	// Initialize 2D array for the gray value of the image (row first)
	imageArr := make([][]uint8, gray.Bounds().Max.X)

	for x := 0; x < gray.Bounds().Max.X; x++ {
		// Intialize the column
		imageArr[x] = make([]uint8, gray.Bounds().Max.Y)
		for y := 0; y < gray.Bounds().Max.Y; y++ {
			imageArr[x][y] = gray.GrayAt(x, y).Y / 255
		}
	}

	return imageArr
}

// Binarize the given imageArr using
// Best algorithm based on this paper https://pdfs.semanticscholar.org/6347/5461213fdaa24e418c33454c72bdbbe8f8b4.pdf is Sauvola
// Sauvola Reference: http://www.mediateam.oulu.fi/publications/pdf/24.p
// TODO: Implement Sauvola algorithm
func SauvolaBinarization(imageArr [][]uint8) [][]uint8 {

	return nil
}

func ReadCSV(path string) [][]string {
	// Read the file
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer file.Close()

	reader := csv.NewReader(file)
	var datas [][]string

	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		}

		if err != nil {
			panic(err)
		}

		datas = append(datas, record)
	}

	return datas
}

// Training method
// The train folder should include index.csv and images that inside the index.csv
func Train(sampleFolderPath string, modelPath string) {

	indexPath := sampleFolderPath + "/index.csv"
	indexData := ReadCSV(indexPath)

	// Initialize model data
	modelData := make(map[string][][]uint8)

	// Read and binarize each image to array 0 and 1
	for _, elm := range indexData {
		image := ReadImage(sampleFolderPath + elm[0])
		binaryImageArray := ImageToBinaryArray(image)

		modelData[elm[1]] = binaryImageArray
	}

	// Create the model file
	modelFile, err := os.Create(modelPath + "model.gob")
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer modelFile.Close()

	// Create encoder
	encoder := gob.NewEncoder(modelFile)
	// Write the file
	if err := encoder.Encode(modelData); err != nil {
		panic(err)
	}

}
<commit_msg>adding Model type used for saving and reading Model<commit_after>package gocr

import (
	"encoding/csv"
	"encoding/gob"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"os"

	"github.com/anthonynsimon/bild/segment"
)

type ModelImage struct {
	Label string
	Data  [][]uint8
}

type Model struct {
	Name        string
	ModelImages []ModelImage
}

// Read image in path
func ReadImage(path string) image.Image {
	// Read the file
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer file.Close()

	// Decode the file to image (will decode any type of image .png, .jpg, .gif)
	src, _, err := image.Decode(file)
	if err != nil {
		panic(err)
	}

	return src
}

//Convert image to grayscale 2D array
func ImageToGraysclaeArray(src image.Image) [][]uint8 {
	// Convert the image to Grayscale
	bounds := src.Bounds()
	w, h := bounds.Max.X, bounds.Max.Y
	gray := image.NewGray(image.Rect(0, 0, w, h))
	for x := 0; x < w; x++ {
		for y := 0; y < h; y++ {
			oldColor := src.At(x, y)
			grayColor := gray.ColorModel().Convert(oldColor)
			gray.Set(x, y, grayColor)
		}
	}

	// Initialize 2D array for the gray value of the image (row first)
	imageArr := make([][]uint8, gray.Bounds().Max.X)

	for x := 0; x < gray.Bounds().Max.X; x++ {
		// Intialize the column
		imageArr[x] = make([]uint8, gray.Bounds().Max.Y)
		for y := 0; y < gray.Bounds().Max.Y; y++ {
			imageArr[x][y] = gray.GrayAt(x, y).Y
		}
	}

	// Return the 2D array
	return imageArr
}

func ImageToBinaryArray(src image.Image) [][]uint8 {
	// FIXME: still finding the best Threshold
	gray := segment.Threshold(src, 128)

	// Initialize 2D array for the gray value of the image (row first)
	imageArr := make([][]uint8, gray.Bounds().Max.X)

	for x := 0; x < gray.Bounds().Max.X; x++ {
		// Intialize the column
		imageArr[x] = make([]uint8, gray.Bounds().Max.Y)
		for y := 0; y < gray.Bounds().Max.Y; y++ {
			imageArr[x][y] = gray.GrayAt(x, y).Y / 255
		}
	}

	return imageArr
}

// Binarize the given imageArr using
// Best algorithm based on this paper https://pdfs.semanticscholar.org/6347/5461213fdaa24e418c33454c72bdbbe8f8b4.pdf is Sauvola
// Sauvola Reference: http://www.mediateam.oulu.fi/publications/pdf/24.p
// TODO: Implement Sauvola algorithm
func SauvolaBinarization(imageArr [][]uint8) [][]uint8 {

	return nil
}

func ReadCSV(path string) [][]string {
	// Read the file
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer file.Close()

	reader := csv.NewReader(file)
	var datas [][]string

	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		}

		if err != nil {
			panic(err)
		}

		datas = append(datas, record)
	}

	return datas
}

// Training method
// The train folder should include index.csv and images that inside the index.csv
func Train(sampleFolderPath string, modelPath string) {

	indexPath := sampleFolderPath + "/index.csv"
	indexData := ReadCSV(indexPath)

	// Initialize model
	model := Model{}

	// Read and binarize each image to array 0 and 1
	for _, elm := range indexData {
		image := ReadImage(sampleFolderPath + elm[0])
		binaryImageArray := ImageToBinaryArray(image)

		model.ModelImages = append(model.ModelImages, ModelImage{
			Label: elm[1],
			Data:  binaryImageArray,
		})
	}

	// Create the model file
	modelFile, err := os.Create(modelPath + "model.gob")
	if err != nil {
		panic(err)
	}

	// Close the file later
	defer modelFile.Close()

	// Create encoder
	encoder := gob.NewEncoder(modelFile)
	// Write the file
	if err := encoder.Encode(model); err != nil {
		panic(err)
	}

}
<|endoftext|>


<commit_before>package ihex

import (
    "encoding/hex"
    "fmt"
    "strings"
)

type RecordType uint8

const (
    Data RecordType = 0x00
    EndOfFile RecordType = 0x01
)

// Represents a single IHEX record.
type Record struct {
    // The type of record (either Data or EndOfFile).
    Type RecordType

    // The address assocated with the record's data (for Data records).
    Address uint16

    // The payload of the record.
    Data []byte
}

// Interpreting bytes as the binary form of an IHEX record, decode and return a
// Record. err may be non-nil if there was a checksum mismatch.
func DecodeRecord(bytes []byte) (rec Record, err error) {
    dataLen := int(bytes[0])
    address := (uint16(bytes[1]) << 8) | uint16(bytes[2])
    recType := RecordType(bytes[3])

    checksumIndex := 4 + dataLen
    if bytes[checksumIndex] != Checksum(bytes[:checksumIndex]) {
        return rec, fmt.Errorf("checksum mismatch")
    }

    data := make([]byte, dataLen)
    copy(data, bytes[4:checksumIndex])

    return Record{
        Type: recType,
        Address: address,
        Data: data,
    }, nil
}

// Interpreting hexStr as the hexadecimal form of an IHEX record with or without
// the leading start token (colon), deocde and return a Record. err may be
// non-nil if there was a checksum mismatch or if the decoding from hexadecimal
// failed.
func DecodeRecordHex(hexStr string) (rec Record, err error) {
    bytes, err := hex.DecodeString(strings.TrimLeft(hexStr, ":"))
    if err != nil {
        return rec, err
    }
    return DecodeRecord(bytes)
}

// Encode the record to the binary form of an IHEX record.
func (rec Record) Encode() (bytes []byte) {
    bytes = make([]byte, len(rec.Data) + 5)
    bytes[0] = byte(len(rec.Data))
    bytes[1] = byte(rec.Address >> 8)
    bytes[2] = byte(rec.Address)
    bytes[3] = byte(rec.Type)
    copy(bytes[4:], rec.Data)

    checksumIndex := 4 + len(rec.Data)
    bytes[checksumIndex] = Checksum(bytes[:checksumIndex])
    return bytes
}

// Encode the record to the hexadecimal form of an IHEX record, with the leading
// start token (colon).
func (rec Record) EncodeHex() (hexStr string) {
    return hex.EncodeToString(rec.Encode())
}
<commit_msg>Fix documentation of Record.EncodeHex function not matching what function actually does<commit_after>package ihex

import (
    "encoding/hex"
    "fmt"
    "strings"
)

type RecordType uint8

const (
    Data RecordType = 0x00
    EndOfFile RecordType = 0x01
)

// Represents a single IHEX record.
type Record struct {
    // The type of record (either Data or EndOfFile).
    Type RecordType

    // The address assocated with the record's data (for Data records).
    Address uint16

    // The payload of the record.
    Data []byte
}

// Interpreting bytes as the binary form of an IHEX record, decode and return a
// Record. err may be non-nil if there was a checksum mismatch.
func DecodeRecord(bytes []byte) (rec Record, err error) {
    dataLen := int(bytes[0])
    address := (uint16(bytes[1]) << 8) | uint16(bytes[2])
    recType := RecordType(bytes[3])

    checksumIndex := 4 + dataLen
    if bytes[checksumIndex] != Checksum(bytes[:checksumIndex]) {
        return rec, fmt.Errorf("checksum mismatch")
    }

    data := make([]byte, dataLen)
    copy(data, bytes[4:checksumIndex])

    return Record{
        Type: recType,
        Address: address,
        Data: data,
    }, nil
}

// Interpreting hexStr as the hexadecimal form of an IHEX record with or without
// the leading start token (colon), deocde and return a Record. err may be
// non-nil if there was a checksum mismatch or if the decoding from hexadecimal
// failed.
func DecodeRecordHex(hexStr string) (rec Record, err error) {
    bytes, err := hex.DecodeString(strings.TrimLeft(hexStr, ":"))
    if err != nil {
        return rec, err
    }
    return DecodeRecord(bytes)
}

// Encode the record to the binary form of an IHEX record.
func (rec Record) Encode() (bytes []byte) {
    bytes = make([]byte, len(rec.Data) + 5)
    bytes[0] = byte(len(rec.Data))
    bytes[1] = byte(rec.Address >> 8)
    bytes[2] = byte(rec.Address)
    bytes[3] = byte(rec.Type)
    copy(bytes[4:], rec.Data)

    checksumIndex := 4 + len(rec.Data)
    bytes[checksumIndex] = Checksum(bytes[:checksumIndex])
    return bytes
}

// Encode the record to the hexadecimal form of an IHEX record, with the leading
// start token (colon).
func (rec Record) EncodeHex() (hexStr string) {
    return ":" + hex.EncodeToString(rec.Encode())
}
<|endoftext|>


<commit_before><commit_msg>fix error with submodule GIT_SSH<commit_after><|endoftext|>


<commit_before>package gondole

import (
	"github.com/urfave/cli"
	"gopkg.in/asn1-ber.v1"
	"net/textproto"
	"time"
)

type Gondole struct {
	Name        string
	RedirectURI string
}

type Client struct {
	BaseURL     string
	BearerToken string
}

/*

Entities:

Everything manipulated/returned by the API
*/

type Account struct {
	ID          int
	Username    string
	Acct        string
	DisplayName string
	Note        string
	URL         string
	Avatar      string
	Header      string
	Locked      bool
	Followers   int
	Followings  int
	Statuses    int
}

type Application struct {
	Name    string
	Website string
}

type Attachement struct {
	ID         int
	Type       string
	URL        string
	RemoteURL  string
	PreviewURL string
	TextURL    string
}

type Card struct {
	URL         string
	Title       string
	Description string
	Image       string
}

type Context struct {
	Ancestors   []Status
	Descendents []Status
}

type Error struct {
	Text string
}

type Instance struct {
	URI         string
	Title       string
	Description string
	Email       string
}

type Mention struct {
	ID       int
	URL      string
	Username string
	Acct     string
}

type Notification struct {
	ID        int
	Type      string
	CreatedAt time.Time
	Account   *Account
	Status    *Status
}

type Relationship struct {
	Following  bool
	FollowedBy bool
	Blocking   bool
	Muting     bool
	Requested  bool
}
type Report struct {
	ID          int
	ActionTaken string
}

type Result struct {
	Accounts []Account
	Statutes []Status
	Hashtags []Tag
}

type Status struct {
	ID                 int
	URI                string
	URL                string
	Account            *Account
	InReplyToId        int
	InReplyToAccountID int
	Reblog             *Status
	Content            string
	CreatedAT          time.Time
	Reblogs            int
	Favourites         int
	Reblogged          bool
	Favourited         bool
	Sensitive          bool
	SpoilerText        string
	Visibility         string
	MediaAttachments   []Attachement
	Mentions           []Mention
	Tags               []Tag
	App                Application
}

type Tag struct {
	Name string
	URL  string
}
<commit_msg>Cleanup imports.<commit_after>package gondole

import (
	"time"
)

type Gondole struct {
	Name        string
	RedirectURI string
}

type Client struct {
	BaseURL     string
	BearerToken string
}

/*

Entities:

Everything manipulated/returned by the API
*/

type Account struct {
	ID          int
	Username    string
	Acct        string
	DisplayName string
	Note        string
	URL         string
	Avatar      string
	Header      string
	Locked      bool
	Followers   int
	Followings  int
	Statuses    int
}

type Application struct {
	Name    string
	Website string
}

type Attachement struct {
	ID         int
	Type       string
	URL        string
	RemoteURL  string
	PreviewURL string
	TextURL    string
}

type Card struct {
	URL         string
	Title       string
	Description string
	Image       string
}

type Context struct {
	Ancestors   []Status
	Descendents []Status
}

type Error struct {
	Text string
}

type Instance struct {
	URI         string
	Title       string
	Description string
	Email       string
}

type Mention struct {
	ID       int
	URL      string
	Username string
	Acct     string
}

type Notification struct {
	ID        int
	Type      string
	CreatedAt time.Time
	Account   *Account
	Status    *Status
}

type Relationship struct {
	Following  bool
	FollowedBy bool
	Blocking   bool
	Muting     bool
	Requested  bool
}
type Report struct {
	ID          int
	ActionTaken string
}

type Result struct {
	Accounts []Account
	Statutes []Status
	Hashtags []Tag
}

type Status struct {
	ID                 int
	URI                string
	URL                string
	Account            *Account
	InReplyToId        int
	InReplyToAccountID int
	Reblog             *Status
	Content            string
	CreatedAT          time.Time
	Reblogs            int
	Favourites         int
	Reblogged          bool
	Favourited         bool
	Sensitive          bool
	SpoilerText        string
	Visibility         string
	MediaAttachments   []Attachement
	Mentions           []Mention
	Tags               []Tag
	App                Application
}

type Tag struct {
	Name string
	URL  string
}
<|endoftext|>


<commit_before>package gomarathon

// RequestOptions passed for query api
type RequestOptions struct {
	Method string
	Path   string
	Datas  interface{}
	Params *Parameters
}

// Parameters to build url query
type Parameters struct {
	Cmd         string
	Host        string
	Scale       bool
	CallbackURL string
}

// Response representation of a full marathon response
type Response struct {
	Code         int
	Apps         []*Application `json:"apps,omitempty"`
	App          *Application   `json:"app,omitempty"`
	Versions     []string       `json:",omitempty"`
	Tasks        []*Task        `json:"tasks,omitempty"`
	DeploymentId string         `json:"deployment_id,omitempty"`
}

// Application marathon application see :
// https://github.com/mesosphere/marathon/blob/master/REST.md#apps
type Application struct {
	ID              string            `json:"id"`
	Cmd             string            `json:"cmd,omitempty"`
	Constraints     [][]string        `json:"constraints,omitempty"`
	Container       *Container        `json:"container,omitempty"`
	CPUs            float32           `json:"cpus,omitempty"`
	Deployments     []*Deployment     `json:"deployments,omitempty"`
	Env             map[string]string `json:"env,omitempty"`
	Executor        string            `json:"executor,omitempty"`
	HealthChecks    []*HealthCheck    `json:"healthChecks,omitempty"`
	Instances       int               `json:"instances,omitemptys"`
	Mem             float32           `json:"mem,omitempty"`
	Tasks           []*Task           `json:"tasks,omitempty"`
	Ports           []int             `json:"ports,omitempty"`
	RequirePorts    bool              `json:"requirePorts,omitempty"`
	BackoffFactor   float32           `json:"backoffFactor,omitempty"`
	TasksRunning    int               `json:"tasksRunning,omitempty"`
	TasksStaged     int               `json:"tasksStaged,omitempty"`
	UpgradeStrategy *UpgradeStrategy  `json:"upgradeStrategy,omitempty"`
	Uris            []string          `json:"uris,omitempty"`
	Version         string            `json:"version,omitempty"`
}

// Container is docker parameters
type Container struct {
	Type    string    `json:"type,omitempty"`
	Docker  *Docker   `json:"docker,omitempty"`
	Volumes []*Volume `json:"volumes,omitempty"`
}

// Docker options
type Docker struct {
	Image        string         `json:"image,omitempty"`
	Network      string         `json:"network,omitempty"`
	PortMappings []*PortMapping `json:"portMappings,omitempty"`
}

// Volume is used for mounting a host directory as a container volume
type Volume struct {
	ContainerPath string `json:"containerPath,omitempty"`
	HostPath      string `json:"hostPath,omitempty"`
	Mode          string `json:"mode,omitempty"`
}

// Container PortMappings
type PortMapping struct {
	ContainerPort int    `json:"containerPort,omitempty"`
	HostPort      int    `json:"hostPort,omitempty"`
	ServicePort   int    `json:"servicePort,omitempty"`
	Protocol      string `json:"protocol,omitempty"`
}

// UpgradeStrategy has a minimumHealthCapacity which defines the minimum number of healty nodes
type UpgradeStrategy struct {
	MinimumHealthCapacity float32 `json:"minimumHealthCapacity,omitempty"`
}

// HealthCheck is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#healthchecks
type HealthCheck struct {
	Protocol               string `json:"protocol,omitempty"`
	Path                   string `json:"path,omitempty"`
	GracePeriodSeconds     int    `json:"gracePeriodSeconds,omitempty"`
	IntervalSeconds        int    `json:"intervalSeconds,omitempty"`
	PortIndex              int    `json:"portIndex,omitempty"`
	TimeoutSeconds         int    `json:"timeoutSeconds,omitempty"`
	MaxConsecutiveFailures int    `json:"maxConsecutiveFailures"`
}

type HealthCheckResult struct {
	Alive               bool   `json:"alive,omitempty"`
	ConsecutiveFailures int    `json:"consecutiveFailures,omitempty"`
	FirstSuccess        string `json:"firstSuccess,omitempty"`
	LastFailure         string `json:"lastFailure,omitempty"`
	LastSuccess         string `json:"lastSuccess,omitempty"`
	TaskID              string `json:"taskId,omitempty"`
}

// Task is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#tasks
type Task struct {
	AppID              string               `json:"appId"`
	Host               string               `json:"host"`
	ID                 string               `json:"id"`
	Ports              []int                `json:"ports"`
	StagedAt           string               `json:"stagedAt"`
	StartedAt          string               `json:"startedAt"`
	Version            string               `json:"version"`
	HealthCheckResults []*HealthCheckResult `json:"healthCheckResults"`
}

// Deployment is described here:
// https://mesosphere.github.io/marathon/docs/rest-api.html#get-/v2/deployments
type Deployment struct {
	AffectedApps   []string          `json:"affectedApps"`
	ID             string            `json:"id"`
	Steps          []*DeploymentStep `json:"steps"`
	CurrentActions []*DeploymentStep `json:"currentActions"`
	CurrentStep    int               `json:"currentStep"`
	TotalSteps     int               `json:"totalSteps"`
	Version        string            `json:"version"`
}

// Deployment steps
type DeploymentStep struct {
	Action string `json:"action"`
	App    string `json:"app"`
}

// EventSubscription is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#event-subscriptions
type EventSubscription struct {
	CallbackURL  string   `json:"CallbackUrl"`
	ClientIP     string   `json:"ClientIp"`
	EventType    string   `json:"eventType"`
	CallbackURLs []string `json:"CallbackUrls"`
}
<commit_msg>Add labels to the gomarathon lib<commit_after>package gomarathon

// RequestOptions passed for query api
type RequestOptions struct {
	Method string
	Path   string
	Datas  interface{}
	Params *Parameters
}

// Parameters to build url query
type Parameters struct {
	Cmd         string
	Host        string
	Scale       bool
	CallbackURL string
}

// Response representation of a full marathon response
type Response struct {
	Code         int
	Apps         []*Application `json:"apps,omitempty"`
	App          *Application   `json:"app,omitempty"`
	Versions     []string       `json:",omitempty"`
	Tasks        []*Task        `json:"tasks,omitempty"`
	DeploymentId string         `json:"deployment_id,omitempty"`
}

// Application marathon application see :
// https://github.com/mesosphere/marathon/blob/master/REST.md#apps
type Application struct {
	ID              string            `json:"id"`
	Cmd             string            `json:"cmd,omitempty"`
	Constraints     [][]string        `json:"constraints,omitempty"`
	Container       *Container        `json:"container,omitempty"`
	CPUs            float32           `json:"cpus,omitempty"`
	Deployments     []*Deployment     `json:"deployments,omitempty"`
	Env             map[string]string `json:"env,omitempty"`
	Executor        string            `json:"executor,omitempty"`
	HealthChecks    []*HealthCheck    `json:"healthChecks,omitempty"`
	Instances       int               `json:"instances,omitemptys"`
	Mem             float32           `json:"mem,omitempty"`
	Tasks           []*Task           `json:"tasks,omitempty"`
	Ports           []int             `json:"ports,omitempty"`
	RequirePorts    bool              `json:"requirePorts,omitempty"`
	BackoffFactor   float32           `json:"backoffFactor,omitempty"`
	TasksRunning    int               `json:"tasksRunning,omitempty"`
	TasksStaged     int               `json:"tasksStaged,omitempty"`
	UpgradeStrategy *UpgradeStrategy  `json:"upgradeStrategy,omitempty"`
	Uris            []string          `json:"uris,omitempty"`
	Version         string            `json:"version,omitempty"`
    Labels          map[string]string `json: "labels,omitempty"`
}

// Container is docker parameters
type Container struct {
	Type    string    `json:"type,omitempty"`
	Docker  *Docker   `json:"docker,omitempty"`
	Volumes []*Volume `json:"volumes,omitempty"`
}

// Docker options
type Docker struct {
	Image        string         `json:"image,omitempty"`
	Network      string         `json:"network,omitempty"`
	PortMappings []*PortMapping `json:"portMappings,omitempty"`
}

// Volume is used for mounting a host directory as a container volume
type Volume struct {
	ContainerPath string `json:"containerPath,omitempty"`
	HostPath      string `json:"hostPath,omitempty"`
	Mode          string `json:"mode,omitempty"`
}

// Container PortMappings
type PortMapping struct {
	ContainerPort int    `json:"containerPort,omitempty"`
	HostPort      int    `json:"hostPort,omitempty"`
	ServicePort   int    `json:"servicePort,omitempty"`
	Protocol      string `json:"protocol,omitempty"`
}

// UpgradeStrategy has a minimumHealthCapacity which defines the minimum number of healty nodes
type UpgradeStrategy struct {
	MinimumHealthCapacity float32 `json:"minimumHealthCapacity,omitempty"`
}

// HealthCheck is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#healthchecks
type HealthCheck struct {
	Protocol               string `json:"protocol,omitempty"`
	Path                   string `json:"path,omitempty"`
	GracePeriodSeconds     int    `json:"gracePeriodSeconds,omitempty"`
	IntervalSeconds        int    `json:"intervalSeconds,omitempty"`
	PortIndex              int    `json:"portIndex,omitempty"`
	TimeoutSeconds         int    `json:"timeoutSeconds,omitempty"`
	MaxConsecutiveFailures int    `json:"maxConsecutiveFailures"`
}

type HealthCheckResult struct {
	Alive               bool   `json:"alive,omitempty"`
	ConsecutiveFailures int    `json:"consecutiveFailures,omitempty"`
	FirstSuccess        string `json:"firstSuccess,omitempty"`
	LastFailure         string `json:"lastFailure,omitempty"`
	LastSuccess         string `json:"lastSuccess,omitempty"`
	TaskID              string `json:"taskId,omitempty"`
}

// Task is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#tasks
type Task struct {
	AppID              string               `json:"appId"`
	Host               string               `json:"host"`
	ID                 string               `json:"id"`
	Ports              []int                `json:"ports"`
	StagedAt           string               `json:"stagedAt"`
	StartedAt          string               `json:"startedAt"`
	Version            string               `json:"version"`
	HealthCheckResults []*HealthCheckResult `json:"healthCheckResults"`
}

// Deployment is described here:
// https://mesosphere.github.io/marathon/docs/rest-api.html#get-/v2/deployments
type Deployment struct {
	AffectedApps   []string          `json:"affectedApps"`
	ID             string            `json:"id"`
	Steps          []*DeploymentStep `json:"steps"`
	CurrentActions []*DeploymentStep `json:"currentActions"`
	CurrentStep    int               `json:"currentStep"`
	TotalSteps     int               `json:"totalSteps"`
	Version        string            `json:"version"`
}

// Deployment steps
type DeploymentStep struct {
	Action string `json:"action"`
	App    string `json:"app"`
}

// EventSubscription is described here:
// https://github.com/mesosphere/marathon/blob/master/REST.md#event-subscriptions
type EventSubscription struct {
	CallbackURL  string   `json:"CallbackUrl"`
	ClientIP     string   `json:"ClientIp"`
	EventType    string   `json:"eventType"`
	CallbackURLs []string `json:"CallbackUrls"`
}
<|endoftext|>


<commit_before>package storm

//TupleMessage - A tuple an it's processing metadata
type TupleMessage struct {

	//Id - To identifiy this tuple, for messaging guarantees
	Id string `json:"id",omitempty`

	//Stream - Id of the stream this tuple is emmited to. Blank==default stream
	Stream string `json:"stream",omitempty`

	//Task - For direct emit
	Task *int32 `json:"task",omitempty`

	//Tuple - A 'row' of data
	Tuple []interface{} `json:"tuple"`
}

//Spout Input & Output
type SpoutMessage struct {

	//TupleMessage - the tuple and it's metadata
	TupleMessage

	// Command - next, ack, fail, emit, log, sync
	Command string `json:"command"`

	//Message - for log only
	Message string `json:"message",omitempty`
}

// Transformer - Enables an implementation of a Bolt Transform
type TupleProcessor interface {
	Process(tuple *TupleMessage) (error, *TupleMessage)
}

type Spouter interface {
	Emit() *TupleMessage
	Ack(id string)
	Fail(id string)
	AssociateTasks(id string, taskIds []int)
}

type ComponentDef struct {
	ShellCommand string //to execute
	OutputFields []string
	Direct       bool
	Parallelism  int32
}

type DistributeHow string

const (
	DistributeByShuffle      = "shuffle"
	DistributeByField        = "field"
	DistributeToAll          = "all"
	DistributeDirect         = "direct"
	DistributeAny            = "none" //none means no choice, don't care
	DistributeLocalOrShuffle = "localorshuffle"
)
<commit_msg>tweak<commit_after>package storm

//TupleMessage - A tuple an it's processing metadata
type TupleMessage struct {

	//Id - To identifiy this tuple, for messaging guarantees
	Id string `json:"id",omitempty`

	//Stream - Id of the stream this tuple is emmited to. Blank==default stream
	Stream string `json:"stream",omitempty`

	//Task - For direct emit
	Task *int32 `json:"task",omitempty`

	//Tuple - A 'row' of data
	Tuple []interface{} `json:"tuple"`
}

//Spout Input & Output
type SpoutMessage struct {

	//TupleMessage - the tuple and it's metadata
	TupleMessage

	// Command - next, ack, fail, emit, log, sync
	Command string `json:"command"`

	//Message - for log only
	Message string `json:"message",omitempty`
}

// Transformer - Enables an implementation of a Bolt Transform
type TupleProcessor interface {
	Process(tuple *TupleMessage) (*TupleMessage, error)
}

type Spouter interface {
	Emit() *TupleMessage
	Ack(id string)
	Fail(id string)
	AssociateTasks(id string, taskIds []int)
}

type ComponentDef struct {
	ShellCommand string //to execute
	OutputFields []string
	Direct       bool
	Parallelism  int32
}

type DistributeHow string

const (
	DistributeByShuffle      = "shuffle"
	DistributeByField        = "field"
	DistributeToAll          = "all"
	DistributeDirect         = "direct"
	DistributeAny            = "none" //none means no choice, don't care
	DistributeLocalOrShuffle = "localorshuffle"
)
<|endoftext|>


<commit_before>// types.go

// This file contains the various types used by the API

package atlas

import (
	"log"
	"net/http"
)

// Client is the main struct holding state in an API client
type Client struct {
	config Config
	client *http.Client
	log    *log.Logger
	opts   map[string]string // Default, optional options
}

// Config is the main object when creating an API Client
type Config struct {
	endpoint     string
	APIKey       string
	DefaultProbe int
	AreaType     string
	AreaValue    string
	IsOneOff     bool
	PoolSize     int
	WantAF       string
	ProxyAuth    string
	Verbose      bool
	Tags         string
	Log          *log.Logger
}

// APIError is for errors returned by the RIPE API.
type APIError struct {
	Error struct {
		Status int    `json:"status"`
		Code   int    `json:"code"`
		Detail string `json:"detail"`
		Title  string `json:"title"`
		Errors []struct {
			Source struct {
				Pointer string
			} `json:"source"`
			Detail string
		} `json:"errors"`
	} `json:"error"`
}

// Key is holding the API key parameters
type Key struct {
	UUID      string `json:"uuid"`
	ValidFrom string `json:"valid_from"`
	ValidTo   string `json:"valid_to"`
	Enabled   bool
	IsActive  bool    `json:"is_active"`
	CreatedAt string  `json:"created_at"`
	Label     string  `json:"label"`
	Grants    []Grant `json:"grants"`
	Type      string  `json:"type"`
}

// Grant is the permission(s) associated with a key
type Grant struct {
	Permission string `json:"permission"`
	Target     struct {
		Type string `json:"type"`
		ID   string `json:"id"`
	} `json:"target"`
}

// Credits is holding credits data
type Credits struct {
	CurrentBalance            int    `json:"current_balance"`
	EstimatedDailyIncome      int    `json:"estimated_daily_income"`
	EstimatedDailyExpenditure int    `json:"estimated_daily_expenditure"`
	EstimatedDailyBalance     int    `json:"estimated_daily_balance"`
	CalculationTime           string `json:"calculation_time"`
	EstimatedRunoutSeconds    int    `json:"estimated_runout_seconds"`
	PastDayMeasurementResults int    `json:"past_day_measurement_results"`
	PastDayCreditsSpent       int    `json:"past_day_credits_spent"`
	IncomeItems               string `json:"income_items"`
	ExpenseItems              string `json:"expense_items"`
	Transactions              string `json:"transactions"`
}

// Probe is holding probe's data
type Probe struct {
	AddressV4      string `json:"address_v4"`
	AddressV6      string `json:"address_v6"`
	AsnV4          int    `json:"asn_v4"`
	AsnV6          int    `json:"asn_v6"`
	CountryCode    string `json:"country_code"`
	Description    string `json:"description"`
	FirstConnected int    `json:"first_connected"`
	Geometry       struct {
		Type        string    `json:"type"`
		Coordinates []float64 `json:"coordinates"`
	} `json:"geometry"`
	ID            int    `json:"id"`
	IsAnchor      bool   `json:"is_anchor"`
	IsPublic      bool   `json:"is_public"`
	LastConnected int    `json:"last_connected"`
	PrefixV4      string `json:"prefix_v4"`
	PrefixV6      string `json:"prefix_v6"`
	Status        struct {
		Since string `json:"since"`
		ID    int    `json:"id"`
		Name  string `json:"name"`
	} `json:"status"`
	StatusSince int `json:"status_since"`
	Tags        []struct {
		Name string `json:"name"`
		Slug string `json:"slug"`
	} `json:"tags"`
	Type string `json:"type"`
}

// Measurement is what we are working with
type Measurement struct {
	Af                    int                    `json:"af"`
	CreationTime          int                    `json:"creation_time"`
	Description           string                 `json:"description"`
	DestinationOptionSize interface{}            `json:"destination_option_size"`
	DontFragment          interface{}            `json:"dont_fragment"`
	DuplicateTimeout      interface{}            `json:"duplicate_timeout"`
	FirstHop              int                    `json:"first_hop"`
	Group                 string                 `json:"group"`
	GroupID               int                    `json:"group_id"`
	HopByHopOptionSize    interface{}            `json:"hop_by_hop_option_size"`
	ID                    int                    `json:"id"`
	InWifiGroup           bool                   `json:"in_wifi_group"`
	Interval              int                    `json:"interval"`
	IsAllScheduled        bool                   `json:"is_all_scheduled"`
	IsOneoff              bool                   `json:"is_oneoff"`
	IsPublic              bool                   `json:"is_public"`
	MaxHops               int                    `json:"max_hops"`
	PacketInterval        interface{}            `json:"packet_interval"`
	Packets               int                    `json:"packets"`
	Paris                 int                    `json:"paris"`
	ParticipantCount      int                    `json:"participant_count"`
	ParticipationRequests []ParticipationRequest `json:"participation_requests"`
	Port                  interface{}            `json:"port"`
	ProbesRequested       int                    `json:"probes_requested"`
	ProbesScheduled       int                    `json:"probes_scheduled"`
	Protocol              string                 `json:"protocol"`
	ResolveOnProbe        bool                   `json:"resolve_on_probe"`
	ResolvedIPs           []string               `json:"resolved_ips"`
	ResponseTimeout       int                    `json:"response_timeout"`
	Result                string                 `json:"result"`
	Size                  int                    `json:"size"`
	Spread                interface{}            `json:"spread"`
	StartTime             int                    `json:"start_time"`
	Status                struct {
		ID   int    `json:"id"`
		Name string `json:"name"`
	} `json:"status"`
	StopTime  int    `json:"stop_time"`
	Target    string `json:"target"`
	TargetASN int    `json:"target_asn"`
	TargetIP  string `json:"target_ip"`
	Type      string `json:"type"`
}

// ParticipationRequest allow you to add or remove probes from a measurement that
// was already created
type ParticipationRequest struct {
	Action        string `json:"action"`
	CreatedAt     int    `json:"created_at,omitempty"`
	ID            int    `json:"id,omitempty"`
	Self          string `json:"self,omitempty"`
	Measurement   string `json:"measurement,omitempty"`
	MeasurementID int    `json:"measurement_id,omitempty"`
	Requested     int    `json:"requested,omitempty"`
	Type          string `json:"type,omitempty"`
	Value         string `json:"value,omitempty"`
	Logs          string `json:"logs,omitempty"`
}

var (
	// ProbeTypes should be obvious
	ProbeTypes = []string{"area", "country", "prefix", "asn", "probes", "msm"}
	// AreaTypes should also be obvious
	AreaTypes = []string{"WW", "West", "North-Central", "South-Central", "North-East", "South-East"}
)

// MeasurementRequest contains the different measurement to create/view
type MeasurementRequest struct {
	// see below for definition
	Definitions []Definition `json:"definitions"`

	// requested set of probes
	Probes []ProbeSet `json:"probes"`
	//
	BillTo       int  `json:"bill_to,omitempty"`
	IsOneoff     bool `json:"is_oneoff,omitempty"`
	SkipDNSCheck bool `json:"skip_dns_check,omitempty"`
	Times        int  `json:"times,omitempty"`
	StartTime    int  `json:"start_time,omitempty"`
	StopTime     int  `json:"stop_time,omitempty"`
}

// ProbeSet is a set of probes obviously
type ProbeSet struct {
	Requested   int    `json:"requested"` // number of probes
	Type        string `json:"type"`      // area, country, prefix, asn, probes, msm
	Value       string `json:"value"`     // can be numeric or string
	TagsInclude string `json:"tags_include,omitempty"`
	TagsExclude string `json:"tags_exclude,omitempty"`
}

// Definition is used to create measurements
type Definition struct {
	// Required fields
	Description string `json:"description"`
	Type        string `json:"type"`
	AF          int    `json:"af"`

	// Required for all but "dns"
	Target string `json:"target,omitempty"`

	GroupID        int      `json:"group_id,omitempty"`
	Group          string   `json:"group,omitempty"`
	InWifiGroup    bool     `json:"in_wifi_group,omitempty"`
	Spread         int      `json:"spread,omitempty"`
	Packets        int      `json:"packets,omitempty"`
	PacketInterval int      `json:"packet_interval,omitempty"`
	Tags           []string `json:"tags"`

	// Common parameters
	ExtraWait      int  `json:"extra_wait,omitempty"`
	IsOneoff       bool `json:"is_oneoff,omitempty"`
	IsPublic       bool `json:"is_public,omitempty"`
	ResolveOnProbe bool `json:"resolve_on_probe,omitempty"`

	// Default depends on type
	Interval int `json:"interval,omitempty"`

	// dns & traceroute parameters
	Protocol string `json:"protocol,omitempty"`

	// dns parameters
	QueryClass       string `json:"query_class,omitempty"`
	QueryType        string `json:"query_type,omitempty"`
	QueryArgument    string `json:"query_argument,omitempty"`
	Retry            int    `json:"retry,omitempty"`
	SetCDBit         bool   `json:"set_cd_bit,omitempty"`
	SetDOBit         bool   `json:"set_do_bit,omitempty"`
	SetNSIDBit       bool   `json:"set_nsid_bit,omitempty"`
	SetRDBit         bool   `json:"set_rd_bit,omitempty"`
	UDPPayloadSize   int    `json:"udp_payload_size,omitempty"`
	UseProbeResolver bool   `json:"use_probe_resolver"`

	// ping parameters
	//   none (see target)

	// traceroute parameters
	DestinationOptionSize int  `json:"destination_option_size,omitempty"`
	DontFragment          bool `json:"dont_fragment,omitempty"`
	DuplicateTimeout      int  `json:"duplicate_timeout,omitempty"`
	FirstHop              int  `json:"first_hop,omitempty"`
	HopByHopOptionSize    int  `json:"hop_by_hop_option_size,omitempty"`
	MaxHops               int  `json:"max_hops,omitempty"`
	Paris                 int  `json:"paris,omitempty"`

	// ntp parameters
	//   none (see target)

	// http parameters
	ExtendedTiming     bool   `json:"extended_timing,omitempty"`
	HeaderBytes        int    `json:"header_bytes,omitempty"`
	Method             string `json:"method,omitempty"`
	MoreExtendedTiming bool   `json:"more_extended_timing,omitempty"`
	Path               string `json:"path,omitempty"`
	QueryOptions       string `json:"query_options,omitempty"`
	UserAgent          string `json:"user_agent,omitempty"`
	Version            string `json:"version,omitempty"`

	// sslcert parameters
	//   none (see target)

	// sslcert & traceroute & http parameters
	Port int `json:"port,omitempty"`

	// ping & traceroute parameters
	Size int `json:"size,omitempty"`

	// wifi parameters
	AnonymousIdentity string `json:"anonymous_identity,omitempty"`
	Cert              string `json:"cert,omitempty"`
	EAP               string `json:"eap,omitempty"`
}
<commit_msg>Add the usual ",omitempty" tag.<commit_after>// types.go

// This file contains the various types used by the API

package atlas

import (
	"log"
	"net/http"
)

// Client is the main struct holding state in an API client
type Client struct {
	config Config
	client *http.Client
	log    *log.Logger
	opts   map[string]string // Default, optional options
}

// Config is the main object when creating an API Client
type Config struct {
	endpoint     string
	APIKey       string
	DefaultProbe int
	AreaType     string
	AreaValue    string
	IsOneOff     bool
	PoolSize     int
	WantAF       string
	ProxyAuth    string
	Verbose      bool
	Tags         string
	Log          *log.Logger
}

// APIError is for errors returned by the RIPE API.
type APIError struct {
	Error struct {
		Status int    `json:"status"`
		Code   int    `json:"code"`
		Detail string `json:"detail"`
		Title  string `json:"title"`
		Errors []struct {
			Source struct {
				Pointer string
			} `json:"source"`
			Detail string
		} `json:"errors"`
	} `json:"error"`
}

// Key is holding the API key parameters
type Key struct {
	UUID      string `json:"uuid"`
	ValidFrom string `json:"valid_from"`
	ValidTo   string `json:"valid_to"`
	Enabled   bool
	IsActive  bool    `json:"is_active"`
	CreatedAt string  `json:"created_at"`
	Label     string  `json:"label"`
	Grants    []Grant `json:"grants"`
	Type      string  `json:"type"`
}

// Grant is the permission(s) associated with a key
type Grant struct {
	Permission string `json:"permission"`
	Target     struct {
		Type string `json:"type"`
		ID   string `json:"id"`
	} `json:"target"`
}

// Credits is holding credits data
type Credits struct {
	CurrentBalance            int    `json:"current_balance"`
	EstimatedDailyIncome      int    `json:"estimated_daily_income"`
	EstimatedDailyExpenditure int    `json:"estimated_daily_expenditure"`
	EstimatedDailyBalance     int    `json:"estimated_daily_balance"`
	CalculationTime           string `json:"calculation_time"`
	EstimatedRunoutSeconds    int    `json:"estimated_runout_seconds"`
	PastDayMeasurementResults int    `json:"past_day_measurement_results"`
	PastDayCreditsSpent       int    `json:"past_day_credits_spent"`
	IncomeItems               string `json:"income_items"`
	ExpenseItems              string `json:"expense_items"`
	Transactions              string `json:"transactions"`
}

// Probe is holding probe's data
type Probe struct {
	AddressV4      string `json:"address_v4"`
	AddressV6      string `json:"address_v6"`
	AsnV4          int    `json:"asn_v4"`
	AsnV6          int    `json:"asn_v6"`
	CountryCode    string `json:"country_code"`
	Description    string `json:"description"`
	FirstConnected int    `json:"first_connected"`
	Geometry       struct {
		Type        string    `json:"type"`
		Coordinates []float64 `json:"coordinates"`
	} `json:"geometry"`
	ID            int    `json:"id"`
	IsAnchor      bool   `json:"is_anchor"`
	IsPublic      bool   `json:"is_public"`
	LastConnected int    `json:"last_connected"`
	PrefixV4      string `json:"prefix_v4"`
	PrefixV6      string `json:"prefix_v6"`
	Status        struct {
		Since string `json:"since"`
		ID    int    `json:"id"`
		Name  string `json:"name"`
	} `json:"status"`
	StatusSince int `json:"status_since"`
	Tags        []struct {
		Name string `json:"name"`
		Slug string `json:"slug"`
	} `json:"tags"`
	Type string `json:"type"`
}

// Measurement is what we are working with
type Measurement struct {
	Af                    int                    `json:"af"`
	CreationTime          int                    `json:"creation_time"`
	Description           string                 `json:"description"`
	DestinationOptionSize interface{}            `json:"destination_option_size"`
	DontFragment          interface{}            `json:"dont_fragment"`
	DuplicateTimeout      interface{}            `json:"duplicate_timeout"`
	FirstHop              int                    `json:"first_hop"`
	Group                 string                 `json:"group"`
	GroupID               int                    `json:"group_id"`
	HopByHopOptionSize    interface{}            `json:"hop_by_hop_option_size"`
	ID                    int                    `json:"id"`
	InWifiGroup           bool                   `json:"in_wifi_group"`
	Interval              int                    `json:"interval"`
	IsAllScheduled        bool                   `json:"is_all_scheduled"`
	IsOneoff              bool                   `json:"is_oneoff"`
	IsPublic              bool                   `json:"is_public"`
	MaxHops               int                    `json:"max_hops"`
	PacketInterval        interface{}            `json:"packet_interval"`
	Packets               int                    `json:"packets"`
	Paris                 int                    `json:"paris"`
	ParticipantCount      int                    `json:"participant_count"`
	ParticipationRequests []ParticipationRequest `json:"participation_requests"`
	Port                  interface{}            `json:"port"`
	ProbesRequested       int                    `json:"probes_requested"`
	ProbesScheduled       int                    `json:"probes_scheduled"`
	Protocol              string                 `json:"protocol"`
	ResolveOnProbe        bool                   `json:"resolve_on_probe"`
	ResolvedIPs           []string               `json:"resolved_ips"`
	ResponseTimeout       int                    `json:"response_timeout"`
	Result                string                 `json:"result"`
	Size                  int                    `json:"size"`
	Spread                interface{}            `json:"spread"`
	StartTime             int                    `json:"start_time"`
	Status                struct {
		ID   int    `json:"id"`
		Name string `json:"name"`
	} `json:"status"`
	StopTime  int    `json:"stop_time"`
	Target    string `json:"target"`
	TargetASN int    `json:"target_asn"`
	TargetIP  string `json:"target_ip"`
	Type      string `json:"type"`
}

// ParticipationRequest allow you to add or remove probes from a measurement that
// was already created
type ParticipationRequest struct {
	Action        string `json:"action"`
	CreatedAt     int    `json:"created_at,omitempty"`
	ID            int    `json:"id,omitempty"`
	Self          string `json:"self,omitempty"`
	Measurement   string `json:"measurement,omitempty"`
	MeasurementID int    `json:"measurement_id,omitempty"`
	Requested     int    `json:"requested,omitempty"`
	Type          string `json:"type,omitempty"`
	Value         string `json:"value,omitempty"`
	Logs          string `json:"logs,omitempty"`
}

var (
	// ProbeTypes should be obvious
	ProbeTypes = []string{"area", "country", "prefix", "asn", "probes", "msm"}
	// AreaTypes should also be obvious
	AreaTypes = []string{"WW", "West", "North-Central", "South-Central", "North-East", "South-East"}
)

// MeasurementRequest contains the different measurement to create/view
type MeasurementRequest struct {
	// see below for definition
	Definitions []Definition `json:"definitions"`

	// requested set of probes
	Probes []ProbeSet `json:"probes"`
	//
	BillTo       int  `json:"bill_to,omitempty"`
	IsOneoff     bool `json:"is_oneoff,omitempty"`
	SkipDNSCheck bool `json:"skip_dns_check,omitempty"`
	Times        int  `json:"times,omitempty"`
	StartTime    int  `json:"start_time,omitempty"`
	StopTime     int  `json:"stop_time,omitempty"`
}

// ProbeSet is a set of probes obviously
type ProbeSet struct {
	Requested   int    `json:"requested"` // number of probes
	Type        string `json:"type"`      // area, country, prefix, asn, probes, msm
	Value       string `json:"value"`     // can be numeric or string
	TagsInclude string `json:"tags_include,omitempty"`
	TagsExclude string `json:"tags_exclude,omitempty"`
}

// Definition is used to create measurements
type Definition struct {
	// Required fields
	Description string `json:"description"`
	Type        string `json:"type"`
	AF          int    `json:"af"`

	// Required for all but "dns"
	Target string `json:"target,omitempty"`

	GroupID        int      `json:"group_id,omitempty"`
	Group          string   `json:"group,omitempty"`
	InWifiGroup    bool     `json:"in_wifi_group,omitempty"`
	Spread         int      `json:"spread,omitempty"`
	Packets        int      `json:"packets,omitempty"`
	PacketInterval int      `json:"packet_interval,omitempty"`
	Tags           []string `json:"tags,omitempty"`

	// Common parameters
	ExtraWait      int  `json:"extra_wait,omitempty"`
	IsOneoff       bool `json:"is_oneoff,omitempty"`
	IsPublic       bool `json:"is_public,omitempty"`
	ResolveOnProbe bool `json:"resolve_on_probe,omitempty"`

	// Default depends on type
	Interval int `json:"interval,omitempty"`

	// dns & traceroute parameters
	Protocol string `json:"protocol,omitempty"`

	// dns parameters
	QueryClass       string `json:"query_class,omitempty"`
	QueryType        string `json:"query_type,omitempty"`
	QueryArgument    string `json:"query_argument,omitempty"`
	Retry            int    `json:"retry,omitempty"`
	SetCDBit         bool   `json:"set_cd_bit,omitempty"`
	SetDOBit         bool   `json:"set_do_bit,omitempty"`
	SetNSIDBit       bool   `json:"set_nsid_bit,omitempty"`
	SetRDBit         bool   `json:"set_rd_bit,omitempty"`
	UDPPayloadSize   int    `json:"udp_payload_size,omitempty"`
	UseProbeResolver bool   `json:"use_probe_resolver"`

	// ping parameters
	//   none (see target)

	// traceroute parameters
	DestinationOptionSize int  `json:"destination_option_size,omitempty"`
	DontFragment          bool `json:"dont_fragment,omitempty"`
	DuplicateTimeout      int  `json:"duplicate_timeout,omitempty"`
	FirstHop              int  `json:"first_hop,omitempty"`
	HopByHopOptionSize    int  `json:"hop_by_hop_option_size,omitempty"`
	MaxHops               int  `json:"max_hops,omitempty"`
	Paris                 int  `json:"paris,omitempty"`

	// ntp parameters
	//   none (see target)

	// http parameters
	ExtendedTiming     bool   `json:"extended_timing,omitempty"`
	HeaderBytes        int    `json:"header_bytes,omitempty"`
	Method             string `json:"method,omitempty"`
	MoreExtendedTiming bool   `json:"more_extended_timing,omitempty"`
	Path               string `json:"path,omitempty"`
	QueryOptions       string `json:"query_options,omitempty"`
	UserAgent          string `json:"user_agent,omitempty"`
	Version            string `json:"version,omitempty"`

	// sslcert parameters
	//   none (see target)

	// sslcert & traceroute & http parameters
	Port int `json:"port,omitempty"`

	// ping & traceroute parameters
	Size int `json:"size,omitempty"`

	// wifi parameters
	AnonymousIdentity string `json:"anonymous_identity,omitempty"`
	Cert              string `json:"cert,omitempty"`
	EAP               string `json:"eap,omitempty"`
}
<|endoftext|>