<commit_before>package irc

import (
	"testing"
	"time"

	"github.com/jriddick/geoffrey/mockd"
	. "github.com/smartystreets/goconvey/convey"
)

var (
	defaultConfig = Config{
		Hostname:           "127.0.0.1",
		Port:               5000,
		Secure:             false,
		InsecureSkipVerify: false,
		Timeout:            time.Second * 30,
		TimeoutLimit:       5,
		MessagesPerSecond:  120,
	}
)

func TestClient(t *testing.T) {
	// Create the mockd server
	mockd := mockd.NewMockd(5000)

	// Start listening
	mockd.Listen()

	// Start accepting connections
	go mockd.Handle()

	Convey("With the default IRC client", t, func() {
		Convey("It should be able to connect", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect the client
			So(client.Connect(), ShouldBeNil)

			// Get the reader channel
			reader := client.Reader()

			// Read from the server
			So(<-reader, ShouldNotBeNil)
		})

		Convey("It should be able to register", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect to the server
			So(client.Connect(), ShouldBeNil)

			// Get the reader and writer channel
			reader := client.Reader()
			writer := client.Writer()

			// Read the first message
			So(<-reader, ShouldNotBeNil)

			// Send our registration
			writer <- "NICK geoffrey"
			writer <- "USER geoffrey 0 * :geoffrey"

			// Wait for our verification
			result := <-reader

			// Verify that we got what we needed
			So(result, ShouldNotBeNil)
			So(result.String(), ShouldEqual, ":geoffrey.com 001 Geoffrey :Welcome to the Geoffrey IRC Network!")
		})

		Convey("It should be able to reconnect", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect
			So(client.Connect(), ShouldBeNil)

			// Get the reader
			reader := client.Reader()

			// Wait until we get opening
			So(<-reader, ShouldNotBeNil)

			// Reconnect
			So(client.Reconnect(), ShouldBeNil)

			// Wait until we get opening
			So(<-reader, ShouldNotBeNil)
		})

		Convey("It should reject empty hostname", func() {
			// Open client
			client := NewIRC(Config{
				Hostname:           "",
				Port:               defaultConfig.Port,
				Secure:             defaultConfig.Secure,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            defaultConfig.Timeout,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should fail to connect
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should fail to connect securely to non-ssl server", func() {
			// Create the client
			client := NewIRC(Config{
				Hostname:           defaultConfig.Hostname,
				Port:               defaultConfig.Port,
				Secure:             true,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            defaultConfig.Timeout,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should fail to connect
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should not be able to connect twice", func() {
			// Create the client
			client := NewIRC(defaultConfig)

			// Should succeed to connect
			So(client.Connect(), ShouldBeNil)

			// Should not succeed a second time
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should not be able to send empty messages", func() {
			// Create the client
			client := NewIRC(defaultConfig)

			// Should succeed to connect
			So(client.Connect(), ShouldBeNil)

			// Get the writer
			writer := client.Writer()

			// Send empty message
			writer <- ""

			// Get error channel
			errors := client.Errors()

			// We should receive error
			err := <-errors

			// Check the error
			So(err, ShouldNotBeNil)
			So(err.Error(), ShouldEqual, "tried to send empty message")
		})

		Convey("It should be able to disconnect", func() {
			// Create the client
			client := NewIRC(Config{
				Hostname:           defaultConfig.Hostname,
				Port:               defaultConfig.Port,
				Secure:             defaultConfig.Secure,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            time.Second * 1,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should connect
			So(client.Connect(), ShouldBeNil)

			// Should disconnect
			client.Disconnect("Leaving")
		})
	})
}
<commit_msg>Fix exepected error message<commit_after>package irc

import (
	"testing"
	"time"

	"github.com/jriddick/geoffrey/mockd"
	. "github.com/smartystreets/goconvey/convey"
)

var (
	defaultConfig = Config{
		Hostname:           "127.0.0.1",
		Port:               5000,
		Secure:             false,
		InsecureSkipVerify: false,
		Timeout:            time.Second * 30,
		TimeoutLimit:       5,
		MessagesPerSecond:  120,
	}
)

func TestClient(t *testing.T) {
	// Create the mockd server
	mockd := mockd.NewMockd(5000)

	// Start listening
	mockd.Listen()

	// Start accepting connections
	go mockd.Handle()

	Convey("With the default IRC client", t, func() {
		Convey("It should be able to connect", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect the client
			So(client.Connect(), ShouldBeNil)

			// Get the reader channel
			reader := client.Reader()

			// Read from the server
			So(<-reader, ShouldNotBeNil)
		})

		Convey("It should be able to register", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect to the server
			So(client.Connect(), ShouldBeNil)

			// Get the reader and writer channel
			reader := client.Reader()
			writer := client.Writer()

			// Read the first message
			So(<-reader, ShouldNotBeNil)

			// Send our registration
			writer <- "NICK geoffrey"
			writer <- "USER geoffrey 0 * :geoffrey"

			// Wait for our verification
			result := <-reader

			// Verify that we got what we needed
			So(result, ShouldNotBeNil)
			So(result.String(), ShouldEqual, ":geoffrey.com 001 Geoffrey :Welcome to the Geoffrey IRC Network!")
		})

		Convey("It should be able to reconnect", func() {
			// Open client
			client := NewIRC(defaultConfig)

			// Connect
			So(client.Connect(), ShouldBeNil)

			// Get the reader
			reader := client.Reader()

			// Wait until we get opening
			So(<-reader, ShouldNotBeNil)

			// Reconnect
			So(client.Reconnect(), ShouldBeNil)

			// Wait until we get opening
			So(<-reader, ShouldNotBeNil)
		})

		Convey("It should reject empty hostname", func() {
			// Open client
			client := NewIRC(Config{
				Hostname:           "",
				Port:               defaultConfig.Port,
				Secure:             defaultConfig.Secure,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            defaultConfig.Timeout,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should fail to connect
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should fail to connect securely to non-ssl server", func() {
			// Create the client
			client := NewIRC(Config{
				Hostname:           defaultConfig.Hostname,
				Port:               defaultConfig.Port,
				Secure:             true,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            defaultConfig.Timeout,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should fail to connect
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should not be able to connect twice", func() {
			// Create the client
			client := NewIRC(defaultConfig)

			// Should succeed to connect
			So(client.Connect(), ShouldBeNil)

			// Should not succeed a second time
			So(client.Connect(), ShouldNotBeNil)
		})

		Convey("It should not be able to send empty messages", func() {
			// Create the client
			client := NewIRC(defaultConfig)

			// Should succeed to connect
			So(client.Connect(), ShouldBeNil)

			// Get the writer
			writer := client.Writer()

			// Send empty message
			writer <- ""

			// Get error channel
			errors := client.Errors()

			// We should receive error
			err := <-errors

			// Check the error
			So(err, ShouldNotBeNil)
			So(err.Error(), ShouldEqual, "[geoffrey] Tried to send empty message")
		})

		Convey("It should be able to disconnect", func() {
			// Create the client
			client := NewIRC(Config{
				Hostname:           defaultConfig.Hostname,
				Port:               defaultConfig.Port,
				Secure:             defaultConfig.Secure,
				InsecureSkipVerify: defaultConfig.InsecureSkipVerify,
				Timeout:            time.Second * 1,
				TimeoutLimit:       defaultConfig.TimeoutLimit,
				MessagesPerSecond:  defaultConfig.MessagesPerSecond,
			})

			// Should connect
			So(client.Connect(), ShouldBeNil)

			// Should disconnect
			client.Disconnect("Leaving")
		})
	})
}
<|endoftext|>


<commit_before>package irc

import (
	"strings"
	"fmt"
	"time"
	"strconv"
)

func (irc *IRCConnection) AddCallback(eventcode string, callback func(*IRCEvent)) {
	eventcode = strings.ToUpper(eventcode)
	if event, ok := irc.events[eventcode]; ok {
		// TODO: Grow this dynamically
		event = event[0 : len(event)+1]
		event[len(event)-1] = callback
	} else {
		event = make([]func(*IRCEvent), 1, 20)
		event[0] = callback
		irc.events[eventcode] = event
	}
}

func (irc *IRCConnection) ReplaceCallback(i uint8, eventcode string, callback func(*IRCEvent)) {
	eventcode = strings.ToUpper(eventcode)
	if event, ok := irc.events[eventcode]; ok {
		event[i] = callback
	} else {
		event = make([]func(*IRCEvent), 1, 20)
		event[0] = callback
		irc.events[eventcode] = event
	}
}

func (irc *IRCConnection) RunCallbacks(event *IRCEvent) {
	if event.Code == "PRIVMSG" && event.Message[0] == '\x01' {
		event.Code = "CTCP" //Unknown CTCP
		if i := strings.LastIndex(event.Message, "\x01"); i > -1 {
			event.Message = event.Message[1:i]
		}
		if event.Message == "VERSION" {
			event.Code = "CTCP_VERSION"
		} else if event.Message == "TIME" {
			event.Code = "CTCP_TIME"
		} else if event.Message[0:4] == "PING" {
			event.Code = "CTCP_PING"
		} else if event.Message == "USERINFO" {
			event.Code = "CTCP_USERINFO"
		} else if event.Message == "CLIENTINFO" {
			event.Code = "CTCP_CLIENTINFO"
		}
	}
	if callbacks, ok := irc.events[event.Code]; ok {
		for _, callback := range callbacks {
			go callback(event)
		}
	} else {
		fmt.Printf("No callback for: %#v\n", event)
	}
}

func (irc *IRCConnection) setupCallbacks() {
	irc.events = make(map[string][]func(*IRCEvent))

	//Handle ping events
	irc.AddCallback("PING", func(e *IRCEvent) { irc.SendRaw("PONG :" + e.Message) })

	//Version handler
	irc.AddCallback("CTCP_VERSION", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01VERSION %s\x01", e.Nick, VERSION))
	})

	irc.AddCallback("CTCP_USERINFO", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01USERINFO %s\x01", e.Nick, irc.user))
	})

	irc.AddCallback("CTCP_CLIENTINFO", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\x01", e.Nick))
	})

	irc.AddCallback("CTCP_TIME", func(e *IRCEvent) {
		ltime := time.LocalTime();
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01TIME %s\x01", e.Nick, ltime.String()))
	})

	irc.AddCallback("CTCP_PING", func(e *IRCEvent) { irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01%s\x01", e.Nick, e.Message)) })

	irc.AddCallback("437", func(e *IRCEvent) {
		irc.nick = irc.nick + "_"
		irc.SendRaw(fmt.Sprintf("NICK %s", irc.nick))
	})

	irc.AddCallback("433", func(e *IRCEvent) {
		irc.nick = irc.nick + "_"
		irc.SendRaw(fmt.Sprintf("NICK %s", irc.nick))
	})

	irc.AddCallback("PONG", func(e *IRCEvent) {
		ns, _ := strconv.Atoi64(e.Message)
		fmt.Printf("Lag: %fs\n", float((time.Nanoseconds()-ns))/1000/1000/1000)
	})
}
<commit_msg>Better parameter order for ReplaceCallback<commit_after>package irc

import (
	"strings"
	"fmt"
	"time"
	"strconv"
)

func (irc *IRCConnection) AddCallback(eventcode string, callback func(*IRCEvent)) {
	eventcode = strings.ToUpper(eventcode)
	if event, ok := irc.events[eventcode]; ok {
		// TODO: Grow this dynamically
		event = event[0 : len(event)+1]
		event[len(event)-1] = callback
	} else {
		event = make([]func(*IRCEvent), 1, 20)
		event[0] = callback
		irc.events[eventcode] = event
	}
}

func (irc *IRCConnection) ReplaceCallback(eventcode string, i uint8, callback func(*IRCEvent)) {
	eventcode = strings.ToUpper(eventcode)
	if event, ok := irc.events[eventcode]; ok {
		event[i] = callback
	} else {
		event = make([]func(*IRCEvent), 1, 20)
		event[0] = callback
		irc.events[eventcode] = event
	}
}

func (irc *IRCConnection) RunCallbacks(event *IRCEvent) {
	if event.Code == "PRIVMSG" && event.Message[0] == '\x01' {
		event.Code = "CTCP" //Unknown CTCP
		if i := strings.LastIndex(event.Message, "\x01"); i > -1 {
			event.Message = event.Message[1:i]
		}
		if event.Message == "VERSION" {
			event.Code = "CTCP_VERSION"
		} else if event.Message == "TIME" {
			event.Code = "CTCP_TIME"
		} else if event.Message[0:4] == "PING" {
			event.Code = "CTCP_PING"
		} else if event.Message == "USERINFO" {
			event.Code = "CTCP_USERINFO"
		} else if event.Message == "CLIENTINFO" {
			event.Code = "CTCP_CLIENTINFO"
		}
	}
	if callbacks, ok := irc.events[event.Code]; ok {
		for _, callback := range callbacks {
			go callback(event)
		}
	} else {
		fmt.Printf("No callback for: %#v\n", event)
	}
}

func (irc *IRCConnection) setupCallbacks() {
	irc.events = make(map[string][]func(*IRCEvent))

	//Handle ping events
	irc.AddCallback("PING", func(e *IRCEvent) { irc.SendRaw("PONG :" + e.Message) })

	//Version handler
	irc.AddCallback("CTCP_VERSION", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01VERSION %s\x01", e.Nick, VERSION))
	})

	irc.AddCallback("CTCP_USERINFO", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01USERINFO %s\x01", e.Nick, irc.user))
	})

	irc.AddCallback("CTCP_CLIENTINFO", func(e *IRCEvent) {
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\x01", e.Nick))
	})

	irc.AddCallback("CTCP_TIME", func(e *IRCEvent) {
		ltime := time.LocalTime();
		irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01TIME %s\x01", e.Nick, ltime.String()))
	})

	irc.AddCallback("CTCP_PING", func(e *IRCEvent) { irc.SendRaw(fmt.Sprintf("NOTICE %s :\x01%s\x01", e.Nick, e.Message)) })

	irc.AddCallback("437", func(e *IRCEvent) {
		irc.nick = irc.nick + "_"
		irc.SendRaw(fmt.Sprintf("NICK %s", irc.nick))
	})

	irc.AddCallback("433", func(e *IRCEvent) {
		irc.nick = irc.nick + "_"
		irc.SendRaw(fmt.Sprintf("NICK %s", irc.nick))
	})

	irc.AddCallback("PONG", func(e *IRCEvent) {
		ns, _ := strconv.Atoi64(e.Message)
		fmt.Printf("Lag: %fs\n", float((time.Nanoseconds()-ns))/1000/1000/1000)
	})
}
<|endoftext|>


<commit_before>package main

// These constants come from /usr/include/X11/keysymdef.h.

import (
	xp "github.com/BurntSushi/xgb/xproto"
)

const (
	xkISOLeftTab = 0xfe20
	xkBackspace  = 0xff08
	xkTab        = 0xff09
	xkReturn     = 0xff0d
	xkEscape     = 0xff1b
	xkHome       = 0xff50
	xkLeft       = 0xff51
	xkUp         = 0xff52
	xkRight      = 0xff53
	xkDown       = 0xff54
	xkPageUp     = 0xff55
	xkPageDown   = 0xff56
	xkEnd        = 0xff57
	xkMenu       = 0xff67
	xkF1         = 0xffbe
	xkF2         = 0xffbf
	xkF3         = 0xffc0
	xkF4         = 0xffc1
	xkF5         = 0xffc2
	xkF6         = 0xffc3
	xkF7         = 0xffc4
	xkF8         = 0xffc5
	xkF9         = 0xffc6
	xkF10        = 0xffc7
	xkF11        = 0xffc8
	xkF12        = 0xffc9
	xkShiftL     = 0xffe1
	xkShiftR     = 0xffe2
	xkControlL   = 0xffe3
	xkControlR   = 0xffe4
	xkCapsLock   = 0xffe5
	xkShiftLock  = 0xffe6
	xkMetaL      = 0xffe7
	xkMetaR      = 0xffe8
	xkAltL       = 0xffe9
	xkAltR       = 0xffea
	xkSuperL     = 0xffeb
	xkSuperR     = 0xffec
	xkHyperL     = 0xffed
	xkHyperR     = 0xffee
	xkDelete     = 0xffff
)

func keysymString(keysym xp.Keysym) string {
	switch keysym {
	case xkShiftL:
		return "ShiftL"
	case xkShiftR:
		return "ShiftR"
	case xkControlL:
		return "ControlL"
	case xkControlR:
		return "ControlR"
	case xkCapsLock:
		return "CapsLock"
	case xkShiftLock:
		return "ShiftLock"
	case xkMetaL:
		return "MetaL"
	case xkMetaR:
		return "MetaR"
	case xkAltL:
		return "AltL"
	case xkAltR:
		return "AltR"
	case xkSuperL:
		return "SuperL"
	case xkSuperR:
		return "SuperR"
	case xkHyperL:
		return "HyperL"
	case xkHyperR:
		return "HyperR"
	}
	return "UnknownKeysym"
}
<commit_msg>taowm: add a keysymString case for xkMenu.<commit_after>package main

// These constants come from /usr/include/X11/keysymdef.h.

import (
	xp "github.com/BurntSushi/xgb/xproto"
)

const (
	xkISOLeftTab = 0xfe20
	xkBackspace  = 0xff08
	xkTab        = 0xff09
	xkReturn     = 0xff0d
	xkEscape     = 0xff1b
	xkHome       = 0xff50
	xkLeft       = 0xff51
	xkUp         = 0xff52
	xkRight      = 0xff53
	xkDown       = 0xff54
	xkPageUp     = 0xff55
	xkPageDown   = 0xff56
	xkEnd        = 0xff57
	xkMenu       = 0xff67
	xkF1         = 0xffbe
	xkF2         = 0xffbf
	xkF3         = 0xffc0
	xkF4         = 0xffc1
	xkF5         = 0xffc2
	xkF6         = 0xffc3
	xkF7         = 0xffc4
	xkF8         = 0xffc5
	xkF9         = 0xffc6
	xkF10        = 0xffc7
	xkF11        = 0xffc8
	xkF12        = 0xffc9
	xkShiftL     = 0xffe1
	xkShiftR     = 0xffe2
	xkControlL   = 0xffe3
	xkControlR   = 0xffe4
	xkCapsLock   = 0xffe5
	xkShiftLock  = 0xffe6
	xkMetaL      = 0xffe7
	xkMetaR      = 0xffe8
	xkAltL       = 0xffe9
	xkAltR       = 0xffea
	xkSuperL     = 0xffeb
	xkSuperR     = 0xffec
	xkHyperL     = 0xffed
	xkHyperR     = 0xffee
	xkDelete     = 0xffff
)

func keysymString(keysym xp.Keysym) string {
	switch keysym {
	case xkMenu:
		return "Menu"
	case xkShiftL:
		return "ShiftL"
	case xkShiftR:
		return "ShiftR"
	case xkControlL:
		return "ControlL"
	case xkControlR:
		return "ControlR"
	case xkCapsLock:
		return "CapsLock"
	case xkShiftLock:
		return "ShiftLock"
	case xkMetaL:
		return "MetaL"
	case xkMetaR:
		return "MetaR"
	case xkAltL:
		return "AltL"
	case xkAltR:
		return "AltR"
	case xkSuperL:
		return "SuperL"
	case xkSuperR:
		return "SuperR"
	case xkHyperL:
		return "HyperL"
	case xkHyperR:
		return "HyperR"
	}
	return "UnknownKeysym"
}
<|endoftext|>


<commit_before>package auth

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"os"

	"github.com/Sirupsen/logrus"
)

// AuthResource represents the user after a valid authentication
// EntityId is the primary identifier
// EntityType is the type of user to authorize, like user, group, robot ...
// DisplayName is the user friendly name for the user id
// Email is the email of the user
// AuthType is the type of authentication used for this user
// Extra is a flexible field for auth providers to provide extra information
type AuthResource struct {
	Username    string `json:"username"`
	DisplayName string `json:"displayName"`
	Email       string `json:"email"`
}

func newAuthResource(username, displayName, email string) *AuthResource {
	// do some validations
	// authType, username, userUser, email valid chars PORTABLE v3
	authRes := AuthResource{username, displayName, email}
	return &authRes
}

// AuthProvider is a AuthProvider that uses a MySQL database
// for authentication purposes.
type AuthProvider struct {
	authFile string
}

// NewAuthProvider returns a AuthPovider or an error in case of failure
func NewAuthProvider(authFile string) (*AuthProvider, error) {
	return &AuthProvider{authFile}, nil
}

// Authenticate authenticate the request agains the file and returns
// an AuthResource or a validation error or a serve error
func (a *AuthProvider) Authenticate(username, password string) (*AuthResource, error) {
	fd, err := os.Open(a.authFile)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	data, err := ioutil.ReadAll(fd)
	type user struct {
		Username    string `json:"username"`
		Password    string `json:"password"`
		DisplayName string `json:"display_name"`
		Email       string `json:"email"`
	}
	users := make([]*user, 0)
	err = json.Unmarshal(data, &users)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	for _, user := range users {
		if user.Username == username && user.Password == password {
			authRes := newAuthResource(user.Username, user.DisplayName, user.Email)
			return authRes, nil
		}
	}
	return nil, errors.New("user not found")
}
<commit_msg>fix typo<commit_after>package auth

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"os"

	"github.com/Sirupsen/logrus"
)

