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

// Marshalling and unmarshalling of
// JSON data into Go structs using reflection.

package json

import (
	"fmt"
	"io"
	"os"
	"reflect"
	"strings"
)

type structBuilder struct {
	val reflect.Value

	// if map_ != nil, write val to map_[key] on each change
	map_ *reflect.MapValue
	key  reflect.Value
}

var nobuilder *structBuilder

func isfloat(v reflect.Value) bool {
	switch v.(type) {
	case *reflect.FloatValue, *reflect.Float32Value, *reflect.Float64Value:
		return true
	}
	return false
}

func setfloat(v reflect.Value, f float64) {
	switch v := v.(type) {
	case *reflect.FloatValue:
		v.Set(float(f))
	case *reflect.Float32Value:
		v.Set(float32(f))
	case *reflect.Float64Value:
		v.Set(float64(f))
	}
}

func setint(v reflect.Value, i int64) {
	switch v := v.(type) {
	case *reflect.IntValue:
		v.Set(int(i))
	case *reflect.Int8Value:
		v.Set(int8(i))
	case *reflect.Int16Value:
		v.Set(int16(i))
	case *reflect.Int32Value:
		v.Set(int32(i))
	case *reflect.Int64Value:
		v.Set(int64(i))
	case *reflect.UintValue:
		v.Set(uint(i))
	case *reflect.Uint8Value:
		v.Set(uint8(i))
	case *reflect.Uint16Value:
		v.Set(uint16(i))
	case *reflect.Uint32Value:
		v.Set(uint32(i))
	case *reflect.Uint64Value:
		v.Set(uint64(i))
	}
}

// If updating b.val is not enough to update the original,
// copy a changed b.val out to the original.
func (b *structBuilder) Flush() {
	if b == nil {
		return
	}
	if b.map_ != nil {
		b.map_.SetElem(b.key, b.val)
	}
}

func (b *structBuilder) Int64(i int64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, float64(i))
	} else {
		setint(v, i)
	}
}

func (b *structBuilder) Uint64(i uint64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, float64(i))
	} else {
		setint(v, int64(i))
	}
}

func (b *structBuilder) Float64(f float64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, f)
	} else {
		setint(v, int64(f))
	}
}

func (b *structBuilder) Null() {}

func (b *structBuilder) String(s string) {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.StringValue); ok {
		v.Set(s)
	}
}

func (b *structBuilder) Bool(tf bool) {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.BoolValue); ok {
		v.Set(tf)
	}
}

func (b *structBuilder) Array() {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.SliceValue); ok {
		if v.IsNil() {
			v.Set(reflect.MakeSlice(v.Type().(*reflect.SliceType), 0, 8))
		}
	}
}

func (b *structBuilder) Elem(i int) Builder {
	if b == nil || i < 0 {
		return nobuilder
	}
	switch v := b.val.(type) {
	case *reflect.ArrayValue:
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	case *reflect.SliceValue:
		if i >= v.Cap() {
			n := v.Cap()
			if n < 8 {
				n = 8
			}
			for n <= i {
				n *= 2
			}
			nv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n)
			reflect.ArrayCopy(nv, v)
			v.Set(nv)
		}
		if v.Len() <= i && i < v.Cap() {
			v.SetLen(i + 1)
		}
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	}
	return nobuilder
}

func (b *structBuilder) Map() {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.PtrValue); ok && v.IsNil() {
		if v.IsNil() {
			v.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem()))
			b.Flush()
		}
		b.map_ = nil
		b.val = v.Elem()
	}
	if v, ok := b.val.(*reflect.MapValue); ok && v.IsNil() {
		v.Set(reflect.MakeMap(v.Type().(*reflect.MapType)))
	}
}

func (b *structBuilder) Key(k string) Builder {
	if b == nil {
		return nobuilder
	}
	switch v := reflect.Indirect(b.val).(type) {
	case *reflect.StructValue:
		t := v.Type().(*reflect.StructType)
		// Case-insensitive field lookup.
		k = strings.ToLower(k)
		for i := 0; i < t.NumField(); i++ {
			if strings.ToLower(t.Field(i).Name) == k {
				return &structBuilder{val: v.Field(i)}
			}
		}
	case *reflect.MapValue:
		t := v.Type().(*reflect.MapType)
		if t.Key() != reflect.Typeof(k) {
			break
		}
		key := reflect.NewValue(k)
		elem := v.Elem(key)
		if elem == nil {
			v.SetElem(key, reflect.MakeZero(t.Elem()))
			elem = v.Elem(key)
		}
		return &structBuilder{val: elem, map_: v, key: key}
	}
	return nobuilder
}

// Unmarshal parses the JSON syntax string s and fills in
// an arbitrary struct or slice pointed at by val.
// It uses the reflect package to assign to fields
// and arrays embedded in val.  Well-formed data that does not fit
// into the struct is discarded.
//
// For example, given these definitions:
//
//	type Email struct {
//		Where string;
//		Addr string;
//	}
//
//	type Result struct {
//		Name string;
//		Phone string;
//		Email []Email
//	}
//
//	var r = Result{ "name", "phone", nil }
//
// unmarshalling the JSON syntax string
//
//	{
//	  "email": [
//	    {
//	      "where": "home",
//	      "addr": "gre@example.com"
//	    },
//	    {
//	      "where": "work",
//	      "addr": "gre@work.com"
//	    }
//	  ],
//	  "name": "Grace R. Emlin",
//	  "address": "123 Main Street"
//	}
//
// via Unmarshal(s, &r) is equivalent to assigning
//
//	r = Result{
//		"Grace R. Emlin",	// name
//		"phone",		// no phone given
//		[]Email{
//			Email{ "home", "gre@example.com" },
//			Email{ "work", "gre@work.com" }
//		}
//	}
//
// Note that the field r.Phone has not been modified and
// that the JSON field "address" was discarded.
//
// Because Unmarshal uses the reflect package, it can only
// assign to upper case fields.  Unmarshal uses a case-insensitive
// comparison to match JSON field names to struct field names.
//
// To unmarshal a top-level JSON array, pass in a pointer to an empty
// slice of the correct type.
//
// On success, Unmarshal returns with ok set to true.
// On a syntax error, it returns with ok set to false and errtok
// set to the offending token.
func Unmarshal(s string, val interface{}) (ok bool, errtok string) {
	v := reflect.NewValue(val)
	var b *structBuilder

	// If val is a pointer to a slice, we append to the slice.
	if ptr, ok := v.(*reflect.PtrValue); ok {
		if slice, ok := ptr.Elem().(*reflect.SliceValue); ok {
			b = &structBuilder{val: slice}
		}
	}

	if b == nil {
		b = &structBuilder{val: v}
	}

	ok, _, errtok = Parse(s, b)
	if !ok {
		return false, errtok
	}
	return true, ""
}

type MarshalError struct {
	T reflect.Type
}

func (e *MarshalError) String() string {
	return "json cannot encode value of type " + e.T.String()
}
func writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) os.Error {
	fmt.Fprint(w, "[")

	for i := 0; i < val.Len(); i++ {
		if err := writeValue(w, val.Elem(i)); err != nil {
			return err
		}

		if i < val.Len()-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "]")
	return nil
}

func writeMap(w io.Writer, val *reflect.MapValue) os.Error {
	key := val.Type().(*reflect.MapType).Key()
	if _, ok := key.(*reflect.StringType); !ok {
		return &MarshalError{val.Type()}
	}

	keys := val.Keys()
	fmt.Fprint(w, "{")
	for i := 0; i < len(keys); i++ {
		fmt.Fprintf(w, "%q:", keys[i].(*reflect.StringValue).Get())

		if err := writeValue(w, val.Elem(keys[i])); err != nil {
			return err
		}

		if i < len(keys)-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "}")
	return nil
}

func writeStruct(w io.Writer, val *reflect.StructValue) os.Error {
	fmt.Fprint(w, "{")

	typ := val.Type().(*reflect.StructType)

	for i := 0; i < val.NumField(); i++ {
		fieldValue := val.Field(i)
		fmt.Fprintf(w, "%q:", typ.Field(i).Name)
		writeValue(w, fieldValue)
		if i < val.NumField()-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "}")
	return nil
}

func writeValue(w io.Writer, val reflect.Value) (err os.Error) {
	if val == nil {
		fmt.Fprint(w, "null")
		return
	}

	switch v := val.(type) {
	case *reflect.StringValue:
		fmt.Fprintf(w, "%q", v.Get())
	case *reflect.ArrayValue:
		err = writeArrayOrSlice(w, v)
	case *reflect.SliceValue:
		err = writeArrayOrSlice(w, v)
	case *reflect.MapValue:
		err = writeMap(w, v)
	case *reflect.StructValue:
		err = writeStruct(w, v)
	case *reflect.ChanValue,
		*reflect.PtrValue,
		*reflect.UnsafePointerValue:
		err = &MarshalError{val.Type()}
	case *reflect.InterfaceValue:
		if v.IsNil() {
			fmt.Fprint(w, "null")
		} else {
			err = &MarshalError{val.Type()}
		}
	default:
		value := val.(reflect.Value)
		fmt.Fprint(w, value.Interface())
	}
	return
}

func Marshal(w io.Writer, val interface{}) os.Error {
	return writeValue(w, reflect.NewValue(val))
}
<commit_msg>Check for errors when writing fields of a struct.<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Marshalling and unmarshalling of
// JSON data into Go structs using reflection.

package json

import (
	"fmt"
	"io"
	"os"
	"reflect"
	"strings"
)

type structBuilder struct {
	val reflect.Value

	// if map_ != nil, write val to map_[key] on each change
	map_ *reflect.MapValue
	key  reflect.Value
}

var nobuilder *structBuilder

func isfloat(v reflect.Value) bool {
	switch v.(type) {
	case *reflect.FloatValue, *reflect.Float32Value, *reflect.Float64Value:
		return true
	}
	return false
}

func setfloat(v reflect.Value, f float64) {
	switch v := v.(type) {
	case *reflect.FloatValue:
		v.Set(float(f))
	case *reflect.Float32Value:
		v.Set(float32(f))
	case *reflect.Float64Value:
		v.Set(float64(f))
	}
}

func setint(v reflect.Value, i int64) {
	switch v := v.(type) {
	case *reflect.IntValue:
		v.Set(int(i))
	case *reflect.Int8Value:
		v.Set(int8(i))
	case *reflect.Int16Value:
		v.Set(int16(i))
	case *reflect.Int32Value:
		v.Set(int32(i))
	case *reflect.Int64Value:
		v.Set(int64(i))
	case *reflect.UintValue:
		v.Set(uint(i))
	case *reflect.Uint8Value:
		v.Set(uint8(i))
	case *reflect.Uint16Value:
		v.Set(uint16(i))
	case *reflect.Uint32Value:
		v.Set(uint32(i))
	case *reflect.Uint64Value:
		v.Set(uint64(i))
	}
}

// If updating b.val is not enough to update the original,
// copy a changed b.val out to the original.
func (b *structBuilder) Flush() {
	if b == nil {
		return
	}
	if b.map_ != nil {
		b.map_.SetElem(b.key, b.val)
	}
}

func (b *structBuilder) Int64(i int64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, float64(i))
	} else {
		setint(v, i)
	}
}

func (b *structBuilder) Uint64(i uint64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, float64(i))
	} else {
		setint(v, int64(i))
	}
}

func (b *structBuilder) Float64(f float64) {
	if b == nil {
		return
	}
	v := b.val
	if isfloat(v) {
		setfloat(v, f)
	} else {
		setint(v, int64(f))
	}
}

func (b *structBuilder) Null() {}

func (b *structBuilder) String(s string) {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.StringValue); ok {
		v.Set(s)
	}
}

func (b *structBuilder) Bool(tf bool) {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.BoolValue); ok {
		v.Set(tf)
	}
}

func (b *structBuilder) Array() {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.SliceValue); ok {
		if v.IsNil() {
			v.Set(reflect.MakeSlice(v.Type().(*reflect.SliceType), 0, 8))
		}
	}
}

func (b *structBuilder) Elem(i int) Builder {
	if b == nil || i < 0 {
		return nobuilder
	}
	switch v := b.val.(type) {
	case *reflect.ArrayValue:
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	case *reflect.SliceValue:
		if i >= v.Cap() {
			n := v.Cap()
			if n < 8 {
				n = 8
			}
			for n <= i {
				n *= 2
			}
			nv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n)
			reflect.ArrayCopy(nv, v)
			v.Set(nv)
		}
		if v.Len() <= i && i < v.Cap() {
			v.SetLen(i + 1)
		}
		if i < v.Len() {
			return &structBuilder{val: v.Elem(i)}
		}
	}
	return nobuilder
}

func (b *structBuilder) Map() {
	if b == nil {
		return
	}
	if v, ok := b.val.(*reflect.PtrValue); ok && v.IsNil() {
		if v.IsNil() {
			v.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem()))
			b.Flush()
		}
		b.map_ = nil
		b.val = v.Elem()
	}
	if v, ok := b.val.(*reflect.MapValue); ok && v.IsNil() {
		v.Set(reflect.MakeMap(v.Type().(*reflect.MapType)))
	}
}

func (b *structBuilder) Key(k string) Builder {
	if b == nil {
		return nobuilder
	}
	switch v := reflect.Indirect(b.val).(type) {
	case *reflect.StructValue:
		t := v.Type().(*reflect.StructType)
		// Case-insensitive field lookup.
		k = strings.ToLower(k)
		for i := 0; i < t.NumField(); i++ {
			if strings.ToLower(t.Field(i).Name) == k {
				return &structBuilder{val: v.Field(i)}
			}
		}
	case *reflect.MapValue:
		t := v.Type().(*reflect.MapType)
		if t.Key() != reflect.Typeof(k) {
			break
		}
		key := reflect.NewValue(k)
		elem := v.Elem(key)
		if elem == nil {
			v.SetElem(key, reflect.MakeZero(t.Elem()))
			elem = v.Elem(key)
		}
		return &structBuilder{val: elem, map_: v, key: key}
	}
	return nobuilder
}

