<commit_before>package handlers

import (
  "encoding/json"
  "fmt"
  "html/template"
  "math/rand"
  "net/http"
)

type PageOpts struct {
  Page string
  OnSale bool
}

type Product struct {
  Id int `json:"id"`
  Name string `json:"name"`
  Description string `json:"description"`
  Price int `json:"price"`
  Weight int `json:"weight"`
}

func Index(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("Index: %s\n", r.URL.String())
  if r.URL.Path != "/" {
    Error(w, r, http.StatusNotFound)
    return
  }

  opts := PageOpts{ Page: "index" }
  if rand.Intn(5) == 0 {
    opts.OnSale = true
  }
  processLayout(w, r, opts)
}

func About(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("Products: %s\n", r.URL.String())
  opts := PageOpts{ Page: "about" }
  processLayout(w, r, opts)
}

func Products(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("Products: %s\n", r.URL.String())
  opts := PageOpts{ Page: "products" }
  processLayout(w, r, opts)
}

func ProductData(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("Product Data: %s\n", r.URL.String())
  product := Product{Id:1, Name:"asdf", Description:"cool thing", Price:1000, Weight:10}
  output, _ := json.MarshalIndent(&product, "", "\t")
  w.Header().Set("Content-Type", "application/json")
  w.Write(output)
}

func Error(w http.ResponseWriter, r *http.Request, status int) {
  fmt.Printf("Error: %s\t%d\n", r.URL.String(), status)
  w.WriteHeader(status)

  opts := PageOpts{ Page: "error" }
  processLayout(w, r, opts)
}

func processLayout(w http.ResponseWriter, r *http.Request, pageOpts PageOpts) {
  extraFile := fmt.Sprintf("templates/%s.html", pageOpts.Page)
  t, _ := template.ParseFiles("templates/layout.html", extraFile)
  t.ExecuteTemplate(w, "layout", pageOpts)
}
<commit_msg>add time to output<commit_after>package handlers

import (
  "encoding/json"
  "fmt"
  "html/template"
  "math/rand"
  "net/http"
  "time"
)

type PageOpts struct {
  Page string
  OnSale bool
}

type Product struct {
  Id int `json:"id"`
  Name string `json:"name"`
  Description string `json:"description"`
  Price int `json:"price"`
  Weight int `json:"weight"`
}

func Index(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("%s\t%s\n", time.Now().String(), r.URL.String())
  if r.URL.Path != "/" {
    Error(w, r, http.StatusNotFound)
    return
  }

  opts := PageOpts{ Page: "index" }
  if rand.Intn(5) == 0 {
    opts.OnSale = true
  }
  processLayout(w, r, opts)
}

func About(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("%s\t%s\n", time.Now().String(), r.URL.String())
  opts := PageOpts{ Page: "about" }
  processLayout(w, r, opts)
}

func Products(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("%s\t%s\n", time.Now().String(), r.URL.String())
  opts := PageOpts{ Page: "products" }
  processLayout(w, r, opts)
}

func ProductData(w http.ResponseWriter, r *http.Request) {
  fmt.Printf("%s\t%s\n", time.Now().String(), r.URL.String())
  product := Product{Id:1, Name:"asdf", Description:"cool thing", Price:1000, Weight:10}
  output, _ := json.MarshalIndent(&product, "", "\t")
  w.Header().Set("Content-Type", "application/json")
  w.Write(output)
}

func Error(w http.ResponseWriter, r *http.Request, status int) {
  fmt.Printf("%s\tERROR\t%s\n", time.Now().String(), r.URL.String())
  w.WriteHeader(status)

  opts := PageOpts{ Page: "error" }
  processLayout(w, r, opts)
}

func processLayout(w http.ResponseWriter, r *http.Request, pageOpts PageOpts) {
  extraFile := fmt.Sprintf("templates/%s.html", pageOpts.Page)
  t, _ := template.ParseFiles("templates/layout.html", extraFile)
  t.ExecuteTemplate(w, "layout", pageOpts)
}
<|endoftext|>


<commit_before>package gocsv

import (
	"encoding"
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"encoding/json"
)

// --------------------------------------------------------------------------
// Conversion interfaces

// TypeMarshaller is implemented by any value that has a MarshalCSV method
// This converter is used to convert the value to it string representation
type TypeMarshaller interface {
	MarshalCSV() (string, error)
}

// TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method
// This converter is used to convert a string to your value representation of that string
type TypeUnmarshaller interface {
	UnmarshalCSV(string) error
}

// NoUnmarshalFuncError is the custom error type to be raised in case there is no unmarshal function defined on type
type NoUnmarshalFuncError struct {
	msg string
}

func (e NoUnmarshalFuncError) Error() string {
	return e.msg
}

// NoMarshalFuncError is the custom error type to be raised in case there is no marshal function defined on type
type NoMarshalFuncError struct {
	ty reflect.Type
}

func (e NoMarshalFuncError) Error() string {
	return "No known conversion from " + e.ty.String() + " to string, " + e.ty.String() + " does not implement TypeMarshaller nor Stringer"
}

// --------------------------------------------------------------------------
// Conversion helpers

func toString(in interface{}) (string, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return inValue.String(), nil
	case reflect.Bool:
		b := inValue.Bool()
		if b {
			return "true", nil
		}
		return "false", nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fmt.Sprintf("%v", inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return fmt.Sprintf("%v", inValue.Uint()), nil
	case reflect.Float32:
		return strconv.FormatFloat(inValue.Float(), byte('f'), -1, 32), nil
	case reflect.Float64:
		return strconv.FormatFloat(inValue.Float(), byte('f'), -1, 64), nil
	}
	return "", fmt.Errorf("No known conversion from " + inValue.Type().String() + " to string")
}

func toBool(in interface{}) (bool, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := inValue.String()
		s = strings.TrimSpace(s)
		if strings.EqualFold(s, "yes") {
			return true, nil
		} else if strings.EqualFold(s, "no") || s == "" {
			return false, nil
		} else {
			return strconv.ParseBool(s)
		}
	case reflect.Bool:
		return inValue.Bool(), nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i := inValue.Int()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		i := inValue.Uint()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Float32, reflect.Float64:
		f := inValue.Float()
		if f != 0 {
			return true, nil
		}
		return false, nil
	}
	return false, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to bool")
}