// AuthResource represents the user after a valid authentication
// EntityId is the primary identifier
// EntityType is the type of user to authorize, like user, group, robot ...
// DisplayName is the user friendly name for the user id
// Email is the email of the user
// AuthType is the type of authentication used for this user
// Extra is a flexible field for auth providers to provide extra information
type AuthResource struct {
	Username    string `json:"username"`
	DisplayName string `json:"displayName"`
	Email       string `json:"email"`
}

func newAuthResource(username, displayName, email string) *AuthResource {
	// do some validations
	// authType, username, userUser, email valid chars PORTABLE v3
	authRes := AuthResource{username, displayName, email}
	return &authRes
}

// AuthProvider is a AuthProvider that uses a MySQL database
// for authentication purposes.
type AuthProvider struct {
	authFile string
}

// NewAuthProvider returns a AuthPovider or an error in case of failure
func NewAuthProvider(authFile string) (*AuthProvider, error) {
	return &AuthProvider{authFile}, nil
}

// Authenticate authenticate the request agains the file and returns
// an AuthResource or a validation error or a serve error
func (a *AuthProvider) Authenticate(username, password string) (*AuthResource, error) {
	fd, err := os.Open(a.authFile)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	data, err := ioutil.ReadAll(fd)
	type user struct {
		Username    string `json:"username"`
		Password    string `json:"password"`
		DisplayName string `json:"displayName"`
		Email       string `json:"email"`
	}
	users := make([]*user, 0)
	err = json.Unmarshal(data, &users)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	for _, user := range users {
		if user.Username == username && user.Password == password {
			authRes := newAuthResource(user.Username, user.DisplayName, user.Email)
			return authRes, nil
		}
	}
	return nil, errors.New("user not found")
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"net/url"
	"os"
	"strings"

	"code.cloudfoundry.org/cli/plugin"
	"github.com/contraband/autopilot/rewind"
)