// Unmarshal parses the JSON syntax string s and fills in
// an arbitrary struct or slice pointed at by val.
// It uses the reflect package to assign to fields
// and arrays embedded in val.  Well-formed data that does not fit
// into the struct is discarded.
//
// For example, given these definitions:
//
//	type Email struct {
//		Where string;
//		Addr string;
//	}
//
//	type Result struct {
//		Name string;
//		Phone string;
//		Email []Email
//	}
//
//	var r = Result{ "name", "phone", nil }
//
// unmarshalling the JSON syntax string
//
//	{
//	  "email": [
//	    {
//	      "where": "home",
//	      "addr": "gre@example.com"
//	    },
//	    {
//	      "where": "work",
//	      "addr": "gre@work.com"
//	    }
//	  ],
//	  "name": "Grace R. Emlin",
//	  "address": "123 Main Street"
//	}
//
// via Unmarshal(s, &r) is equivalent to assigning
//
//	r = Result{
//		"Grace R. Emlin",	// name
//		"phone",		// no phone given
//		[]Email{
//			Email{ "home", "gre@example.com" },
//			Email{ "work", "gre@work.com" }
//		}
//	}
//
// Note that the field r.Phone has not been modified and
// that the JSON field "address" was discarded.
//
// Because Unmarshal uses the reflect package, it can only
// assign to upper case fields.  Unmarshal uses a case-insensitive
// comparison to match JSON field names to struct field names.
//
// To unmarshal a top-level JSON array, pass in a pointer to an empty
// slice of the correct type.
//
// On success, Unmarshal returns with ok set to true.
// On a syntax error, it returns with ok set to false and errtok
// set to the offending token.
func Unmarshal(s string, val interface{}) (ok bool, errtok string) {
	v := reflect.NewValue(val)
	var b *structBuilder

	// If val is a pointer to a slice, we append to the slice.
	if ptr, ok := v.(*reflect.PtrValue); ok {
		if slice, ok := ptr.Elem().(*reflect.SliceValue); ok {
			b = &structBuilder{val: slice}
		}
	}

	if b == nil {
		b = &structBuilder{val: v}
	}

	ok, _, errtok = Parse(s, b)
	if !ok {
		return false, errtok
	}
	return true, ""
}

type MarshalError struct {
	T reflect.Type
}

func (e *MarshalError) String() string {
	return "json cannot encode value of type " + e.T.String()
}
func writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) os.Error {
	fmt.Fprint(w, "[")

	for i := 0; i < val.Len(); i++ {
		if err := writeValue(w, val.Elem(i)); err != nil {
			return err
		}

		if i < val.Len()-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "]")
	return nil
}

func writeMap(w io.Writer, val *reflect.MapValue) os.Error {
	key := val.Type().(*reflect.MapType).Key()
	if _, ok := key.(*reflect.StringType); !ok {
		return &MarshalError{val.Type()}
	}

	keys := val.Keys()
	fmt.Fprint(w, "{")
	for i := 0; i < len(keys); i++ {
		fmt.Fprintf(w, "%q:", keys[i].(*reflect.StringValue).Get())

		if err := writeValue(w, val.Elem(keys[i])); err != nil {
			return err
		}

		if i < len(keys)-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "}")
	return nil
}

func writeStruct(w io.Writer, val *reflect.StructValue) os.Error {
	fmt.Fprint(w, "{")

	typ := val.Type().(*reflect.StructType)

	for i := 0; i < val.NumField(); i++ {
		fieldValue := val.Field(i)
		fmt.Fprintf(w, "%q:", typ.Field(i).Name)

		if err := writeValue(w, fieldValue); err != nil {
			return err
		}

		if i < val.NumField()-1 {
			fmt.Fprint(w, ",")
		}
	}

	fmt.Fprint(w, "}")
	return nil
}

func writeValue(w io.Writer, val reflect.Value) (err os.Error) {
	if val == nil {
		fmt.Fprint(w, "null")
		return
	}

	switch v := val.(type) {
	case *reflect.StringValue:
		fmt.Fprintf(w, "%q", v.Get())
	case *reflect.ArrayValue:
		err = writeArrayOrSlice(w, v)
	case *reflect.SliceValue:
		err = writeArrayOrSlice(w, v)
	case *reflect.MapValue:
		err = writeMap(w, v)
	case *reflect.StructValue:
		err = writeStruct(w, v)
	case *reflect.ChanValue,
		*reflect.PtrValue,
		*reflect.UnsafePointerValue:
		err = &MarshalError{val.Type()}
	case *reflect.InterfaceValue:
		if v.IsNil() {
			fmt.Fprint(w, "null")
		} else {
			err = &MarshalError{val.Type()}
		}
	default:
		value := val.(reflect.Value)
		fmt.Fprint(w, value.Interface())
	}
	return
}

func Marshal(w io.Writer, val interface{}) os.Error {
	return writeValue(w, reflect.NewValue(val))
}
<|endoftext|>


<commit_before>package cpf

import (
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"strings"

	"github.com/go-chat-bot/bot"
)

const (
	tamanhoCPF                      = 11
	msgParametroInvalido            = "Parâmetro inválido."
	msgQuantidadeParametrosInvalida = "Quantidade de parâmetros inválida."
	msgFmtCpfValido                 = "CPF %s é válido."
	msgFmtCpfInvalido               = "CPF %s é inválido."
)

func cpf(command *bot.Cmd) (string, error) {

	var param string
	switch len(command.Args) {
	case 0:
		param = "1"
	case 1:
		param = command.Args[0]
	default:
		return msgQuantidadeParametrosInvalida, nil

	}

	if len(param) > 2 {
		if valid(param) {
			return fmt.Sprintf(msgFmtCpfValido, command.Args[0]), nil
		}
		return fmt.Sprintf(msgFmtCpfInvalido, command.Args[0]), nil
	}

	qtCPF, err := strconv.Atoi(param)
	if err != nil {
		return msgParametroInvalido, nil
	}

	var cpf string
	for i := 0; i < qtCPF; i++ {
		cpf += gerarCPF() + " "
	}
	return cpf, nil
}

func gerarCPF() string {
	doc := make([]int, 9)
	for i := 0; i < 9; i++ {
		doc[i] = rand.Intn(9)
	}
	dv1 := calcDV(doc)
	doc = append(doc, dv1)
	dv2 := calcDV(doc)
	doc = append(doc, dv2)

	var str string
	for _, value := range doc {
		str += strconv.Itoa(value)
	}
	return str
}

func calcDV(doc []int) int {
	var calc float64
	for i, j := 2, len(doc)-1; j >= 0; i, j = i+1, j-1 {
		calc += float64(i * doc[j])
	}
	mod := int(math.Mod(calc*10, 11))
	if mod == 10 {
		return 0
	}
	return mod
}

func valid(cpf string) bool {
	if len(cpf) != tamanhoCPF {
		return false
	}

	for i := 0; i <= 9; i++ {
		if cpf == strings.Repeat(string(i), 11) {
			return false
		}
	}

	s := strings.Split(cpf, "")

	doc := make([]int, 9)
	for i := 0; i <= 8; i++ {
		digito, err := strconv.Atoi(s[i])
		if err != nil {
			return false
		}
		doc[i] = digito
	}

	dv1 := calcDV(doc)
	doc = append(doc, dv1)
	dv2 := calcDV(doc)

	dv1Valido := strconv.Itoa(dv1) == string(s[9])
	dv2Valido := strconv.Itoa(dv2) == string(s[10])
	return dv1Valido && dv2Valido
}

func init() {
	bot.RegisterCommand(
		"cpf",
		"Gerador/Validador de CPF.",
		"n para gerar n CPF e !cpf 12345678909 para validar um CPF",
		cpf)
}
<commit_msg>using martinusso/go-docs<commit_after>package cpf

import (
	"fmt"
	"strconv"

	"github.com/go-chat-bot/bot"
	cpfHelper "github.com/martinusso/go-docs/cpf"
)

const (
	msgParametroInvalido            = "Parâmetro inválido."
	msgQuantidadeParametrosInvalida = "Quantidade de parâmetros inválida."
	msgFmtCpfValido                 = "CPF %s é válido."
	msgFmtCpfInvalido               = "CPF %s é inválido."
)

func cpf(command *bot.Cmd) (string, error) {

	var param string
	switch len(command.Args) {
	case 0:
		param = "1"
	case 1:
		param = command.Args[0]
	default:
		return msgQuantidadeParametrosInvalida, nil

	}

	if len(param) > 2 {
		if valid(param) {
			return fmt.Sprintf(msgFmtCpfValido, command.Args[0]), nil
		}
		return fmt.Sprintf(msgFmtCpfInvalido, command.Args[0]), nil
	}

	qtCPF, err := strconv.Atoi(param)
	if err != nil {
		return msgParametroInvalido, nil
	}

	var cpf string
	for i := 0; i < qtCPF; i++ {
		cpf += gerarCPF() + " "
	}
	return cpf, nil
}

func gerarCPF() string {
	return cpfHelper.Generate()
}

func valid(cpf string) bool {
	return cpfHelper.Valid(cpf)
}

func init() {
	bot.RegisterCommand(
		"cpf",
		"Gerador/Validador de CPF.",
		"n para gerar n CPF e !cpf 12345678909 para validar um CPF",
		cpf)
}
<|endoftext|>


<commit_before>package brdoc

import (
	"bytes"
	"regexp"
	"strconv"
	"unicode"
)

// IsCPF verifies if the string is a valid CPF document.
func IsCPF(doc string) bool {
	return isCPFOrCNPJ(
		doc,
		ValidateCPFFormat,
		9,
		10, 11,
	)
}

// IsCNPJ verifies if the string is a valid CNPJ document.
func IsCNPJ(doc string) bool {
	return isCPFOrCNPJ(
		doc,
		ValidateCNPJFormat,
		12,
		5, 6,
	)
}

func isCPFOrCNPJ(doc string, validate func(string) bool, size int, pos1, pos2 int) bool {

	if !validate(doc) {
		return false
	}

	// Removes special characters.
	doc = clean(doc)

	// Calculates the first digit.
	d := doc[:size]
	digit := calculateDigit(d, pos1)

	// Calculates the second digit.
	d = d + digit
	digit = calculateDigit(d, pos2)

	return doc == d+digit
}

// ValidateCPFFormat verifies if the CPF has a valid format.
func ValidateCPFFormat(doc string) bool {
	return validateFormat("^\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}$", doc,
		"^000\\.?000\\.?000-?00$",
		"^111\\.?111\\.?111-?11$",
		"^222\\.?222\\.?222-?22$",
		"^333\\.?333\\.?333-?33$",
		"^444\\.?444\\.?444-?44$",
		"^555\\.?555\\.?555-?55$",
		"^666\\.?666\\.?666-?66$",
		"^777\\.?777\\.?777-?77$",
		"^888\\.?888\\.?888-?88$",
		"^999\\.?999\\.?999-?99$")
}

// ValidateCNPJFormat verifies if the CNPJ has a valid format.
func ValidateCNPJFormat(doc string) bool {
	return validateFormat("^\\d{2}\\.?\\d{3}\\.?\\d{3}\\/?\\d{4}-?\\d{2}$", doc,
		"^\\d{2}\\.?\\d{3}\\.?\\d{3}\\/?0000-?\\d{2}$",
		"^11\\.?111\\.?111\\/?1111-?11$",
		"^22\\.?222\\.?222\\/?2222-?22$",
		"^33\\.?333\\.?333\\/?3333-?33$",
		"^44\\.?444\\.?444\\/?4444-?44$",
		"^55\\.?555\\.?555\\/?5555-?55$",
		"^66\\.?666\\.?666\\/?6666-?66$",
		"^77\\.?777\\.?777\\/?7777-?77$",
		"^88\\.?888\\.?888\\/?8888-?88$",
		"^99\\.?999\\.?999\\/?9999-?99$")
}

func validateFormat(pattern, doc string, invalid ...string) bool {
	for _, p := range invalid {
		if ok, err := regexp.MatchString(p, doc); err != nil || ok {
			return false
		}
	}
	ok, err := regexp.MatchString(pattern, doc)
	return err == nil && ok
}

func clean(doc string) string {

	buf := bytes.NewBufferString("")
	for _, r := range doc {
		if unicode.IsDigit(r) {
			buf.WriteRune(r)
		}
	}

	return buf.String()
}

func calculateDigit(doc string, positions int) string {
	sum := 0

	// Sums all the digits in the document.
	// Ex.
	//   3    4    2    6    1    8    7    1    0
	// x10   x9   x8   x7   x6   x5   x4   x3   x2
	//  30 + 36 + 16 + 42 +  6 + 40 + 28 +  3 +  0 = 201
	for i := 0; i < len(doc); i++ {
		digit, _ := strconv.Atoi(string(doc[i]))

		sum += int(digit) * positions
		positions--

		if positions < 2 {
			positions = 9
		}
	}

	sum %= 11
	if sum < 2 {
		return "0"
	}
	return strconv.Itoa(11 - sum)
}
<commit_msg>Stupidly faster.<commit_after>package brdoc

import (
	"bytes"
	"regexp"
	"strconv"
	"unicode"
)

// IsCPF verifies if the string is a valid CPF document.
func IsCPF(doc string) bool {
	return isCPFOrCNPJ(
		doc,
		ValidateCPFFormat,
		9,
		10, 11,
	)
}

// IsCNPJ verifies if the string is a valid CNPJ document.
func IsCNPJ(doc string) bool {
	return isCPFOrCNPJ(
		doc,
		ValidateCNPJFormat,
		12,
		5, 6,
	)
}

func isCPFOrCNPJ(doc string, validate func(string) bool, size int, pos1, pos2 int) bool {

	if !validate(doc) {
		return false
	}

	// Removes special characters.
	clean(&doc)

	// Invalidates documents with all
	// digits equal.
	if allEq(doc) {
		return false
	}

	// Calculates the first digit.
	d := doc[:size]
	digit := calculateDigit(d, pos1)

	// Calculates the second digit.
	d = d + digit
	digit = calculateDigit(d, pos2)

	return doc == d+digit
}