func toInt(in interface{}) (int64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseInt(s, 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return inValue.Int(), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return int64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return int64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to int")
}

func toUint(in interface{}) (uint64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}

		// support the float input
		if strings.Contains(s, ".") {
			f, err := strconv.ParseFloat(s, 64)
			if err != nil {
				return 0, err
			}
			return uint64(f), nil
		}
		return strconv.ParseUint(s, 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return uint64(inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return inValue.Uint(), nil
	case reflect.Float32, reflect.Float64:
		return uint64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to uint")
}

func toFloat(in interface{}) (float64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseFloat(s, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return inValue.Float(), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to float")
}

func setField(field reflect.Value, value string, omitEmpty bool) error {
	if field.Kind() == reflect.Ptr {
		if omitEmpty && value == "" {
			return nil
		}
		if field.IsNil() {
			field.Set(reflect.New(field.Type().Elem()))
		}
		field = field.Elem()
	}

	switch field.Interface().(type) {
	case string:
		s, err := toString(value)
		if err != nil {
			return err
		}
		field.SetString(s)
	case bool:
		b, err := toBool(value)
		if err != nil {
			return err
		}
		field.SetBool(b)
	case int, int8, int16, int32, int64:
		i, err := toInt(value)
		if err != nil {
			return err
		}
		field.SetInt(i)
	case uint, uint8, uint16, uint32, uint64:
		ui, err := toUint(value)
		if err != nil {
			return err
		}
		field.SetUint(ui)
	case float32, float64:
		f, err := toFloat(value)
		if err != nil {
			return err
		}
		field.SetFloat(f)
	default:
		// Not a native type, check for unmarshal method
		if err := unmarshall(field, value); err != nil {
			if _, ok := err.(NoUnmarshalFuncError); !ok {
				return err
			}
			// Could not unmarshal, check for kind, e.g. renamed type from basic type
			switch field.Kind() {
			case reflect.String:
				s, err := toString(value)
				if err != nil {
					return err
				}
				field.SetString(s)
			case reflect.Bool:
				b, err := toBool(value)
				if err != nil {
					return err
				}
				field.SetBool(b)
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				i, err := toInt(value)
				if err != nil {
					return err
				}
				field.SetInt(i)
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				ui, err := toUint(value)
				if err != nil {
					return err
				}
				field.SetUint(ui)
			case reflect.Float32, reflect.Float64:
				f, err := toFloat(value)
				if err != nil {
					return err
				}
				field.SetFloat(f)
			case reflect.Slice, reflect.Struct:
				err := json.Unmarshal([]byte(value), field.Addr().Interface())
				if err != nil {
					return err
				}
			default:
				return err
			}
		} else {
			return nil
		}
	}
	return nil
}

func getFieldAsString(field reflect.Value) (str string, err error) {
	switch field.Kind() {
	case reflect.Interface:
	case reflect.Ptr:
		if field.IsNil() {
			return "", nil
		}
		return getFieldAsString(field.Elem())
	default:
		// Check if field is go native type
		switch field.Interface().(type) {
		case string:
			return field.String(), nil
		case bool:
			str, err = toString(field.Bool())
			if err != nil {
				return str, err
			}
		case int, int8, int16, int32, int64:
			str, err = toString(field.Int())
			if err != nil {
				return str, err
			}
		case uint, uint8, uint16, uint32, uint64:
			str, err = toString(field.Uint())
			if err != nil {
				return str, err
			}
		case float32:
			str, err = toString(float32(field.Float()))
			if err != nil {
				return str, err
			}
		case float64:
			str, err = toString(field.Float())
			if err != nil {
				return str, err
			}
		default:
			// Not a native type, check for marshal method
			str, err = marshall(field)
			if err != nil {
				if _, ok := err.(NoMarshalFuncError); !ok {
					return str, err
				}
				// If not marshal method, is field compatible with/renamed from native type
				switch field.Kind() {
				case reflect.String:
					return field.String(), nil
				case reflect.Bool:
					str, err = toString(field.Bool())
					if err != nil {
						return str, err
					}
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					str, err = toString(field.Int())
					if err != nil {
						return str, err
					}
				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
					str, err = toString(field.Uint())
					if err != nil {
						return str, err
					}
				case reflect.Float32:
					str, err = toString(float32(field.Float()))
					if err != nil {
						return str, err
					}
				case reflect.Float64:
					str, err = toString(field.Float())
					if err != nil {
						return str, err
					}
				}
			} else {
				return str, nil
			}
		}
	}
	return str, nil
}

// --------------------------------------------------------------------------
// Un/serializations helpers

func canMarshal(t reflect.Type) bool {
	// unless it implements marshalText or marshalCSV. Structs that implement this
	// should result in one value and not have their fields exposed
	_, canMarshalText := t.MethodByName("MarshalText")
	_, canMarshalCSV := t.MethodByName("MarshalCSV")
	return canMarshalCSV || canMarshalText
}

func unmarshall(field reflect.Value, value string) error {
	dupField := field
	unMarshallIt := func(finalField reflect.Value) error {
		if finalField.CanInterface() {
			fieldIface := finalField.Interface()

			fieldTypeUnmarshaller, ok := fieldIface.(TypeUnmarshaller)
			if ok {
				return fieldTypeUnmarshaller.UnmarshalCSV(value)
			}

			// Otherwise try to use TextUnmarshaler
			fieldTextUnmarshaler, ok := fieldIface.(encoding.TextUnmarshaler)
			if ok {
				return fieldTextUnmarshaler.UnmarshalText([]byte(value))
			}
		}

		return NoUnmarshalFuncError{"No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implement TypeUnmarshaller"}
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			dupField = reflect.New(field.Type().Elem())
			field.Set(dupField)
			return unMarshallIt(dupField)
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return unMarshallIt(dupField.Addr())
	}
	return NoUnmarshalFuncError{"No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implement TypeUnmarshaller"}
}

func marshall(field reflect.Value) (value string, err error) {
	dupField := field
	marshallIt := func(finalField reflect.Value) (string, error) {
		if finalField.CanInterface() {
			fieldIface := finalField.Interface()

			// Use TypeMarshaller when possible
			fieldTypeMarhaller, ok := fieldIface.(TypeMarshaller)
			if ok {
				return fieldTypeMarhaller.MarshalCSV()
			}

			// Otherwise try to use TextMarshaller
			fieldTextMarshaler, ok := fieldIface.(encoding.TextMarshaler)
			if ok {
				text, err := fieldTextMarshaler.MarshalText()
				return string(text), err
			}

			// Otherwise try to use Stringer
			fieldStringer, ok := fieldIface.(fmt.Stringer)
			if ok {
				return fieldStringer.String(), nil
			}
		}

		return value, NoMarshalFuncError{field.Type()}
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			return value, nil
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		dupField = dupField.Addr()
	}
	return marshallIt(dupField)
}
<commit_msg>Fix switch statement fall-through bug.<commit_after>package gocsv

import (
	"encoding"
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"encoding/json"
)

// --------------------------------------------------------------------------
// Conversion interfaces

// TypeMarshaller is implemented by any value that has a MarshalCSV method
// This converter is used to convert the value to it string representation
type TypeMarshaller interface {
	MarshalCSV() (string, error)
}

// TypeUnmarshaller is implemented by any value that has an UnmarshalCSV method
// This converter is used to convert a string to your value representation of that string
type TypeUnmarshaller interface {
	UnmarshalCSV(string) error
}

// NoUnmarshalFuncError is the custom error type to be raised in case there is no unmarshal function defined on type
type NoUnmarshalFuncError struct {
	msg string
}

func (e NoUnmarshalFuncError) Error() string {
	return e.msg
}

// NoMarshalFuncError is the custom error type to be raised in case there is no marshal function defined on type
type NoMarshalFuncError struct {
	ty reflect.Type
}

func (e NoMarshalFuncError) Error() string {
	return "No known conversion from " + e.ty.String() + " to string, " + e.ty.String() + " does not implement TypeMarshaller nor Stringer"
}

// --------------------------------------------------------------------------
// Conversion helpers

func toString(in interface{}) (string, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		return inValue.String(), nil
	case reflect.Bool:
		b := inValue.Bool()
		if b {
			return "true", nil
		}
		return "false", nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fmt.Sprintf("%v", inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return fmt.Sprintf("%v", inValue.Uint()), nil
	case reflect.Float32:
		return strconv.FormatFloat(inValue.Float(), byte('f'), -1, 32), nil
	case reflect.Float64:
		return strconv.FormatFloat(inValue.Float(), byte('f'), -1, 64), nil
	}
	return "", fmt.Errorf("No known conversion from " + inValue.Type().String() + " to string")
}

func toBool(in interface{}) (bool, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := inValue.String()
		s = strings.TrimSpace(s)
		if strings.EqualFold(s, "yes") {
			return true, nil
		} else if strings.EqualFold(s, "no") || s == "" {
			return false, nil
		} else {
			return strconv.ParseBool(s)
		}
	case reflect.Bool:
		return inValue.Bool(), nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i := inValue.Int()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		i := inValue.Uint()
		if i != 0 {
			return true, nil
		}
		return false, nil
	case reflect.Float32, reflect.Float64:
		f := inValue.Float()
		if f != 0 {
			return true, nil
		}
		return false, nil
	}
	return false, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to bool")
}

func toInt(in interface{}) (int64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseInt(s, 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return inValue.Int(), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return int64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return int64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to int")
}

func toUint(in interface{}) (uint64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}

		// support the float input
		if strings.Contains(s, ".") {
			f, err := strconv.ParseFloat(s, 64)
			if err != nil {
				return 0, err
			}
			return uint64(f), nil
		}
		return strconv.ParseUint(s, 0, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return uint64(inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return inValue.Uint(), nil
	case reflect.Float32, reflect.Float64:
		return uint64(inValue.Float()), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to uint")
}

func toFloat(in interface{}) (float64, error) {
	inValue := reflect.ValueOf(in)

	switch inValue.Kind() {
	case reflect.String:
		s := strings.TrimSpace(inValue.String())
		if s == "" {
			return 0, nil
		}
		return strconv.ParseFloat(s, 64)
	case reflect.Bool:
		if inValue.Bool() {
			return 1, nil
		}
		return 0, nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return float64(inValue.Int()), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return float64(inValue.Uint()), nil
	case reflect.Float32, reflect.Float64:
		return inValue.Float(), nil
	}
	return 0, fmt.Errorf("No known conversion from " + inValue.Type().String() + " to float")
}

func setField(field reflect.Value, value string, omitEmpty bool) error {
	if field.Kind() == reflect.Ptr {
		if omitEmpty && value == "" {
			return nil
		}
		if field.IsNil() {
			field.Set(reflect.New(field.Type().Elem()))
		}
		field = field.Elem()
	}

	switch field.Interface().(type) {
	case string:
		s, err := toString(value)
		if err != nil {
			return err
		}
		field.SetString(s)
	case bool:
		b, err := toBool(value)
		if err != nil {
			return err
		}
		field.SetBool(b)
	case int, int8, int16, int32, int64:
		i, err := toInt(value)
		if err != nil {
			return err
		}
		field.SetInt(i)
	case uint, uint8, uint16, uint32, uint64:
		ui, err := toUint(value)
		if err != nil {
			return err
		}
		field.SetUint(ui)
	case float32, float64:
		f, err := toFloat(value)
		if err != nil {
			return err
		}
		field.SetFloat(f)
	default:
		// Not a native type, check for unmarshal method
		if err := unmarshall(field, value); err != nil {
			if _, ok := err.(NoUnmarshalFuncError); !ok {
				return err
			}
			// Could not unmarshal, check for kind, e.g. renamed type from basic type
			switch field.Kind() {
			case reflect.String:
				s, err := toString(value)
				if err != nil {
					return err
				}
				field.SetString(s)
			case reflect.Bool:
				b, err := toBool(value)
				if err != nil {
					return err
				}
				field.SetBool(b)
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				i, err := toInt(value)
				if err != nil {
					return err
				}
				field.SetInt(i)
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
				ui, err := toUint(value)
				if err != nil {
					return err
				}
				field.SetUint(ui)
			case reflect.Float32, reflect.Float64:
				f, err := toFloat(value)
				if err != nil {
					return err
				}
				field.SetFloat(f)
			case reflect.Slice, reflect.Struct:
				err := json.Unmarshal([]byte(value), field.Addr().Interface())
				if err != nil {
					return err
				}
			default:
				return err
			}
		} else {
			return nil
		}
	}
	return nil
}

func getFieldAsString(field reflect.Value) (str string, err error) {
	switch field.Kind() {
	case reflect.Interface, reflect.Ptr:
		if field.IsNil() {
			return "", nil
		}
		return getFieldAsString(field.Elem())
	default:
		// Check if field is go native type
		switch field.Interface().(type) {
		case string:
			return field.String(), nil
		case bool:
			str, err = toString(field.Bool())
			if err != nil {
				return str, err
			}
		case int, int8, int16, int32, int64:
			str, err = toString(field.Int())
			if err != nil {
				return str, err
			}
		case uint, uint8, uint16, uint32, uint64:
			str, err = toString(field.Uint())
			if err != nil {
				return str, err
			}
		case float32:
			str, err = toString(float32(field.Float()))
			if err != nil {
				return str, err
			}
		case float64:
			str, err = toString(field.Float())
			if err != nil {
				return str, err
			}
		default:
			// Not a native type, check for marshal method
			str, err = marshall(field)
			if err != nil {
				if _, ok := err.(NoMarshalFuncError); !ok {
					return str, err
				}
				// If not marshal method, is field compatible with/renamed from native type
				switch field.Kind() {
				case reflect.String:
					return field.String(), nil
				case reflect.Bool:
					str, err = toString(field.Bool())
					if err != nil {
						return str, err
					}
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					str, err = toString(field.Int())
					if err != nil {
						return str, err
					}
				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
					str, err = toString(field.Uint())
					if err != nil {
						return str, err
					}
				case reflect.Float32:
					str, err = toString(float32(field.Float()))
					if err != nil {
						return str, err
					}
				case reflect.Float64:
					str, err = toString(field.Float())
					if err != nil {
						return str, err
					}
				}
			} else {
				return str, nil
			}
		}
	}
	return str, nil
}

// --------------------------------------------------------------------------
// Un/serializations helpers

func canMarshal(t reflect.Type) bool {
	// unless it implements marshalText or marshalCSV. Structs that implement this
	// should result in one value and not have their fields exposed
	_, canMarshalText := t.MethodByName("MarshalText")
	_, canMarshalCSV := t.MethodByName("MarshalCSV")
	return canMarshalCSV || canMarshalText
}

func unmarshall(field reflect.Value, value string) error {
	dupField := field
	unMarshallIt := func(finalField reflect.Value) error {
		if finalField.CanInterface() {
			fieldIface := finalField.Interface()

			fieldTypeUnmarshaller, ok := fieldIface.(TypeUnmarshaller)
			if ok {
				return fieldTypeUnmarshaller.UnmarshalCSV(value)
			}

			// Otherwise try to use TextUnmarshaler
			fieldTextUnmarshaler, ok := fieldIface.(encoding.TextUnmarshaler)
			if ok {
				return fieldTextUnmarshaler.UnmarshalText([]byte(value))
			}
		}

		return NoUnmarshalFuncError{"No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implement TypeUnmarshaller"}
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			dupField = reflect.New(field.Type().Elem())
			field.Set(dupField)
			return unMarshallIt(dupField)
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		return unMarshallIt(dupField.Addr())
	}
	return NoUnmarshalFuncError{"No known conversion from string to " + field.Type().String() + ", " + field.Type().String() + " does not implement TypeUnmarshaller"}
}

func marshall(field reflect.Value) (value string, err error) {
	dupField := field
	marshallIt := func(finalField reflect.Value) (string, error) {
		if finalField.CanInterface() {
			fieldIface := finalField.Interface()

			// Use TypeMarshaller when possible
			fieldTypeMarhaller, ok := fieldIface.(TypeMarshaller)
			if ok {
				return fieldTypeMarhaller.MarshalCSV()
			}

			// Otherwise try to use TextMarshaller
			fieldTextMarshaler, ok := fieldIface.(encoding.TextMarshaler)
			if ok {
				text, err := fieldTextMarshaler.MarshalText()
				return string(text), err
			}

			// Otherwise try to use Stringer
			fieldStringer, ok := fieldIface.(fmt.Stringer)
			if ok {
				return fieldStringer.String(), nil
			}
		}

		return value, NoMarshalFuncError{field.Type()}
	}
	for dupField.Kind() == reflect.Interface || dupField.Kind() == reflect.Ptr {
		if dupField.IsNil() {
			return value, nil
		}
		dupField = dupField.Elem()
	}
	if dupField.CanAddr() {
		dupField = dupField.Addr()
	}
	return marshallIt(dupField)
}
<|endoftext|>


<commit_before>// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo

// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file contains custom types, currently only a timestamp wrapper.

package discordgo

import (
	"time"
)

type Timestamp string

func (t Timestamp) Parse() (time.Time, error) {
	return time.Parse("2006-01-02T15:04:05.000000-07:00", string(t))
}
<commit_msg>Comments<commit_after>// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo

// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file contains custom types, currently only a timestamp wrapper.

package discordgo

import (
	"time"
)

// A timestamp, in the format YYYY-MM-DDTHH:MM:SS.MSMSMS-TZ:TZ.
type Timestamp string

// Parse parses a timestamp string into a time.Time object.
// The only time this can fail is if you're parsing an invalid timestamp.
func (t Timestamp) Parse() (time.Time, error) {
	return time.Parse("2006-01-02T15:04:05.000000-07:00", string(t))
}
<|endoftext|>


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

package pkcs11

/*
#define CK_PTR *
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)

#include <stdlib.h>
#include "pkcs11.h"

CK_ULONG Index(CK_ULONG_PTR array, CK_ULONG i)
{
	return array[i];
}

CK_ULONG Sizeof()
{
	return sizeof(CK_ULONG);
}
*/
import "C"

import (
	"fmt"
	"time"
	"unsafe"
)

// toList converts from a C style array to a []uint.
func toList(clist C.CK_ULONG_PTR, size C.CK_ULONG) []uint {
	l := make([]uint, int(size))
	for i := 0; i < len(l); i++ {
		l[i] = uint(C.Index(clist, C.CK_ULONG(i)))
	}
	defer C.free(unsafe.Pointer(clist))
	return l
}

// cBBool converts a bool to a CK_BBOOL.
func cBBool(x bool) C.CK_BBOOL {
	if x {
		return C.CK_BBOOL(C.CK_TRUE)
	}
	return C.CK_BBOOL(C.CK_FALSE)
}

// Error represents an PKCS#11 error.
type Error uint

func (e Error) Error() string {
	return "pkcs11: " + fmt.Sprintf("pkcs11: 0x%X: %s", uint(e), strerror[uint(e)])
}

func toError(e C.CK_RV) error {
	if e == C.CKR_OK {
		return nil
	}
	return Error(e)
}

/* SessionHandle is a Cryptoki-assigned value that identifies a session. */
type SessionHandle uint

/* ObjectHandle is a token-specific identifier for an object.  */
type ObjectHandle uint

// Version represents any version information from the library.
type Version struct {
	Major byte
	Minor byte
}

func toVersion(version C.CK_VERSION) Version {
	return Version{byte(version.major), byte(version.minor)}
}

// SlotEvent holds the SlotID which for which an slot event (token insertion,
// removal, etc.) occurred.
type SlotEvent struct {
	SlotID uint
}

// Info provides information about the library and hardware used.
type Info struct {
	CryptokiVersion    Version
	ManufacturerID     string
	Flags              uint
	LibraryDescription string
	LibraryVersion     Version
}

/* SlotInfo provides information about a slot. */
type SlotInfo struct {
	SlotDescription string // 64 bytes.
	ManufacturerID  string // 32 bytes.
	Flags           uint
	HardwareVersion Version
	FirmwareVersion Version
}

/* TokenInfo provides information about a token. */
type TokenInfo struct {
	Label              string
	ManufacturerID     string
	Model              string
	SerialNumber       string
	Flags              uint
	MaxSessionCount    uint
	SessionCount       uint
	MaxRwSessionCount  uint
	RwSessionCount     uint
	MaxPinLen          uint
	MinPinLen          uint
	TotalPublicMemory  uint
	FreePublicMemory   uint
	TotalPrivateMemory uint
	FreePrivateMemory  uint
	HardwareVersion    Version
	FirmwareVersion    Version
	UTCTime            string
}

/* SesionInfo provides information about a session. */
type SessionInfo struct {
	SlotID      uint
	State       uint
	Flags       uint
	DeviceError uint
}

// Attribute holds an attribute type/value combination.
type Attribute struct {
	Type  uint
	Value []byte
}

func NewAttribute(typ uint, x interface{}) *Attribute {
	a := new(Attribute)
	a.Type = typ
	if x == nil {
		return a
	}
	switch x.(type) {
	case bool: // create bbool
		if x.(bool) {
			a.Value = []byte{1}
			break
		}
		a.Value = []byte{0}
	case uint, int:
		var y uint
		if _, ok := x.(int); ok {
			y = uint(x.(int))
		}
		if _, ok := x.(uint); ok {
			y = x.(uint)
		}
		switch int(C.Sizeof()) {
		case 4:
			a.Value = make([]byte, 4)
			a.Value[0] = byte(y)
			a.Value[1] = byte(y >> 8)
			a.Value[2] = byte(y >> 16)
			a.Value[3] = byte(y >> 24)
		case 8:
			a.Value = make([]byte, 8)
			a.Value[0] = byte(y)
			a.Value[1] = byte(y >> 8)
			a.Value[2] = byte(y >> 16)
			a.Value[3] = byte(y >> 24)
			a.Value[4] = byte(y >> 32)
			a.Value[5] = byte(y >> 40)
			a.Value[6] = byte(y >> 48)
			a.Value[7] = byte(y >> 56)
		}
	case string:
		a.Value = []byte(x.(string))
	case []byte: // just copy
		a.Value = x.([]byte)
	case time.Time: // for CKA_DATE
		a.Value = cDate(x.(time.Time))
	default:
		panic("pkcs11: unhandled attribute type")
	}
	return a
}

// cAttribute returns the start address and the length of an attribute list.
func cAttributeList(a []*Attribute) (C.CK_ATTRIBUTE_PTR, C.CK_ULONG) {
	if len(a) == 0 {
		return nil, 0
	}
	pa := make([]C.CK_ATTRIBUTE, len(a))
	for i := 0; i < len(a); i++ {
		pa[i]._type = C.CK_ATTRIBUTE_TYPE(a[i].Type)
		if a[i].Value == nil {
			continue
		}
		pa[i].pValue = C.CK_VOID_PTR((&a[i].Value[0]))
		pa[i].ulValueLen = C.CK_ULONG(len(a[i].Value))
	}
	return C.CK_ATTRIBUTE_PTR(&pa[0]), C.CK_ULONG(len(a))
}

func cDate(t time.Time) []byte {
	b := make([]byte, 8)
	year, month, day := t.Date()
	y := fmt.Sprintf("%4d", year)
	m := fmt.Sprintf("%02d", month)
	d1 := fmt.Sprintf("%02d", day)
	b[0], b[1], b[2], b[3] = y[0], y[1], y[2], y[3]
	b[4], b[5] = m[0], m[1]
	b[6], b[7] = d1[0], d1[1]
	return b
}

// Mechanism holds an mechanism type/value combination.
type Mechanism struct {
	Mechanism uint
	Parameter []byte
}

func NewMechanism(mech uint, x interface{}) *Mechanism {
	m := new(Mechanism)
	m.Mechanism = mech
	if x == nil {
		return m
	}
	// TODO(miek): Not seen anything as elaborate as Attributes, so for know do nothing.
	return m
}

func cMechanismList(m []*Mechanism) (C.CK_MECHANISM_PTR, C.CK_ULONG) {
	if len(m) == 0 {
		return nil, 0
	}
	pm := make([]C.CK_MECHANISM, len(m))
	for i := 0; i < len(m); i++ {
		pm[i].mechanism = C.CK_MECHANISM_TYPE(m[i].Mechanism)
		if m[i].Parameter == nil {
			continue
		}
		pm[i].pParameter = C.CK_VOID_PTR(&(m[i].Parameter[0]))
		pm[i].ulParameterLen = C.CK_ULONG(len(m[i].Parameter))
	}
	return C.CK_MECHANISM_PTR(&pm[0]), C.CK_ULONG(len(m))
}

// MechanismInfo provides information about a particular mechanism.
type MechanismInfo struct {
	MinKeySize uint
	MaxKeySize uint
	Flags      uint
}
<commit_msg>doc update<commit_after>// Copyright 2013 Miek Gieben. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package pkcs11

/*
#define CK_PTR *
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)

#include <stdlib.h>
#include "pkcs11.h"

CK_ULONG Index(CK_ULONG_PTR array, CK_ULONG i)
{
	return array[i];
}

CK_ULONG Sizeof()
{
	return sizeof(CK_ULONG);
}
*/
import "C"

import (
	"fmt"
	"time"
	"unsafe"
)

// toList converts from a C style array to a []uint.
func toList(clist C.CK_ULONG_PTR, size C.CK_ULONG) []uint {
	l := make([]uint, int(size))
	for i := 0; i < len(l); i++ {
		l[i] = uint(C.Index(clist, C.CK_ULONG(i)))
	}
	defer C.free(unsafe.Pointer(clist))
	return l
}

// cBBool converts a bool to a CK_BBOOL.
func cBBool(x bool) C.CK_BBOOL {
	if x {
		return C.CK_BBOOL(C.CK_TRUE)
	}
	return C.CK_BBOOL(C.CK_FALSE)
}

// Error represents an PKCS#11 error.
type Error uint

func (e Error) Error() string {
	return "pkcs11: " + fmt.Sprintf("pkcs11: 0x%X: %s", uint(e), strerror[uint(e)])
}

func toError(e C.CK_RV) error {
	if e == C.CKR_OK {
		return nil
	}
	return Error(e)
}

/* SessionHandle is a Cryptoki-assigned value that identifies a session. */
type SessionHandle uint

/* ObjectHandle is a token-specific identifier for an object.  */
type ObjectHandle uint

// Version represents any version information from the library.
type Version struct {
	Major byte
	Minor byte
}

func toVersion(version C.CK_VERSION) Version {
	return Version{byte(version.major), byte(version.minor)}
}

// SlotEvent holds the SlotID which for which an slot event (token insertion,
// removal, etc.) occurred.
type SlotEvent struct {
	SlotID uint
}

// Info provides information about the library and hardware used.
type Info struct {
	CryptokiVersion    Version
	ManufacturerID     string
	Flags              uint
	LibraryDescription string
	LibraryVersion     Version
}

/* SlotInfo provides information about a slot. */
type SlotInfo struct {
	SlotDescription string // 64 bytes.
	ManufacturerID  string // 32 bytes.
	Flags           uint
	HardwareVersion Version
	FirmwareVersion Version
}

/* TokenInfo provides information about a token. */
type TokenInfo struct {
	Label              string
	ManufacturerID     string
	Model              string
	SerialNumber       string
	Flags              uint
	MaxSessionCount    uint
	SessionCount       uint
	MaxRwSessionCount  uint
	RwSessionCount     uint
	MaxPinLen          uint
	MinPinLen          uint
	TotalPublicMemory  uint
	FreePublicMemory   uint
	TotalPrivateMemory uint
	FreePrivateMemory  uint
	HardwareVersion    Version
	FirmwareVersion    Version
	UTCTime            string
}

/* SesionInfo provides information about a session. */
type SessionInfo struct {
	SlotID      uint
	State       uint
	Flags       uint
	DeviceError uint
}

// Attribute holds an attribute type/value combination.
type Attribute struct {
	Type  uint
	Value []byte
}

// NewAttribute allocates a Attribute and returns a pointer to it.
// Note that this is merely a convience function, as values returned
// from the HSM are not converted back to Go values. There are raw
// byte slices.
func NewAttribute(typ uint, x interface{}) *Attribute {
	a := new(Attribute)
	a.Type = typ
	if x == nil {
		return a
	}
	switch x.(type) {
	case bool: // create bbool
		if x.(bool) {
			a.Value = []byte{1}
			break
		}
		a.Value = []byte{0}
	case uint, int:
		var y uint
		if _, ok := x.(int); ok {
			y = uint(x.(int))
		}
		if _, ok := x.(uint); ok {
			y = x.(uint)
		}
		switch int(C.Sizeof()) {
		case 4:
			a.Value = make([]byte, 4)
			a.Value[0] = byte(y)
			a.Value[1] = byte(y >> 8)
			a.Value[2] = byte(y >> 16)
			a.Value[3] = byte(y >> 24)
		case 8:
			a.Value = make([]byte, 8)
			a.Value[0] = byte(y)
			a.Value[1] = byte(y >> 8)
			a.Value[2] = byte(y >> 16)
			a.Value[3] = byte(y >> 24)
			a.Value[4] = byte(y >> 32)
			a.Value[5] = byte(y >> 40)
			a.Value[6] = byte(y >> 48)
			a.Value[7] = byte(y >> 56)
		}
	case string:
		a.Value = []byte(x.(string))
	case []byte: // just copy
		a.Value = x.([]byte)
	case time.Time: // for CKA_DATE
		a.Value = cDate(x.(time.Time))
	default:
		panic("pkcs11: unhandled attribute type")
	}
	return a
}

// cAttribute returns the start address and the length of an attribute list.
func cAttributeList(a []*Attribute) (C.CK_ATTRIBUTE_PTR, C.CK_ULONG) {
	if len(a) == 0 {
		return nil, 0
	}
	pa := make([]C.CK_ATTRIBUTE, len(a))
	for i := 0; i < len(a); i++ {
		pa[i]._type = C.CK_ATTRIBUTE_TYPE(a[i].Type)
		if a[i].Value == nil {
			continue
		}
		pa[i].pValue = C.CK_VOID_PTR((&a[i].Value[0]))
		pa[i].ulValueLen = C.CK_ULONG(len(a[i].Value))
	}
	return C.CK_ATTRIBUTE_PTR(&pa[0]), C.CK_ULONG(len(a))
}

func cDate(t time.Time) []byte {
	b := make([]byte, 8)
	year, month, day := t.Date()
	y := fmt.Sprintf("%4d", year)
	m := fmt.Sprintf("%02d", month)
	d1 := fmt.Sprintf("%02d", day)
	b[0], b[1], b[2], b[3] = y[0], y[1], y[2], y[3]
	b[4], b[5] = m[0], m[1]
	b[6], b[7] = d1[0], d1[1]
	return b
}

// Mechanism holds an mechanism type/value combination.
type Mechanism struct {
	Mechanism uint
	Parameter []byte
}

func NewMechanism(mech uint, x interface{}) *Mechanism {
	m := new(Mechanism)
	m.Mechanism = mech
	if x == nil {
		return m
	}
	// TODO(miek): Not seen anything as elaborate as Attributes, so for know do nothing.
	return m
}

func cMechanismList(m []*Mechanism) (C.CK_MECHANISM_PTR, C.CK_ULONG) {
	if len(m) == 0 {
		return nil, 0
	}
	pm := make([]C.CK_MECHANISM, len(m))
	for i := 0; i < len(m); i++ {
		pm[i].mechanism = C.CK_MECHANISM_TYPE(m[i].Mechanism)
		if m[i].Parameter == nil {
			continue
		}
		pm[i].pParameter = C.CK_VOID_PTR(&(m[i].Parameter[0]))
		pm[i].ulParameterLen = C.CK_ULONG(len(m[i].Parameter))
	}
	return C.CK_MECHANISM_PTR(&pm[0]), C.CK_ULONG(len(m))
}

// MechanismInfo provides information about a particular mechanism.
type MechanismInfo struct {
	MinKeySize uint
	MaxKeySize uint
	Flags      uint
}
<|endoftext|>


<commit_before>package blockcy

import "time"

//Blockchain represents information about
//the state of a blockchain.
type Blockchain struct {
	Name             string    `json:"name"`
	Height           int       `json:"height"`
	Hash             string    `json:"hash"`
	Time             time.Time `json:"time"`
	LatestURL        string    `json:"latest_url"`
	PrevHash         string    `json:"previous_hash"`
	PrevURL          string    `json:"previous_url"`
	PeerCount        int       `json:"peer_count"`
	HighFee          int       `json:"high_fee_per_kb"`
	MediumFee        int       `json:"medium_fee_per_kb"`
	LowFee           int       `json:"low_fee_per_kb"`
	UnconfirmedCount int       `json:"unconfirmed_count"`
	LastForkHeight   int       `json:"last_fork_height"`
	LastForkHash     string    `json:"last_fork_hash"`
}

//Block represents information about the state
//of a given block in a blockchain.
type Block struct {
	Hash         string    `json:"hash"`
	Height       int       `json:"height"`
	Depth        int       `json:"depth"`
	Chain        string    `json:"chain"`
	Total        int       `json:"total"`
	Fees         int       `json:"fees"`
	Ver          int       `json:"ver"`
	Time         time.Time `json:"time"`
	ReceivedTime time.Time `json:"received_time"`
	RelayedBy    string    `json:"relayed_by,omitempty"`
	Bits         int       `json:"bits"`
	Nonce        int       `json:"nonce"`
	NumTX        int       `json:"n_tx"`
	PrevBlock    string    `json:"prev_block"`
	PrevBlockURL string    `json:"prev_block_url"`
	MerkleRoot   string    `json:"mrkl_root"`
	TXids        []string  `json:"txids"`
	NextTXs      string    `json:"next_txids"`
}

//TX represents information about the state
//of a given transaction in a blockchain.
type TX struct {
	BlockHash     string     `json:"block_hash,omitempty"`
	BlockHeight   int        `json:"block_height,omitempty"`
	Hash          string     `json:"hash,omitempty"`
	Addresses     []string   `json:"addresses,omitempty"`
	Total         int        `json:"total,omitempty"`
	Fees          int        `json:"fees,omitempty"`
	Size          int        `json:"size"`
	Preference    string     `json:"preference,omitempty"`
	RelayedBy     string     `json:"relayed_by,omitempty"`
	Received      time.Time  `json:"received,omitempty"`
	Confirmed     time.Time  `json:"confirmed,omitempty"`
	Confirmations int        `json:"confirmations,omitempty"`
	Confidence    float64    `json:"confidence,omitempty"`
	Ver           int        `json:"ver,omitempty"`
	LockTime      int        `json:"lock_time,omitempty"`
	DoubleSpend   bool       `json:"double_spend,omitempty"`
	DoubleOf      string     `json:"double_of,omitempty"`
	ReceiveCount  int        `json:"receive_count,omitempty"`
	VinSize       int        `json:"vin_sz,omitempty"`
	VoutSize      int        `json:"vout_sz,omitempty"`
	Hex           string     `json:"hex,omitempty"`
	ChangeAddress string     `json:"change_address,omitempty"`
	NextInputs    string     `json:"next_inputs,omitempty"`
	NextOutputs   string     `json:"next_outputs,omitempty"`
	Inputs        []TXInput  `json:"inputs"`
	Outputs       []TXOutput `json:"outputs"`
}

//TXInput represents the state of a transaction input
type TXInput struct {
	PrevHash    string   `json:"prev_hash,omitempty"`
	OutputIndex int      `json:"output_index,omitempty"`
	OutputValue int      `json:"output_value,omitempty"`
	Addresses   []string `json:"addresses"`
	Sequence    int      `json:"sequence,omitempty"`
	ScriptType  string   `json:"script_type,omitempty"`
	Script      string   `json:"script,omitempty"`
	Age         int      `json:"age,omitempty"`
	WalletName  string   `json:"wallet_name,omitempty"`
}

//TXOutput represents the state of a transaction output
type TXOutput struct {
	SpentBy    string   `json:"spent_by,omitempty"`
	Value      int      `json:"value"`
	Addresses  []string `json:"addresses"`
	ScriptType string   `json:"script_type,omitempty"`
	Script     string   `json:"script,omitempty"`
	DataHex    string   `json:"data_hex,omitempty"`
	DataString string   `json:"data_string,omitempty"`
}

//TXConf represents information about the
//confidence of an unconfirmed transaction.
type TXConf struct {
	Age          int     `json:"age_millis"`
	ReceiveCount int     `json:"receive_count,omitempty"`
	Confidence   float64 `json:"confidence"`
	TXHash       string  `json:"txhash"`
}

//TXRef represents summarized data about a
//transaction input or output.
type TXRef struct {
	BlockHeight   int       `json:"block_height"`
	TXHash        string    `json:"tx_hash"`
	TXInputN      int       `json:"tx_input_n"`
	TXOutputN     int       `json:"tx_output_n"`
	Value         int       `json:"value"`
	Pref          string    `json:"preference"`
	Spent         bool      `json:"spent"`
	DoubleSpend   bool      `json:"double_spend"`
	DoubleOf      string    `json:"double_of,omitempty"`
	Confirmations int       `json:"confirmations"`
	RefBalance    int       `json:"ref_balance,omitempty"`
	Confidence    float64   `json:"confidence,omitempty"`
	Confirmed     time.Time `json:"confirmed,omitempty"`
	SpentBy       string    `json:"spent_by,omitempty"`
	Received      time.Time `json:"received,omitempty"`
	ReceivedCount int       `json:"received_count,omitempty"`
}

//TXSkel represents the return call to BlockCypher's
//txs/new endpoint, and includes error information,
//hex transactions that need to be signed, and space
//for the signed transactions and associated public keys.
type TXSkel struct {
	Trans      TX          `json:"tx"`
	ToSign     []string    `json:"tosign"`
	Signatures []string    `json:"signatures"`
	PubKeys    []string    `json:"pubkeys,omitempty"`
	ToSignTX   []string    `json:"tosign_tx,omitempty"`
	Errors     []txSkelErr `json:"errors,omitempty"`
}

//used within for JSON serialization.
type txSkelErr struct {
	Error string `json:"error,omitempty"`
}

//NullData represents the call and return to BlockCypher's
//Data API, allowing you to embed up to 80 bytes into
//a blockchain via an OP_RETURN.
type NullData struct {
	Data     string `json:"data"`
	Encoding string `json:"encoding,omitempty"`
	Hash     string `json:"hash,omitempty"`
}

//MicroTX represents a microtransaction. For small-value
//transactions, BlockCypher will sign the transaction
//on your behalf, with your private key (if provided).
//Setting a separate change address is recommended.
//Where your application model allows it, consider
//only using public keys with microtransactions,
//and sign the microtransaction with your private key
//(without sending to BlockCypher's server).
type MicroTX struct {
	//Only one of Pubkey/Private/Wif is required
	Pubkey     string        `json:"from_pubkey,omitempty"`
	Priv       string        `json:"from_private,omitempty"`
	Wif        string        `json:"from_wif,omitempty"`
	ToAddr     string        `json:"to_address"`
	Value      int           `json:"value_satoshis"`
	ChangeAddr string        `json:"change_address,omitempty"`
	Wait       bool          `json:"wait_guarantee,omitempty"`
	ToSign     []string      `json:"tosign,omitempty"`
	Signatures []string      `json:"signatures,omitempty"`
	Hash       string        `json:"hash,omitempty"`
	Inputs     []MicroInput  `json:"inputs,omitempty"`
	Outputs    []MicroOutput `json:"outputs,omitempty"`
	Fees       int           `json:"fees,omitempty"`
}

//MicroInput represents pared down TXInput data
//within a Microtransaction.
type MicroInput struct {
	PrevHash    string `json:"prev_hash"`
	OutputIndex int    `json:"output_index"`
}

//MicroOutput represents pared down TXOutput data
//within a Microtransaction.
type MicroOutput struct {
	Value   int    `json:"value"`
	Address string `json:"address"`
}

//Addr represents information about the state
//of a public address.
type Addr struct {
	Address            string  `json:"address"`
	TotalReceived      int     `json:"total_received"`
	TotalSent          int     `json:"total_sent"`
	Balance            int     `json:"balance"`
	UnconfirmedBalance int     `json:"unconfirmed_balance"`
	FinalBalance       int     `json:"final_balance"`
	NumTX              int     `json:"n_tx"`
	UnconfirmedNumTX   int     `json:"unconfirmed_n_tx"`
	FinalNumTX         int     `json:"final_n_tx"`
	TXs                []TX    `json:"txs,omitempty"`
	TXRefs             []TXRef `json:"txrefs,omitempty"`
	UnconfirmedTXRefs  []TXRef `json:"unconfirmed_txrefs,omitempty"`
	HasMore            bool    `json:"hasMore,omitempty"`
}

//AddrKeychain represents information about a generated
//public-private key pair from BlockCypher's address
//generation API. Large amounts are not recommended to be
//stored with these addresses.
type AddrKeychain struct {
	Address    string   `json:"address,omitempty"`
	Private    string   `json:"private,omitempty"`
	Public     string   `json:"public,omitempty"`
	Wif        string   `json:"wif,omitempty"`
	PubKeys    []string `json:"pubkeys,omitempty"`
	ScriptType string   `json:"script_type,omitempty"`
}

//Wallet represents information about a standard wallet.
//Typically, wallets can be used wherever an address can be
//used within the API.
type Wallet struct {
	Name      string   `json:"name,omitempty"`
	Addresses []string `json:"addresses,omitempty"`
}

//Hook represents a WebHook/WebSockets event.
//BlockCypher supports the following events:
//	Event = "unconfirmed-tx"
//	Event = "new-block"
//	Event = "confirmed-tx"
//	Event = "tx-confirmation"
//	Event = "double-spend-tx"
//  Event = "tx-confidence"
//Hash, Address, and Script are all optional; creating
//a WebHook with any of them will filter the resulting
//notifications, if appropriate. ID is returned by
//BlockCyphers servers after Posting a new WebHook; you
//shouldn't manually generate this field.
type Hook struct {
	ID            string  `json:"id,omitempty"`
	Event         string  `json:"event"`
	Hash          string  `json:"hash,omitempty"`
	WalletName    string  `json:"wallet_name,omitempty"`
	Address       string  `json:"address,omitempty"`
	Confirmations int     `json:"confirmations,omitempty"`
	Confidence    float32 `json:"confidence,omitempty"`
	Script        string  `json:"script,omitempty"`
	URL           string  `json:"url,omitempty"`
	CallbackErrs  int     `json:"callback_errors,omitempty"`
}

//PaymentFwd represents a reference to
//a Payment Forwarding request.
type PaymentFwd struct {
	ID             string   `json:"id,omitempty"`
	Destination    string   `json:"destination"`
	InputAddr      string   `json:"input_address,omitempty"`
	ProcessAddr    string   `json:"process_fees_address,omitempty"`
	ProcessPercent float64  `json:"process_fees_percent,omitempty"`
	ProcessValue   int      `json:"process_fees_satoshis,omitempty"`
	CallbackURL    string   `json:"callback_url,omitempty"`
	EnableConfirm  bool     `json:"enable_confirmations,omitempty"`
	MiningFees     int      `json:"mining_fees_satoshis,omitempty"`
	TXHistory      []string `json:"transactions,omitempty"`
}

//Payback represents a Payment Forwarding Callback.
//It's more fun to call it a "payback."
type Payback struct {
	Value       int    `json:"value"`
	Destination string `json:"destination"`
	DestHash    string `json:"transaction_hash"`
	InputAddr   string `json:"input_address"`
	InputHash   string `json:"input_transaction_hash"`
}
<commit_msg>add dataprotocol to tx type<commit_after>package blockcy

import "time"

//Blockchain represents information about
//the state of a blockchain.
type Blockchain struct {
	Name             string    `json:"name"`
	Height           int       `json:"height"`
	Hash             string    `json:"hash"`
	Time             time.Time `json:"time"`
	LatestURL        string    `json:"latest_url"`
	PrevHash         string    `json:"previous_hash"`
	PrevURL          string    `json:"previous_url"`
	PeerCount        int       `json:"peer_count"`
	HighFee          int       `json:"high_fee_per_kb"`
	MediumFee        int       `json:"medium_fee_per_kb"`
	LowFee           int       `json:"low_fee_per_kb"`
	UnconfirmedCount int       `json:"unconfirmed_count"`
	LastForkHeight   int       `json:"last_fork_height"`
	LastForkHash     string    `json:"last_fork_hash"`
}

//Block represents information about the state
//of a given block in a blockchain.
type Block struct {
	Hash         string    `json:"hash"`
	Height       int       `json:"height"`
	Depth        int       `json:"depth"`
	Chain        string    `json:"chain"`
	Total        int       `json:"total"`
	Fees         int       `json:"fees"`
	Ver          int       `json:"ver"`
	Time         time.Time `json:"time"`
	ReceivedTime time.Time `json:"received_time"`
	RelayedBy    string    `json:"relayed_by,omitempty"`
	Bits         int       `json:"bits"`
	Nonce        int       `json:"nonce"`
	NumTX        int       `json:"n_tx"`
	PrevBlock    string    `json:"prev_block"`
	PrevBlockURL string    `json:"prev_block_url"`
	MerkleRoot   string    `json:"mrkl_root"`
	TXids        []string  `json:"txids"`
	NextTXs      string    `json:"next_txids"`
}

//TX represents information about the state
//of a given transaction in a blockchain.
type TX struct {
	BlockHash     string     `json:"block_hash,omitempty"`
	BlockHeight   int        `json:"block_height,omitempty"`
	Hash          string     `json:"hash,omitempty"`
	Addresses     []string   `json:"addresses,omitempty"`
	Total         int        `json:"total,omitempty"`
	Fees          int        `json:"fees,omitempty"`
	Size          int        `json:"size"`
	Preference    string     `json:"preference,omitempty"`
	RelayedBy     string     `json:"relayed_by,omitempty"`
	Received      time.Time  `json:"received,omitempty"`
	Confirmed     time.Time  `json:"confirmed,omitempty"`
	Confirmations int        `json:"confirmations,omitempty"`
	Confidence    float64    `json:"confidence,omitempty"`
	Ver           int        `json:"ver,omitempty"`
	LockTime      int        `json:"lock_time,omitempty"`
	DoubleSpend   bool       `json:"double_spend,omitempty"`
	DoubleOf      string     `json:"double_of,omitempty"`
	ReceiveCount  int        `json:"receive_count,omitempty"`
	VinSize       int        `json:"vin_sz,omitempty"`
	VoutSize      int        `json:"vout_sz,omitempty"`
	Hex           string     `json:"hex,omitempty"`
	DataProtocol  string     `json:"data_protocol,omitempty"`
	ChangeAddress string     `json:"change_address,omitempty"`
	NextInputs    string     `json:"next_inputs,omitempty"`
	NextOutputs   string     `json:"next_outputs,omitempty"`
	Inputs        []TXInput  `json:"inputs"`
	Outputs       []TXOutput `json:"outputs"`
}

//TXInput represents the state of a transaction input
type TXInput struct {
	PrevHash    string   `json:"prev_hash,omitempty"`
	OutputIndex int      `json:"output_index,omitempty"`
	OutputValue int      `json:"output_value,omitempty"`
	Addresses   []string `json:"addresses"`
	Sequence    int      `json:"sequence,omitempty"`
	ScriptType  string   `json:"script_type,omitempty"`
	Script      string   `json:"script,omitempty"`
	Age         int      `json:"age,omitempty"`
	WalletName  string   `json:"wallet_name,omitempty"`
}

//TXOutput represents the state of a transaction output
type TXOutput struct {
	SpentBy    string   `json:"spent_by,omitempty"`
	Value      int      `json:"value"`
	Addresses  []string `json:"addresses"`
	ScriptType string   `json:"script_type,omitempty"`
	Script     string   `json:"script,omitempty"`
	DataHex    string   `json:"data_hex,omitempty"`
	DataString string   `json:"data_string,omitempty"`
}

//TXConf represents information about the
//confidence of an unconfirmed transaction.
type TXConf struct {
	Age          int     `json:"age_millis"`
	ReceiveCount int     `json:"receive_count,omitempty"`
	Confidence   float64 `json:"confidence"`
	TXHash       string  `json:"txhash"`
}

//TXRef represents summarized data about a
//transaction input or output.
type TXRef struct {
	BlockHeight   int       `json:"block_height"`
	TXHash        string    `json:"tx_hash"`
	TXInputN      int       `json:"tx_input_n"`
	TXOutputN     int       `json:"tx_output_n"`
	Value         int       `json:"value"`
	Pref          string    `json:"preference"`
	Spent         bool      `json:"spent"`
	DoubleSpend   bool      `json:"double_spend"`
	DoubleOf      string    `json:"double_of,omitempty"`
	Confirmations int       `json:"confirmations"`
	RefBalance    int       `json:"ref_balance,omitempty"`
	Confidence    float64   `json:"confidence,omitempty"`
	Confirmed     time.Time `json:"confirmed,omitempty"`
	SpentBy       string    `json:"spent_by,omitempty"`
	Received      time.Time `json:"received,omitempty"`
	ReceivedCount int       `json:"received_count,omitempty"`
}

//TXSkel represents the return call to BlockCypher's
//txs/new endpoint, and includes error information,
//hex transactions that need to be signed, and space
//for the signed transactions and associated public keys.
type TXSkel struct {
	Trans      TX          `json:"tx"`
	ToSign     []string    `json:"tosign"`
	Signatures []string    `json:"signatures"`
	PubKeys    []string    `json:"pubkeys,omitempty"`
	ToSignTX   []string    `json:"tosign_tx,omitempty"`
	Errors     []txSkelErr `json:"errors,omitempty"`
}

//used within for JSON serialization.
type txSkelErr struct {
	Error string `json:"error,omitempty"`
}

//NullData represents the call and return to BlockCypher's
//Data API, allowing you to embed up to 80 bytes into
//a blockchain via an OP_RETURN.
type NullData struct {
	Data     string `json:"data"`
	Encoding string `json:"encoding,omitempty"`
	Hash     string `json:"hash,omitempty"`
}

//MicroTX represents a microtransaction. For small-value
//transactions, BlockCypher will sign the transaction
//on your behalf, with your private key (if provided).
//Setting a separate change address is recommended.
//Where your application model allows it, consider
//only using public keys with microtransactions,
//and sign the microtransaction with your private key
//(without sending to BlockCypher's server).
type MicroTX struct {
	//Only one of Pubkey/Private/Wif is required
	Pubkey     string        `json:"from_pubkey,omitempty"`
	Priv       string        `json:"from_private,omitempty"`
	Wif        string        `json:"from_wif,omitempty"`
	ToAddr     string        `json:"to_address"`
	Value      int           `json:"value_satoshis"`
	ChangeAddr string        `json:"change_address,omitempty"`
	Wait       bool          `json:"wait_guarantee,omitempty"`
	ToSign     []string      `json:"tosign,omitempty"`
	Signatures []string      `json:"signatures,omitempty"`
	Hash       string        `json:"hash,omitempty"`
	Inputs     []MicroInput  `json:"inputs,omitempty"`
	Outputs    []MicroOutput `json:"outputs,omitempty"`
	Fees       int           `json:"fees,omitempty"`
}

//MicroInput represents pared down TXInput data
//within a Microtransaction.
type MicroInput struct {
	PrevHash    string `json:"prev_hash"`
	OutputIndex int    `json:"output_index"`
}

//MicroOutput represents pared down TXOutput data
//within a Microtransaction.
type MicroOutput struct {
	Value   int    `json:"value"`
	Address string `json:"address"`
}

//Addr represents information about the state
//of a public address.
type Addr struct {
	Address            string  `json:"address"`
	TotalReceived      int     `json:"total_received"`
	TotalSent          int     `json:"total_sent"`
	Balance            int     `json:"balance"`
	UnconfirmedBalance int     `json:"unconfirmed_balance"`
	FinalBalance       int     `json:"final_balance"`
	NumTX              int     `json:"n_tx"`
	UnconfirmedNumTX   int     `json:"unconfirmed_n_tx"`
	FinalNumTX         int     `json:"final_n_tx"`
	TXs                []TX    `json:"txs,omitempty"`
	TXRefs             []TXRef `json:"txrefs,omitempty"`
	UnconfirmedTXRefs  []TXRef `json:"unconfirmed_txrefs,omitempty"`
	HasMore            bool    `json:"hasMore,omitempty"`
}

//AddrKeychain represents information about a generated
//public-private key pair from BlockCypher's address
//generation API. Large amounts are not recommended to be
//stored with these addresses.
type AddrKeychain struct {
	Address    string   `json:"address,omitempty"`
	Private    string   `json:"private,omitempty"`
	Public     string   `json:"public,omitempty"`
	Wif        string   `json:"wif,omitempty"`
	PubKeys    []string `json:"pubkeys,omitempty"`
	ScriptType string   `json:"script_type,omitempty"`
}

//Wallet represents information about a standard wallet.
//Typically, wallets can be used wherever an address can be
//used within the API.
type Wallet struct {
	Name      string   `json:"name,omitempty"`
	Addresses []string `json:"addresses,omitempty"`
}

//Hook represents a WebHook/WebSockets event.
//BlockCypher supports the following events:
//	Event = "unconfirmed-tx"
//	Event = "new-block"
//	Event = "confirmed-tx"
//	Event = "tx-confirmation"
//	Event = "double-spend-tx"
//  Event = "tx-confidence"
//Hash, Address, and Script are all optional; creating
//a WebHook with any of them will filter the resulting
//notifications, if appropriate. ID is returned by
//BlockCyphers servers after Posting a new WebHook; you
//shouldn't manually generate this field.
type Hook struct {
	ID            string  `json:"id,omitempty"`
	Event         string  `json:"event"`
	Hash          string  `json:"hash,omitempty"`
	WalletName    string  `json:"wallet_name,omitempty"`
	Address       string  `json:"address,omitempty"`
	Confirmations int     `json:"confirmations,omitempty"`
	Confidence    float32 `json:"confidence,omitempty"`
	Script        string  `json:"script,omitempty"`
	URL           string  `json:"url,omitempty"`
	CallbackErrs  int     `json:"callback_errors,omitempty"`
}

//PaymentFwd represents a reference to
//a Payment Forwarding request.
type PaymentFwd struct {
	ID             string   `json:"id,omitempty"`
	Destination    string   `json:"destination"`
	InputAddr      string   `json:"input_address,omitempty"`
	ProcessAddr    string   `json:"process_fees_address,omitempty"`
	ProcessPercent float64  `json:"process_fees_percent,omitempty"`
	ProcessValue   int      `json:"process_fees_satoshis,omitempty"`
	CallbackURL    string   `json:"callback_url,omitempty"`
	EnableConfirm  bool     `json:"enable_confirmations,omitempty"`
	MiningFees     int      `json:"mining_fees_satoshis,omitempty"`
	TXHistory      []string `json:"transactions,omitempty"`
}

//Payback represents a Payment Forwarding Callback.
//It's more fun to call it a "payback."
type Payback struct {
	Value       int    `json:"value"`
	Destination string `json:"destination"`
	DestHash    string `json:"transaction_hash"`
	InputAddr   string `json:"input_address"`
	InputHash   string `json:"input_transaction_hash"`
}
<|endoftext|>


<commit_before>package tripeg

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

//Hole struct that contains information
//about a hole in the board, its location
//and whether or not it has a peg in it.
type Hole struct {
	Row   int //make of 5
	Col   int //max of 9
	Peg   bool
	Links []*Hole //Other Holes the hole is connected to
}

//Jump moves a peg from one hole to another
//If it can jump, it removes the peg from the
//overHole hole.
func (h *Hole) Jump(b *Board, overHole *Hole) bool {
	if !overHole.Peg {
		//If there is no peg in the overHole, no jump possible
		return false
	}

	rDif := h.Row - overHole.Row
	cDif := overHole.Col - h.Col
	if cDif == 0 && rDif == 0 {
		//Holes are the same, not valid
		return false
	}
	if math.Abs(float64(rDif)) > 1 {
		//You can't jump over more than 1 row horizontally
		return false
	}
	if rDif > 0 && math.Abs(float64(cDif)) > 1 {
		//You can't jump over more than 1 col vertically
		return false
	}
	if rDif == 0 && math.Abs(float64(cDif)) > 2 {
		return false
		//You can't jump more than 2 cols horizontally
	}
	targetR := 0
	targetC := 0
	if rDif == 0 {
		//This is a horizontal jump
		targetR = h.Row
	}
	if rDif > 0 {
		targetR = overHole.Row - 1
		//This is a up
	}
	if rDif < 0 {
		targetR = overHole.Row + 1
		//This is a jump down
	}
	if cDif < 0 {
		x := 1
		if rDif == 0 {
			x = 2
		}
		targetC = overHole.Col - x
		//This is a jump left
	}
	if cDif > 0 {
		x := 1
		if rDif == 0 {
			x = 2
		}
		targetC = overHole.Col + x
		//This is a jump right
	}
	targetHole := b.GetHole(targetR, targetC)
	if targetHole == nil {
		return false
	}
	if targetHole.Peg {
		return false
	}
	h.Peg = false
	overHole.Peg = false
	targetHole.Peg = true
	return true
}

//Board contains all the holes that contain the pegs
type Board struct {
	Holes   []*Hole
	MoveLog []string
}

//GetHole gets a pointer to a hole based on the row,col coordinates
func (b Board) GetHole(r, c int) *Hole {
	if r < 0 || r > 6 || c < 0 || c > 9 {
		return nil
	}
	for _, v := range b.Holes {
		if v.Col == c && v.Row == r {
			return v
		}
	}
	return nil
}

//BuildBoard makes a board of peg holes.
//All holes have a peg except one randomly assigned.
//The top row has 1, then
//2,3,4,5 for a total of 16 holes.
func BuildBoard(empty int) Board {
	var b Board
	s2 := rand.NewSource(time.Now().UnixNano())
	r2 := rand.New(s2)
	if empty == 0 {
		empty = r2.Intn(15)
	} else {
		empty--
	}

	for r := 1; r < 6; r++ {
		for c := 1; c < r+1; c++ {
			col := 4 - (r) + (c * 2)
			h := Hole{Row: r, Col: col, Peg: true}
			if empty == len(b.Holes) {
				h.Peg = false
			}
			b.Holes = append(b.Holes, &h)
		}
	}
	return b
}

func (b *Board) Solve() {
	b.MoveLog = []string{}
	//Find out how many holes
	//can make a legal Move
	//randomly pick one of those holes
	//find out how many moves can be made from that hole
	//randomly pick one of those
	//try again until there are no moves to make
	//or 14 legal moves have been made, (winner)
	//Print out all the winning moves
	cMoves := []*Hole{}
	_ = cMoves
	for _, v := range b.Holes {
		if v.Peg == true {
			o := b.GetHole(v.Row-1, v.Col-2)
			if v.Jump(b, o) {
				//upleft

			}
			//upright
			//right
			//left
			//downleft
			//downright
		}
	}
}

func (b Board) String() string {
	result := "\n"
	for r := 1; r < 6; r++ {
		for c := 1; c < 10; c++ {
			h := b.GetHole(r, c)
			mark := " "
			if h != nil {
				mark = "O"
				if h.Peg {
					mark = "*"
				}
			}
			result += mark
		}
		result += "\n"
	}
	return result
}
func even(number int) bool {
	return number%2 == 0
}
<commit_msg>up and to the right doesn't work<commit_after>package tripeg

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

//Hole struct that contains information
//about a hole in the board, its location
//and whether or not it has a peg in it.
type Hole struct {
	Row   int //make of 5
	Col   int //max of 9
	Peg   bool
	Links []*Hole //Other Holes the hole is connected to
}

//Jump moves a peg from one hole to another
//If it can jump, it removes the peg from the
//overHole hole.
func (h *Hole) Jump(b *Board, overHole *Hole) bool {
	if !overHole.Peg {
		//If there is no peg in the overHole, no jump possible
		return false
	}

	rDif := h.Row - overHole.Row
	cDif := overHole.Col - h.Col
	if cDif == 0 && rDif == 0 {
		//Holes are the same, not valid
		return false
	}
	if math.Abs(float64(rDif)) > 1 {
		//You can't jump over more than 1 row horizontally
		return false
	}
	if rDif > 0 && math.Abs(float64(cDif)) > 1 {
		//You can't jump over more than 1 col vertically
		return false
	}
	if rDif == 0 && math.Abs(float64(cDif)) > 2 {
		return false
		//You can't jump more than 2 cols horizontally
	}
	targetR := 0
	targetC := 0
	if rDif == 0 {
		//This is a horizontal jump
		targetR = h.Row
	}
	if rDif > 0 {
		targetR = overHole.Row - 1
		//This is a up
	}
	if rDif < 0 {
		targetR = overHole.Row + 1
		//This is a jump down
	}
	if cDif < 0 {
		x := 1
		if rDif == 0 {
			x = 2
		}
		targetC = overHole.Col - x
		//This is a jump left
	}
	if cDif > 0 {
		x := 1
		if rDif == 0 {
			x = 2
		}
		targetC = overHole.Col + x
		//This is a jump right
	}
	targetHole := b.GetHole(targetR, targetC)
	if targetHole == nil {
		return false
	}
	if targetHole.Peg {
		return false
	}
	h.Peg = false
	overHole.Peg = false
	targetHole.Peg = true
	return true
}

//Board contains all the holes that contain the pegs
type Board struct {
	Holes   []*Hole
	MoveLog []string
}

//GetHole gets a pointer to a hole based on the row,col coordinates
func (b Board) GetHole(r, c int) *Hole {
	if r < 0 || r > 6 || c < 0 || c > 9 {
		return nil
	}
	for _, v := range b.Holes {
		if v.Col == c && v.Row == r {
			return v
		}
	}
	return nil
}

//BuildBoard makes a board of peg holes.
//All holes have a peg except one randomly assigned.
//The top row has 1, then
//2,3,4,5 for a total of 16 holes.
func BuildBoard(empty int) Board {
	var b Board
	s2 := rand.NewSource(time.Now().UnixNano())
	r2 := rand.New(s2)
	if empty == 0 {
		empty = r2.Intn(15)
	} else {
		empty--
	}

	for r := 1; r < 6; r++ {
		for c := 1; c < r+1; c++ {
			col := 4 - (r) + (c * 2)
			h := Hole{Row: r, Col: col, Peg: true}
			if empty == len(b.Holes) {
				h.Peg = false
			}
			b.Holes = append(b.Holes, &h)
		}
	}
	return b
}

func (b *Board) Solve() {
	b.MoveLog = []string{}
	//Find out how many holes
	//can make a legal Move
	//find out how many moves can be made from those hole
	//randomly pick one of those
	//try again until there are no moves to make
	//or 14 legal moves have been made, (winner)
	//Print out all the winning moves
	type cMove struct {
		H *Hole
		O *Hole
	}
	cMoves := []cMove{}
	moves := 0
	for _, v := range b.Holes {
		if v.Peg == true {
			o := b.GetHole(v.Row-1, v.Col-1)
			if o != nil {
				if v.Jump(b, o) {
					//upleft
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
			o = b.GetHole(v.Row-1, v.Col+1)
			if o != nil {
				if v.Jump(b, o) {
					//upright
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
			o = b.GetHole(v.Row, v.Col+2)
			if o != nil {
				if v.Jump(b, o) {
					//right
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
			o = b.GetHole(v.Row, v.Col-2)
			if o != nil {
				if v.Jump(b, o) {
					//left
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
			o = b.GetHole(v.Row+1, v.Col-2)
			if o != nil {
				if v.Jump(b, o) {
					//downleft
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
			o = b.GetHole(v.Row+1, v.Col+2)
			if o != nil {
				if v.Jump(b, o) {
					//downright
					cMoves = append(cMoves, cMove{H: v, O: o})
				}
			}
		}

		//s2 := rand.NewSource(time.Now().UnixNano())
		//r2 := rand.New(s2)
		// if len(cMoves) == 0 {
		// 	fmt.Println("Dead End...", moves)
		// 	return
		// }
		// m := cMoves[r2.Intn(len(cMoves))]
		// if m.H.Jump(b, m.O) {
		// 	moves++
		// }
		// if moves == 3 {
		// 	fmt.Println("Made to the goal")
		// }
	}
	_ = moves
	for _, mv := range cMoves {
		fmt.Println(mv.H, mv.O)
	}
	return
}

func (b Board) String() string {
	result := "\n"
	for r := 1; r < 6; r++ {
		for c := 1; c < 10; c++ {
			h := b.GetHole(r, c)
			mark := " "
			if h != nil {
				mark = "O"
				if h.Peg {
					mark = "*"
				}
			}
			result += mark
		}
		result += "\n"
	}
	return result
}
<|endoftext|>


<commit_before>// Copyright ©2014 The gonum 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 optimize

import (
	"errors"
	"fmt"
	"math"
	"time"

	"github.com/gonum/matrix/mat64"
)

const defaultGradientAbsTol = 1e-6

// EvaluationType is used by a Method to specify the objective-function
// information needed at an x location.
type EvaluationType uint

// Evaluation types can be composed together using the binary or operator, for
// example 'FuncEvaluation | GradEvaluation' to evaluate both the function
// value and the gradient.
const (
	NoEvaluation   EvaluationType = 0
	FuncEvaluation EvaluationType = 1 << iota
	GradEvaluation
	HessEvaluation
)

func (e EvaluationType) String() string {
	if s, ok := evaluationStrings[e]; ok {
		return s
	}
	return fmt.Sprintf("EvaluationType(%d)", e)
}

var evaluationStrings = map[EvaluationType]string{
	NoEvaluation:   "NoEvaluation",
	FuncEvaluation: "FuncEvaluation",
	GradEvaluation: "GradEvaluation",
	HessEvaluation: "HessEvaluation",
}

// IterationType specifies the type of iteration.
type IterationType int

const (
	NoIteration IterationType = iota
	MajorIteration
	MinorIteration
	SubIteration
	InitIteration
	PostIteration // Iteration after the optimization. Sent to Recorder.
)

func (i IterationType) String() string {
	if i < 0 || int(i) >= len(iterationStrings) {
		return fmt.Sprintf("IterationType(%d)", i)
	}
	return iterationStrings[i]
}

var iterationStrings = [...]string{
	"NoIteration",
	"MajorIteration",
	"MinorIteration",
	"SubIteration",
	"InitIteration",
	"PostIteration",
}

// Location represents a location in the optimization procedure.
type Location struct {
	X        []float64
	F        float64
	Gradient []float64
	Hessian  *mat64.SymDense
}

// LinesearchLocation is a location for a linesearch subiteration
type LinesearchLocation struct {
	F          float64 // Function value at the step
	Derivative float64 // Projected gradient in the linesearch direction
}

// Result represents the answer of an optimization run. It contains the optimum
// location as well as the Status at convergence and Statistics taken during the
// run.
type Result struct {
	Location
	Stats
	Status Status
}

// Stats contains the statistics of the run.
type Stats struct {
	MajorIterations int           // Total number of major iterations
	FuncEvaluations int           // Number of evaluations of Func()
	GradEvaluations int           // Number of evaluations of Grad()
	HessEvaluations int           // Number of evaluations of Hess()
	Runtime         time.Duration // Total runtime of the optimization
}

// FunctionInfo is data to give to the optimizer about the objective function.
type FunctionInfo struct {
	IsGradient                bool
	IsHessian                 bool
	IsFunctionGradient        bool
	IsFunctionGradientHessian bool
	IsStatuser                bool
}

// functionInfo contains information about which interfaces the objective
// function F implements and the actual methods of F that have been
// successfully type switched.
type functionInfo struct {
	FunctionInfo

	function Function
	gradient Gradient
	hessian  Hessian
	statuser Statuser
}

func newFunctionInfo(f Function) *functionInfo {
	gradient, isGradient := f.(Gradient)
	hessian, isHessian := f.(Hessian)
	statuser, isStatuser := f.(Statuser)

	return &functionInfo{
		FunctionInfo: FunctionInfo{
			IsGradient: isGradient,
			IsHessian:  isHessian,
			IsStatuser: isStatuser,
		},
		function: f,
		gradient: gradient,
		hessian:  hessian,
		statuser: statuser,
	}
}

// TODO(btracey): Think about making this an exported function when the
// constraint interface is designed.
func (f functionInfo) satisfies(method Method) error {
	if method.Needs().Gradient && !f.IsGradient {
		return errors.New("optimize: function does not implement needed Gradient interface")
	}
	if method.Needs().Hessian && !f.IsHessian {
		return errors.New("optimize: function does not implement needed Hessian interface")
	}
	return nil
}

// complementEval returns an evaluation type that evaluates fields of loc not
// evaluated by eval.
func complementEval(loc *Location, eval EvaluationType) (complEval EvaluationType) {
	if eval&FuncEvaluation == 0 {
		complEval = FuncEvaluation
	}
	if loc.Gradient != nil && eval&GradEvaluation == 0 {
		complEval |= GradEvaluation
	}
	if loc.Hessian != nil && eval&HessEvaluation == 0 {
		complEval |= HessEvaluation
	}
	return complEval
}

// Settings represents settings of the optimization run. It contains initial
// settings, convergence information, and Recorder information. In general, users
// should use DefaultSettings() rather than constructing a Settings literal.
//
// If UseInitData is true, InitialValue, InitialGradient and InitialHessian
// specify function information at the initial location.
//
// If Recorder is nil, no information will be recorded.
type Settings struct {
	UseInitialData  bool            // Use supplied information about the conditions at the initial x.
	InitialValue    float64         // Func(x) at the initial x.
	InitialGradient []float64       // Grad(x) at the initial x.
	InitialHessian  *mat64.SymDense // Hess(x) at the initial x.

	// FunctionThreshold is the threshold for acceptably small values of the
	// objective function. FunctionThreshold status is returned if
	// the objective function is less than this value.
	// The default value is -inf.
	FunctionThreshold float64

	// GradientThreshold determines the accuracy to which the minimum is found.
	// GradientThreshold status is returned if the infinity norm of
	// the gradient is less than this value.
	// Has no effect if gradient information is not used.
	// The default value is 1e-6.
	GradientThreshold float64

	// FunctionConverge tests that the function value decreases by a significant
	// amount over the specified number of iterations. If
	//  f < f_best && f_best - f > Relative * maxabs(f, f_best) + Absolute
	// then a significant decrease has occured, and f_best is updated. If there is
	// no significant decrease for Iterations major iterations, FunctionConvergence
	// is returned. If this is nil or if Iterations == 0, it has no effect.
	FunctionConverge *FunctionConverge

	// MajorIterations is the maximum number of iterations allowed.
	// IterationLimit status is returned if the number of major iterations
	// equals or exceeds this value.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	MajorIterations int

	// Runtime is the maximum runtime allowed. RuntimeLimit status is returned
	// if the duration of the run is longer than this value. Runtime is only
	// checked at iterations of the Method.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	Runtime time.Duration

	// FuncEvaluations is the maximum allowed number of function evaluations.
	// FunctionEvaluationLimit status is returned if the total number of calls
	// to Func() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	FuncEvaluations int

	// GradEvaluations is the maximum allowed number of gradient evaluations.
	// GradientEvaluationLimit status is returned if the total number of calls
	// to Grad() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	GradEvaluations int

	// HessEvaluations is the maximum allowed number of Hessian evaluations.
	// HessianEvaluationLimit status is returned if the total number of calls
	// to Hess() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	HessEvaluations int

	Recorder Recorder
}

// DefaultSettings returns a new Settings struct containing the default settings.
func DefaultSettings() *Settings {
	return &Settings{
		GradientThreshold: defaultGradientAbsTol,
		FunctionThreshold: math.Inf(-1),
		Recorder:          NewPrinter(),
		FunctionConverge: &FunctionConverge{
			Absolute:   1e-10,
			Iterations: 20,
		},
	}
}

// resize takes x and returns a slice of length dim. It returns a resliced x
// if cap(x) >= dim, and a new slice otherwise.
func resize(x []float64, dim int) []float64 {
	if dim > cap(x) {
		return make([]float64, dim)
	}
	return x[:dim]
}
<commit_msg>Change formatting of EvaluationType<commit_after>// Copyright ©2014 The gonum 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 optimize

import (
	"errors"
	"fmt"
	"math"
	"time"

	"github.com/gonum/matrix/mat64"
)

const defaultGradientAbsTol = 1e-6

// EvaluationType is used by a Method to specify the objective-function
// information needed at an x location.
type EvaluationType uint

// Evaluation types can be composed together using the binary or operator, for
// example 'FuncEvaluation | GradEvaluation' to evaluate both the function
// value and the gradient.
const (
	NoEvaluation   EvaluationType = 0
	FuncEvaluation EvaluationType = 1 << (iota - 1)
	GradEvaluation
	HessEvaluation
)

func (e EvaluationType) String() string {
	return fmt.Sprintf("EvaluationType(Func: %t, Grad: %t, Hess: %t, Extra: 0b%b)",
		e&FuncEvaluation != 0,
		e&GradEvaluation != 0,
		e&HessEvaluation != 0,
		e&^(FuncEvaluation|GradEvaluation|HessEvaluation))
}

// IterationType specifies the type of iteration.
type IterationType int

const (
	NoIteration IterationType = iota
	MajorIteration
	MinorIteration
	SubIteration
	InitIteration
	PostIteration // Iteration after the optimization. Sent to Recorder.
)

func (i IterationType) String() string {
	if i < 0 || int(i) >= len(iterationStrings) {
		return fmt.Sprintf("IterationType(%d)", i)
	}
	return iterationStrings[i]
}

var iterationStrings = [...]string{
	"NoIteration",
	"MajorIteration",
	"MinorIteration",
	"SubIteration",
	"InitIteration",
	"PostIteration",
}

// Location represents a location in the optimization procedure.
type Location struct {
	X        []float64
	F        float64
	Gradient []float64
	Hessian  *mat64.SymDense
}

// LinesearchLocation is a location for a linesearch subiteration
type LinesearchLocation struct {
	F          float64 // Function value at the step
	Derivative float64 // Projected gradient in the linesearch direction
}

// Result represents the answer of an optimization run. It contains the optimum
// location as well as the Status at convergence and Statistics taken during the
// run.
type Result struct {
	Location
	Stats
	Status Status
}

// Stats contains the statistics of the run.
type Stats struct {
	MajorIterations int           // Total number of major iterations
	FuncEvaluations int           // Number of evaluations of Func()
	GradEvaluations int           // Number of evaluations of Grad()
	HessEvaluations int           // Number of evaluations of Hess()
	Runtime         time.Duration // Total runtime of the optimization
}

// FunctionInfo is data to give to the optimizer about the objective function.
type FunctionInfo struct {
	IsGradient                bool
	IsHessian                 bool
	IsFunctionGradient        bool
	IsFunctionGradientHessian bool
	IsStatuser                bool
}

// functionInfo contains information about which interfaces the objective
// function F implements and the actual methods of F that have been
// successfully type switched.
type functionInfo struct {
	FunctionInfo

	function Function
	gradient Gradient
	hessian  Hessian
	statuser Statuser
}

func newFunctionInfo(f Function) *functionInfo {
	gradient, isGradient := f.(Gradient)
	hessian, isHessian := f.(Hessian)
	statuser, isStatuser := f.(Statuser)

	return &functionInfo{
		FunctionInfo: FunctionInfo{
			IsGradient: isGradient,
			IsHessian:  isHessian,
			IsStatuser: isStatuser,
		},
		function: f,
		gradient: gradient,
		hessian:  hessian,
		statuser: statuser,
	}
}

// TODO(btracey): Think about making this an exported function when the
// constraint interface is designed.
func (f functionInfo) satisfies(method Method) error {
	if method.Needs().Gradient && !f.IsGradient {
		return errors.New("optimize: function does not implement needed Gradient interface")
	}
	if method.Needs().Hessian && !f.IsHessian {
		return errors.New("optimize: function does not implement needed Hessian interface")
	}
	return nil
}

// complementEval returns an evaluation type that evaluates fields of loc not
// evaluated by eval.
func complementEval(loc *Location, eval EvaluationType) (complEval EvaluationType) {
	if eval&FuncEvaluation == 0 {
		complEval = FuncEvaluation
	}
	if loc.Gradient != nil && eval&GradEvaluation == 0 {
		complEval |= GradEvaluation
	}
	if loc.Hessian != nil && eval&HessEvaluation == 0 {
		complEval |= HessEvaluation
	}
	return complEval
}

// Settings represents settings of the optimization run. It contains initial
// settings, convergence information, and Recorder information. In general, users
// should use DefaultSettings() rather than constructing a Settings literal.
//
// If UseInitData is true, InitialValue, InitialGradient and InitialHessian
// specify function information at the initial location.
//
// If Recorder is nil, no information will be recorded.
type Settings struct {
	UseInitialData  bool            // Use supplied information about the conditions at the initial x.
	InitialValue    float64         // Func(x) at the initial x.
	InitialGradient []float64       // Grad(x) at the initial x.
	InitialHessian  *mat64.SymDense // Hess(x) at the initial x.

	// FunctionThreshold is the threshold for acceptably small values of the
	// objective function. FunctionThreshold status is returned if
	// the objective function is less than this value.
	// The default value is -inf.
	FunctionThreshold float64

	// GradientThreshold determines the accuracy to which the minimum is found.
	// GradientThreshold status is returned if the infinity norm of
	// the gradient is less than this value.
	// Has no effect if gradient information is not used.
	// The default value is 1e-6.
	GradientThreshold float64

	// FunctionConverge tests that the function value decreases by a significant
	// amount over the specified number of iterations. If
	//  f < f_best && f_best - f > Relative * maxabs(f, f_best) + Absolute
	// then a significant decrease has occured, and f_best is updated. If there is
	// no significant decrease for Iterations major iterations, FunctionConvergence
	// is returned. If this is nil or if Iterations == 0, it has no effect.
	FunctionConverge *FunctionConverge

	// MajorIterations is the maximum number of iterations allowed.
	// IterationLimit status is returned if the number of major iterations
	// equals or exceeds this value.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	MajorIterations int

	// Runtime is the maximum runtime allowed. RuntimeLimit status is returned
	// if the duration of the run is longer than this value. Runtime is only
	// checked at iterations of the Method.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	Runtime time.Duration

	// FuncEvaluations is the maximum allowed number of function evaluations.
	// FunctionEvaluationLimit status is returned if the total number of calls
	// to Func() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	FuncEvaluations int

	// GradEvaluations is the maximum allowed number of gradient evaluations.
	// GradientEvaluationLimit status is returned if the total number of calls
	// to Grad() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	GradEvaluations int

	// HessEvaluations is the maximum allowed number of Hessian evaluations.
	// HessianEvaluationLimit status is returned if the total number of calls
	// to Hess() equals or exceeds this number.
	// If it equals zero, this setting has no effect.
	// The default value is 0.
	HessEvaluations int

	Recorder Recorder
}

// DefaultSettings returns a new Settings struct containing the default settings.
func DefaultSettings() *Settings {
	return &Settings{
		GradientThreshold: defaultGradientAbsTol,
		FunctionThreshold: math.Inf(-1),
		Recorder:          NewPrinter(),
		FunctionConverge: &FunctionConverge{
			Absolute:   1e-10,
			Iterations: 20,
		},
	}
}

// resize takes x and returns a slice of length dim. It returns a resliced x
// if cap(x) >= dim, and a new slice otherwise.
func resize(x []float64, dim int) []float64 {
	if dim > cap(x) {
		return make([]float64, dim)
	}
	return x[:dim]
}
<|endoftext|>


<commit_before>package gogo

import (
	"net/http"

	"github.com/dolab/httpdispatch"
)

// Handler represents server handlers
type Handler interface {
	http.Handler

	Handle(string, string, httpdispatch.Handle)
	ServeFiles(string, http.FileSystem)
}

// Middleware represents request filters and resource handler
// NOTE: It is the filter's responsibility to invoke ctx.Next() for chainning.
type Middleware func(ctx *Context)

// Render represents HTTP response render
type Render interface {
	ContentType() string
	Render(v interface{}) error
}

// StatusCoder represents HTTP response status code
type StatusCoder interface {
	StatusCode() int
}

// Responser represents HTTP response interface
type Responser interface {
	http.ResponseWriter
	http.Flusher

	Before(filter ResponseFilter) // register before filter
	Size() int                    // return the size of response body
	Status() int                  // response status code
	HeaderFlushed() bool          // whether response header has been sent?
	FlushHeader()                 // send response header
}

// ResponseFilter defines filter interface applied to response
type ResponseFilter func(w Responser, b []byte) []byte

// Logger defines interface of application log apis.
type Logger interface {
	New(requestID string) Logger
	Reuse(log Logger)
	RequestID() string
	SetLevelByName(level string) error
	SetColor(color bool)

	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
}
<commit_msg>What: rename httpdispatch.Handle to httpdispatch.Handler<commit_after>package gogo

import (
	"net/http"

	"github.com/dolab/httpdispatch"
)

// Handler represents server handlers
type Handler interface {
	http.Handler

	Handle(string, string, httpdispatch.Handler)
	ServeFiles(string, http.FileSystem)
}

// Middleware represents request filters and resource handler
// NOTE: It is the filter's responsibility to invoke ctx.Next() for chainning.
type Middleware func(ctx *Context)

// Responser represents HTTP response interface
type Responser interface {
	http.ResponseWriter
	http.Flusher

	Before(filter ResponseFilter) // register before filter
	Size() int                    // return the size of response body
	Status() int                  // response status code
	HeaderFlushed() bool          // whether response header has been sent?
	FlushHeader()                 // send response header
}

// ResponseFilter defines filter interface applied to response
type ResponseFilter func(w Responser, b []byte) []byte

// StatusCoder represents HTTP response status code
// it is useful for custom response data with response status code
type StatusCoder interface {
	StatusCode() int
}

// Render represents HTTP response render
type Render interface {
	ContentType() string
	Render(v interface{}) error
}

// Logger defines interface of application log apis.
type Logger interface {
	New(requestID string) Logger
	Reuse(log Logger)
	RequestID() string
	SetLevelByName(level string) error
	SetColor(color bool)

	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
}
<|endoftext|>