func fatalIf(err error) {
	if err != nil {
		fmt.Fprintln(os.Stdout, "error:", err)
		os.Exit(1)
	}
}

func main() {
	plugin.Start(&AutopilotPlugin{})
}

type AutopilotPlugin struct{}

func venerableAppName(appName string) string {
	return fmt.Sprintf("%s-venerable", appName)
}

func getActionsForExistingApp(appRepo *ApplicationRepo, appName, manifestPath, appPath string) []rewind.Action {
	return []rewind.Action{
		// rename
		{
			Forward: func() error {
				return appRepo.RenameApplication(appName, venerableAppName(appName))
			},
		},
		// push
		{
			Forward: func() error {
				return appRepo.PushApplication(appName, manifestPath, appPath)
			},
			ReversePrevious: func() error {
				// If the app cannot start we'll have a lingering application
				// We delete this application so that the rename can succeed
				appRepo.DeleteApplication(appName)

				return appRepo.RenameApplication(venerableAppName(appName), appName)
			},
		},
		// delete
		{
			Forward: func() error {
				return appRepo.DeleteApplication(venerableAppName(appName))
			},
		},
	}
}

func getActionsForNewApp(appRepo *ApplicationRepo, appName, manifestPath, appPath string) []rewind.Action {
	return []rewind.Action{
		// push
		{
			Forward: func() error {
				return appRepo.PushApplication(appName, manifestPath, appPath)
			},
		},
	}
}

func (plugin AutopilotPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	if len(args) > 0 && args[0] == "CLI-MESSAGE-UNINSTALL" {
		return
	}

	appRepo := NewApplicationRepo(cliConnection)
	appName, manifestPath, appPath, err := ParseArgs(args)
	fatalIf(err)

	appExists, err := appRepo.DoesAppExist(appName)
	fatalIf(err)

	var actionList []rewind.Action

	if appExists {
		actionList = getActionsForExistingApp(appRepo, appName, manifestPath, appPath)
	} else {
		actionList = getActionsForNewApp(appRepo, appName, manifestPath, appPath)
	}

	actions := rewind.Actions{
		Actions:              actionList,
		RewindFailureMessage: "Oh no. Something's gone wrong. I've tried to roll back but you should check to see if everything is OK.",
	}

	err = actions.Execute()
	fatalIf(err)

	fmt.Println()
	fmt.Println("A new version of your application has successfully been pushed!")
	fmt.Println()

	_ = appRepo.ListApplications()
}

func (AutopilotPlugin) GetMetadata() plugin.PluginMetadata {
	return plugin.PluginMetadata{
		Name: "autopilot",
		Version: plugin.VersionType{
			Major: 0,
			Minor: 0,
			Build: 3,
		},
		Commands: []plugin.Command{
			{
				Name:     "zero-downtime-push",
				HelpText: "Perform a zero-downtime push of an application over the top of an old one",
				UsageDetails: plugin.Usage{
					Usage: "$ cf zero-downtime-push application-to-replace \\ \n \t-f path/to/new_manifest.yml \\ \n \t-p path/to/new/path",
				},
			},
		},
	}
}

func ParseArgs(args []string) (string, string, string, error) {
	flags := flag.NewFlagSet("zero-downtime-push", flag.ContinueOnError)
	manifestPath := flags.String("f", "", "path to an application manifest")
	appPath := flags.String("p", "", "path to application files")

	err := flags.Parse(args[2:])
	if err != nil {
		return "", "", "", err
	}

	appName := args[1]

	if *manifestPath == "" {
		return "", "", "", ErrNoManifest
	}

	return appName, *manifestPath, *appPath, nil
}

var ErrNoManifest = errors.New("a manifest is required to push this application")

type ApplicationRepo struct {
	conn plugin.CliConnection
}

func NewApplicationRepo(conn plugin.CliConnection) *ApplicationRepo {
	return &ApplicationRepo{
		conn: conn,
	}
}

func (repo *ApplicationRepo) RenameApplication(oldName, newName string) error {
	_, err := repo.conn.CliCommand("rename", oldName, newName)
	return err
}

func (repo *ApplicationRepo) PushApplication(appName, manifestPath, appPath string) error {
	args := []string{"push", appName, "-f", manifestPath}

	if appPath != "" {
		args = append(args, "-p", appPath)
	}

	_, err := repo.conn.CliCommand(args...)
	return err
}

func (repo *ApplicationRepo) DeleteApplication(appName string) error {
	_, err := repo.conn.CliCommand("delete", appName, "-f")
	return err
}

func (repo *ApplicationRepo) ListApplications() error {
	_, err := repo.conn.CliCommand("apps")
	return err
}

func (repo *ApplicationRepo) DoesAppExist(appName string) (bool, error) {
	space, err := repo.conn.GetCurrentSpace()
	if err != nil {
		return false, err
	}

	path := fmt.Sprintf(`v2/apps?q=name:%s&q=space_guid:%s`, url.QueryEscape(appName), space.Guid)
	result, err := repo.conn.CliCommandWithoutTerminalOutput("curl", path)

	if err != nil {
		return false, err
	}

	jsonResp := strings.Join(result, "")

	output := make(map[string]interface{})
	err = json.Unmarshal([]byte(jsonResp), &output)

	if err != nil {
		return false, err
	}

	totalResults, ok := output["total_results"]

	if !ok {
		return false, errors.New("Missing total_results from api response")
	}

	count, ok := totalResults.(float64)

	if !ok {
		return false, fmt.Errorf("total_results didn't have a number %v", totalResults)
	}

	return count == 1, nil
}
<commit_msg>bump to fix version problem<commit_after>package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"net/url"
	"os"
	"strings"

	"code.cloudfoundry.org/cli/plugin"
	"github.com/contraband/autopilot/rewind"
)

func fatalIf(err error) {
	if err != nil {
		fmt.Fprintln(os.Stdout, "error:", err)
		os.Exit(1)
	}
}

func main() {
	plugin.Start(&AutopilotPlugin{})
}

type AutopilotPlugin struct{}

func venerableAppName(appName string) string {
	return fmt.Sprintf("%s-venerable", appName)
}

func getActionsForExistingApp(appRepo *ApplicationRepo, appName, manifestPath, appPath string) []rewind.Action {
	return []rewind.Action{
		// rename
		{
			Forward: func() error {
				return appRepo.RenameApplication(appName, venerableAppName(appName))
			},
		},
		// push
		{
			Forward: func() error {
				return appRepo.PushApplication(appName, manifestPath, appPath)
			},
			ReversePrevious: func() error {
				// If the app cannot start we'll have a lingering application
				// We delete this application so that the rename can succeed
				appRepo.DeleteApplication(appName)

				return appRepo.RenameApplication(venerableAppName(appName), appName)
			},
		},
		// delete
		{
			Forward: func() error {
				return appRepo.DeleteApplication(venerableAppName(appName))
			},
		},
	}
}

func getActionsForNewApp(appRepo *ApplicationRepo, appName, manifestPath, appPath string) []rewind.Action {
	return []rewind.Action{
		// push
		{
			Forward: func() error {
				return appRepo.PushApplication(appName, manifestPath, appPath)
			},
		},
	}
}

func (plugin AutopilotPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	if len(args) > 0 && args[0] == "CLI-MESSAGE-UNINSTALL" {
		return
	}

	appRepo := NewApplicationRepo(cliConnection)
	appName, manifestPath, appPath, err := ParseArgs(args)
	fatalIf(err)

	appExists, err := appRepo.DoesAppExist(appName)
	fatalIf(err)

	var actionList []rewind.Action

	if appExists {
		actionList = getActionsForExistingApp(appRepo, appName, manifestPath, appPath)
	} else {
		actionList = getActionsForNewApp(appRepo, appName, manifestPath, appPath)
	}

	actions := rewind.Actions{
		Actions:              actionList,
		RewindFailureMessage: "Oh no. Something's gone wrong. I've tried to roll back but you should check to see if everything is OK.",
	}

	err = actions.Execute()
	fatalIf(err)

	fmt.Println()
	fmt.Println("A new version of your application has successfully been pushed!")
	fmt.Println()

	_ = appRepo.ListApplications()
}

func (AutopilotPlugin) GetMetadata() plugin.PluginMetadata {
	return plugin.PluginMetadata{
		Name: "autopilot",
		Version: plugin.VersionType{
			Major: 0,
			Minor: 0,
			Build: 4,
		},
		Commands: []plugin.Command{
			{
				Name:     "zero-downtime-push",
				HelpText: "Perform a zero-downtime push of an application over the top of an old one",
				UsageDetails: plugin.Usage{
					Usage: "$ cf zero-downtime-push application-to-replace \\ \n \t-f path/to/new_manifest.yml \\ \n \t-p path/to/new/path",
				},
			},
		},
	}
}