// ValidateCPFFormat verifies if the CPF has a valid format.
func ValidateCPFFormat(doc string) bool {

	const (
		pattern = `^\d{3}\.?\d{3}\.?\d{3}-?\d{2}$`
	)

	return regexp.MustCompile(pattern).MatchString(doc)
}

// ValidateCNPJFormat verifies if the CNPJ has a valid format.
func ValidateCNPJFormat(doc string) bool {

	const (
		pattern = `^\d{2}\.?\d{3}\.?\d{3}\/?(:?\d{3}[1-9]|\d{2}[1-9]\d|\d[1-9]\d{2}|[1-9]\d{3})-?\d{2}$`
	)

	return regexp.MustCompile(pattern).MatchString(doc)
}

func clean(doc *string) {

	buf := bytes.NewBufferString("")
	for _, r := range *doc {
		if unicode.IsDigit(r) {
			buf.WriteRune(r)
		}
	}

	*doc = buf.String()
}

func allEq(doc string) bool {

	if len(doc) == 0 {
		return true
	}

	base := doc[0]
	for i := 1; i < len(doc); i++ {
		if base != doc[i] {
			return false
		}
	}

	return true
}

func calculateDigit(doc string, positions int) string {
	sum := 0

	// Sums all the digits in the document.
	// Ex.
	//   3    4    2    6    1    8    7    1    0
	// x10   x9   x8   x7   x6   x5   x4   x3   x2
	//  30 + 36 + 16 + 42 +  6 + 40 + 28 +  3 +  0 = 201
	for i := 0; i < len(doc); i++ {
		digit, _ := strconv.Atoi(string(doc[i]))

		sum += int(digit) * positions
		positions--

		if positions < 2 {
			positions = 9
		}
	}

	sum %= 11
	if sum < 2 {
		return "0"
	}
	return strconv.Itoa(11 - sum)
}
<|endoftext|>


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

package main

import (
	"flag"
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// TODO: Check CPU performance governor before each benchmark.

// TODO: Mode to prioritize commits around big performance changes.

// TODO: Support running pre-built binaries without specific hashes.
// This is useful for testing things that aren't yet committed or that
// require unusual build steps.

var run struct {
	order      string
	topLevel   string
	benchFlags string
	buildCmd   string
	iterations int
	goverSave  bool
}

var cmdRunFlags = flag.NewFlagSet(os.Args[0]+" run", flag.ExitOnError)

func init() {
	f := cmdRunFlags
	f.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s run [flags] <revision range>\n", os.Args[0])
		f.PrintDefaults()
	}
	f.StringVar(&run.order, "order", "seq", "run benchmarks in `order`, which must be one of: seq, spread")
	f.StringVar(&gitDir, "C", "", "run git in `dir`")
	f.StringVar(&run.benchFlags, "benchflags", "", "pass `flags` to benchmark")
	f.StringVar(&run.buildCmd, "buildcmd", "go test -c", "build benchmark using \"`cmd` -o <bin>\"")
	f.IntVar(&run.iterations, "n", 5, "run each benchmark `N` times")
	f.StringVar(&outDir, "o", "", "write binaries and logs to `directory`")
	f.BoolVar(&run.goverSave, "gover-save", false, "save toolchain builds with gover")
	f.BoolVar(&dryRun, "dry-run", false, "print commands but do not run them")
	registerSubcommand("run", "[flags] <revision range> - run benchmarks", cmdRun, f)
}

func cmdRun() {
	if cmdRunFlags.NArg() < 1 {
		cmdRunFlags.Usage()
		os.Exit(2)
	}

	var pickCommit func([]*commitInfo) *commitInfo
	switch run.order {
	case "seq":
		pickCommit = pickCommitSeq
	case "spread":
		pickCommit = pickCommitSpread
	default:
		fmt.Fprintf(os.Stderr, "unknown order: %s\n", run.order)
		cmdRunFlags.Usage()
		os.Exit(2)
	}

	commits := getCommits(cmdRunFlags.Args())

	// Get other git information.
	run.topLevel = trimNL(git("rev-parse", "--show-toplevel"))

	status := NewStatusReporter()
	defer status.Stop()

	for {
		doneIters, totalIters, partialCommits, doneCommits, failedCommits := runStats(commits)
		unstartedCommits := len(commits) - (partialCommits + doneCommits + failedCommits)
		msg := fmt.Sprintf("%d/%d runs, %d unstarted+%d partial+%d done+%d failed commits", doneIters, totalIters, unstartedCommits, partialCommits, doneCommits, failedCommits)
		// TODO: Count builds and runs separately.
		status.Progress(msg, float64(doneIters)/float64(totalIters))

		commit := pickCommit(commits)
		if commit == nil {
			break
		}
		runBenchmark(commit, status)
	}
}

func runStats(commits []*commitInfo) (doneIters, totalIters, partialCommits, doneCommits, failedCommits int) {
	for _, c := range commits {
		if c.count >= run.iterations {
			// Don't care if it failed.
			doneIters += c.count
			totalIters += c.count
		} else if c.runnable() {
			doneIters += c.count
			totalIters += run.iterations
		}

		if c.count == run.iterations {
			doneCommits++
		} else if c.runnable() {
			if c.count != 0 {
				partialCommits++
			}
		} else {
			failedCommits++
		}
	}
	return
}

// pickCommitSeq picks the next commit to run based on the most recent
// commit with the fewest iterations.
func pickCommitSeq(commits []*commitInfo) *commitInfo {
	var minCommit *commitInfo
	for _, commit := range commits {
		if !commit.runnable() {
			continue
		}
		if minCommit == nil || commit.count < minCommit.count {
			minCommit = commit
		}
	}
	return minCommit
}

// pickCommitSpread picks the next commit to run from commits using an
// algorithm that spreads out the runs.
func pickCommitSpread(commits []*commitInfo) *commitInfo {
	// Assign weights to each commit. This is thoroughly
	// heuristic, but it's geared toward either increasing the
	// iteration count of commits that we have, or picking a new
	// commit so as to spread out the commits we have.
	weights := make([]int, len(commits))
	totalWeight := 0

	nPartial := 0
	for _, commit := range commits {
		if commit.partial() {
			nPartial++
		}
	}
	if nPartial >= len(commits)/10 {
		// Limit the number of partially completed revisions
		// to 10% by only choosing a partial commit in this
		// case.
		for i, commit := range commits {
			if commit.partial() {
				// Bias toward commits that are
				// further from done.
				weights[i] = run.iterations - commit.count
			}
		}
	} else {
		// Pick a new commit weighted by its distance from a
		// commit that we already have.

		// Find distance from left to right.
		distance := len(commits)
		haveAny := false
		for i, commit := range commits {
			if commit.count > 0 {
				distance = 1
				haveAny = true
			} else if commit.runnable() {
				distance++
			}
			weights[i] = distance
		}

		// Find distance from right to left.
		distance = len(commits)
		for i := len(commits) - 1; i >= 0; i-- {
			commit := commits[i]
			if commit.count > 0 {
				distance = 1
			} else if commit.runnable() {
				distance++
			}

			if distance < weights[i] {
				weights[i] = distance
			}
		}

		if !haveAny {
			// We don't have any commits. Pick one uniformly.
			for i := range commits {
				weights[i] = 1
			}
		}

		// Zero non-runnable commits.
		for i, commit := range commits {
			if !commit.runnable() {
				weights[i] = 0
			}
		}
	}

	for _, w := range weights {
		totalWeight += w
	}
	if totalWeight == 0 {
		return nil
	}

	// Pick a commit based on the weights.
	x := rand.Intn(totalWeight)
	cumulative := 0
	for i, w := range weights {
		cumulative += w
		if cumulative > x {
			return commits[i]
		}
	}
	panic("unreachable")
}

// runBenchmark runs the benchmark at commit. It updates commit.count,
// commit.fails, and commit.buildFailed as appropriate and writes to
// the commit log to record the outcome.
func runBenchmark(commit *commitInfo, status *StatusReporter) {
	isXBenchmark := false
	if abs, _ := os.Getwd(); strings.HasSuffix(abs, "golang.org/x/benchmarks/bench") {
		isXBenchmark = true
	}

	// Build the benchmark if necessary.
	if !exists(commit.binPath) {
		runStatus(status, commit, "building")

		// Check out the appropriate commit. This is necessary
		// even if we're using gover because the benchmark
		// itself might have changed (e.g., bug fixes).
		git("checkout", "-q", commit.hash)

		var buildCmd []string
		if commit.gover {
			// TODO: It would be better if gover took a
			// long hash and did the right thing.
			buildCmd = []string{"gover", "run", commit.hash[:7]}
		} else {
			// If this is the Go toolchain, do a full
			// make.bash. Otherwise, we assume that go
			// test -c will build the necessary
			// dependencies.
			if exists(filepath.Join(run.topLevel, "src", "make.bash")) {
				cmd := exec.Command("./make.bash")
				cmd.Dir = filepath.Join(run.topLevel, "src")
				if dryRun {
					dryPrint(cmd)
				} else if out, err := cmd.CombinedOutput(); err != nil {
					detail := indent(string(out)) + indent(err.Error())
					fmt.Fprintf(os.Stderr, "failed to build toolchain at %s:\n%s", commit.hash, detail)
					commit.buildFailed = true
					commit.writeLog([]byte("BUILD FAILED:\n" + detail))
					return
				}
				if run.goverSave && doGoverSave() == nil {
					commit.gover = true
				}
			}
			// Assume build command is in $PATH.
			//
			// TODO: Force PATH if we built the toolchain.
			buildCmd = []string{}
		}

		if isXBenchmark {
			buildCmd = append(buildCmd, "go", "build", "-o", commit.binPath)
		} else {
			buildCmd = append(buildCmd, strings.Fields(run.buildCmd)...)
			buildCmd = append(buildCmd, "-o", commit.binPath)
		}
		cmd := exec.Command(buildCmd[0], buildCmd[1:]...)
		if dryRun {
			dryPrint(cmd)
		} else if out, err := cmd.CombinedOutput(); err != nil {
			detail := indent(string(out)) + indent(err.Error())
			fmt.Fprintf(os.Stderr, "failed to build tests at %s:\n%s", commit.hash, detail)
			commit.buildFailed = true
			commit.writeLog([]byte("BUILD FAILED:\n" + detail))
			return
		}
	}

	// Run the benchmark.
	runStatus(status, commit, "running")
	var args []string
	if isXBenchmark {
		args = []string{}
	} else {
		args = []string{"-test.run", "NONE", "-test.bench", "."}
	}
	args = append(args, strings.Fields(run.benchFlags)...)
	name := commit.binPath
	if filepath.Base(name) == name {
		// Make exec.Command treat this as a relative path.
		name = "./" + name
	}
	cmd := exec.Command(name, args...)
	if dryRun {
		dryPrint(cmd)
		commit.count++
		return
	}
	out, err := cmd.CombinedOutput()
	if err == nil {
		commit.count++
	} else {
		fmt.Fprintf(os.Stderr, "failed to run benchmark at %s:\n%s", commit.hash, out)
		commit.fails++
		// Indent the output so we don't get confused by
		// benchmarks in it or "PASS" lines.
		out = []byte("FAILED:\n" + indent(string(out)) + indent(err.Error()))
	}

	// Write the benchmark output.
	commit.writeLog(out)
}

func doGoverSave() error {
	cmd := exec.Command("gover", "save")
	cmd.Dir = run.topLevel
	if dryRun {
		dryPrint(cmd)
		return nil
	} else {
		out, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "gover save failed: %s:\n%s", err, indent(string(out)))
		}
		return err
	}
}

// runStatus updates the status message for commit.
func runStatus(sr *StatusReporter, commit *commitInfo, status string) {
	sr.Message(fmt.Sprintf("commit %s, iteration %d/%d: %s...", commit.hash[:7], commit.count+1, run.iterations, status))
}
<commit_msg>benchmany: move x/benchmarks logic to flag defaults<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// TODO: Check CPU performance governor before each benchmark.

// TODO: Mode to prioritize commits around big performance changes.

// TODO: Support running pre-built binaries without specific hashes.
// This is useful for testing things that aren't yet committed or that
// require unusual build steps.

var run struct {
	order      string
	topLevel   string
	benchFlags string
	buildCmd   string
	iterations int
	goverSave  bool
}

var cmdRunFlags = flag.NewFlagSet(os.Args[0]+" run", flag.ExitOnError)

func init() {
	isXBenchmark := false
	if abs, _ := os.Getwd(); strings.HasSuffix(abs, "golang.org/x/benchmarks/bench") {
		isXBenchmark = true
	}

	f := cmdRunFlags
	f.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s run [flags] <revision range>\n", os.Args[0])
		f.PrintDefaults()
	}
	f.StringVar(&run.order, "order", "seq", "run benchmarks in `order`, which must be one of: seq, spread")
	f.StringVar(&gitDir, "C", "", "run git in `dir`")
	defaultBenchFlags := "-test.run NONE -test.bench ."
	if isXBenchmark {
		defaultBenchFlags = ""
	}
	f.StringVar(&run.benchFlags, "benchflags", defaultBenchFlags, "pass `flags` to benchmark")
	defaultBuildCmd := "go test -c"
	if isXBenchmark {
		defaultBuildCmd = "go build"
	}
	f.StringVar(&run.buildCmd, "buildcmd", defaultBuildCmd, "build benchmark using \"`cmd` -o <bin>\"")
	f.IntVar(&run.iterations, "n", 5, "run each benchmark `N` times")
	f.StringVar(&outDir, "o", "", "write binaries and logs to `directory`")
	f.BoolVar(&run.goverSave, "gover-save", false, "save toolchain builds with gover")
	f.BoolVar(&dryRun, "dry-run", false, "print commands but do not run them")
	registerSubcommand("run", "[flags] <revision range> - run benchmarks", cmdRun, f)
}