func ParseArgs(args []string) (string, string, string, error) {
	flags := flag.NewFlagSet("zero-downtime-push", flag.ContinueOnError)
	manifestPath := flags.String("f", "", "path to an application manifest")
	appPath := flags.String("p", "", "path to application files")

	err := flags.Parse(args[2:])
	if err != nil {
		return "", "", "", err
	}

	appName := args[1]

	if *manifestPath == "" {
		return "", "", "", ErrNoManifest
	}

	return appName, *manifestPath, *appPath, nil
}

var ErrNoManifest = errors.New("a manifest is required to push this application")

type ApplicationRepo struct {
	conn plugin.CliConnection
}

func NewApplicationRepo(conn plugin.CliConnection) *ApplicationRepo {
	return &ApplicationRepo{
		conn: conn,
	}
}

func (repo *ApplicationRepo) RenameApplication(oldName, newName string) error {
	_, err := repo.conn.CliCommand("rename", oldName, newName)
	return err
}

func (repo *ApplicationRepo) PushApplication(appName, manifestPath, appPath string) error {
	args := []string{"push", appName, "-f", manifestPath}

	if appPath != "" {
		args = append(args, "-p", appPath)
	}

	_, err := repo.conn.CliCommand(args...)
	return err
}

func (repo *ApplicationRepo) DeleteApplication(appName string) error {
	_, err := repo.conn.CliCommand("delete", appName, "-f")
	return err
}

func (repo *ApplicationRepo) ListApplications() error {
	_, err := repo.conn.CliCommand("apps")
	return err
}

func (repo *ApplicationRepo) DoesAppExist(appName string) (bool, error) {
	space, err := repo.conn.GetCurrentSpace()
	if err != nil {
		return false, err
	}

	path := fmt.Sprintf(`v2/apps?q=name:%s&q=space_guid:%s`, url.QueryEscape(appName), space.Guid)
	result, err := repo.conn.CliCommandWithoutTerminalOutput("curl", path)

	if err != nil {
		return false, err
	}

	jsonResp := strings.Join(result, "")

	output := make(map[string]interface{})
	err = json.Unmarshal([]byte(jsonResp), &output)

	if err != nil {
		return false, err
	}

	totalResults, ok := output["total_results"]

	if !ok {
		return false, errors.New("Missing total_results from api response")
	}

	count, ok := totalResults.(float64)

	if !ok {
		return false, fmt.Errorf("total_results didn't have a number %v", totalResults)
	}

	return count == 1, nil
}
<|endoftext|>


<commit_before>package sim

import (
	"encoding/json"
	"time"

	"github.com/Queens-Hacks/Propagate/sandbox"
	"github.com/Sirupsen/logrus"
)

type MarshalledState struct {
	State []byte
	Diff  []byte
}

// After calling this function it is no longer safe to do anything with s from
// outside of the simulation
func (s *State) StartSimulate() <-chan MarshalledState {
	ch := make(chan MarshalledState)

	go func() {
		// We want to run the thing every 500 milliseconds
		tick := time.NewTicker(time.Millisecond * 500)

		for {
			s.simulateTick()

			if !s.diff.isEmpty() {
				md, err := json.Marshal(s.diff)
				if err != nil {
					logrus.Fatal(err)
				}
				ms, err := json.Marshal(s.state)
				if err != nil {
					logrus.Fatal(err)
				}

				spores := []spore{}
				if s.diff.Spores != nil {
					spores = s.diff.Spores
				}

				s.diff = diff{[]tileDiff{}, map[string]*Species{}, []string{}, spores}
				ch <- MarshalledState{ms, md}
			}

			<-tick.C
		}
	}()

	return ch
}

func (s *State) mkWorldState(_ *growthRoot) sandbox.WorldState {
	var ws sandbox.WorldState
	ws.Lighting = map[sandbox.Direction]float64{}

	ws.Lighting[sandbox.Left] = 0
	ws.Lighting[sandbox.Right] = 0
	ws.Lighting[sandbox.Up] = 0
	ws.Lighting[sandbox.Down] = 0

	return ws
}

func boundsCheck(loc Location, mh int, mw int) Location {
	// Can't move there, it's out of bounds!
	if loc.Y < 0 {
		logrus.Info("newY out of bounds", loc.Y)
		loc.Y = 0
	}

	if loc.Y >= mh {
		logrus.Info("newY out of bounds", loc.Y)
		loc.Y = mh - 1
	}

	// loop around loop
	if loc.X < 0 {
		loc.X = mw + loc.X
	} else if loc.X >= mw {
		loc.X = loc.X - mw
	}

	return loc
}

func (s *State) DirectionToLocation(loc Location, dir sandbox.Direction) Location {
	new := loc

	if dir == sandbox.Left {
		new.X -= 1
	} else if dir == sandbox.Right {
		new.X += 1
	} else if dir == sandbox.Up {
		new.Y -= 1
	} else if dir == sandbox.Down {
		new.Y += 1
	}

	new = boundsCheck(new, s.Height(), s.Width())

	return new // new looks good!
}

func (s *State) applyChanges(root *growthRoot, in sandbox.NewState) {
	new := root.Loc

	if in.Operation == sandbox.Move {
		new = s.DirectionToLocation(root.Loc, in.Dir)
		s.SetTile(new, Tile{PlantTile, &extraTileInfo{
			root.SpeciesId,
			root.Loc,
			false,
			root.Plant,
		}})
	} else if in.Operation == sandbox.Split {
		tmp := s.DirectionToLocation(root.Loc, in.Dir)
		s.SetTile(tmp, Tile{PlantTile, &extraTileInfo{
			root.SpeciesId,
			root.Loc,
			false,
			root.Plant,
		}})

		// Add the new root for the new plant
		s.AddGrowth(tmp, root.Plant, in.Meta)
	} else if in.Operation == sandbox.Wait {
		// that was easy
		return
	} else {
		logrus.Warn("Unrecognized Operation")
		return
	}

	// XXX Should this go through a method rather than direct mutation?
	// Move the growth root to the new location
	root.Loc = new
}

type newStateInfo struct {
	ch   <-chan sandbox.NewState
	root *growthRoot
}

// This is called by a timer every n time units
func (s *State) simulateTick() {
	responses := []newStateInfo{}
	deadNodes := []*growthRoot{}

	// Tell each root to run until the next move operation
	for root := range s.state.roots {
		ch, ok := root.node.Update(s.mkWorldState(root))
		if !ok {
			// We have to remove the node later
			deadNodes = append(deadNodes, root)
			continue
		}

		responses = append(responses, newStateInfo{ch, root})
	}

	for _, dead := range deadNodes {
		delete(s.state.roots, dead)
	}

	for _, response := range responses {
		newState, ok := <-response.ch
		if !ok {
			continue
		}
		s.applyChanges(response.root, newState)
	}

	spores := []spore{}
	for _, p := range s.diff.Spores {
		// UpdateSpore returns true if it has planted the spore
		spawned := s.UpdateSpore(&p)
		// Unplanted spores are kept for next tick
		if !spawned {
			spores = append(spores, p)
		}
	}
	s.diff.Spores = spores

	surviving := make([]*Plant, 0, len(s.state.plants))
	for _, p := range s.state.plants {
		deltaEnergy := 0
		for _ = range p.tiles {
			deltaEnergy += 10
		}

		p.Energy += deltaEnergy
		p.Energy -= (p.Age * p.Age)

		if p.Energy < 0 {
			for t := range p.tiles {
				t.Type = AirTile
				t.Extra = nil
			}
			for r := range s.state.roots {
				if r.Plant == p {
					s.HaltGrowth(r)
				}
			}

		} else {
			surviving = append(surviving, p)
		}

		p.Age++
	}
	s.state.plants = surviving

}
<commit_msg>add check to stop PlantTile overwriting in applyChanges<commit_after>package sim

import (
	"encoding/json"
	"time"

	"github.com/Queens-Hacks/Propagate/sandbox"
	"github.com/Sirupsen/logrus"
)

type MarshalledState struct {
	State []byte
	Diff  []byte
}

// After calling this function it is no longer safe to do anything with s from
// outside of the simulation
func (s *State) StartSimulate() <-chan MarshalledState {
	ch := make(chan MarshalledState)

	go func() {
		// We want to run the thing every 500 milliseconds
		tick := time.NewTicker(time.Millisecond * 500)

		for {
			s.simulateTick()

			if !s.diff.isEmpty() {
				md, err := json.Marshal(s.diff)
				if err != nil {
					logrus.Fatal(err)
				}
				ms, err := json.Marshal(s.state)
				if err != nil {
					logrus.Fatal(err)
				}

				spores := []spore{}
				if s.diff.Spores != nil {
					spores = s.diff.Spores
				}

				s.diff = diff{[]tileDiff{}, map[string]*Species{}, []string{}, spores}
				ch <- MarshalledState{ms, md}
			}

			<-tick.C
		}
	}()

	return ch
}

func (s *State) mkWorldState(_ *growthRoot) sandbox.WorldState {
	var ws sandbox.WorldState
	ws.Lighting = map[sandbox.Direction]float64{}

	ws.Lighting[sandbox.Left] = 0
	ws.Lighting[sandbox.Right] = 0
	ws.Lighting[sandbox.Up] = 0
	ws.Lighting[sandbox.Down] = 0

	return ws
}

func boundsCheck(loc Location, mh int, mw int) Location {
	// Can't move there, it's out of bounds!
	if loc.Y < 0 {
		logrus.Info("newY out of bounds", loc.Y)
		loc.Y = 0
	}

	if loc.Y >= mh {
		logrus.Info("newY out of bounds", loc.Y)
		loc.Y = mh - 1
	}

	// loop around loop
	if loc.X < 0 {
		loc.X = mw + loc.X
	} else if loc.X >= mw {
		loc.X = loc.X - mw
	}

	return loc
}

func (s *State) DirectionToLocation(loc Location, dir sandbox.Direction) Location {
	new := loc

	if dir == sandbox.Left {
		new.X -= 1
	} else if dir == sandbox.Right {
		new.X += 1
	} else if dir == sandbox.Up {
		new.Y -= 1
	} else if dir == sandbox.Down {
		new.Y += 1
	}

	new = boundsCheck(new, s.Height(), s.Width())

	return new // new looks good!
}

func (s *State) applyChanges(root *growthRoot, in sandbox.NewState) {
	new := root.Loc

	if in.Operation == sandbox.Move {
		new = s.DirectionToLocation(root.Loc, in.Dir)

		if s.GetTile(new).Type == PlantTile {
			return
		}

		s.SetTile(new, Tile{PlantTile, &extraTileInfo{
			root.SpeciesId,
			root.Loc,
			false,
			root.Plant,
		}})
	} else if in.Operation == sandbox.Split {
		tmp := s.DirectionToLocation(root.Loc, in.Dir)

		if s.GetTile(tmp).Type == PlantTile {
			return
		}

		s.SetTile(tmp, Tile{PlantTile, &extraTileInfo{
			root.SpeciesId,
			root.Loc,
			false,
			root.Plant,
		}})

		// Add the new root for the new plant
		s.AddGrowth(tmp, root.Plant, in.Meta)
	} else if in.Operation == sandbox.Wait {
		// that was easy
		return
	} else {
		logrus.Warn("Unrecognized Operation")
		return
	}

	// XXX Should this go through a method rather than direct mutation?
	// Move the growth root to the new location
	root.Loc = new
}

type newStateInfo struct {
	ch   <-chan sandbox.NewState
	root *growthRoot
}

// This is called by a timer every n time units
func (s *State) simulateTick() {
	responses := []newStateInfo{}
	deadNodes := []*growthRoot{}

	// Tell each root to run until the next move operation
	for root := range s.state.roots {
		ch, ok := root.node.Update(s.mkWorldState(root))
		if !ok {
			// We have to remove the node later
			deadNodes = append(deadNodes, root)
			continue
		}

		responses = append(responses, newStateInfo{ch, root})
	}

	for _, dead := range deadNodes {
		delete(s.state.roots, dead)
	}

	for _, response := range responses {
		newState, ok := <-response.ch
		if !ok {
			continue
		}
		s.applyChanges(response.root, newState)
	}

	spores := []spore{}
	for _, p := range s.diff.Spores {
		// UpdateSpore returns true if it has planted the spore
		spawned := s.UpdateSpore(&p)
		// Unplanted spores are kept for next tick
		if !spawned {
			spores = append(spores, p)
		}
	}
	s.diff.Spores = spores

	surviving := make([]*Plant, 0, len(s.state.plants))
	for _, p := range s.state.plants {
		deltaEnergy := 0
		for _ = range p.tiles {
			deltaEnergy += 10
		}

		p.Energy += deltaEnergy
		p.Energy -= (p.Age * p.Age)

		if p.Energy < 0 {
			for t := range p.tiles {
				t.Type = AirTile
				t.Extra = nil
			}
			for r := range s.state.roots {
				if r.Plant == p {
					s.HaltGrowth(r)
				}
			}

		} else {
			surviving = append(surviving, p)
		}

		p.Age++
	}
	s.state.plants = surviving

}
<|endoftext|>


<commit_before>// $G $D/$F.go && $L $F.$A && ./$A.out

// 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.

package main

var c = make(chan int)

func check(a []int) {
	for i := 0; i < len(a); i++ {
		n := <-c
		if n != a[i] {
			println("want", a[i], "got", n, "at", i)
			panic("fail")
		}
	}
}

func f() {
	var i, j int

	i = 1
	j = 2
	f := func() {
		c <- i
		i = 4
		g := func() {
			c <- i
			c <- j
		}
		g()
		c <- i
	}
	j = 5
	f()
}

// Accumulator generator
func accum(n int) func(int) int {
	return func(i int) int {
		n += i
		return n
	}
}

func g(a, b func(int) int) {
	c <- a(2)
	c <- b(3)
	c <- a(4)
	c <- b(5)
}

func h() {
	var x8 byte = 100
	var x64 int64 = 200

	c <- int(x8)
	c <- int(x64)
	f := func(z int) {
		g := func() {
			c <- int(x8)
			c <- int(x64)
			c <- z
		}
		g()
		c <- int(x8)
		c <- int(x64)
		c <- int(z)
	}
	x8 = 101
	x64 = 201
	f(500)
}

func newfunc() func(int) int { return func(x int) int { return x } }

func main() {
	go f()
	check([]int{1, 4, 5, 4})

	a := accum(0)
	b := accum(1)
	go g(a, b)
	check([]int{2, 4, 6, 9})

	go h()
	check([]int{100, 200, 101, 201, 500, 101, 201, 500})

	x, y := newfunc(), newfunc()
	if x(1) != 1 || y(2) != 2 {
		println("newfunc returned broken funcs")
		panic("fail")
	}

	ff(1)
}

func ff(x int) {
	call(func() {
		_ = x
	})
}

func call(func()) {
}
<commit_msg>gc: test that asserts closures are not wrapped when they don't have closure vars.<commit_after>// $G $D/$F.go && $L $F.$A && ./$A.out

// 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.

package main

import "runtime"

var c = make(chan int)

func check(a []int) {
	for i := 0; i < len(a); i++ {
		n := <-c
		if n != a[i] {
			println("want", a[i], "got", n, "at", i)
			panic("fail")
		}
	}
}

func f() {
	var i, j int

	i = 1
	j = 2
	f := func() {
		c <- i
		i = 4
		g := func() {
			c <- i
			c <- j
		}
		g()
		c <- i
	}
	j = 5
	f()
}

// Accumulator generator
func accum(n int) func(int) int {
	return func(i int) int {
		n += i
		return n
	}
}

func g(a, b func(int) int) {
	c <- a(2)
	c <- b(3)
	c <- a(4)
	c <- b(5)
}

func h() {
	var x8 byte = 100
	var x64 int64 = 200

	c <- int(x8)
	c <- int(x64)
	f := func(z int) {
		g := func() {
			c <- int(x8)
			c <- int(x64)
			c <- z
		}
		g()
		c <- int(x8)
		c <- int(x64)
		c <- int(z)
	}
	x8 = 101
	x64 = 201
	f(500)
}

func newfunc() func(int) int { return func(x int) int { return x } }

func main() {
	var fail bool

	go f()
	check([]int{1, 4, 5, 4})

	a := accum(0)
	b := accum(1)
	go g(a, b)
	check([]int{2, 4, 6, 9})

	go h()
	check([]int{100, 200, 101, 201, 500, 101, 201, 500})

	runtime.UpdateMemStats()
        n0 := runtime.MemStats.Mallocs

	x, y := newfunc(), newfunc()
	if x(1) != 1 || y(2) != 2 {
		println("newfunc returned broken funcs")
		fail = true
	}

	runtime.UpdateMemStats()
        if n0 != runtime.MemStats.Mallocs {
		println("newfunc allocated unexpectedly")
		fail = true
	}

	ff(1)

	if fail {
		panic("fail")
	}
}

func ff(x int) {
	call(func() {
		_ = x
	})
}

func call(func()) {
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/cactus/go-statsd-client/statsd"
	"io/ioutil"
	"net"
	"os"
	"strings"
	"time"
)

func dieIfError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s\n", err.Error())
		os.Exit(1)
	}
}
func doEvery(d time.Duration, f func(*statsd.Client), s *statsd.Client) {
	f(s)
	for _ = range time.Tick(d) {
		f(s)
	}
}

func process_targets(s *statsd.Client) {
	content, err := ioutil.ReadFile("targets")
	if err != nil {
		fmt.Println("couldn't open targets file")
		return
	}
	targets := strings.Split(string(content), "\n")
	for _, target := range targets {
		if len(target) < 1 {
			continue
		}
		go test(target, s)
	}
}
func test(target string, s *statsd.Client) {
	pre := time.Now()
	conn, err := net.Dial("tcp", target)
	if err != nil {
		fmt.Println("connect error", target)
		s.Inc(fmt.Sprintf("error.%s.dial_failed", target), 1, 1)
		return
	}
	duration := time.Since(pre)
	tuple := strings.Split(target, ":")
	host := strings.Replace(tuple[0], ".", "_", -1)
	port := tuple[1]
	ms := int64(duration / time.Millisecond)
	fmt.Printf("%s.%s.duration %d\n", host, port, ms)
	s.Timing(fmt.Sprintf("dial.%s.%s", host, port), ms, 1)
	conn.Close()
}

func main() {
	if len(os.Args) == 1 {
		fmt.Println("Usage: smoketcp <statsd_host>:<statsd_port>")
		os.Exit(1)
	}

	hostname, err := os.Hostname()
	dieIfError(err)
	s, err := statsd.Dial(os.Args[1], fmt.Sprintf("smoketcp.%s", hostname))
	dieIfError(err)
	defer s.Close()
	doEvery(time.Second, process_targets, s)
}
<commit_msg>specify graphite bucket prefix on the command line<commit_after>package main

import (
  "fmt"
  "github.com/cactus/go-statsd-client/statsd"
  "io/ioutil"
  "net"
  "os"
  "strings"
  "time"
)

func dieIfError(err error) {
  if err != nil {
    fmt.Fprintf(os.Stderr, "Fatal error: %s\n", err.Error())
    os.Exit(1)
  }
}

func doEvery(d time.Duration, s *statsd.Client, bucket string) {
  process_targets(s, bucket)
  for _ = range time.Tick(d) {
    process_targets(s, bucket)
  }
}

func process_targets(s *statsd.Client, bucket string) {
  content, err := ioutil.ReadFile("targets")
  if err != nil {
    fmt.Println("couldn't open targets file")
    return
  }
  targets := strings.Split(string(content), "\n")
  for _, target := range targets {
    if len(target) < 1 {
      continue
    }
    go test(target, s, bucket)
  }
}

func test(target string, s *statsd.Client, bucket string) {
  tuple := strings.Split(target, ":")
  host := tuple[0]
  port := tuple[1]
  hostport := strings.Join([]string{host, port}, ":")

  pre := time.Now()
  conn, err := net.Dial("tcp", hostport)
  if err != nil {
    fmt.Println("connect error", target)
    s.Inc(fmt.Sprintf("%s.smokeping.%s.%s.dial_failed", bucket, host, port), 1, 1)
    return
  }
  duration := time.Since(pre)
  subhost := strings.Replace(host, ".", "_", -1)
  ms := int64(duration / time.Millisecond)
  fmt.Printf("%s.smokeping.%s.%s.duration %d\n", bucket, subhost, port, ms)
  s.Timing(fmt.Sprintf("%s.smokeping.%s.%s", bucket, host, port), ms, 1)
  conn.Close()
}

func main() {
  if len(os.Args) < 3 {
    fmt.Println("Usage: smoketcp <statsd_host>:<statsd_port> <bucket_prefix>")
    fmt.Println("\nEx: smoketcp statsd.cashstar.net:8125 PROD.us-east-1.dw1")
    os.Exit(1)
  }

  hostname, err := os.Hostname()
  dieIfError(err)
  s, err := statsd.New(os.Args[1], fmt.Sprintf("smoketcp.%s", hostname))
  dieIfError(err)
  bucket := os.Args[2]
  defer s.Close()
  doEvery(time.Second, s, bucket)
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/tyba/beanstool/cli"

	"github.com/jessevdk/go-flags"
)