func cmdRun() {
	if cmdRunFlags.NArg() < 1 {
		cmdRunFlags.Usage()
		os.Exit(2)
	}

	var pickCommit func([]*commitInfo) *commitInfo
	switch run.order {
	case "seq":
		pickCommit = pickCommitSeq
	case "spread":
		pickCommit = pickCommitSpread
	default:
		fmt.Fprintf(os.Stderr, "unknown order: %s\n", run.order)
		cmdRunFlags.Usage()
		os.Exit(2)
	}

	commits := getCommits(cmdRunFlags.Args())

	// Get other git information.
	run.topLevel = trimNL(git("rev-parse", "--show-toplevel"))

	status := NewStatusReporter()
	defer status.Stop()

	for {
		doneIters, totalIters, partialCommits, doneCommits, failedCommits := runStats(commits)
		unstartedCommits := len(commits) - (partialCommits + doneCommits + failedCommits)
		msg := fmt.Sprintf("%d/%d runs, %d unstarted+%d partial+%d done+%d failed commits", doneIters, totalIters, unstartedCommits, partialCommits, doneCommits, failedCommits)
		// TODO: Count builds and runs separately.
		status.Progress(msg, float64(doneIters)/float64(totalIters))

		commit := pickCommit(commits)
		if commit == nil {
			break
		}
		runBenchmark(commit, status)
	}
}

func runStats(commits []*commitInfo) (doneIters, totalIters, partialCommits, doneCommits, failedCommits int) {
	for _, c := range commits {
		if c.count >= run.iterations {
			// Don't care if it failed.
			doneIters += c.count
			totalIters += c.count
		} else if c.runnable() {
			doneIters += c.count
			totalIters += run.iterations
		}

		if c.count == run.iterations {
			doneCommits++
		} else if c.runnable() {
			if c.count != 0 {
				partialCommits++
			}
		} else {
			failedCommits++
		}
	}
	return
}

// pickCommitSeq picks the next commit to run based on the most recent
// commit with the fewest iterations.
func pickCommitSeq(commits []*commitInfo) *commitInfo {
	var minCommit *commitInfo
	for _, commit := range commits {
		if !commit.runnable() {
			continue
		}
		if minCommit == nil || commit.count < minCommit.count {
			minCommit = commit
		}
	}
	return minCommit
}

// pickCommitSpread picks the next commit to run from commits using an
// algorithm that spreads out the runs.
func pickCommitSpread(commits []*commitInfo) *commitInfo {
	// Assign weights to each commit. This is thoroughly
	// heuristic, but it's geared toward either increasing the
	// iteration count of commits that we have, or picking a new
	// commit so as to spread out the commits we have.
	weights := make([]int, len(commits))
	totalWeight := 0

	nPartial := 0
	for _, commit := range commits {
		if commit.partial() {
			nPartial++
		}
	}
	if nPartial >= len(commits)/10 {
		// Limit the number of partially completed revisions
		// to 10% by only choosing a partial commit in this
		// case.
		for i, commit := range commits {
			if commit.partial() {
				// Bias toward commits that are
				// further from done.
				weights[i] = run.iterations - commit.count
			}
		}
	} else {
		// Pick a new commit weighted by its distance from a
		// commit that we already have.

		// Find distance from left to right.
		distance := len(commits)
		haveAny := false
		for i, commit := range commits {
			if commit.count > 0 {
				distance = 1
				haveAny = true
			} else if commit.runnable() {
				distance++
			}
			weights[i] = distance
		}

		// Find distance from right to left.
		distance = len(commits)
		for i := len(commits) - 1; i >= 0; i-- {
			commit := commits[i]
			if commit.count > 0 {
				distance = 1
			} else if commit.runnable() {
				distance++
			}

			if distance < weights[i] {
				weights[i] = distance
			}
		}

		if !haveAny {
			// We don't have any commits. Pick one uniformly.
			for i := range commits {
				weights[i] = 1
			}
		}

		// Zero non-runnable commits.
		for i, commit := range commits {
			if !commit.runnable() {
				weights[i] = 0
			}
		}
	}

	for _, w := range weights {
		totalWeight += w
	}
	if totalWeight == 0 {
		return nil
	}

	// Pick a commit based on the weights.
	x := rand.Intn(totalWeight)
	cumulative := 0
	for i, w := range weights {
		cumulative += w
		if cumulative > x {
			return commits[i]
		}
	}
	panic("unreachable")
}

// runBenchmark runs the benchmark at commit. It updates commit.count,
// commit.fails, and commit.buildFailed as appropriate and writes to
// the commit log to record the outcome.
func runBenchmark(commit *commitInfo, status *StatusReporter) {
	// Build the benchmark if necessary.
	if !exists(commit.binPath) {
		runStatus(status, commit, "building")

		// Check out the appropriate commit. This is necessary
		// even if we're using gover because the benchmark
		// itself might have changed (e.g., bug fixes).
		git("checkout", "-q", commit.hash)

		var buildCmd []string
		if commit.gover {
			// TODO: It would be better if gover took a
			// long hash and did the right thing.
			buildCmd = []string{"gover", "run", commit.hash[:7]}
		} else {
			// If this is the Go toolchain, do a full
			// make.bash. Otherwise, we assume that go
			// test -c will build the necessary
			// dependencies.
			if exists(filepath.Join(run.topLevel, "src", "make.bash")) {
				cmd := exec.Command("./make.bash")
				cmd.Dir = filepath.Join(run.topLevel, "src")
				if dryRun {
					dryPrint(cmd)
				} else if out, err := cmd.CombinedOutput(); err != nil {
					detail := indent(string(out)) + indent(err.Error())
					fmt.Fprintf(os.Stderr, "failed to build toolchain at %s:\n%s", commit.hash, detail)
					commit.buildFailed = true
					commit.writeLog([]byte("BUILD FAILED:\n" + detail))
					return
				}
				if run.goverSave && doGoverSave() == nil {
					commit.gover = true
				}
			}
			// Assume build command is in $PATH.
			//
			// TODO: Force PATH if we built the toolchain.
			buildCmd = []string{}
		}

		buildCmd = append(buildCmd, strings.Fields(run.buildCmd)...)
		buildCmd = append(buildCmd, "-o", commit.binPath)
		cmd := exec.Command(buildCmd[0], buildCmd[1:]...)
		if dryRun {
			dryPrint(cmd)
		} else if out, err := cmd.CombinedOutput(); err != nil {
			detail := indent(string(out)) + indent(err.Error())
			fmt.Fprintf(os.Stderr, "failed to build tests at %s:\n%s", commit.hash, detail)
			commit.buildFailed = true
			commit.writeLog([]byte("BUILD FAILED:\n" + detail))
			return
		}
	}

	// Run the benchmark.
	runStatus(status, commit, "running")
	name := commit.binPath
	if filepath.Base(name) == name {
		// Make exec.Command treat this as a relative path.
		name = "./" + name
	}
	cmd := exec.Command(name, strings.Fields(run.benchFlags)...)
	if dryRun {
		dryPrint(cmd)
		commit.count++
		return
	}
	out, err := cmd.CombinedOutput()
	if err == nil {
		commit.count++
	} else {
		fmt.Fprintf(os.Stderr, "failed to run benchmark at %s:\n%s", commit.hash, out)
		commit.fails++
		// Indent the output so we don't get confused by
		// benchmarks in it or "PASS" lines.
		out = []byte("FAILED:\n" + indent(string(out)) + indent(err.Error()))
	}

	// Write the benchmark output.
	commit.writeLog(out)
}

func doGoverSave() error {
	cmd := exec.Command("gover", "save")
	cmd.Dir = run.topLevel
	if dryRun {
		dryPrint(cmd)
		return nil
	} else {
		out, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "gover save failed: %s:\n%s", err, indent(string(out)))
		}
		return err
	}
}

// runStatus updates the status message for commit.
func runStatus(sr *StatusReporter, commit *commitInfo, status string) {
	sr.Message(fmt.Sprintf("commit %s, iteration %d/%d: %s...", commit.hash[:7], commit.count+1, run.iterations, status))
}
<|endoftext|>


<commit_before>package main

//
// Copyright @ 2015 Tony Asleson <tasleson@redhat.com>
// License: Apache License Version 2.0, see:
// http://www.apache.org/licenses/LICENSE-2.0.html
//
// Note: My very first exposure to golang, so this is probably could be done
// much better.

import (
	"errors"
	"fmt"
	"github.com/runner-mei/gowbem"
	"net"
	"net/url"
	"os"
	"strconv"
	"strings"
)

func getArrayUri(url_in, user, password string) *url.URL {

	// TODO Use a regular expression to really validate the url.
	r := strings.Split(url_in, "://")

	if len(r) != 2 {
		Bail(5, fmt.Sprintf("Invalid URL (%s)", url_in))
	}

	scheme := "http"

	if r[0] == "https" {
		scheme = "https"
	}

	return &url.URL{
		Scheme: scheme,
		User:   url.UserPassword(user, password),
		Host:   r[1],
		Path:   "/",
	}
}

func Bail(ec int, args ...interface{}) {
	fmt.Printf("%s", fmt.Sprintln(args...))
	os.Exit(ec)
}

func HostAvailable(host string) {
	// Lets try to establish a socket to the host and port for some additional
	// diagnostics
	conn, err := net.Dial("tcp", host)
	if nil != err {
		Bail(4, "Host down or port not open! ", host)
	}
	conn.Close()
}

func GetRps(c *gowbem.ClientCIMXML) (gowbem.CIMInstanceWithName, string, error) {

	name_spaces := [...]string{"interop", "root/interop", "root/PG_Interop"}

	for _, ns := range name_spaces {
		instances, e := c.EnumerateInstances(ns, "CIM_RegisteredProfile",
			false, false, false, false, nil)
		if nil != e {
			// At the moment the gowbem library just returns the XML from the
			// failed operation, we will look through it for likely causes
			// until the library can handle this better.
			if strings.Contains(e.Error(), "CIM_ERR_ACCESS_DENIED") {
				Bail(2, "Incorrect credentials!")
			} else if strings.Contains(e.Error(), "CIM_ERR_INVALID_NAMESPACE") {
				// Expected error at times.
				continue
			} else {
				fmt.Printf("Enumerate instances ns=(%s) result(%s)", ns, e)
			}
			continue
		}

		if instances != nil && len(instances) > 0 {
			for _, inst := range instances {
				prop := inst.GetInstance().GetPropertyByName("RegisteredOrganization")

				v := prop.GetValue()
				t := prop.GetType()

				if t.GetType() == gowbem.UINT16 {
					t_int_val, e := strconv.Atoi(v.(string))

					if nil != e {
						Bail(5, e)
					}

					if t_int_val == 11 {
						reg_name := inst.GetInstance().GetPropertyByName("RegisteredName")

						if nil != reg_name {
							if "Array" == inst.GetInstance().GetPropertyByName("RegisteredName").GetValue().(string) {
								return inst, ns, nil
							}
						}
					}
				}
			}
		}
	}

	return nil, "", errors.New("Provider does not apprear to support interop or username/password incorrect")
}

func main() {
	if len(os.Args) != 4 {
		fmt.Printf("Usage: %s <url> <username> <password>\n", os.Args[0])
		fmt.Printf("   eg. %s https://127.0.0.1:5989 someuser uber_secret\n", os.Args[0])
		fmt.Printf("Source: https://github.com/tasleson/smisping\n")
		os.Exit(10)
	}

	connection_info := getArrayUri(os.Args[1], os.Args[2], os.Args[3])

	// Lets see if we can establish a socket to the one supplied.
	HostAvailable(connection_info.Host)

	c, e := gowbem.NewClientCIMXML(connection_info, true)

	if nil != e {
		Bail(5, e)
	}

	item, namespace, e := GetRps(c)
	if nil != e {
		Bail(3, e)
	}

	systems, e := c.AssociatorInstances(
		namespace, item.GetName(),
		"CIM_ElementConformsToProfile", "CIM_ComputerSystem", "", "",
		false, nil)

	if nil != e {
		Bail(5, e)
	}

	if len(systems) > 0 {
		fmt.Printf("Found %d system(s)\n", len(systems))
		os.Exit(0)
	}
	fmt.Printf("No systems found\n")
	os.Exit(1)
}
<commit_msg>fix comment language<commit_after>package main

//
// Copyright @ 2015 Tony Asleson <tasleson@redhat.com>
// License: Apache License Version 2.0, see:
// http://www.apache.org/licenses/LICENSE-2.0.html
//
// Note: My very first exposure to golang, so this probably could be done
// much better.

import (
	"errors"
	"fmt"
	"github.com/runner-mei/gowbem"
	"net"
	"net/url"
	"os"
	"strconv"
	"strings"
)

func getArrayUri(url_in, user, password string) *url.URL {

	// TODO Use a regular expression to really validate the url.
	r := strings.Split(url_in, "://")

	if len(r) != 2 {
		Bail(5, fmt.Sprintf("Invalid URL (%s)", url_in))
	}

	scheme := "http"

	if r[0] == "https" {
		scheme = "https"
	}

	return &url.URL{
		Scheme: scheme,
		User:   url.UserPassword(user, password),
		Host:   r[1],
		Path:   "/",
	}
}

func Bail(ec int, args ...interface{}) {
	fmt.Printf("%s", fmt.Sprintln(args...))
	os.Exit(ec)
}

func HostAvailable(host string) {
	// Lets try to establish a socket to the host and port for some additional
	// diagnostics
	conn, err := net.Dial("tcp", host)
	if nil != err {
		Bail(4, "Host down or port not open! ", host)
	}
	conn.Close()
}