func main() {
	parser := flags.NewNamedParser("event-relay", flags.Default)
	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
	parser.AddCommand("peek", "peeks a job from a queue", "", &cli.PeekCommand{})
	parser.AddCommand("kick", "kicks jobs from buried back into ready", "", &cli.KickCommand{})

	_, err := parser.Parse()
	if err != nil {
		if _, ok := err.(*flags.Error); ok {
			parser.WriteHelp(os.Stdout)
		}

		os.Exit(1)
	}
}
<commit_msg>correct name<commit_after>package main

import (
	"os"

	"github.com/tyba/beanstool/cli"

	"github.com/jessevdk/go-flags"
)

func main() {
	parser := flags.NewNamedParser("beanstool", flags.Default)
	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
	parser.AddCommand("peek", "peeks a job from a queue", "", &cli.PeekCommand{})
	parser.AddCommand("kick", "kicks jobs from buried back into ready", "", &cli.KickCommand{})
	parser.AddCommand("put", "put a job into a tube", "", &cli.PutCommand{})

	_, err := parser.Parse()
	if err != nil {
		if _, ok := err.(*flags.Error); ok {
			parser.WriteHelp(os.Stdout)
		}

		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"loveoneanother.at/tiedot/db"
	"math/rand"
	"os"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
)

const BENCH_SIZE = 400000 // don't make it too large... unmarshaled JSON takes lots of memory!

// Run function a number of times and calculate average time consumption per iteration.
func average(name string, total int, init func(), do func()) {
	numThreads := runtime.GOMAXPROCS(-1)
	wp := new(sync.WaitGroup)
	init()
	iter := float64(total)
	start := float64(time.Now().UTC().UnixNano())
	for i := 0; i < total; i += total / numThreads {
		wp.Add(1)
		go func() {
			defer wp.Done()
			for j := 0; j < total/numThreads; j++ {
				do()
			}
		}()
	}
	wp.Wait()
	end := float64(time.Now().UTC().UnixNano())
	fmt.Printf("%s %d: %d ns/iter, %d iter/sec\n", name, int(total), int((end-start)/iter), int(1000000000/((end-start)/iter)))
}

// Individual feature benchmarks.
func benchmark() {
	// initialization
	rand.Seed(time.Now().UTC().UnixNano())
	// prepare benchmark data
	docs := [BENCH_SIZE]interface{}{}
	for i := range docs {
		if err := json.Unmarshal([]byte(
			`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`}},`+
				`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`},`+
				`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docs[i]); err != nil {
			panic("json error")
		}
	}
	// prepare collection
	tmp := "/tmp/tiedot_bench"
	os.RemoveAll(tmp)
	defer os.RemoveAll(tmp)
	col, err := db.OpenCol(tmp)
	if err != nil {
		panic(err)
	}
	col.Index([]string{"a", "b", "c"})
	col.Index([]string{"c", "d"})
	// start benchmarks
	average("insert", BENCH_SIZE, func() {}, func() {
		if _, err := col.Insert(docs[rand.Intn(BENCH_SIZE)]); err != nil {
			panic("insert error")
		}
	})
	ids := make([]uint64, 0)
	average("read", BENCH_SIZE, func() {
		col.ForAll(func(id uint64, doc interface{}) bool {
			ids = append(ids, id)
			return true
		})
	}, func() {
		var doc interface{}
		err = col.Read(ids[uint64(rand.Intn(BENCH_SIZE))], &doc)
		if doc == nil {
			panic("read error")
		}
	})
	average("lookup", BENCH_SIZE, func() {}, func() {
		var query interface{}
		if err := json.Unmarshal([]byte(`{"c": [{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["a", "b", "c"], "limit": 1}, `+
			`{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["c", "d"], "limit": 1}]}`), &query); err != nil {
			panic("json error")
		}
		result := make(map[uint64]struct{})
		if err := db.EvalQueryV2(query, col, &result); err != nil {
			panic("query error")
		}
	})
	average("update", BENCH_SIZE, func() {}, func() {
		if _, err := col.Update(ids[rand.Intn(BENCH_SIZE)], docs[rand.Intn(BENCH_SIZE)]); err != nil {
			panic("update error")
		}
	})
	average("delete", BENCH_SIZE, func() {}, func() {
		col.Delete(ids[rand.Intn(BENCH_SIZE)])
	})
	col.Close()
}

// Insert/update/delete/query all running at once.
func benchmark2() {
	numThreads := runtime.GOMAXPROCS(-1)
	rand.Seed(time.Now().UTC().UnixNano())
	// prepare collection
	tmp := "/tmp/tiedot_bench"
	os.RemoveAll(tmp)
	col, err := db.OpenCol(tmp)
	if err != nil {
		panic(err)
	}
	col.Index([]string{"a", "b", "c"})
	col.Index([]string{"c", "d"})
	docs := make([]uint64, 0, BENCH_SIZE)
	// Prepare 1000 docs as a start
	var docToInsert interface{}
	for j := 0; j < 1000; j++ {
		if err = json.Unmarshal([]byte(
			`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`}},`+
				`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`},`+
				`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docToInsert); err != nil {
			panic(err)
		}
		if newID, err := col.Insert(docToInsert); err == nil {
			docs = append(docs, newID)
		} else {
			panic(err)
		}
	}
	// benchmark begins
	wp := new(sync.WaitGroup)
	wp.Add(5 * numThreads) // (CRUD + query) * number of benchmark threads
	start := float64(time.Now().UTC().UnixNano())
	// insert BENCH_SIZE * 2 documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var docToInsert interface{}
			var err error
			for j := 0; j < BENCH_SIZE/numThreads*2; j++ {
				if err = json.Unmarshal([]byte(
					`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`}},`+
						`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`},`+
						`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docToInsert); err != nil {
					panic(err)
				}
				if newID, err := col.Insert(docToInsert); err == nil {
					docs = append(docs, newID)
				} else {
					panic(err)
				}
			}
		}()
	}
	// read BENCH_SIZE * 2 documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var doc interface{}
			for j := 0; j < BENCH_SIZE/numThreads*2; j++ {
				col.Read(docs[uint64(rand.Intn(len(docs)))], &doc)
			}
		}()
	}
	// query BENCH_SIZE times
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var query interface{}
			var err error
			for j := 0; j < BENCH_SIZE/numThreads; j++ {
				if err = json.Unmarshal([]byte(`{"c": [{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["a", "b", "c"], "limit": 1}, `+
					`{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["c", "d"], "limit": 1}]}`), &query); err != nil {
					panic("json error")
				}
				result := make(map[uint64]struct{})
				if err = db.EvalQueryV2(query, col, &result); err != nil {
					panic("query error")
				}
			}
		}()
	}
	// update BENCH_SIZE documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var updated interface{}
			var err error
			for j := 0; j < BENCH_SIZE/numThreads; j++ {
				if err = json.Unmarshal([]byte(
					`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`}},`+
						`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`},`+
						`"more": "abcdefghijklmnopqrstuvwxyz"}`), &updated); err != nil {
					panic(err)
				}
				if _, err = col.Update(docs[uint64(rand.Intn(len(docs)))], updated); err != nil {
					// "does not exist" indicates that a deleted document is being updated, it is safe to ignore
					if !strings.Contains(fmt.Sprint(err), "does not exist") {
						fmt.Println(err)
					}
				}
			}
		}()
	}
	// delete BENCH_SIZE documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			for j := 0; j < BENCH_SIZE/numThreads; j++ {
				col.Delete(docs[uint64(rand.Intn(len(docs)))])
			}
		}()
	}
	wp.Wait()
	end := float64(time.Now().UTC().UnixNano())
	fmt.Printf("Total operations %d: %d ns/iter, %d iter/sec\n", BENCH_SIZE*7, int((end-start)/BENCH_SIZE/7), int(1000000000/((end-start)/BENCH_SIZE/7)))
}
<commit_msg>increase "bench2" benchmark sample size<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"loveoneanother.at/tiedot/db"
	"math/rand"
	"os"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
)

const BENCH_SIZE = 400000  // don't make it too large... unmarshaled JSON takes lots of memory!
const BENCH2_SIZE = 800000 // feel free to make this one larger!

// Run function a number of times and calculate average time consumption per iteration.
func average(name string, total int, init func(), do func()) {
	numThreads := runtime.GOMAXPROCS(-1)
	wp := new(sync.WaitGroup)
	init()
	iter := float64(total)
	start := float64(time.Now().UTC().UnixNano())
	for i := 0; i < total; i += total / numThreads {
		wp.Add(1)
		go func() {
			defer wp.Done()
			for j := 0; j < total/numThreads; j++ {
				do()
			}
		}()
	}
	wp.Wait()
	end := float64(time.Now().UTC().UnixNano())
	fmt.Printf("%s %d: %d ns/iter, %d iter/sec\n", name, int(total), int((end-start)/iter), int(1000000000/((end-start)/iter)))
}

// Individual feature benchmarks.
func benchmark() {
	// initialization
	rand.Seed(time.Now().UTC().UnixNano())
	// prepare benchmark data
	docs := [BENCH_SIZE]interface{}{}
	for i := range docs {
		if err := json.Unmarshal([]byte(
			`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`}},`+
				`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`},`+
				`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docs[i]); err != nil {
			panic("json error")
		}
	}
	// prepare collection
	tmp := "/tmp/tiedot_bench"
	os.RemoveAll(tmp)
	defer os.RemoveAll(tmp)
	col, err := db.OpenCol(tmp)
	if err != nil {
		panic(err)
	}
	col.Index([]string{"a", "b", "c"})
	col.Index([]string{"c", "d"})
	// start benchmarks
	average("insert", BENCH_SIZE, func() {}, func() {
		if _, err := col.Insert(docs[rand.Intn(BENCH_SIZE)]); err != nil {
			panic("insert error")
		}
	})
	ids := make([]uint64, 0)
	average("read", BENCH_SIZE, func() {
		col.ForAll(func(id uint64, doc interface{}) bool {
			ids = append(ids, id)
			return true
		})
	}, func() {
		var doc interface{}
		err = col.Read(ids[uint64(rand.Intn(BENCH_SIZE))], &doc)
		if doc == nil {
			panic("read error")
		}
	})
	average("lookup", BENCH_SIZE, func() {}, func() {
		var query interface{}
		if err := json.Unmarshal([]byte(`{"c": [{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["a", "b", "c"], "limit": 1}, `+
			`{"eq": `+strconv.Itoa(rand.Intn(BENCH_SIZE))+`, "in": ["c", "d"], "limit": 1}]}`), &query); err != nil {
			panic("json error")
		}
		result := make(map[uint64]struct{})
		if err := db.EvalQueryV2(query, col, &result); err != nil {
			panic("query error")
		}
	})
	average("update", BENCH_SIZE, func() {}, func() {
		if _, err := col.Update(ids[rand.Intn(BENCH_SIZE)], docs[rand.Intn(BENCH_SIZE)]); err != nil {
			panic("update error")
		}
	})
	average("delete", BENCH_SIZE, func() {}, func() {
		col.Delete(ids[rand.Intn(BENCH_SIZE)])
	})
	col.Close()
}