func GetRps(c *gowbem.ClientCIMXML) (gowbem.CIMInstanceWithName, string, error) {

	name_spaces := [...]string{"interop", "root/interop", "root/PG_Interop"}

	for _, ns := range name_spaces {
		instances, e := c.EnumerateInstances(ns, "CIM_RegisteredProfile",
			false, false, false, false, nil)
		if nil != e {
			// At the moment the gowbem library just returns the XML from the
			// failed operation, we will look through it for likely causes
			// until the library can handle this better.
			if strings.Contains(e.Error(), "CIM_ERR_ACCESS_DENIED") {
				Bail(2, "Incorrect credentials!")
			} else if strings.Contains(e.Error(), "CIM_ERR_INVALID_NAMESPACE") {
				// Expected error at times.
				continue
			} else {
				fmt.Printf("Enumerate instances ns=(%s) result(%s)", ns, e)
			}
			continue
		}

		if instances != nil && len(instances) > 0 {
			for _, inst := range instances {
				prop := inst.GetInstance().GetPropertyByName("RegisteredOrganization")

				v := prop.GetValue()
				t := prop.GetType()

				if t.GetType() == gowbem.UINT16 {
					t_int_val, e := strconv.Atoi(v.(string))

					if nil != e {
						Bail(5, e)
					}

					if t_int_val == 11 {
						reg_name := inst.GetInstance().GetPropertyByName("RegisteredName")

						if nil != reg_name {
							if "Array" == inst.GetInstance().GetPropertyByName("RegisteredName").GetValue().(string) {
								return inst, ns, nil
							}
						}
					}
				}
			}
		}
	}

	return nil, "", errors.New("Provider does not apprear to support interop or username/password incorrect")
}

func main() {
	if len(os.Args) != 4 {
		fmt.Printf("Usage: %s <url> <username> <password>\n", os.Args[0])
		fmt.Printf("   eg. %s https://127.0.0.1:5989 someuser uber_secret\n", os.Args[0])
		fmt.Printf("Source: https://github.com/tasleson/smisping\n")
		os.Exit(10)
	}

	connection_info := getArrayUri(os.Args[1], os.Args[2], os.Args[3])

	// Lets see if we can establish a socket to the one supplied.
	HostAvailable(connection_info.Host)

	c, e := gowbem.NewClientCIMXML(connection_info, true)

	if nil != e {
		Bail(5, e)
	}

	item, namespace, e := GetRps(c)
	if nil != e {
		Bail(3, e)
	}

	systems, e := c.AssociatorInstances(
		namespace, item.GetName(),
		"CIM_ElementConformsToProfile", "CIM_ComputerSystem", "", "",
		false, nil)

	if nil != e {
		Bail(5, e)
	}

	if len(systems) > 0 {
		fmt.Printf("Found %d system(s)\n", len(systems))
		os.Exit(0)
	}
	fmt.Printf("No systems found\n")
	os.Exit(1)
}
<|endoftext|>


<commit_before>package scummatlas

import (
	_ "bufio"
	"fmt"
	"image"
	"image/color"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

type Box struct {
	ulx   int
	uly   int
	urx   int
	ury   int
	lrx   int
	lry   int
	llx   int
	lly   int
	mask  byte
	flags byte
	scale int
}

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

func (self Box) Corners() [4]Point {
	ll := Point{self.llx, self.lly}
	ul := Point{self.ulx, self.uly}
	lr := Point{self.lrx, self.lry}
	ur := Point{self.urx, self.ury}
	return [4]Point{ul, ll, lr, ur}
}

type BoxMatrix bool

type Room struct {
	data     []byte
	offset   int
	Width    int
	Height   int
	ObjCount int
	//ColorCycle ColorCycle
	TranspIndex   int
	Palette       color.Palette
	Image         *image.RGBA
	Objects       []Object
	ObjectImage   image.Paletted
	ObjectScripts []Script
	ExitScript    Script
	EntryScript   Script
	Boxes         []Box
	LocalScripts  []Script
	BoxMatrix     BoxMatrix
}

type Object struct {
	Image  *image.RGBA
	Script Script
	Name   string
	Id     int
	X      int
	Y      int
	Width  int
	Height int
	//TODO Direction uint8
	Flags  uint8
	Parent uint8
}

func NewRoom(data []byte) *Room {
	room := new(Room)
	room.data = data
	room.offset = 0

	blockName := room.getBlockName()
	if blockName != "ROOM" {
		panic("Can't find ROOM")
	}

	room.offset = 8
	fmt.Printf("Block Name\tBlock Size\n=============\n")
	for room.offset < len(data) {
		blockName := room.getBlockName()
		fmt.Printf("%v\t%v bytes\n", blockName, room.getBlockSize())

		switch blockName {
		case "RMHD":
			room.parseRMHD()
		case "BOXD":
			room.parseBOXD()
		case "EXCD":
			room.parseEXCD()
		case "ENCD":
			room.parseENCD()
		case "EPAL":
			room.parseEPAL()
		case "CLUT":
			log.SetOutput(ioutil.Discard)
			room.parseCLUT()
		case "LSCR":
			room.parseLSCR()
		case "OBCD":
			room.parseOBCD()
		case "RMIM":
			room.parseRMIM()
		case "TRNS":
			room.parseTRNS()
		}
		log.SetOutput(os.Stdout)
		room.nextBlock()
	}

	fmt.Println("New ROOM\n")
	room.Print()
	return room
}

func (r *Room) parseLSCR() {
	scriptId := int(r.data[r.offset+8])
	fmt.Println("ScriptID", scriptId)
	script := parseScriptBlock(
		r.data[r.offset+9 : r.offset+r.getBlockSize()])
	r.LocalScripts = append(r.LocalScripts, script)
}

func (r *Room) parseTRNS() {
	r.TranspIndex = int(r.data[r.offset+8])
	fmt.Println("Transparent index", r.TranspIndex)
}

func (r *Room) parseOBCD() {
	var obj Object
	headerOffset := r.offset + 8
	if FourCharString(r.data, headerOffset) != "CDHD" {
		panic("NOOO")
	}
	headerSize := BE32(r.data, headerOffset+4)
	fmt.Println("Header size", headerSize)
	obj.Id = LE16(r.data, headerOffset+8)
	obj.X = LE16(r.data, headerOffset+10)
	obj.Y = LE16(r.data, headerOffset+12)
	obj.Width = LE16(r.data, headerOffset+14)
	obj.Height = LE16(r.data, headerOffset+16)
	obj.Flags = r.data[headerOffset+18]
	obj.Parent = r.data[headerOffset+19]

	verbOffset := headerOffset + headerSize
	if FourCharString(r.data, verbOffset) != "VERB" {
		panic("Object with no verbs")
	}
	verbSize := BE32(r.data, verbOffset+4)
	objNameOffset := verbOffset + verbSize
	if FourCharString(r.data, objNameOffset) != "OBNA" {
		panic("Object with no name")
	}
	objNameSize := BE32(r.data, objNameOffset+4)
	obj.Name = strings.Trim(
		strings.Replace(
			string(r.data[objNameOffset+4:objNameOffset+objNameSize]),
			"@", "", -1),
		"@ ï¿½")

	r.Objects = append(r.Objects, obj)
}

func (r *Room) parseENCD() {
	r.EntryScript = parseScriptBlock(r.data[r.offset+8 : r.offset+r.getBlockSize()])
}

func (r *Room) parseEPAL() {
	fmt.Println("EGA palette, not used")
	/*
		paletteData := r.data[r.offset+8 : r.offset+r.getBlockSize()]
		fmt.Println("Palette data size ", len(paletteData))

		r.Palette = parsePalette(r.data[r.offset+8 : r.offset+8+3*256])
		fmt.Println("Palette length", len(r.Palette))
		fmt.Println(r.Palette)
	*/

}

func (r *Room) parseCLUT() {
	paletteData := r.data[r.offset+8 : r.offset+r.getBlockSize()]
	log.Println("Palette data size ", len(paletteData))

	r.Palette = parsePalette(r.data[r.offset+8 : r.offset+8+3*256])
	log.Println("Palette length", len(r.Palette))

	for _, color := range r.Palette {
		r, g, b, _ := color.RGBA()
		r8, g8, b8 := uint8(r), uint8(g), uint8(b)
		log.Printf(" %x%x%x", r8, g8, b8)
	}
	log.Println()
}

func (r *Room) parseEXCD() {
	r.EntryScript = parseScriptBlock(r.data[r.offset+8 : r.offset+r.getBlockSize()])
}

func (r *Room) parseRMIM() {
	if string(r.data[r.offset+8:r.offset+12]) != "RMIH" {
		panic("Not room image header")
	}
	headerSize := BE32(r.data, r.offset+12)
	zBuffers := LE16(r.data, r.offset+16)
	fmt.Println("headerSize", headerSize)
	fmt.Println("zBuffers", zBuffers)

	if FourCharString(r.data, r.offset+18) != "IM00" {
		panic("Not room image found")
	}
	imageOffset := r.offset + 18
	imageSize := BE32(r.data, imageOffset+4)
	fmt.Println(FourCharString(r.data, imageOffset), imageSize)

	r.Image = parseImage(
		r.data[imageOffset:imageOffset+4+imageSize],
		zBuffers,
		r.Width,
		r.Height,
		r.Palette,
		uint8(r.TranspIndex))

}

func (r *Room) parseBOXD() {
	boxCount := LE16(r.data, r.offset+8)
	var boxOffset int
	fmt.Println("BOXCOUNT", boxCount)
	for i := 0; i < boxCount; i++ {
		boxOffset = r.offset + 10 + i*20
		box := NewBox(r.data[boxOffset : boxOffset+20])
		r.Boxes = append(r.Boxes, box)
	}
}

func (r *Room) parseRMHD() {
	fmt.Println("RMHD offset", r.offset)
	r.Width = LE16(r.data, r.offset+8)
	r.Height = LE16(r.data, r.offset+10)
	r.ObjCount = LE16(r.data, r.offset+12)
	fmt.Printf("Room size %vx%v\n", r.Width, r.Height)
}

func (r Room) Print() {
	fmt.Println("Size: ", r.Width, r.Height)
	fmt.Println("Object count: ", r.ObjCount)
	fmt.Println("Boxes: ", len(r.Boxes))
}

func (r Room) getBlockName() string {
	return string(r.data[r.offset : r.offset+4])
}

func (r Room) getBlockSize() int {
	return BE32(r.data, r.offset+4)
}

func (r *Room) nextBlock() {
	r.offset += r.getBlockSize()
}

func NewBox(data []byte) Box {
	box := new(Box)

	box.ulx = LE16(data, 0)
	box.uly = LE16(data, 2)
	box.urx = LE16(data, 4)
	box.ury = LE16(data, 6)
	box.lrx = LE16(data, 8)
	box.lry = LE16(data, 10)
	box.llx = LE16(data, 12)
	box.lly = LE16(data, 14)
	box.mask = data[16]
	box.flags = data[17]
	box.scale = LE16(data, 18)

	return *box
}
<commit_msg>Filter object names<commit_after>package scummatlas

import (
	_ "bufio"
	"fmt"
	"image"
	"image/color"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

type Box struct {
	ulx   int
	uly   int
	urx   int
	ury   int
	lrx   int
	lry   int
	llx   int
	lly   int
	mask  byte
	flags byte
	scale int
}

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

func (self Box) Corners() [4]Point {
	ll := Point{self.llx, self.lly}
	ul := Point{self.ulx, self.uly}
	lr := Point{self.lrx, self.lry}
	ur := Point{self.urx, self.ury}
	return [4]Point{ul, ll, lr, ur}
}

type BoxMatrix bool

type Room struct {
	data     []byte
	offset   int
	Width    int
	Height   int
	ObjCount int
	//ColorCycle ColorCycle
	TranspIndex   int
	Palette       color.Palette
	Image         *image.RGBA
	Objects       []Object
	ObjectImage   image.Paletted
	ObjectScripts []Script
	ExitScript    Script
	EntryScript   Script
	Boxes         []Box
	LocalScripts  []Script
	BoxMatrix     BoxMatrix
}

type Object struct {
	Image  *image.RGBA
	Script Script
	Name   string
	Id     int
	X      int
	Y      int
	Width  int
	Height int
	//TODO Direction uint8
	Flags  uint8
	Parent uint8
}

func NewRoom(data []byte) *Room {
	room := new(Room)
	room.data = data
	room.offset = 0

	blockName := room.getBlockName()
	if blockName != "ROOM" {
		panic("Can't find ROOM")
	}

	room.offset = 8
	fmt.Printf("Block Name\tBlock Size\n=============\n")
	for room.offset < len(data) {
		blockName := room.getBlockName()
		fmt.Printf("%v\t%v bytes\n", blockName, room.getBlockSize())

		switch blockName {
		case "RMHD":
			room.parseRMHD()
		case "BOXD":
			room.parseBOXD()
		case "EXCD":
			room.parseEXCD()
		case "ENCD":
			room.parseENCD()
		case "EPAL":
			room.parseEPAL()
		case "CLUT":
			log.SetOutput(ioutil.Discard)
			room.parseCLUT()
		case "LSCR":
			room.parseLSCR()
		case "OBCD":
			room.parseOBCD()
		case "RMIM":
			room.parseRMIM()
		case "TRNS":
			room.parseTRNS()
		}
		log.SetOutput(os.Stdout)
		room.nextBlock()
	}

	fmt.Println("New ROOM\n")
	room.Print()
	return room
}

func (r *Room) parseLSCR() {
	scriptId := int(r.data[r.offset+8])
	fmt.Println("ScriptID", scriptId)
	script := parseScriptBlock(
		r.data[r.offset+9 : r.offset+r.getBlockSize()])
	r.LocalScripts = append(r.LocalScripts, script)
}

func (r *Room) parseTRNS() {
	r.TranspIndex = int(r.data[r.offset+8])
	fmt.Println("Transparent index", r.TranspIndex)
}

func (r *Room) parseOBCD() {
	var obj Object
	headerOffset := r.offset + 8
	if FourCharString(r.data, headerOffset) != "CDHD" {
		panic("NOOO")
	}
	headerSize := BE32(r.data, headerOffset+4)
	fmt.Println("Header size", headerSize)
	obj.Id = LE16(r.data, headerOffset+8)
	obj.X = LE16(r.data, headerOffset+10)
	obj.Y = LE16(r.data, headerOffset+12)
	obj.Width = LE16(r.data, headerOffset+14)
	obj.Height = LE16(r.data, headerOffset+16)
	obj.Flags = r.data[headerOffset+18]
	obj.Parent = r.data[headerOffset+19]

	verbOffset := headerOffset + headerSize
	if FourCharString(r.data, verbOffset) != "VERB" {
		panic("Object with no verbs")
	}
	verbSize := BE32(r.data, verbOffset+4)
	objNameOffset := verbOffset + verbSize
	if FourCharString(r.data, objNameOffset) != "OBNA" {
		panic("Object with no name")
	}
	objNameSize := BE32(r.data, objNameOffset+4)
	obj.Name = ""
	name := r.data[objNameOffset+4 : objNameOffset+objNameSize]
	filtered := []byte{}
	for _, v := range name {
		if v != 0x40 && v != 0x00 && v != 0x0f {
			filtered = append(filtered, v)
		}
	}
	obj.Name = strings.TrimSpace(string(filtered))
	r.Objects = append(r.Objects, obj)
}

func (r *Room) parseENCD() {
	r.EntryScript = parseScriptBlock(r.data[r.offset+8 : r.offset+r.getBlockSize()])
}

func (r *Room) parseEPAL() {
	fmt.Println("EGA palette, not used")
	/*
		paletteData := r.data[r.offset+8 : r.offset+r.getBlockSize()]
		fmt.Println("Palette data size ", len(paletteData))

		r.Palette = parsePalette(r.data[r.offset+8 : r.offset+8+3*256])
		fmt.Println("Palette length", len(r.Palette))
		fmt.Println(r.Palette)
	*/

}

func (r *Room) parseCLUT() {
	paletteData := r.data[r.offset+8 : r.offset+r.getBlockSize()]
	log.Println("Palette data size ", len(paletteData))

	r.Palette = parsePalette(r.data[r.offset+8 : r.offset+8+3*256])
	log.Println("Palette length", len(r.Palette))

	for _, color := range r.Palette {
		r, g, b, _ := color.RGBA()
		r8, g8, b8 := uint8(r), uint8(g), uint8(b)
		log.Printf(" %x%x%x", r8, g8, b8)
	}
	log.Println()
}

func (r *Room) parseEXCD() {
	r.EntryScript = parseScriptBlock(r.data[r.offset+8 : r.offset+r.getBlockSize()])
}

func (r *Room) parseRMIM() {
	if string(r.data[r.offset+8:r.offset+12]) != "RMIH" {
		panic("Not room image header")
	}
	headerSize := BE32(r.data, r.offset+12)
	zBuffers := LE16(r.data, r.offset+16)
	fmt.Println("headerSize", headerSize)
	fmt.Println("zBuffers", zBuffers)

	if FourCharString(r.data, r.offset+18) != "IM00" {
		panic("Not room image found")
	}
	imageOffset := r.offset + 18
	imageSize := BE32(r.data, imageOffset+4)
	fmt.Println(FourCharString(r.data, imageOffset), imageSize)

	r.Image = parseImage(
		r.data[imageOffset:imageOffset+4+imageSize],
		zBuffers,
		r.Width,
		r.Height,
		r.Palette,
		uint8(r.TranspIndex))

}

func (r *Room) parseBOXD() {
	boxCount := LE16(r.data, r.offset+8)
	var boxOffset int
	fmt.Println("BOXCOUNT", boxCount)
	for i := 0; i < boxCount; i++ {
		boxOffset = r.offset + 10 + i*20
		box := NewBox(r.data[boxOffset : boxOffset+20])
		r.Boxes = append(r.Boxes, box)
	}
}

func (r *Room) parseRMHD() {
	fmt.Println("RMHD offset", r.offset)
	r.Width = LE16(r.data, r.offset+8)
	r.Height = LE16(r.data, r.offset+10)
	r.ObjCount = LE16(r.data, r.offset+12)
	fmt.Printf("Room size %vx%v\n", r.Width, r.Height)
}

func (r Room) Print() {
	fmt.Println("Size: ", r.Width, r.Height)
	fmt.Println("Object count: ", r.ObjCount)
	fmt.Println("Boxes: ", len(r.Boxes))
}

func (r Room) getBlockName() string {
	return string(r.data[r.offset : r.offset+4])
}

func (r Room) getBlockSize() int {
	return BE32(r.data, r.offset+4)
}

func (r *Room) nextBlock() {
	r.offset += r.getBlockSize()
}

func NewBox(data []byte) Box {
	box := new(Box)

	box.ulx = LE16(data, 0)
	box.uly = LE16(data, 2)
	box.urx = LE16(data, 4)
	box.ury = LE16(data, 6)
	box.lrx = LE16(data, 8)
	box.lry = LE16(data, 10)
	box.llx = LE16(data, 12)
	box.lly = LE16(data, 14)
	box.mask = data[16]
	box.flags = data[17]
	box.scale = LE16(data, 18)

	return *box
}
<|endoftext|>


<commit_before>package server

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"ipCircBuffer"
	"net"
	"net/http"
	"nginxParser"
	"posts"
	"shortlink"
	"strconv"
	"time"
)

func getPost(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	WriteOutputError(w, map[string]*posts.Post{"Post": post}, err)
}

func getPostList(w http.ResponseWriter, r *http.Request) {
	WriteJson(w, map[string][]string{"Posts": posts.GetPostList()})
}

func getParagraph(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	i, err := strconv.Atoi(vars["id"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}

	if i >= len(post.Content) {
		WriteErrorString(w, fmt.Sprintf("%s does not have paragraph %d", vars["Title"], i), 400)
		return
	}

	paragraph := post.Content[i]
	WriteJson(w, map[string]string{"Paragraph": paragraph})
}

func getInfo(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	info := (*post).Info()
	WriteJson(w, map[string]posts.PostInfo{"Info": info})
}

func getDesktopIP(w http.ResponseWriter, r *http.Request) {

	ip := ipCircBuffer.DesktopIP.Get()
	if ip == nil {
		ip = net.ParseIP("0.0.0.0")
	}
	fmt.Fprint(w, ip.String())
}

func postDesktopIP(w http.ResponseWriter, r *http.Request) {
	stringIP := r.FormValue("IP")
	if stringIP == "-1" {
		ipCircBuffer.DesktopIP.Revert()
		fmt.Fprint(w, "Reverted")
		return
	}
	ipCircBuffer.DesktopIP.Set(stringIP)
	fmt.Fprint(w, stringIP)
}

func clearDesktopIP(w http.ResponseWriter, r *http.Request) {
	ipCircBuffer.RaspberryIP.Clear()
	fmt.Fprint(w, "Cleared")
}

func getRaspberryIP(w http.ResponseWriter, r *http.Request) {

	ip := ipCircBuffer.RaspberryIP.Get()
	if ip == nil {
		ip = net.ParseIP("0.0.0.0")
	}
	fmt.Fprint(w, ip.String())
}

func postRaspberryIP(w http.ResponseWriter, r *http.Request) {
	stringIP := r.FormValue("IP")
	if stringIP == "-1" {
		ipCircBuffer.RaspberryIP.Revert()
		fmt.Fprint(w, "Reverted")
		return
	}
	ipCircBuffer.RaspberryIP.Set(stringIP)
	fmt.Fprint(w, stringIP)
}

func clearRaspberryIP(w http.ResponseWriter, r *http.Request) {
	ipCircBuffer.RaspberryIP.Clear()
	fmt.Fprint(w, "Cleared")
}

func get24HourRequests(w http.ResponseWriter, r *http.Request) {
	requests, err := nginxParser.GetRequests(24*time.Hour, "/var/log/nginx/access.log")
	WriteOutputError(w, map[string]int{"Requests": requests}, err)
}
func redirectToShortlink(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/beta#shortlink", 302)
}

func makeShortlink(w http.ResponseWriter, r *http.Request) {

	parsedJson := make(map[string]string)
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&parsedJson)
	if err != nil {
		WriteErrorString(w, err.Error()+" in parsing POST body (JSON)", 400)
		return
	}

	link, ok := parsedJson["Link"]
	if !ok {
		WriteErrorString(w, "'Link' not in JSON body", 400)
		return
	}

	newID, err := shortlink.Add(link)
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	WriteJson(w, map[string]string{"ID": newID})
}

func getShortlink(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	linkID := vars["linkID"]
	if linkID == "" {
		http.Redirect(w, r, "/beta#shortlink", 302)
		//WriteErrorString(w, "link ID empty", 400)
		return
	}

	//pads front with 0
	for len(linkID) < 4 {
		linkID = "0" + linkID
	}
	link, err := shortlink.Get(linkID)
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	http.Redirect(w, r, link, 302)

}
<commit_msg>redirects shortlink to main page<commit_after>package server

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"ipCircBuffer"
	"net"
	"net/http"
	"nginxParser"
	"posts"
	"shortlink"
	"strconv"
	"time"
)

func getPost(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	WriteOutputError(w, map[string]*posts.Post{"Post": post}, err)
}

func getPostList(w http.ResponseWriter, r *http.Request) {
	WriteJson(w, map[string][]string{"Posts": posts.GetPostList()})
}

func getParagraph(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	i, err := strconv.Atoi(vars["id"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}

	if i >= len(post.Content) {
		WriteErrorString(w, fmt.Sprintf("%s does not have paragraph %d", vars["Title"], i), 400)
		return
	}

	paragraph := post.Content[i]
	WriteJson(w, map[string]string{"Paragraph": paragraph})
}

func getInfo(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	post, err := posts.GetPost(vars["Title"])
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	info := (*post).Info()
	WriteJson(w, map[string]posts.PostInfo{"Info": info})
}

func getDesktopIP(w http.ResponseWriter, r *http.Request) {

	ip := ipCircBuffer.DesktopIP.Get()
	if ip == nil {
		ip = net.ParseIP("0.0.0.0")
	}
	fmt.Fprint(w, ip.String())
}

func postDesktopIP(w http.ResponseWriter, r *http.Request) {
	stringIP := r.FormValue("IP")
	if stringIP == "-1" {
		ipCircBuffer.DesktopIP.Revert()
		fmt.Fprint(w, "Reverted")
		return
	}
	ipCircBuffer.DesktopIP.Set(stringIP)
	fmt.Fprint(w, stringIP)
}

func clearDesktopIP(w http.ResponseWriter, r *http.Request) {
	ipCircBuffer.RaspberryIP.Clear()
	fmt.Fprint(w, "Cleared")
}

func getRaspberryIP(w http.ResponseWriter, r *http.Request) {

	ip := ipCircBuffer.RaspberryIP.Get()
	if ip == nil {
		ip = net.ParseIP("0.0.0.0")
	}
	fmt.Fprint(w, ip.String())
}

func postRaspberryIP(w http.ResponseWriter, r *http.Request) {
	stringIP := r.FormValue("IP")
	if stringIP == "-1" {
		ipCircBuffer.RaspberryIP.Revert()
		fmt.Fprint(w, "Reverted")
		return
	}
	ipCircBuffer.RaspberryIP.Set(stringIP)
	fmt.Fprint(w, stringIP)
}

func clearRaspberryIP(w http.ResponseWriter, r *http.Request) {
	ipCircBuffer.RaspberryIP.Clear()
	fmt.Fprint(w, "Cleared")
}

func get24HourRequests(w http.ResponseWriter, r *http.Request) {
	requests, err := nginxParser.GetRequests(24*time.Hour, "/var/log/nginx/access.log")
	WriteOutputError(w, map[string]int{"Requests": requests}, err)
}
func redirectToShortlink(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/#shortlink", 302)
}

func makeShortlink(w http.ResponseWriter, r *http.Request) {

	parsedJson := make(map[string]string)
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&parsedJson)
	if err != nil {
		WriteErrorString(w, err.Error()+" in parsing POST body (JSON)", 400)
		return
	}

	link, ok := parsedJson["Link"]
	if !ok {
		WriteErrorString(w, "'Link' not in JSON body", 400)
		return
	}

	newID, err := shortlink.Add(link)
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	WriteJson(w, map[string]string{"ID": newID})
}

func getShortlink(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	linkID := vars["linkID"]
	if linkID == "" {
		http.Redirect(w, r, "/beta#shortlink", 302)
		//WriteErrorString(w, "link ID empty", 400)
		return
	}

	//pads front with 0
	for len(linkID) < 4 {
		linkID = "0" + linkID
	}
	link, err := shortlink.Get(linkID)
	if err != nil {
		WriteError(w, err, 400)
		return
	}
	http.Redirect(w, r, link, 302)

}
<|endoftext|>


<commit_before>package service

import (
    "bloom"
    "fmt"
    "net/http"
    "log"
    "github.com/gorilla/mux"
)

var filter bloom.Filter = bloom.New(100,0.01)

func add(w http.ResponseWriter, r *http.Request) {
    key := r.URL.Path[len("/add/"):]

    filter.Add([]byte(key));

    w.WriteHeader(http.StatusCreated)
    fmt.Fprintf(w, "/contains/%s", key)
}

func contains(w http.ResponseWriter, r *http.Request) {
    key := r.URL.Path[len("/contains/"):]

    if (filter.Contains([]byte(key))) {
        w.WriteHeader(http.StatusOK)

        return
    }

    w.WriteHeader(http.StatusNotFound)
}

func createFilter(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "createFilter%+v\n", mux.Vars(r))
}

func retrieveFilter(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "retrieveFilter %+v\n", mux.Vars(r))
}

func deleteFilter(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "deleteFilter %+v\n", mux.Vars(r))
}

func createEntry(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "createEntry %+v\n", mux.Vars(r))
}

func retrieveEntry(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "retrieveEntry %+v\n", mux.Vars(r))
}

func ListenAndServe(address string) {
    r := mux.NewRouter()
    s := r.PathPrefix("/v1/filters").Subrouter()

    s.HandleFunc("", createFilter).Methods("POST")
    s.HandleFunc("/{filterName}", retrieveFilter).Methods("GET")
    s.HandleFunc("/{filterName}", deleteFilter).Methods("DELETE")
    s.HandleFunc("/{filterName}/entries", createEntry).Methods("POST")
    s.HandleFunc("/{filterName}/entries/{entryName}", retrieveEntry).Methods("GET")

    http.Handle("/", r)
    log.Print("Server starting on ", address)
    http.ListenAndServe(address, nil)
}
<commit_msg>Start reading post values<commit_after>package service