// Insert/update/delete/query all running at once.
func benchmark2() {
	numThreads := runtime.GOMAXPROCS(-1)
	rand.Seed(time.Now().UTC().UnixNano())
	// prepare collection
	tmp := "/tmp/tiedot_bench"
	os.RemoveAll(tmp)
	col, err := db.OpenCol(tmp)
	if err != nil {
		panic(err)
	}
	col.Index([]string{"a", "b", "c"})
	col.Index([]string{"c", "d"})
	docs := make([]uint64, 0, BENCH2_SIZE)
	// Prepare 1000 docs as a start
	var docToInsert interface{}
	for j := 0; j < 1000; j++ {
		if err = json.Unmarshal([]byte(
			`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`}},`+
				`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`},`+
				`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docToInsert); err != nil {
			panic(err)
		}
		if newID, err := col.Insert(docToInsert); err == nil {
			docs = append(docs, newID)
		} else {
			panic(err)
		}
	}
	// benchmark begins
	wp := new(sync.WaitGroup)
	wp.Add(5 * numThreads) // (CRUD + query) * number of benchmark threads
	start := float64(time.Now().UTC().UnixNano())
	// insert BENCH2_SIZE * 2 documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var docToInsert interface{}
			var err error
			for j := 0; j < BENCH2_SIZE/numThreads*2; j++ {
				if err = json.Unmarshal([]byte(
					`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`}},`+
						`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`},`+
						`"more": "abcdefghijklmnopqrstuvwxyz"}`), &docToInsert); err != nil {
					panic(err)
				}
				if newID, err := col.Insert(docToInsert); err == nil {
					docs = append(docs, newID)
				} else {
					panic(err)
				}
			}
		}()
	}
	// read BENCH2_SIZE * 2 documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var doc interface{}
			for j := 0; j < BENCH2_SIZE/numThreads*2; j++ {
				col.Read(docs[uint64(rand.Intn(len(docs)))], &doc)
			}
		}()
	}
	// query BENCH2_SIZE times
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var query interface{}
			var err error
			for j := 0; j < BENCH2_SIZE/numThreads; j++ {
				if err = json.Unmarshal([]byte(`{"c": [{"eq": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`, "in": ["a", "b", "c"], "limit": 1}, `+
					`{"eq": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`, "in": ["c", "d"], "limit": 1}]}`), &query); err != nil {
					panic("json error")
				}
				result := make(map[uint64]struct{})
				if err = db.EvalQueryV2(query, col, &result); err != nil {
					panic("query error")
				}
			}
		}()
	}
	// update BENCH2_SIZE documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			var updated interface{}
			var err error
			for j := 0; j < BENCH2_SIZE/numThreads; j++ {
				if err = json.Unmarshal([]byte(
					`{"a": {"b": {"c": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`}},`+
						`"c": {"d": `+strconv.Itoa(rand.Intn(BENCH2_SIZE))+`},`+
						`"more": "abcdefghijklmnopqrstuvwxyz"}`), &updated); err != nil {
					panic(err)
				}
				if _, err = col.Update(docs[uint64(rand.Intn(len(docs)))], updated); err != nil {
					// "does not exist" indicates that a deleted document is being updated, it is safe to ignore
					if !strings.Contains(fmt.Sprint(err), "does not exist") {
						fmt.Println(err)
					}
				}
			}
		}()
	}
	// delete BENCH2_SIZE documents
	for i := 0; i < numThreads; i++ {
		go func() {
			defer wp.Done()
			for j := 0; j < BENCH2_SIZE/numThreads; j++ {
				col.Delete(docs[uint64(rand.Intn(len(docs)))])
			}
		}()
	}
	wp.Wait()
	end := float64(time.Now().UTC().UnixNano())
	fmt.Printf("Total operations %d: %d ns/iter, %d iter/sec\n", BENCH2_SIZE*7, int((end-start)/BENCH2_SIZE/7), int(1000000000/((end-start)/BENCH2_SIZE/7)))
}
<|endoftext|>


<commit_before>package bf

import (
	"fmt"
	"io"
	"text/scanner"
)

type parser struct {
	s     scanner.Scanner
	eof   bool   // Have we reached eof yet?
	token string // Last token read
}

// Parse parses the formula from the given input Reader.
// It returns the corresponding Formula.
// Formulas are written using the following operators (from lowest to highest priority) :
//
// - for an equivalence, the "=" operator,
// - for an implication, the "->" operator,
// - for a disjunction ("or"), the "|" operator,
// - for a conjunction ("and"), the "&" operator,
// - for a negation, the "^" unary operator.
//
// Parentheses can be used to group subformulas.
func Parse(r io.Reader) (Formula, error) {
	var s scanner.Scanner
	s.Init(r)
	p := parser{s: s}
	p.scan()
	return p.parseEquiv()
}

func isOperator(token string) bool {
	return token == "=" || token == "->" || token == "|" || token == "&"
}

func (p *parser) scan() {
	if p.eof {
		return
	}
	p.eof = (p.s.Scan() == scanner.EOF)
	p.token = p.s.TokenText()
}

func (p *parser) parseEquiv() (f Formula, err error) {
	if p.eof {
		return nil, fmt.Errorf("At position %v, expected expression, found EOF", p.s.Pos())
	}
	if isOperator(p.token) {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	f, err = p.parseImplies()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "=" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseEquiv()
		if err != nil {
			return nil, err
		}
		return Eq(f, f2), nil
	}
	return f, nil
	//return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
}