import (
	"bloom"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

var filter bloom.Filter = bloom.New(100, 0.01)

func add(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[len("/add/"):]

	filter.Add([]byte(key))

	w.WriteHeader(http.StatusCreated)
	fmt.Fprintf(w, "/contains/%s", key)
}

func contains(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[len("/contains/"):]

	if filter.Contains([]byte(key)) {
		w.WriteHeader(http.StatusOK)

		return
	}

	w.WriteHeader(http.StatusNotFound)
}

func createFilter(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "createFilter%+v\n", mux.Vars(r))
	fmt.Fprintf(w, "name:%+v, capacity:%+v, errorRate:%+v\n", r.FormValue("name"), r.FormValue("capacity"), r.FormValue("errorRate"))
}

func retrieveFilter(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "retrieveFilter %+v\n", mux.Vars(r))
}

func deleteFilter(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "deleteFilter %+v\n", mux.Vars(r))
}

func createEntry(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "createEntry %+v\n", mux.Vars(r))
}

func retrieveEntry(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "retrieveEntry %+v\n", mux.Vars(r))
}

func ListenAndServe(address string) {
	r := mux.NewRouter()

	r.HandleFunc("/v1/filters", createFilter).Methods("POST")
	r.HandleFunc("/v1/filters/{filterName}", retrieveFilter).Methods("GET")
	r.HandleFunc("/v1/filters/{filterName}", deleteFilter).Methods("DELETE")
	r.HandleFunc("/v1/filters/{filterName}/entries", createEntry).Methods("POST")
	r.HandleFunc("/v1/filters/{filterName}/entries/{entryName}", retrieveEntry).Methods("GET")

	http.Handle("/", r)

	log.Print("Server starting on ", address)
	http.ListenAndServe(address, nil)
}
<|endoftext|>


<commit_before>package board

import (
	"color"
	"errors"
	"fmt"
	"point"
)

var starting = [8][8]byte{
	{'r', 'n', 'b', 'k', 'q', 'b', 'n', 'r'},
	{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
}

type Board struct {
	matrix [8][8]byte
}

func NewBoard() *Board {
	board := new(Board)
	board.matrix = starting
	return board
}

func (board *Board) Print() {
	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()

	for i := 0; i < 8; i++ {
		fmt.Print(" +")
		for j := 0; j < 8; j++ {
			fmt.Print("-+")
		}
		fmt.Println()
		fmt.Printf("%d|", 8-i)
		for j := 0; j < 8; j++ {
			fmt.Printf("%c|", board.matrix[i][j])
		}
		fmt.Println(8 - i)
	}
	fmt.Print(" +")
	for i := 0; i < 8; i++ {
		fmt.Print("-+")
	}
	fmt.Println()

	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()
}

func InBoard(point point.Point) bool {
	return 0 <= point.X && point.X < 8 && 0 <= point.Y && point.Y < 8
}

func (board *Board) Move(from, to point.Point, c color.Color) error {
	if InBoard(from) == false || InBoard(to) == false {
		return errors.New("out of board")
	}

	fcolor := color.WhichColor(board.matrix[from.Y][from.X])
	tcolor := color.WhichColor(board.matrix[to.Y][to.X])
	if fcolor != c || tcolor == c {
		return errors.New("cannot move this piece")
	}

	board.matrix[to.Y][to.X] = board.matrix[from.Y][from.X]
	board.matrix[from.Y][from.X] = ' '

	return nil
}
<commit_msg>Check piece's kind is movable before move piece<commit_after>package board

import (
	"color"
	"errors"
	"fmt"
	"piece"
	"point"
)

var starting = [8][8]byte{
	{'r', 'n', 'b', 'k', 'q', 'b', 'n', 'r'},
	{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
}

type Board struct {
	matrix [8][8]byte
}

func NewBoard() *Board {
	board := new(Board)
	board.matrix = starting
	return board
}

func (board *Board) Print() {
	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()

	for i := 0; i < 8; i++ {
		fmt.Print(" +")
		for j := 0; j < 8; j++ {
			fmt.Print("-+")
		}
		fmt.Println()
		fmt.Printf("%d|", 8-i)
		for j := 0; j < 8; j++ {
			fmt.Printf("%c|", board.matrix[i][j])
		}
		fmt.Println(8 - i)
	}
	fmt.Print(" +")
	for i := 0; i < 8; i++ {
		fmt.Print("-+")
	}
	fmt.Println()

	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()
}

func InBoard(point point.Point) bool {
	return 0 <= point.X && point.X < 8 && 0 <= point.Y && point.Y < 8
}

func (board *Board) Move(from, to point.Point, c color.Color) error {
	if InBoard(from) == false || InBoard(to) == false {
		return errors.New("out of board")
	}

	fsymbol := board.matrix[from.Y][from.X]
	// tsymbol := board.matrix[to.Y][to.X]

	fcolor := color.WhichColor(board.matrix[from.Y][from.X])
	tcolor := color.WhichColor(board.matrix[to.Y][to.X])
	diff := point.Point{0, 0}
	if fcolor == color.White {
		diff = from.Diff(to)
	} else if fcolor == color.Black {
		diff = to.Diff(from)
	}
	canMove := piece.WhichPiece(fsymbol).CanMove(diff)
	if fcolor != c || tcolor == c || canMove == false {
		return errors.New("cannot move this piece")
	}

	board.matrix[to.Y][to.X] = board.matrix[from.Y][from.X]
	board.matrix[from.Y][from.X] = ' '

	return nil
}
<|endoftext|>


<commit_before>package terp_test

import (
	"testing"

	. "terp"
)

func TestSimpleList3(t *testing.T) {
	a := ParseList("  one  two three  ")
	if len(a) != 3 {
		panic("len not 3")
	}
	MustA(3, len(a))
	MustST("one", a[0])
	MustST("three", a[2])
}

func TestT2(t *testing.T) {
	a := ParseList("  one  { number two } three  ")
	if len(a) != 3 {
		panic("len not 3")
	}
	println(Repr(a))
	MustA(3, len(a))
	MustST("one", a[0])
	MustST(" number two ", a[1])
	MustST("three", a[2])
}

/*
func TestT3(t *testing.T) {
	fr := New()
	a := fr.Eval(MkString("list abc[list def]ghi"))
	MustA("xabcdefghi", a.String())
}
*/
<commit_msg>test backslash escaping<commit_after>package terp_test

import (
	"testing"

	. "terp"
)

func TestSimpleList3(t *testing.T) {
	a := ParseList("  one  two three  ")
	if len(a) != 3 {
		panic("len not 3")
	}
	MustA(3, len(a))
	MustST("one", a[0])
	MustST("three", a[2])
}

func TestT2(t *testing.T) {
	a := ParseList("  one  { number two } three  ")
	if len(a) != 3 {
		panic("len not 3")
	}
	println(Repr(a))
	MustA(3, len(a))
	MustST("one", a[0])
	MustST(" number two ", a[1])
	MustST("three", a[2])
}

/*
func TestT3(t *testing.T) {
	fr := New()
	a := fr.Eval(MkString("list abc[list def]ghi"))
	MustA("xabcdefghi", a.String())
}
*/

func TestParseEscaping(t *testing.T) {
	fr := New()
	s := `proc p {} {
		return "0\132\tNumber\n"
	} ; p`
	x := fr.Eval(MkString(s))
	if x.String() != "0\132\tNumber\n" {
		t.Errorf("Broken x was %q.", x.String())
	}
}

func TestSlashEscaping(t *testing.T) {
	s := "0\132\tNumber\n"
	x := MkString(s).ListElementString()
	if x != `{0Z\011Number\012}` {
		t.Errorf("Broken x was %q.", x)
	}
}

<|endoftext|>


<commit_before>package tritium

import (
	"tritium/linker"
	tp "athena/proto"
	"tritium/packager"
	"os"
)

func Compile(file string) (*tp.Transform, os.Error) {

	defaultPackage := packager.LoadDefaultPackage(PackagePath)
	defaultPackage.BuildUserPackage(UserPackagePath, PackagePath)

	return linker.RunWithPackage(file, defaultPackage.Package)
}

func CompileString(data, path string) (*tp.Transform, os.Error) {

	defaultPackage := packager.LoadDefaultPackage(PackagePath)
	defaultPackage.BuildUserPackage(UserPackagePath, PackagePath)

	return linker.RunStringWithPackage(data, path, defaultPackage.Package)
}

var PackagePath *string
var UserPackagePath *string
<commit_msg>Add mixer support. Now compile takes a package object as input to link / etc<commit_after>package tritium

import (
	"tritium/linker"
	ap "athena/proto"
	"tritium/packager"
	"os"
	"fmt"
	"path/filepath"
	"strings"
)

func Compile(file string, rootPackage *ap.Package) (*ap.Transform, os.Error) {

//	defaultPackage := packager.LoadDefaultPackage(PackagePath)
//	defaultPackage.BuildUserPackage(UserPackagePath, PackagePath)

	// TODO(SJ) : Make a copy constructor from a raw ap.Package object
	//	-- the path here should be optional since I'm passing in the ap.Package

	compileOptions := packager.PackageOptions{"stdout": false, "output_tpkg": false, "use_tpkg": false}

//	defaultPackage := packager.NewPackage(PackagePath, compileOptions)
	defaultPackage := packager.NewPackage(*UserPackagePath, compileOptions)
	defaultPackage.Merge(rootPackage)

	userPackages, _ := filepath.Glob(filepath.Join(*UserPackagePath, "*"))

	for _, path := range userPackages {
		components := strings.Split(path, "/")
		name := components[len(components)-1]
		defaultPackage.Load(name)
	}

//	rootPackage.BuildUserPackage(UserPackagePath, PackagePath)
	fmt.Printf("Using ROOT PACKAGE %v\n", rootPackage)

	return linker.RunWithPackage(file, defaultPackage.Package)
}

func CompileString(data, path string, rootPackage *ap.Package) (*ap.Transform, os.Error) {

	defaultPackage := packager.LoadDefaultPackage(PackagePath)
	defaultPackage.BuildUserPackage(UserPackagePath, PackagePath)

	return linker.RunStringWithPackage(data, path, defaultPackage.Package)
}

var PackagePath *string
var UserPackagePath *string
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os/exec"
)

func main() {
	curlyCmd := exec.Command("curly", "https://github.com")

	cmdOut, err := curlyCmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Print(string(cmdOut))
}
<commit_msg>we are correctly parsing curly data now<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os/exec"
)

// {"url": "http://github.com", "connect_time": 0.031178999999999998, "exit_status": 0, "starttransfer_time": 0.031178999999999998, "t": 1397688864, "local_ip": "107.170.123.131", "primary_ip": "192.30.252.128", "total_time": 0.037648000000000001, "http_status": 301, "namelookup_time": 0.024646000000000001, "local_port": 53858}
type curly_response struct {
	Url               string  `json:"url"`
	ConnectTime       float64 `json:"connect_time"`
	ExitStatus        int     `json:"exit_status"`
	StartTransferTime float64 `json:"starttransfer_time"`
	T                 int     `json:"t"`
	LocalIp           string  `json:"local_ip"`
	PrimaryIp         string  `json:"primary_ip"`
	TotalTime         float64 `json:"total_time"`
	HttpStatus        int     `json:"http_status"`
	NameLookupTime    float64 `json:"namelookup_time"`
}

func main() {
	cmd := exec.Command("curly", "http://github.com")
	cmdOut, _ := cmd.Output()

	var foo curly_response
	if err := json.Unmarshal(cmdOut, &foo); err != nil {
		log.Fatalf("error %v", err)
	}
	fmt.Printf("%s\n", cmdOut)
	fmt.Printf("%v\n", foo)
}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
    //"html"
    "log"
    "net/http"
	"io/ioutil"
	"strings"
)

var (
	head string = `<!DOCTYPE html>

<title>Page Title</title>

This is a Heading
`

	tail string =	`</body></html>`

	script string = ``
)

func main() {
	http.HandleFunc("/List", List)
	http.HandleFunc("/Watch", Watch)
	http.Handle("/", http.FileServer(http.Dir("./Vids/")))
	log.Fatal(http.ListenAndServe(":8080", nil))

}

func List(w http.ResponseWriter, r *http.Request){
	fmt.Fprintf(w, head + getVideos() + tail)
}

func Watch(w http.ResponseWriter, r *http.Request){
	//fileToWatch := r.URL.Path[len("/Watch"):]
	//fmt.Printf("%q", r.URL.Path)
	queryMap := r.URL.Query();
	fileToWatch := queryMap["Vids"][0];
	fileText := ("<video width=\"400\" preload=\"none\" controls><source src=\""+fileToWatch+"\" type=\"video/mp4\">Your browser does not support HTML5 video.</video>")
	fmt.Fprintf(w, head + fileText + script + tail)
}

func getVideos() string{
	fileText:=""
	files, err := ioutil.ReadDir("./Vids")
	if(err != nil){
		fileText = `<p>No Files Found</p>`
	}
	for _, file := range files {
		if strings.Contains(strings.ToLower(file.Name()), "mp4"){
			fileText += (""+file.Name()+"\n
\n")
		}else{
			fileText += ("
" + file.Name() + "
\n
\n")
		}

	}
	return fileText;
}
<commit_msg>Added ability to queue vids and investigate folders<commit_after>package main

import (
    "fmt"
    //"html"
    "log"
    "net/http"
	"io/ioutil"
	"strings"
)

var (
	head string = `<!DOCTYPE html>

<title>Page Title</title>

This is a Heading
`

	tail string =	`</body></html>`

	script string = ``
)

func main() {
	http.HandleFunc("/List/", List)
	http.HandleFunc("/Watch", Watch)
	http.Handle("/", http.FileServer(http.Dir("./Vids/")))
	log.Fatal(http.ListenAndServe(":8080", nil))

}

func List(w http.ResponseWriter, r *http.Request){
	folderPath := "./Vids"
	folderPath += r.URL.Path[len("/List"):]
	fmt.Printf("%q\n", r.URL.Path)
	fmt.Printf("%q\n", folderPath)
	fmt.Fprintf(w, head + getVideos(folderPath) + script + tail)
}

func Watch(w http.ResponseWriter, r *http.Request){
	//fileToWatch := r.URL.Path[len("/Watch"):]
	//fmt.Printf("%q", r.URL.Path)
	queryMap := r.URL.Query();
	fileToWatch := queryMap["Vids"][0];
	fileText := ("<video width=\"400\" preload=\"none\" controls><source src=\""+fileToWatch+"\" type=\"video/mp4\">Your browser does not support HTML5 video.</video>")

	fmt.Fprintf(w, head + fileText + script + tail)
}

func getVideos(path string) string{
	fileText:=""
	files, err := ioutil.ReadDir(path)
	if(err != nil){
		fileText = `<p>No Files Found</p>`
	}
	for _, file := range files {
		fileText += "
"
		fileText += "<input type=\"text\" name=\"order\" size=1>   "
		if strings.Contains(strings.ToLower(file.Name()), "mp4"){
			fileText += (""+file.Name()+"\n
\n")
		} else if file.IsDir() {
			fileText += (""+file.Name()+"\n
\n")
		} else{
			fileText += ("" + file.Name() + "\n
\n")
		}
		fileText += "
"
	}
	fileText += "<button onclick=\"createVidPlaylist()\" type=\"button\">Play Videos</button>"
	return fileText;
}
<|endoftext|>


<commit_before>package irc

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
)

type Client struct {
	connection net.Conn
	serverName string
	nick       string
	server     chan ServerMessage
	out        io.Writer
}

func parseServerMessage(line string) (m ServerMessage) {
	m.Full = line
	m.From, line, _ = nextField(line)
	if m.From[0] != ':' {
		m.Code = m.From
		m.From = ""
	} else {
		m.From = m.From[1:]
		m.Code, line, _ = nextField(line)
	}
	m.To, line, _ = nextField(line)
	m.Raw = line
	m.Fields = make([]string, 0)

	switch m.Code {
	case "NOTICE":
	case "PRIVMSG":
		m.Fields = append(m.Fields, line[1:])
	case RPL_BOUNCE:
	default:
		// fill in variable fields
		var f string
		f, line, b := nextField(line)
		for b {
			if f[0] == ':' {
				if f[1] == '-' {
					break
				}
				// read until f[len(f)-1] is a semicolon
				for b && len(f) > 0 && f[len(f)-1] != ':' {
					f, line, b = nextField(line)
				}
			} else {
				m.Fields = append(m.Fields, f)
			}
			f, line, b = nextField(line)
		}
	}
	return
}

func Connect(serverName, nick, realName string) (*Client, error) {
	conn, err := Dial(serverName)
	if err != nil {
		return conn, err
	}

	conn.Pass("notmeaningfull")
	conn.User(getUname(), getHostname(), getServername(), realName)
	conn.Nick(nick)
	return conn, nil
}

// Low-level method to connect to server - normal clients should not need this.
// Use Connect() instead.
func Dial(server string) (conn *Client, err error) {
	nconn, err := net.Dial("tcp", server)
	if err != nil {
		return
	}

	conn = new(Client)
	conn.connection = nconn
	conn.serverName = server
	conn.server = make(chan ServerMessage, serverMsgBufSize)
	conn.out = conn.connection

	// spawn the connection reader
	go func() {
		r, err := bufio.NewReaderSize(conn.connection, maxlinesize)
		if err != nil {
			panic(err)
		}

		line, beFalse, err := r.ReadLine()
		for err == nil && !beFalse {
			conn.server <- parseServerMessage(string(line))
			line, beFalse, err = r.ReadLine()
		}
		if beFalse {
			log.Fatal("Line too long")
		} else {
			log.Fatal(err) // TODO handle me better
		}
	}()
	return
}

func (c *Client) Pass(pass string) {
	fmt.Fprintf(c.out, "PASS %s\n", pass)
}

// Low-level method to send USER command - normal clients should not need this
func (c *Client) User(user, host, server, name string) {
	fmt.Fprintf(c.out, "USER %s %s %s :%s\n", user, host, server, name)
}

// Low-level method to send NICK command - normal clients should not need this.
func (c *Client) Nick(nick string) {
	fmt.Fprintf(c.out, "NICK %s\n", nick)
	c.nick = nick // TODO fix possible race condition
}

// Listen for messages coming in and return them on the returned channel. Also
// handles low-level information from the server correctly, making information
// available in the Client object as appropriate.
func (c *Client) Listen() <-chan Message {
	ch := make(chan Message)
	handleMessage := func(sm ServerMessage) {
		switch sm.Code {
		case "NOTICE":
			ch <- Message{
				Kind: MSG_NOTICE,
				From: sm.From,
				To:   sm.To,
				Text: sm.Raw[1:],
			}
		case "PRIVMSG":
			ch <- Message{
				Kind: MSG_PRIVMSG,
				From: sm.From,
				To:   sm.To,
				Text: sm.Raw[1:],
			}
		case "PING":
			fmt.Fprintf(c.out, "PONG :%s\n", sm.To)
		case RPL_MOTD:
		case RPL_MOTDSTART:
		case RPL_ENDOFMOTD:
		case RPL_WELCOME:
		case RPL_YOURHOST:
		case RPL_CREATED:
		case RPL_MYINFO:
		case RPL_BOUNCE:
		case RPL_LUSERCLIENT:
		case RPL_LUSEROP:
		case RPL_LUSERUNKNOWN:
		case RPL_LUSERCHANNELS:
		case RPL_LUSERME:
		case "MODE":
		default:
			log.Printf("Unhandled message %s\t\t%s", sm.Code, sm.Full)
		}
	}
	go func() {
		for {
			var m ServerMessage
			select {
			// TODO allow input on stdin
			case m = <-c.server:
				handleMessage(m)
			}
		}
	}()
	return ch
}

// Join the specified channel
func (c *Client) Join(ch string) {
	// TODO don't join until 001 is received
	log.Print("JOIN ", ch)
	fmt.Fprintf(c.out, "JOIN %s\n", ch)
}

// Join the specified channels
func (c *Client) JoinChannels(chs []string) {
	for _, ch := range chs {
		c.Join(ch)
	}
}

// Leave the specified channel
func (c *Client) Part(ch string) {
	log.Print("PART ", ch)
	fmt.Fprintf(c.out, "PART %s\n", ch)
}

func (c *Client) Quit(msg string) {
	log.Print("QUIT :", msg)
	fmt.Fprintf(c.out, "QUIT :%s\n", msg)
}

func (c *Client) PrivMsg(to, msg string) {
	fmt.Fprintf(c.out, "PRIVMSG %s :%s\n", to, msg)
}
<commit_msg>More comments<commit_after>package irc

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
)

type Client struct {
	connection net.Conn
	serverName string
	nick       string
	server     chan ServerMessage
	out        io.Writer
}

func parseServerMessage(line string) (m ServerMessage) {
	m.Full = line
	m.From, line, _ = nextField(line)
	if m.From[0] != ':' {
		m.Code = m.From
		m.From = ""
	} else {
		m.From = m.From[1:]
		m.Code, line, _ = nextField(line)
	}
	m.To, line, _ = nextField(line)
	m.Raw = line
	m.Fields = make([]string, 0)

	switch m.Code {
	case "NOTICE":
	case "PRIVMSG":
		m.Fields = append(m.Fields, line[1:])
	case RPL_BOUNCE:
	default:
		// fill in variable fields
		var f string
		f, line, b := nextField(line)
		for b {
			if f[0] == ':' {
				if f[1] == '-' {
					break
				}
				// read until f[len(f)-1] is a semicolon
				for b && len(f) > 0 && f[len(f)-1] != ':' {
					f, line, b = nextField(line)
				}
			} else {
				m.Fields = append(m.Fields, f)
			}
			f, line, b = nextField(line)
		}
	}
	return
}

func Connect(serverName, nick, realName string) (*Client, error) {
	conn, err := Dial(serverName)
	if err != nil {
		return conn, err
	}

	conn.Pass("notmeaningfull")
	conn.User(getUname(), getHostname(), getServername(), realName)
	conn.Nick(nick)
	return conn, nil
}

// Low-level method to connect to server - normal clients should not need this.
// Use Connect() instead.
func Dial(server string) (conn *Client, err error) {
	nconn, err := net.Dial("tcp", server)
	if err != nil {
		return
	}

	conn = new(Client)
	conn.connection = nconn
	conn.serverName = server
	conn.server = make(chan ServerMessage, serverMsgBufSize)
	conn.out = conn.connection

	// spawn the connection reader
	go func() {
		r, err := bufio.NewReaderSize(conn.connection, maxlinesize)
		if err != nil {
			panic(err)
		}

		line, beFalse, err := r.ReadLine()
		for err == nil && !beFalse {
			conn.server <- parseServerMessage(string(line))
			line, beFalse, err = r.ReadLine()
		}
		if beFalse {
			log.Fatal("Line too long")
		} else {
			log.Fatal(err) // TODO handle me better
		}
	}()
	return
}

func (c *Client) Pass(pass string) {
	fmt.Fprintf(c.out, "PASS %s\n", pass)
}

// Low-level method to send USER command - normal clients should not need this
func (c *Client) User(user, host, server, name string) {
	fmt.Fprintf(c.out, "USER %s %s %s :%s\n", user, host, server, name)
}

// Low-level method to send NICK command - normal clients should not need this.
func (c *Client) Nick(nick string) {
	fmt.Fprintf(c.out, "NICK %s\n", nick)
	c.nick = nick // TODO fix possible race condition
}

// Listen for messages coming in and return them on the returned channel. Also
// handles low-level information from the server correctly, making information
// available in the Client object as appropriate.
func (c *Client) Listen() <-chan Message {
	ch := make(chan Message)
	handleMessage := func(sm ServerMessage) {
		switch sm.Code {
		case "NOTICE":
			ch <- Message{
				Kind: MSG_NOTICE,
				From: sm.From,
				To:   sm.To,
				Text: sm.Raw[1:],
			}
		case "PRIVMSG":
			ch <- Message{
				Kind: MSG_PRIVMSG,
				From: sm.From,
				To:   sm.To,
				Text: sm.Raw[1:],
			}
		case "PING":
			fmt.Fprintf(c.out, "PONG :%s\n", sm.To)
		case RPL_MOTD:
		case RPL_MOTDSTART:
		case RPL_ENDOFMOTD:
		case RPL_WELCOME:
		case RPL_YOURHOST:
		case RPL_CREATED:
		case RPL_MYINFO:
		case RPL_BOUNCE:
		case RPL_LUSERCLIENT:
		case RPL_LUSEROP:
		case RPL_LUSERUNKNOWN:
		case RPL_LUSERCHANNELS:
		case RPL_LUSERME:
		case "MODE":
		default:
			log.Printf("Unhandled message %s\t\t%s", sm.Code, sm.Full)
		}
	}
	go func() {
		for {
			var m ServerMessage
			select {
			// TODO allow input on stdin
			case m = <-c.server:
				handleMessage(m)
			}
		}
	}()
	return ch
}

// Low-level method to join the specified channel. This does not modify the
// Client's internal channel tracking, and so should not be used by most
// clients.
func (c *Client) Join(ch string) {
	// TODO don't join until 001 is received
	log.Print("JOIN ", ch)
	fmt.Fprintf(c.out, "JOIN %s\n", ch)
}

// Join the specified channels. Equivalent to calling Join for each channel in the given slice.
func (c *Client) JoinChannels(chs []string) {
	for _, ch := range chs {
		c.Join(ch)
	}
}

// Low-level method to leave the specified channel. This does not modify the
// Client's internal channel tracking, and so should not be used by most
// clients.
func (c *Client) Part(ch string) {
	log.Print("PART ", ch)
	fmt.Fprintf(c.out, "PART %s\n", ch)
}

// Low-level method to send QUIT to the server.
func (c *Client) Quit(msg string) {
	log.Print("QUIT :", msg)
	fmt.Fprintf(c.out, "QUIT :%s\n", msg)
}

// Low-level method to send a private message (PRIVMSG).
func (c *Client) PrivMsg(to, msg string) {
	fmt.Fprintf(c.out, "PRIVMSG %s :%s\n", to, msg)
}
<|endoftext|>


<commit_before>// +build windows

package term

import (
	"os"
)

func IsANSI(f *os.File) bool {
	return false
}

// IsTerminal returns false on Windows.
func IsTerminal(f *os.File) bool {
	return false
}

// MakeRaw is a no-op on windows. It returns nil.
func MakeRaw(f *os.File) error {
	return nil
}

// Restore is a no-op on windows. It returns nil.
func Restore(f *os.File) error {
	return nil
}

// Cols returns 80 on Windows.
func Cols() (int, error) {
	return 80, nil
}

// Lines returns 24 on Windows.
func Lines() (int, error) {
	return 24, nil
}
<commit_msg>make IsTerminal() work on Windows<commit_after>// +build windows

package term

import (
	"os"
	"syscall"
)

func IsANSI(f *os.File) bool {
	return false
}

// IsTerminal returns false on Windows.
func IsTerminal(f *os.File) bool {
	ft, _ := syscall.GetFileType(syscall.Handle(f.Fd()))
	return ft == syscall.FILE_TYPE_CHAR
}

// MakeRaw is a no-op on windows. It returns nil.
func MakeRaw(f *os.File) error {
	return nil
}

// Restore is a no-op on windows. It returns nil.
func Restore(f *os.File) error {
	return nil
}

// Cols returns 80 on Windows.
func Cols() (int, error) {
	return 80, nil
}

// Lines returns 24 on Windows.
func Lines() (int, error) {
	return 24, nil
}
<|endoftext|>