func (p *parser) parseImplies() (f Formula, err error) {
	f, err = p.parseOr()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "-" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		if p.token != ">" {
			return nil, fmt.Errorf("invalid token %q at %v", "-"+p.token, p.s.Pos())
		}
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseImplies()
		if err != nil {
			return nil, err
		}
		return Implies(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseOr() (f Formula, err error) {
	f, err = p.parseAnd()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "|" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseOr()
		if err != nil {
			return nil, err
		}
		return Or(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseAnd() (f Formula, err error) {
	f, err = p.parseNot()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "&" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseAnd()
		if err != nil {
			return nil, err
		}
		return And(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseNot() (f Formula, err error) {
	if isOperator(p.token) {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	if p.token == "^" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f, err = p.parseNot()
		if err != nil {
			return nil, err
		}
		return Not(f), nil
	}
	f, err = p.parseBasic()
	if err != nil {
		return nil, err
	}
	return f, nil
}

func (p *parser) parseBasic() (f Formula, err error) {
	if isOperator(p.token) || p.token == ")" {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	if p.token == "(" {
		p.scan()
		f, err = p.parseEquiv()
		if err != nil {
			return nil, err
		}
		if p.eof {
			return nil, fmt.Errorf("expected closing parenthesis, found EOF at %s", p.s.Pos())
		}
		if p.token != ")" {
			return nil, fmt.Errorf("expected closing parenthesis, found %q at %s", p.token, p.s.Pos())
		}
		p.scan()
		return f, nil
	}
	defer p.scan()
	return Var(p.token), nil
}
<commit_msg>corrected bug in parser<commit_after>package bf

import (
	"fmt"
	"io"
	"text/scanner"
)

type parser struct {
	s     scanner.Scanner
	eof   bool   // Have we reached eof yet?
	token string // Last token read
}

// Parse parses the formula from the given input Reader.
// It returns the corresponding Formula.
// Formulas are written using the following operators (from lowest to highest priority) :
//
// - for an equivalence, the "=" operator,
// - for an implication, the "->" operator,
// - for a disjunction ("or"), the "|" operator,
// - for a conjunction ("and"), the "&" operator,
// - for a negation, the "^" unary operator.
//
// Parentheses can be used to group subformulas.
func Parse(r io.Reader) (Formula, error) {
	var s scanner.Scanner
	s.Init(r)
	p := parser{s: s}
	p.scan()
	f, err := p.parseEquiv()
	if err != nil {
		return f, err
	}
	if !p.eof {
		return nil, fmt.Errorf("expected EOF, found %q at %v", p.token, p.s.Pos())
	}
	return f, nil
}

func isOperator(token string) bool {
	return token == "=" || token == "->" || token == "|" || token == "&"
}

func (p *parser) scan() {
	if p.eof {
		return
	}
	p.eof = (p.s.Scan() == scanner.EOF)
	p.token = p.s.TokenText()
}

func (p *parser) parseEquiv() (f Formula, err error) {
	if p.eof {
		return nil, fmt.Errorf("At position %v, expected expression, found EOF", p.s.Pos())
	}
	if isOperator(p.token) {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	f, err = p.parseImplies()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "=" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseEquiv()
		if err != nil {
			return nil, err
		}
		return Eq(f, f2), nil
	}
	return f, nil
	//return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
}

func (p *parser) parseImplies() (f Formula, err error) {
	f, err = p.parseOr()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "-" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		if p.token != ">" {
			return nil, fmt.Errorf("invalid token %q at %v", "-"+p.token, p.s.Pos())
		}
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseImplies()
		if err != nil {
			return nil, err
		}
		return Implies(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseOr() (f Formula, err error) {
	f, err = p.parseAnd()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "|" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseOr()
		if err != nil {
			return nil, err
		}
		return Or(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseAnd() (f Formula, err error) {
	f, err = p.parseNot()
	if err != nil {
		return nil, err
	}
	if p.eof {
		return f, nil
	}
	if p.token == "&" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f2, err := p.parseAnd()
		if err != nil {
			return nil, err
		}
		return And(f, f2), nil
	}
	return f, nil
}

func (p *parser) parseNot() (f Formula, err error) {
	if isOperator(p.token) {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	if p.token == "^" {
		p.scan()
		if p.eof {
			return nil, fmt.Errorf("unexpected EOF")
		}
		f, err = p.parseNot()
		if err != nil {
			return nil, err
		}
		return Not(f), nil
	}
	f, err = p.parseBasic()
	if err != nil {
		return nil, err
	}
	return f, nil
}

func (p *parser) parseBasic() (f Formula, err error) {
	if isOperator(p.token) || p.token == ")" {
		return nil, fmt.Errorf("unexpected token %q at %s", p.token, p.s.Pos())
	}
	if p.token == "(" {
		p.scan()
		f, err = p.parseEquiv()
		if err != nil {
			return nil, err
		}
		if p.eof {
			return nil, fmt.Errorf("expected closing parenthesis, found EOF at %s", p.s.Pos())
		}
		if p.token != ")" {
			return nil, fmt.Errorf("expected closing parenthesis, found %q at %s", p.token, p.s.Pos())
		}
		p.scan()
		return f, nil
	}
	defer p.scan()
	return Var(p.token), nil
}
<|endoftext|>


<commit_before>package Lint

import "time"

const (
	// AuthenticationURL - API address to Authenticate Pocket Consumer Key
	AuthenticationURL string = "https://getpocket.com/v3/oauth/request"

	// AuthorisationURL - API address to Authorise and recience a Request Key
	AuthorisationURL string = "https://getpocket.com/v3/oauth/authorize"

	//UserAuthorisationURL - Address that a user must enter into their browser to Authorise Lint to access Pocket
	UserAuthorisationURL string = "https://getpocket.com/auth/authorize?"

	//RedirectURI - Link back location after Authorisation has been granted
	RedirectURI string = "https://github.com/daveym/lint/blob/master/AUTHCOMPLETE.md"
)

type Time time.Time

// Initial Authentication response from Pocket
type authenticationResponse struct {
	Code  string
	State string
}

// Initial Authorisation response from Pocket
type authorisationResponse struct {
	AccessToken string
	Username    string
}

type getListRequest struct {
	State       string
	Favorite    int
	Tag         string
	ContentType string
	Sort        string
	DetailType  string
	Search      string
	Domain      string
	Since       Time
	Count       int
	Offset      int
}

type ItemStatus int
type ItemMediaAttachment int

const (
	ItemStatusUnread   ItemStatus = 0
	ItemStatusArchived            = 1
	ItemStatusDeleted             = 2
)

const (
	ItemMediaAttachmentNoMedia  ItemMediaAttachment = 0
	ItemMediaAttachmentHasMedia                     = 1
	ItemMediaAttachmentIsMedia                      = 2
)

type listItem struct {
	ItemID        int        `json:"item_id,string"`
	ResolvedId    int        `json:"resolved_id,string"`
	GivenURL      string     `json:"given_url"`
	ResolvedURL   string     `json:"resolved_url"`
	GivenTitle    string     `json:"given_title"`
	ResolvedTitle string     `json:"resolved_title"`
	Favorite      int        `json:",string"`
	Status        ItemStatus `json:",string"`
	Excerpt       string
	IsArticle     int                 `json:"is_article,string"`
	HasImage      ItemMediaAttachment `json:"has_image,string"`
	HasVideo      ItemMediaAttachment `json:"has_video,string"`
	WordCount     int                 `json:"word_count,string"`
	Tags          map[string]map[string]interface{}
	Authors       map[string]map[string]interface{}
	Images        map[string]map[string]interface{}
	Videos        map[string]map[string]interface{}
	SortId        int  `json:"sort_id"`
	TimeAdded     Time `json:"time_added"`
	TimeUpdated   Time `json:"time_updated"`
	TimeRead      Time `json:"time_read"`
	TimeFavorited Time `json:"time_favorited"`
}
<commit_msg>Updated Types<commit_after>package Lint

import "time"

// CONSTANTS
const (
	// AuthenticationURL - API address to Authenticate Pocket Consumer Key
	AuthenticationURL string = "https://getpocket.com/v3/oauth/request"
	// AuthorisationURL - API address to Authorise and recience a Request Key
	AuthorisationURL string = "https://getpocket.com/v3/oauth/authorize"
	//UserAuthorisationURL - Address that a user must enter into their browser to Authorise Lint to access Pocket
	UserAuthorisationURL string = "https://getpocket.com/auth/authorize?"
	//RedirectURI - Link back location after Authorisation has been granted
	RedirectURI string = "https://github.com/daveym/lint/blob/master/AUTHCOMPLETE.md"
)

const (
	// ItemStatusUnread - Pocket Item has not been read
	ItemStatusUnread ItemStatus = 0
	// ItemStatusArchived - Pocket Item has been archived
	ItemStatusArchived = 1
	// ItemStatusDeleted - Pocket Item has been deleted
	ItemStatusDeleted = 2
)

const (
	// ItemMediaAttachmentNoMedia - No media attached to the Pocket Item
	ItemMediaAttachmentNoMedia ItemMediaAttachment = 0
	// ItemMediaAttachmentHasMedia - Media is attached to the Pocket Item
	ItemMediaAttachmentHasMedia = 1
	// ItemMediaAttachmentIsMedia - The Pocket Item is media only
	ItemMediaAttachmentIsMedia = 2
)

// TYPES

// Time - alias for time.Time
type Time time.Time

// ItemStatus - Status of the Pocket Item, defined by ItemStatus constants
type ItemStatus int

// ItemMediaAttachment - Is Media attached to the Pocket Item. Defined by ItemMedia constants
type ItemMediaAttachment int

// Initial Authentication response from Pocket
type authenticationResponse struct {
	Code  string
	State string
}

// Initial Authorisation response from Pocket
type authorisationResponse struct {
	AccessToken string
	Username    string
}

type getListRequest struct {
	State       string
	Favorite    int
	Tag         string
	ContentType string
	Sort        string
	DetailType  string
	Search      string
	Domain      string
	Since       Time
	Count       int
	Offset      int
}

type listItem struct {
	ItemID        int        `json:"item_id,string"`
	ResolvedID    int        `json:"resolved_id,string"`
	GivenURL      string     `json:"given_url"`
	ResolvedURL   string     `json:"resolved_url"`
	GivenTitle    string     `json:"given_title"`
	ResolvedTitle string     `json:"resolved_title"`
	Favorite      int        `json:",string"`
	Status        ItemStatus `json:",string"`
	Excerpt       string
	IsArticle     int                 `json:"is_article,string"`
	HasImage      ItemMediaAttachment `json:"has_image,string"`
	HasVideo      ItemMediaAttachment `json:"has_video,string"`
	WordCount     int                 `json:"word_count,string"`
	Tags          map[string]map[string]interface{}
	Authors       map[string]map[string]interface{}
	Images        map[string]map[string]interface{}
	Videos        map[string]map[string]interface{}
	SortID        int  `json:"sort_id"`
	TimeAdded     Time `json:"time_added"`
	TimeUpdated   Time `json:"time_updated"`
	TimeRead      Time `json:"time_read"`
	TimeFavorited Time `json:"time_favorited"`
}
<|endoftext|>


<commit_before>// errchk $G $D/$F.go

// 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.

// make sure that even if a file imports runtime,
// it cannot get at the low-level runtime definitions
// known to the compiler.  for normal packages
// the compiler doesn't even record the lower case
// functions in its symbol table, but some functions
// in runtime are hard-coded into the compiler.

package main

import "runtime"

func main() {
	runtime.printbool(true);	// ERROR "cannot refer"
}
<commit_msg>Recognize gccgo error message.<commit_after>// errchk $G $D/$F.go

// 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.

// make sure that even if a file imports runtime,
// it cannot get at the low-level runtime definitions
// known to the compiler.  for normal packages
// the compiler doesn't even record the lower case
// functions in its symbol table, but some functions
// in runtime are hard-coded into the compiler.

package main

import "runtime"

func main() {
	runtime.printbool(true);	// ERROR "cannot refer|undefined identifier"
}
<|endoftext|>


<commit_before>package functions

import (
	"fmt"
	"math"
	"os"
	"strconv"
)

func LogaritmeFunc() {
	base := os.Args[1]
	tall := os.Args[2]
	tallFloat, _ := strconv.ParseFloat(tall, 64)
	baseFloat, _ := strconv.Atoi(base)

	if baseFloat == 2 {
		fmt.Println("Logaritmen av ",tall, " blir: ", math.Log2(tallFloat), ", beregnet med base 2.")
	} else if baseFloat == 10 {
		fmt.Println("Logaritmen av ",tall, " blir: ", math.Log10(tallFloat), ", beregnet med base 10.")
	} else {
		fmt.Println("Første argumentet må være 2 eller 10")
	}
}
<commit_msg>Update log.go<commit_after>// Copyright 2017 Gruppe 12 IS-105. All rights reserved.
package functions

import (
	"fmt"
	"math"
	"os"
	"strconv"
)

func LogaritmeFunc() {
	base := os.Args[1]
	tall := os.Args[2]
	tallFloat, _ := strconv.ParseFloat(tall, 64)
	baseFloat, _ := strconv.Atoi(base)

	if baseFloat == 2 {
		fmt.Println("Logaritmen av ",tall, " blir: ", math.Log2(tallFloat), ", beregnet med base 2.")
	} else if baseFloat == 10 {
		fmt.Println("Logaritmen av ",tall, " blir: ", math.Log10(tallFloat), ", beregnet med base 10.")
	} else {
		fmt.Println("Første argumentet må være 2 eller 10")
	}
}
<|endoftext|>


<commit_before>package web

import (
	"log"
	"os"
	"time"
)

// Logger can be set to your own logger if you wish
var Logger = log.New(os.Stdout, "", 0)

// LoggerMiddleware is generic middleware that will log requests to Stdout.
func LoggerMiddleware(rw ResponseWriter, req *Request, next NextMiddlewareFunc) {
	startTime := time.Now()

	next(rw, req)

	duration := time.Since(startTime).Nanoseconds()
	var durationUnits string
	switch {
	case duration > 2000000:
		durationUnits = "ms"
		duration /= 1000000
	case duration > 1000:
		durationUnits = "μs"
		duration /= 1000
	default:
		durationUnits = "ns"
	}

	Logger.Printf("[%d %s] %d '%s'\n", duration, durationUnits, rw.StatusCode(), req.URL.Path)
}
<commit_msg>DOC: Clean up Logger comment.<commit_after>package web

import (
	"log"
	"os"
	"time"
)

// Logger can be set to your own logger. Logger only applies to the LoggerMiddleware.
var Logger = log.New(os.Stdout, "", 0)

// LoggerMiddleware is generic middleware that will log requests to Logger (by default, Stdout).
func LoggerMiddleware(rw ResponseWriter, req *Request, next NextMiddlewareFunc) {
	startTime := time.Now()

	next(rw, req)

	duration := time.Since(startTime).Nanoseconds()
	var durationUnits string
	switch {
	case duration > 2000000:
		durationUnits = "ms"
		duration /= 1000000
	case duration > 1000:
		durationUnits = "μs"
		duration /= 1000
	default:
		durationUnits = "ns"
	}

	Logger.Printf("[%d %s] %d '%s'\n", duration, durationUnits, rw.StatusCode(), req.URL.Path)
}
<|endoftext|>