<commit_before>// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package strfmt

import (
	"database/sql/driver"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/mailru/easyjson/jlexer"
	"github.com/mailru/easyjson/jwriter"
)

func init() {
	d := Duration(0)
	Default.Add("duration", &d, IsDuration)
}

var (
	timeUnits = [][]string{
		[]string{"ns", "nano"},
		[]string{"us", "µs", "micro"},
		[]string{"ms", "milli"},
		[]string{"s", "sec"},
		[]string{"m", "min"},
		[]string{"h", "hr", "hour"},
		[]string{"d", "day"},
		[]string{"w", "wk", "week"},
	}

	timeMultiplier = map[string]time.Duration{
		"ns": time.Nanosecond,
		"us": time.Microsecond,
		"ms": time.Millisecond,
		"s":  time.Second,
		"m":  time.Minute,
		"h":  time.Hour,
		"d":  24 * time.Hour,
		"w":  7 * 24 * time.Hour,
	}

	durationMatcher = regexp.MustCompile(`((\d+)\s*([A-Za-zµ]+))`)
)

// IsDuration returns true if the provided string is a valid duration
func IsDuration(str string) bool {
	_, err := ParseDuration(str)
	return err == nil
}

// Duration represents a duration
//
// swagger:strfmt duration
type Duration time.Duration

// MarshalText turns this instance into text
func (d Duration) MarshalText() ([]byte, error) {
	return []byte(time.Duration(d).String()), nil
}

// UnmarshalText hydrates this instance from text
func (d *Duration) UnmarshalText(data []byte) error { // validation is performed later on
	dd, err := ParseDuration(string(data))
	if err != nil {
		return err
	}
	*d = Duration(dd)
	return nil
}

// ParseDuration parses a duration from a string, compatible with scala duration syntax
func ParseDuration(cand string) (time.Duration, error) {
	if dur, err := time.ParseDuration(cand); err == nil {
		return dur, nil
	}

	var dur time.Duration
	ok := false
	for _, match := range durationMatcher.FindAllStringSubmatch(cand, -1) {

		factor, err := strconv.Atoi(match[2]) // converts string to int
		if err != nil {
			return 0, err
		}
		unit := strings.ToLower(strings.TrimSpace(match[3]))

		for _, variants := range timeUnits {
			last := len(variants) - 1
			multiplier := timeMultiplier[variants[0]]

			for i, variant := range variants {
				if (last == i && strings.HasPrefix(unit, variant)) || strings.EqualFold(variant, unit) {
					ok = true
					dur += (time.Duration(factor) * multiplier)
				}
			}
		}
	}

	if ok {
		return dur, nil
	}
	return 0, fmt.Errorf("Unable to parse %s as duration", cand)
}

// Scan reads a Duration value from database driver type.
func (d *Duration) Scan(raw interface{}) error {
	switch v := raw.(type) {
	// TODO: case []byte: // ?
	case int64:
		*d = Duration(v)
	case float64:
		*d = Duration(int64(v))
	case nil:
		*d = Duration(0)
	default:
		return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v)
	}

	return nil
}

// Value converts Duration to a primitive value ready to written to a database.
func (d Duration) Value() (driver.Value, error) {
	return driver.Value(int64(d)), nil
}

// String converts this duration to a string
func (d Duration) String() string {
	return time.Duration(d).String()
}

func (d Duration) MarshalJSON() ([]byte, error) {
	var w jwriter.Writer
	d.MarshalEasyJSON(&w)
	return w.BuildBytes()
}

func (d Duration) MarshalEasyJSON(w *jwriter.Writer) {
	w.String(time.Duration(d).String())
}

func (d *Duration) UnmarshalJSON(data []byte) error {
	l := jlexer.Lexer{Data: data}
	d.UnmarshalEasyJSON(&l)
	return l.Error()
}

func (d *Duration) UnmarshalEasyJSON(in *jlexer.Lexer) {
	if data := in.String(); in.Ok() {
		tt, err := ParseDuration(data)
		if err != nil {
			in.AddError(err)
			return
		}
		*d = Duration(tt)
	}
}
<commit_msg>gofmt -s<commit_after>// Copyright 2015 go-swagger maintainers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package strfmt

import (
	"database/sql/driver"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/mailru/easyjson/jlexer"
	"github.com/mailru/easyjson/jwriter"
)

func init() {
	d := Duration(0)
	Default.Add("duration", &d, IsDuration)
}

var (
	timeUnits = [][]string{
		{"ns", "nano"},
		{"us", "µs", "micro"},
		{"ms", "milli"},
		{"s", "sec"},
		{"m", "min"},
		{"h", "hr", "hour"},
		{"d", "day"},
		{"w", "wk", "week"},
	}

	timeMultiplier = map[string]time.Duration{
		"ns": time.Nanosecond,
		"us": time.Microsecond,
		"ms": time.Millisecond,
		"s":  time.Second,
		"m":  time.Minute,
		"h":  time.Hour,
		"d":  24 * time.Hour,
		"w":  7 * 24 * time.Hour,
	}

	durationMatcher = regexp.MustCompile(`((\d+)\s*([A-Za-zµ]+))`)
)

// IsDuration returns true if the provided string is a valid duration
func IsDuration(str string) bool {
	_, err := ParseDuration(str)
	return err == nil
}

// Duration represents a duration
//
// swagger:strfmt duration
type Duration time.Duration

// MarshalText turns this instance into text
func (d Duration) MarshalText() ([]byte, error) {
	return []byte(time.Duration(d).String()), nil
}

// UnmarshalText hydrates this instance from text
func (d *Duration) UnmarshalText(data []byte) error { // validation is performed later on
	dd, err := ParseDuration(string(data))
	if err != nil {
		return err
	}
	*d = Duration(dd)
	return nil
}

// ParseDuration parses a duration from a string, compatible with scala duration syntax
func ParseDuration(cand string) (time.Duration, error) {
	if dur, err := time.ParseDuration(cand); err == nil {
		return dur, nil
	}

	var dur time.Duration
	ok := false
	for _, match := range durationMatcher.FindAllStringSubmatch(cand, -1) {

		factor, err := strconv.Atoi(match[2]) // converts string to int
		if err != nil {
			return 0, err
		}
		unit := strings.ToLower(strings.TrimSpace(match[3]))

		for _, variants := range timeUnits {
			last := len(variants) - 1
			multiplier := timeMultiplier[variants[0]]

			for i, variant := range variants {
				if (last == i && strings.HasPrefix(unit, variant)) || strings.EqualFold(variant, unit) {
					ok = true
					dur += (time.Duration(factor) * multiplier)
				}
			}
		}
	}

	if ok {
		return dur, nil
	}
	return 0, fmt.Errorf("Unable to parse %s as duration", cand)
}

// Scan reads a Duration value from database driver type.
func (d *Duration) Scan(raw interface{}) error {
	switch v := raw.(type) {
	// TODO: case []byte: // ?
	case int64:
		*d = Duration(v)
	case float64:
		*d = Duration(int64(v))
	case nil:
		*d = Duration(0)
	default:
		return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v)
	}

	return nil
}

// Value converts Duration to a primitive value ready to written to a database.
func (d Duration) Value() (driver.Value, error) {
	return driver.Value(int64(d)), nil
}

// String converts this duration to a string
func (d Duration) String() string {
	return time.Duration(d).String()
}

func (d Duration) MarshalJSON() ([]byte, error) {
	var w jwriter.Writer
	d.MarshalEasyJSON(&w)
	return w.BuildBytes()
}

func (d Duration) MarshalEasyJSON(w *jwriter.Writer) {
	w.String(time.Duration(d).String())
}

func (d *Duration) UnmarshalJSON(data []byte) error {
	l := jlexer.Lexer{Data: data}
	d.UnmarshalEasyJSON(&l)
	return l.Error()
}

func (d *Duration) UnmarshalEasyJSON(in *jlexer.Lexer) {
	if data := in.String(); in.Ok() {
		tt, err := ParseDuration(data)
		if err != nil {
			in.AddError(err)
			return
		}
		*d = Duration(tt)
	}
}
<|endoftext|>


<commit_before>package dwn

import (
	"fmt"
	"net/http"
)

// APIHandler is a filler example as I work on the API
func PostHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "Url contains %s!", r.URL.Path[1:])
}
<commit_msg>fix comment<commit_after>package dwn

import (
	"fmt"
	"net/http"
)

// PostHandler gets, creates, and updates posts
func PostHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "Url contains %s!", r.URL.Path[1:])
}
<|endoftext|>


<commit_before>package ecs

import (
	"time"

	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

type CreateVpcArgs struct {
	RegionId    common.Region
	CidrBlock   string //192.168.0.0/16 or 172.16.0.0/16 (default)
	VpcName     string
	Description string
	ClientToken string
}

type CreateVpcResponse struct {
	common.Response
	VpcId        string
	VRouterId    string
	RouteTableId string
}

// CreateVpc creates Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&createvpc
func (client *Client) CreateVpc(args *CreateVpcArgs) (resp *CreateVpcResponse, err error) {
	response := CreateVpcResponse{}
	err = client.Invoke("CreateVpc", args, &response)
	if err != nil {
		return nil, err
	}
	return &response, err
}

type DeleteVpcArgs struct {
	VpcId string
}

type DeleteVpcResponse struct {
	common.Response
}

// DeleteVpc deletes Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&deletevpc
func (client *Client) DeleteVpc(vpcId string) error {
	args := DeleteVpcArgs{
		VpcId: vpcId,
	}
	response := DeleteVpcResponse{}
	return client.Invoke("DeleteVpc", &args, &response)
}

type VpcStatus string

const (
	VpcStatusPending   = VpcStatus("Pending")
	VpcStatusAvailable = VpcStatus("Available")
)

type DescribeVpcsArgs struct {
	VpcId    string
	RegionId common.Region
	common.Pagination
}

//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&vpcsettype
type VpcSetType struct {
	VpcId      string
	RegionId   common.Region
	Status     VpcStatus // enum Pending | Available
	VpcName    string
	VSwitchIds struct {
		VSwitchId []string
	}
	CidrBlock    string
	VRouterId    string
	Description  string
	IsDefault    bool
	CreationTime util.ISO6801Time
}

type DescribeVpcsResponse struct {
	common.Response
	common.PaginationResult
	Vpcs struct {
		Vpc []VpcSetType
	}
}

// DescribeInstanceStatus describes instance status
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&describevpcs
func (client *Client) DescribeVpcs(args *DescribeVpcsArgs) (vpcs []VpcSetType, pagination *common.PaginationResult, err error) {
	response, err := client.DescribeVpcsWithRaw(args)
	if err != nil {
		return nil, nil, err
	}

	return response.Vpcs.Vpc, &response.PaginationResult, nil
}

func (client *Client) DescribeVpcsWithRaw(args *DescribeVpcsArgs) (response *DescribeVpcsResponse, err error) {
	args.Validate()
	response = &DescribeVpcsResponse{}

	err = client.Invoke("DescribeVpcs", args, response)
	if err != nil {
		return nil, err
	}

	return response, err
}

type ModifyVpcAttributeArgs struct {
	VpcId       string
	VpcName     string
	Description string
}

type ModifyVpcAttributeResponse struct {
	common.Response
}

// ModifyVpcAttribute modifies attribute of Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&modifyvpcattribute
func (client *Client) ModifyVpcAttribute(args *ModifyVpcAttributeArgs) error {
	response := ModifyVpcAttributeResponse{}
	return client.Invoke("ModifyVpcAttribute", args, &response)
}

// WaitForInstance waits for instance to given status
func (client *Client) WaitForVpcAvailable(regionId common.Region, vpcId string, timeout int) error {
	if timeout <= 0 {
		timeout = DefaultTimeout
	}
	args := DescribeVpcsArgs{
		RegionId: regionId,
		VpcId:    vpcId,
	}
	for {
		vpcs, _, err := client.DescribeVpcs(&args)
		if err != nil {
			return err
		}
		if len(vpcs) > 0 && vpcs[0].Status == VpcStatusAvailable {
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
	}
	return nil
}
<commit_msg>VpcSetType.RouterTableIds.RouterTableIds<commit_after>package ecs

import (
	"time"

	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

type CreateVpcArgs struct {
	RegionId    common.Region
	CidrBlock   string //192.168.0.0/16 or 172.16.0.0/16 (default)
	VpcName     string
	Description string
	ClientToken string
}

type CreateVpcResponse struct {
	common.Response
	VpcId        string
	VRouterId    string
	RouteTableId string
}

// CreateVpc creates Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&createvpc
func (client *Client) CreateVpc(args *CreateVpcArgs) (resp *CreateVpcResponse, err error) {
	response := CreateVpcResponse{}
	err = client.Invoke("CreateVpc", args, &response)
	if err != nil {
		return nil, err
	}
	return &response, err
}

type DeleteVpcArgs struct {
	VpcId string
}

type DeleteVpcResponse struct {
	common.Response
}

// DeleteVpc deletes Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&deletevpc
func (client *Client) DeleteVpc(vpcId string) error {
	args := DeleteVpcArgs{
		VpcId: vpcId,
	}
	response := DeleteVpcResponse{}
	return client.Invoke("DeleteVpc", &args, &response)
}

type VpcStatus string

const (
	VpcStatusPending   = VpcStatus("Pending")
	VpcStatusAvailable = VpcStatus("Available")
)

type DescribeVpcsArgs struct {
	VpcId    string
	RegionId common.Region
	common.Pagination
}

//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/datatype&vpcsettype
type VpcSetType struct {
	VpcId      string
	RegionId   common.Region
	Status     VpcStatus // enum Pending | Available
	VpcName    string
	VSwitchIds struct {
		VSwitchId []string
	}
	CidrBlock    string
	VRouterId    string
	Description  string
	IsDefault    bool
	CreationTime util.ISO6801Time
	RouterTableIds struct{
		RouterTableIds []string
	}
}

type DescribeVpcsResponse struct {
	common.Response
	common.PaginationResult
	Vpcs struct {
		Vpc []VpcSetType
	}
}

// DescribeInstanceStatus describes instance status
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&describevpcs
func (client *Client) DescribeVpcs(args *DescribeVpcsArgs) (vpcs []VpcSetType, pagination *common.PaginationResult, err error) {
	response, err := client.DescribeVpcsWithRaw(args)
	if err != nil {
		return nil, nil, err
	}

	return response.Vpcs.Vpc, &response.PaginationResult, nil
}

func (client *Client) DescribeVpcsWithRaw(args *DescribeVpcsArgs) (response *DescribeVpcsResponse, err error) {
	args.Validate()
	response = &DescribeVpcsResponse{}

	err = client.Invoke("DescribeVpcs", args, response)
	if err != nil {
		return nil, err
	}

	return response, err
}

type ModifyVpcAttributeArgs struct {
	VpcId       string
	VpcName     string
	Description string
}

type ModifyVpcAttributeResponse struct {
	common.Response
}

// ModifyVpcAttribute modifies attribute of Virtual Private Cloud
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vpc&modifyvpcattribute
func (client *Client) ModifyVpcAttribute(args *ModifyVpcAttributeArgs) error {
	response := ModifyVpcAttributeResponse{}
	return client.Invoke("ModifyVpcAttribute", args, &response)
}

// WaitForInstance waits for instance to given status
func (client *Client) WaitForVpcAvailable(regionId common.Region, vpcId string, timeout int) error {
	if timeout <= 0 {
		timeout = DefaultTimeout
	}
	args := DescribeVpcsArgs{
		RegionId: regionId,
		VpcId:    vpcId,
	}
	for {
		vpcs, _, err := client.DescribeVpcs(&args)
		if err != nil {
			return err
		}
		if len(vpcs) > 0 && vpcs[0].Status == VpcStatusAvailable {
			break
		}
		timeout = timeout - DefaultWaitForInterval
		if timeout <= 0 {
			return common.GetClientErrorFromString("Timeout")
		}
		time.Sleep(DefaultWaitForInterval * time.Second)
	}
	return nil
}
<|endoftext|>


<commit_before>// +build darwin freebsd linux openbsd netbsd dragonfly

package libedit

import (
	"errors"
	"fmt"
	"io"
	"os"
	"syscall"
	"unsafe"
)

// #cgo openbsd netbsd freebsd dragonfly darwin LDFLAGS: -ledit
// #cgo openbsd netbsd freebsd dragonfly darwin CPPFLAGS: -Ishim
// #cgo linux          LDFLAGS: -lncurses
// #cgo linux          CFLAGS: -Wno-unused-result
// #cgo linux          CPPFLAGS: -Isrc -Isrc/c-libedit -Isrc/c-libedit/editline -Isrc/c-libedit/linux-build
//
// #include <stdlib.h>
// #include <stdio.h>
// #include <unistd.h>
// #include <limits.h>
//
// #include <histedit.h>
// #include "c_editline.h"
import "C"

type EditLine int

type LeftPromptGenerator interface {
	GetLeftPrompt(el EditLine) string
}

type RightPromptGenerator interface {
	GetRightPrompt(el EditLine) string
}

type CompletionGenerator interface {
	GetCompletions(word string) []string
}

type state struct {
	el              *C.EditLine
	h               *C.History
	cIn, cOut, cErr *C.FILE
	inf, outf, errf *os.File
	promptGenLeft   LeftPromptGenerator
	promptGenRight  RightPromptGenerator
	cPromptLeft     *C.char
	cPromptRight    *C.char
	completer       CompletionGenerator
	histFile        *C.char
	autoSaveHistory bool
}

var editors []state

var errUnknown = errors.New("unknown error")

func Init(appName string) (EditLine, error) {
	return InitFiles(appName, os.Stdin, os.Stdout, os.Stderr)
}

func InitFiles(appName string, inf, outf, errf *os.File) (e EditLine, err error) {
	var inFile, outFile, errFile *C.FILE
	defer func() {
		if err == nil {
			return
		}
		if inFile != nil {
			C.fclose(inFile)
		}
		if outFile != nil {
			C.fclose(outFile)
		}
		if errFile != nil {
			C.fclose(errFile)
		}
	}()

	inFile, err = C.fdopen(C.dup(C.int(inf.Fd())), C.go_libedit_mode_read)
	if err != nil {
		return -1, fmt.Errorf("fdopen(inf): %v", err)
	}
	outFile, err = C.fdopen(C.dup(C.int(outf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(outf): %v", err)
	}
	errFile, err = C.fdopen(C.dup(C.int(errf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(errf): %v", err)
	}
	cAppName := C.CString(appName)
	defer C.free(unsafe.Pointer(cAppName))
	el, err := C.go_libedit_init(cAppName, inFile, outFile, errFile)
	if el == nil || err != nil {
		if err == nil {
			err = errUnknown
		}
		return -1, fmt.Errorf("el_init: %v", err)
	}

	st := state{
		el:  el,
		inf: inf, outf: outf, errf: errf,
		cIn: inFile, cOut: outFile, cErr: errFile,
	}
	editors = append(editors, st)
	return EditLine(len(editors) - 1), nil
}

func (el EditLine) Close() {
	st := &editors[el]
	if st.el == nil {
		// Already closed.
		return
	}
	C.el_end(st.el)
	if st.h != nil {
		C.history_end(st.h)
	}
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
	}
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
	}
	C.fclose(st.cIn)
	C.fclose(st.cOut)
	C.fclose(st.cErr)
	*st = state{}
}

var errNoHistory = errors.New("history not configured")
var errNoFileConfigured = errors.New("no savefile configured")

func (el EditLine) SaveHistory() error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}
	if st.histFile == nil {
		return errNoFileConfigured
	}
	_, err := C.go_libedit_write_history(st.h, st.histFile)
	if err != nil {
		return fmt.Errorf("write_history: %v", err)
	}
	return nil
}

func (el EditLine) AddHistory(line string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	cLine := C.CString(line)
	defer C.free(unsafe.Pointer(cLine))

	_, err := C.go_libedit_add_history(st.h, cLine)
	if err != nil {
		return fmt.Errorf("add_history: %v", err)
	}

	if st.autoSaveHistory && st.histFile != nil {
		_, err := C.go_libedit_write_history(st.h, histFile)
		if err != nil {
			return fmt.Errorf("write_history: %v", err)
		}
	}
	return nil
}

func (el EditLine) LoadHistory(file string, autoSave bool) error {
	st := &editors[el]
	var newHistFile *C.char
	if file != "" {
		newHistFile = C.CString(file)
		_, err := C.go_libedit_read_history(st.h, newHistFile)
		if err != nil && err != syscall.ENOENT {
			C.free(unsafe.Pointer(newHistFile))
			return fmt.Errorf("read_history: %v", err)
		}
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
		st.histFile = nil
	}
	st.histFile = newHistFile
	st.autoSaveHistory = autoSave
	return nil
}

func (el EditLine) UseHistory(maxEntries int, dedup bool) error {
	st := &editors[el]

	cDedup := 0
	if dedup {
		cDedup = 1
	}

	cMaxEntries := C.int(maxEntries)
	if maxEntries < 0 {
		cMaxEntries = C.INT_MAX
	}

	h, err := C.go_libedit_setup_history(st.el, cMaxEntries, C.int(cDedup))
	if err != nil {
		return fmt.Errorf("init_history: %v", err)
	}
	if st.h != nil {
		C.history_end(st.h)
	}
	st.h = h
	return nil
}

var ErrInterrupted = errors.New("interrupted")

func (el EditLine) GetLine() (string, error) {
	st := &editors[el]

	var count C.int
	var interrupted C.int
	s, err := C.go_libedit_gets(st.el, &count, &interrupted)
	if interrupted > 0 {
		return "", ErrInterrupted
	}
	if err != nil {
		return "", err
	}
	if s == nil {
		return "", io.EOF
	}
	return C.GoStringN(s, count), nil
}

func (el EditLine) Stdin() *os.File {
	return editors[el].inf
}

func (el EditLine) Stdout() *os.File {
	return editors[el].outf
}

func (el EditLine) Stderr() *os.File {
	return editors[el].errf
}

func (el EditLine) SetCompleter(gen CompletionGenerator) {
	editors[el].completer = gen
}

func (el EditLine) SetLeftPrompt(gen LeftPromptGenerator) {
	st := &editors[el]
	st.promptGenLeft = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, C.go_libedit_prompt_left_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, nil)
	}
}

func (el EditLine) SetRightPrompt(gen RightPromptGenerator) {
	st := &editors[el]
	st.promptGenRight = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, C.go_libedit_prompt_right_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, nil)
	}
}

//export go_libedit_getcompletions
func go_libedit_getcompletions(cI C.int, cWord *C.char) **C.char {
	if int(cI) < 0 || int(cI) >= len(editors) {
		return nil
	}
	st := &editors[int(cI)]
	if st.completer == nil {
		return nil
	}

	word := C.GoString(cWord)
	matches := st.completer.GetCompletions(word)
	if len(matches) == 0 {
		return nil
	}

	array := (**C.char)(C.malloc(C.size_t(C.sizeof_pchar * (len(matches) + 1))))
	for i, m := range matches {
		C.go_libedit_set_string_array(array, C.int(i), C.CString(m))
	}
	C.go_libedit_set_string_array(array, C.int(len(matches)), nil)
	return array
}

//export go_libedit_prompt_left
func go_libedit_prompt_left(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
		st.cPromptLeft = nil
	}
	if st.promptGenLeft == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptLeft = C.CString(st.promptGenLeft.GetLeftPrompt(EditLine(e)))
	return st.cPromptLeft
}

//export go_libedit_prompt_right
func go_libedit_prompt_right(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
		st.cPromptRight = nil
	}
	if st.promptGenRight == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptRight = C.CString(st.promptGenRight.GetRightPrompt(EditLine(e)))
	return st.cPromptRight
}
<commit_msg>Separate SetAutoSaveHistory from LoadHistory.<commit_after>// +build darwin freebsd linux openbsd netbsd dragonfly

package libedit

import (
	"errors"
	"fmt"
	"io"
	"os"
	"syscall"
	"unsafe"
)

// #cgo openbsd netbsd freebsd dragonfly darwin LDFLAGS: -ledit
// #cgo openbsd netbsd freebsd dragonfly darwin CPPFLAGS: -Ishim
// #cgo linux          LDFLAGS: -lncurses
// #cgo linux          CFLAGS: -Wno-unused-result
// #cgo linux          CPPFLAGS: -Isrc -Isrc/c-libedit -Isrc/c-libedit/editline -Isrc/c-libedit/linux-build
//
// #include <stdlib.h>
// #include <stdio.h>
// #include <unistd.h>
// #include <limits.h>
//
// #include <histedit.h>
// #include "c_editline.h"
import "C"

type EditLine int

type LeftPromptGenerator interface {
	GetLeftPrompt(el EditLine) string
}

type RightPromptGenerator interface {
	GetRightPrompt(el EditLine) string
}

type CompletionGenerator interface {
	GetCompletions(word string) []string
}

type state struct {
	el              *C.EditLine
	h               *C.History
	cIn, cOut, cErr *C.FILE
	inf, outf, errf *os.File
	promptGenLeft   LeftPromptGenerator
	promptGenRight  RightPromptGenerator
	cPromptLeft     *C.char
	cPromptRight    *C.char
	completer       CompletionGenerator
	histFile        *C.char
	autoSaveHistory bool
}

var editors []state

var errUnknown = errors.New("unknown error")

func Init(appName string) (EditLine, error) {
	return InitFiles(appName, os.Stdin, os.Stdout, os.Stderr)
}

func InitFiles(appName string, inf, outf, errf *os.File) (e EditLine, err error) {
	var inFile, outFile, errFile *C.FILE
	defer func() {
		if err == nil {
			return
		}
		if inFile != nil {
			C.fclose(inFile)
		}
		if outFile != nil {
			C.fclose(outFile)
		}
		if errFile != nil {
			C.fclose(errFile)
		}
	}()

	inFile, err = C.fdopen(C.dup(C.int(inf.Fd())), C.go_libedit_mode_read)
	if err != nil {
		return -1, fmt.Errorf("fdopen(inf): %v", err)
	}
	outFile, err = C.fdopen(C.dup(C.int(outf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(outf): %v", err)
	}
	errFile, err = C.fdopen(C.dup(C.int(errf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(errf): %v", err)
	}
	cAppName := C.CString(appName)
	defer C.free(unsafe.Pointer(cAppName))
	el, err := C.go_libedit_init(cAppName, inFile, outFile, errFile)
	if el == nil || err != nil {
		if err == nil {
			err = errUnknown
		}
		return -1, fmt.Errorf("el_init: %v", err)
	}

	st := state{
		el:  el,
		inf: inf, outf: outf, errf: errf,
		cIn: inFile, cOut: outFile, cErr: errFile,
	}
	editors = append(editors, st)
	return EditLine(len(editors) - 1), nil
}

func (el EditLine) Close() {
	st := &editors[el]
	if st.el == nil {
		// Already closed.
		return
	}
	C.el_end(st.el)
	if st.h != nil {
		C.history_end(st.h)
	}
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
	}
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
	}
	C.fclose(st.cIn)
	C.fclose(st.cOut)
	C.fclose(st.cErr)
	*st = state{}
}

var errNoHistory = errors.New("history not configured")
var errNoFileConfigured = errors.New("no savefile configured")

func (el EditLine) SaveHistory() error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}
	if st.histFile == nil {
		return errNoFileConfigured
	}
	_, err := C.go_libedit_write_history(st.h, st.histFile)
	if err != nil {
		return fmt.Errorf("write_history: %v", err)
	}
	return nil
}

func (el EditLine) AddHistory(line string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	cLine := C.CString(line)
	defer C.free(unsafe.Pointer(cLine))

	_, err := C.go_libedit_add_history(st.h, cLine)
	if err != nil {
		return fmt.Errorf("add_history: %v", err)
	}

	if st.autoSaveHistory && st.histFile != nil {
		_, err := C.go_libedit_write_history(st.h, histFile)
		if err != nil {
			return fmt.Errorf("write_history: %v", err)
		}
	}
	return nil
}

func (el EditLine) LoadHistory(file string) error {
	st := &editors[el]
	if file != "" {
		histFile = C.CString(file)
		defer C.free(unsafe.Pointer(histFile))
		_, err := C.go_libedit_read_history(st.h, histFile)
		if err != nil && err != syscall.ENOENT {
			return fmt.Errorf("read_history: %v", err)
		}
	}
	return nil
}

func (el EditLine) SetAutoSaveHistory(file string, autoSave bool) {
	st := &editors[el]
	var newHistFile *C.char
	if file != "" {
		newHistFile = C.CString(file)
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
		st.histFile = nil
	}
	st.histFile = newHistFile
	st.autoSaveHistory = autoSave
}

func (el EditLine) UseHistory(maxEntries int, dedup bool) error {
	st := &editors[el]

	cDedup := 0
	if dedup {
		cDedup = 1
	}

	cMaxEntries := C.int(maxEntries)
	if maxEntries < 0 {
		cMaxEntries = C.INT_MAX
	}

	h, err := C.go_libedit_setup_history(st.el, cMaxEntries, C.int(cDedup))
	if err != nil {
		return fmt.Errorf("init_history: %v", err)
	}
	if st.h != nil {
		C.history_end(st.h)
	}
	st.h = h
	return nil
}

var ErrInterrupted = errors.New("interrupted")

func (el EditLine) GetLine() (string, error) {
	st := &editors[el]

	var count C.int
	var interrupted C.int
	s, err := C.go_libedit_gets(st.el, &count, &interrupted)
	if interrupted > 0 {
		return "", ErrInterrupted
	}
	if err != nil {
		return "", err
	}
	if s == nil {
		return "", io.EOF
	}
	return C.GoStringN(s, count), nil
}

func (el EditLine) Stdin() *os.File {
	return editors[el].inf
}

func (el EditLine) Stdout() *os.File {
	return editors[el].outf
}

func (el EditLine) Stderr() *os.File {
	return editors[el].errf
}

func (el EditLine) SetCompleter(gen CompletionGenerator) {
	editors[el].completer = gen
}

func (el EditLine) SetLeftPrompt(gen LeftPromptGenerator) {
	st := &editors[el]
	st.promptGenLeft = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, C.go_libedit_prompt_left_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, nil)
	}
}

func (el EditLine) SetRightPrompt(gen RightPromptGenerator) {
	st := &editors[el]
	st.promptGenRight = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, C.go_libedit_prompt_right_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, nil)
	}
}

//export go_libedit_getcompletions
func go_libedit_getcompletions(cI C.int, cWord *C.char) **C.char {
	if int(cI) < 0 || int(cI) >= len(editors) {
		return nil
	}
	st := &editors[int(cI)]
	if st.completer == nil {
		return nil
	}

	word := C.GoString(cWord)
	matches := st.completer.GetCompletions(word)
	if len(matches) == 0 {
		return nil
	}

	array := (**C.char)(C.malloc(C.size_t(C.sizeof_pchar * (len(matches) + 1))))
	for i, m := range matches {
		C.go_libedit_set_string_array(array, C.int(i), C.CString(m))
	}
	C.go_libedit_set_string_array(array, C.int(len(matches)), nil)
	return array
}

//export go_libedit_prompt_left
func go_libedit_prompt_left(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
		st.cPromptLeft = nil
	}
	if st.promptGenLeft == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptLeft = C.CString(st.promptGenLeft.GetLeftPrompt(EditLine(e)))
	return st.cPromptLeft
}

//export go_libedit_prompt_right
func go_libedit_prompt_right(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
		st.cPromptRight = nil
	}
	if st.promptGenRight == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptRight = C.CString(st.promptGenRight.GetRightPrompt(EditLine(e)))
	return st.cPromptRight
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"github.com/codegangsta/cli"
	"github.com/gonium/her0ld/bots"
	irc "github.com/thoj/go-ircevent"
	"log"
	"os"
	"os/signal"
	"time"
)

func main() {
	app := cli.NewApp()
	app.Name = "her0ld"
	app.Usage = "A friendly IRC bot written in Go."
	app.Version = "0.1.0"
	app.HideVersion = true
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose, v",
			Usage: "print verbose messages",
		},
		cli.StringFlag{
			Name:  "config, c",
			Usage: "Load configuration from `FILE`",
		},
	}
	// TODO: Create a command for generating an example configuration
	app.Action = func(c *cli.Context) {
		channel := "#her0ld-dev"
		nick := "her0ld-dev"
		server := "irc.hackint.org:9999"
		quitmsg := `There's been a little complication with my complication.
										-- Mrs. Terrain, Brazil`

		// whenever the bot should be terminated, send a 'true' to this
		// channel.
		quit := make(chan bool)

		// intercept CTRL-C and jump to proper bot termination
		ctrlc := make(chan os.Signal, 1)
		signal.Notify(ctrlc, os.Interrupt)
		go func() {
			for _ = range ctrlc {
				if c.Bool("verbose") {
					log.Printf("Received SIGINT")
				}
				quit <- true
			}
		}()

		ircconn := irc.IRC(nick, "Development of her0ld bot")
		if c.Bool("verbose") {
			log.Printf("Started %s with verbose logging", app.Name)
			ircconn.Debug = true
			//ircconn.VerboseCallbackHandler = true
		}
		ircconn.UseTLS = true
		ircconn.TLSConfig = &tls.Config{InsecureSkipVerify: true}
		ircconn.PingFreq = 1 * time.Minute
		ircconn.QuitMessage = quitmsg

		var allBots []her0ld.Bot
		// the echobot is only helpful during development...
		allBots = append(allBots, her0ld.NewEchoBot("Echobot"))
		allBots = append(allBots, her0ld.NewPingBot("Pingbot"))

		// Join channel upon welcome message
		ircconn.AddCallback("001", func(e *irc.Event) {
			ircconn.Join(channel)
		})
		// When end of nick list of channel received: send hello message
		// to channel
		ircconn.AddCallback("366", func(e *irc.Event) {
			ircconn.Privmsg(channel, "bot is active")
		})

		// forward PRIVMSG to bots
		ircconn.AddCallback("PRIVMSG", func(event *irc.Event) {
			//event.Message() contains the message
			//event.Nick Contains the sender
			//event.Arguments[0] Contains the channel
			for idx, arg := range event.Arguments {
				log.Println("%d - %s", idx, arg)
			}
			source := event.Arguments[0]
			msg := her0ld.InboundMessage{
				Channel: source,
				Nick:    event.Nick,
				Message: event.Message(),
			}
			if msg.IsChannelEvent() {
				// channel message
				log.Printf("Inbound channel message: %s", msg)
				for _, bot := range allBots {
					answerlines, err := bot.ProcessChannelEvent(msg)
					if err != nil {
						log.Printf("Bot %s failed to process inbound channel message \"%s\": %s",
							bot.GetName(), event.Message(), err.Error())
					} else {
						for _, line := range answerlines {
							ircconn.Privmsg(line.Destination, line.Message)
						}
					}
				}
			} else {
				// query message
				// TODO: This is broken. event.Nick does not contain the sender,
				// but the bot itself.
				log.Printf("Inbound query message: %s", msg)
				for _, bot := range allBots {
					answerlines, err := bot.ProcessQueryEvent(msg)
					if err != nil {
						log.Printf("Bot %s failed to process inbound query message \"%s\": %s",
							bot.GetName(), event.Message(), err.Error())
					} else {
						for _, line := range answerlines {
							ircconn.Privmsg(line.Destination, line.Message)
						}
					}
				}

			}
		})

		// now, run the server
		err := ircconn.Connect(server)
		if err != nil {
			log.Fatalf("Failed to connect to %s: %s", server, err.Error())
		}

		// wait for termination signal
		<-quit
		// cleanup tasks
		log.Printf("Terminating bot.")
		ircconn.Quit()
		time.Sleep(1 * time.Second)
	}
	app.Run(os.Args)
}
<commit_msg>stub for generating configuration file<commit_after>package main

import (
	"crypto/tls"
	"github.com/codegangsta/cli"
	"github.com/gonium/her0ld/bots"
	irc "github.com/thoj/go-ircevent"
	"log"
	"os"
	"os/signal"
	"time"
)

func main() {
	app := cli.NewApp()
	app.Name = "her0ld"
	app.Usage = "A friendly IRC bot written in Go."
	app.Version = "0.1.0"
	app.HideVersion = true
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose, v",
			Usage: "print verbose messages",
		},
		cli.StringFlag{
			Name:  "config, c",
			Usage: "Load configuration from given file",
		},
	}
	// TODO: Create a command for generating an example configuration
	app.Commands = []cli.Command{
		{
			Name:  "genconfig",
			Usage: "Generates a sample configuration file",
			Action: func(c *cli.Context) {
				cfgfile := c.String("config")
				if cfgfile == "" {
					log.Fatalf("Please provide a configuration file (-c)")
				}
				if c.Bool("verbose") {
					log.Println("Writing sample configuration to %s", cfgfile)
				}
			},
		},
	}
	app.Action = func(c *cli.Context) {
		channel := "#her0ld-dev"
		nick := "her0ld-dev"
		server := "irc.hackint.org:9999"
		quitmsg := `There's been a little complication with my complication.
										-- Mrs. Terrain, Brazil`

		// whenever the bot should be terminated, send a 'true' to this
		// channel.
		quit := make(chan bool)

		// intercept CTRL-C and jump to proper bot termination
		ctrlc := make(chan os.Signal, 1)
		signal.Notify(ctrlc, os.Interrupt)
		go func() {
			for _ = range ctrlc {
				if c.Bool("verbose") {
					log.Printf("Received SIGINT")
				}
				quit <- true
			}
		}()

		ircconn := irc.IRC(nick, "Development of her0ld bot")
		if c.Bool("verbose") {
			log.Printf("Started %s with verbose logging", app.Name)
			ircconn.Debug = true
			//ircconn.VerboseCallbackHandler = true
		}
		ircconn.UseTLS = true
		ircconn.TLSConfig = &tls.Config{InsecureSkipVerify: true}
		ircconn.PingFreq = 1 * time.Minute
		ircconn.QuitMessage = quitmsg

		var allBots []her0ld.Bot
		// the echobot is only helpful during development...
		allBots = append(allBots, her0ld.NewEchoBot("Echobot"))
		allBots = append(allBots, her0ld.NewPingBot("Pingbot"))

		// Join channel upon welcome message
		ircconn.AddCallback("001", func(e *irc.Event) {
			ircconn.Join(channel)
		})
		// When end of nick list of channel received: send hello message
		// to channel
		ircconn.AddCallback("366", func(e *irc.Event) {
			ircconn.Privmsg(channel, "bot is active")
		})

		// forward PRIVMSG to bots
		ircconn.AddCallback("PRIVMSG", func(event *irc.Event) {
			//event.Message() contains the message
			//event.Nick Contains the sender
			//event.Arguments[0] Contains the channel
			for idx, arg := range event.Arguments {
				log.Println("%d - %s", idx, arg)
			}
			source := event.Arguments[0]
			msg := her0ld.InboundMessage{
				Channel: source,
				Nick:    event.Nick,
				Message: event.Message(),
			}
			if msg.IsChannelEvent() {
				// channel message
				log.Printf("Inbound channel message: %s", msg)
				for _, bot := range allBots {
					answerlines, err := bot.ProcessChannelEvent(msg)
					if err != nil {
						log.Printf("Bot %s failed to process inbound channel message \"%s\": %s",
							bot.GetName(), event.Message(), err.Error())
					} else {
						for _, line := range answerlines {
							ircconn.Privmsg(line.Destination, line.Message)
						}
					}
				}
			} else {
				// query message
				// TODO: This is broken. event.Nick does not contain the sender,
				// but the bot itself.
				log.Printf("Inbound query message: %s", msg)
				for _, bot := range allBots {
					answerlines, err := bot.ProcessQueryEvent(msg)
					if err != nil {
						log.Printf("Bot %s failed to process inbound query message \"%s\": %s",
							bot.GetName(), event.Message(), err.Error())
					} else {
						for _, line := range answerlines {
							ircconn.Privmsg(line.Destination, line.Message)
						}
					}
				}

			}
		})

		// now, run the server
		err := ircconn.Connect(server)
		if err != nil {
			log.Fatalf("Failed to connect to %s: %s", server, err.Error())
		}

		// wait for termination signal
		<-quit
		// cleanup tasks
		log.Printf("Terminating bot.")
		ircconn.Quit()
		time.Sleep(1 * time.Second)
	}
	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package horizon

import (
	"errors"

	"fmt"

	"github.com/stellar/go/xdr"
	"github.com/stellar/horizon/db2"
	"github.com/stellar/horizon/db2/history"
	"github.com/stellar/horizon/render/hal"
	"github.com/stellar/horizon/resource"
)

// TradeIndexAction renders a page of effect resources, filtered to include
// only trades, identified by a normal page query and optionally filtered by an account
// or order book
type TradeIndexAction struct {
	Action
	AccountFilter string
	Selling       xdr.Asset
	Buying        xdr.Asset
	PagingParams  db2.PageQuery
	Records       []history.Effect
	// LedgerRecords is a cache of loaded ledger data used to populate the time
	// when a trade occurred.
	LedgerRecords map[int32]history.Ledger
	Page          hal.Page
}

// JSON is a method for actions.JSON
func (action *TradeIndexAction) JSON() {
	action.Do(
		action.EnsureHistoryFreshness,
		action.loadParams,
		action.loadRecords,
		action.loadLedgers,
		action.loadPage,
		func() {
			hal.Render(action.W, action.Page)
		},
	)
}

// LoadQuery sets action.Query from the request params
func (action *TradeIndexAction) loadParams() {
	action.AccountFilter = action.GetString("account_id")
	action.PagingParams = action.GetPageQuery()

	// scott: It is unfortunate that we have this string guard below.  Instead, we
	// should probably add an alternative to `GetAsset` that returns a zero-value
	// xdr.Asset when not provided by the request.  Perhaps `MaybeGetAsset`?.
	if action.GetString("selling_asset_type") != "" {
		action.Selling = action.GetAsset("selling_")
		action.Buying = action.GetAsset("buying_")
	}
}

// loadRecords populates action.Records
func (action *TradeIndexAction) loadRecords() {
	trades := action.HistoryQ().Effects().OfType(history.EffectTrade)

	if action.AccountFilter != "" {
		trades = trades.ForAccount(action.AccountFilter)
	}

	if (action.Selling != xdr.Asset{} || action.Buying != xdr.Asset{}) {
		trades = trades.ForOrderBook(action.Selling, action.Buying)
	}

	action.Err = trades.Page(action.PagingParams).Select(&action.Records)
}

// loadLedgers collects the unique ledgers referenced in the loaded trades and loads the details for each.
func (action *TradeIndexAction) loadLedgers() {
	if len(action.Records) == 0 {
		return
	}

	ledgerSequences := make([]interface{}, len(action.Records))

	// populate the unique sequences
	for i, trade := range action.Records {
		ledgerSequences[i] = trade.LedgerSequence()
	}

	var ledgers []history.Ledger
	action.Err = action.HistoryQ().LedgersBySequence(
		&ledgers,
		ledgerSequences...,
	)
	if action.Err != nil {
		return
	}

	action.LedgerRecords = map[int32]history.Ledger{}
	for _, l := range ledgers {
		action.LedgerRecords[l.Sequence] = l
	}
}

// loadPage populates action.Page
func (action *TradeIndexAction) loadPage() {
	for _, record := range action.Records {
		var res resource.Trade

		ledger, found := action.LedgerRecords[record.LedgerSequence()]
		if !found {
			msg := fmt.Sprintf("could not find ledger data for sequence %d", record.LedgerSequence())
			action.Err = errors.New(msg)
		}

		action.Err = res.Populate(action.Ctx, record, ledger)
		if action.Err != nil {
			return
		}

		action.Page.Add(res)
	}

	action.Page.BaseURL = action.BaseURL()
	action.Page.BasePath = action.Path()
	action.Page.Limit = action.PagingParams.Limit
	action.Page.Cursor = action.PagingParams.Cursor
	action.Page.Order = action.PagingParams.Order
	action.Page.PopulateLinks()
}
<commit_msg>Add missing error return<commit_after>package horizon

import (
	"errors"

	"fmt"

	"github.com/stellar/go/xdr"
	"github.com/stellar/horizon/db2"
	"github.com/stellar/horizon/db2/history"
	"github.com/stellar/horizon/render/hal"
	"github.com/stellar/horizon/resource"
)

// TradeIndexAction renders a page of effect resources, filtered to include
// only trades, identified by a normal page query and optionally filtered by an account
// or order book
type TradeIndexAction struct {
	Action
	AccountFilter string
	Selling       xdr.Asset
	Buying        xdr.Asset
	PagingParams  db2.PageQuery
	Records       []history.Effect
	// LedgerRecords is a cache of loaded ledger data used to populate the time
	// when a trade occurred.
	LedgerRecords map[int32]history.Ledger
	Page          hal.Page
}

// JSON is a method for actions.JSON
func (action *TradeIndexAction) JSON() {
	action.Do(
		action.EnsureHistoryFreshness,
		action.loadParams,
		action.loadRecords,
		action.loadLedgers,
		action.loadPage,
		func() {
			hal.Render(action.W, action.Page)
		},
	)
}

// LoadQuery sets action.Query from the request params
func (action *TradeIndexAction) loadParams() {
	action.AccountFilter = action.GetString("account_id")
	action.PagingParams = action.GetPageQuery()

	// scott: It is unfortunate that we have this string guard below.  Instead, we
	// should probably add an alternative to `GetAsset` that returns a zero-value
	// xdr.Asset when not provided by the request.  Perhaps `MaybeGetAsset`?.
	if action.GetString("selling_asset_type") != "" {
		action.Selling = action.GetAsset("selling_")
		action.Buying = action.GetAsset("buying_")
	}
}

// loadRecords populates action.Records
func (action *TradeIndexAction) loadRecords() {
	trades := action.HistoryQ().Effects().OfType(history.EffectTrade)

	if action.AccountFilter != "" {
		trades = trades.ForAccount(action.AccountFilter)
	}

	if (action.Selling != xdr.Asset{} || action.Buying != xdr.Asset{}) {
		trades = trades.ForOrderBook(action.Selling, action.Buying)
	}

	action.Err = trades.Page(action.PagingParams).Select(&action.Records)
}

// loadLedgers collects the unique ledgers referenced in the loaded trades and loads the details for each.
func (action *TradeIndexAction) loadLedgers() {
	if len(action.Records) == 0 {
		return
	}

	ledgerSequences := make([]interface{}, len(action.Records))

	// populate the unique sequences
	for i, trade := range action.Records {
		ledgerSequences[i] = trade.LedgerSequence()
	}

	var ledgers []history.Ledger
	action.Err = action.HistoryQ().LedgersBySequence(
		&ledgers,
		ledgerSequences...,
	)
	if action.Err != nil {
		return
	}

	action.LedgerRecords = map[int32]history.Ledger{}
	for _, l := range ledgers {
		action.LedgerRecords[l.Sequence] = l
	}
}

// loadPage populates action.Page
func (action *TradeIndexAction) loadPage() {
	for _, record := range action.Records {
		var res resource.Trade

		ledger, found := action.LedgerRecords[record.LedgerSequence()]
		if !found {
			msg := fmt.Sprintf("could not find ledger data for sequence %d", record.LedgerSequence())
			action.Err = errors.New(msg)
			return
		}

		action.Err = res.Populate(action.Ctx, record, ledger)
		if action.Err != nil {
			return
		}

		action.Page.Add(res)
	}

	action.Page.BaseURL = action.BaseURL()
	action.Page.BasePath = action.Path()
	action.Page.Limit = action.PagingParams.Limit
	action.Page.Cursor = action.PagingParams.Cursor
	action.Page.Order = action.PagingParams.Order
	action.Page.PopulateLinks()
}
<|endoftext|>


<commit_before>package libmyna

import (
	"errors"
	"fmt"
	"github.com/ebfe/scard"
	"github.com/urfave/cli"
	"os"
	"time"
)

type Reader struct {
	ctx  *scard.Context
	c    *cli.Context
	name string
	card *scard.Card
}

func NewReader(c *cli.Context) *Reader {
	ctx, err := scard.EstablishContext()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		return nil
	}

	readers, err := ctx.ListReaders()
	if err != nil || len(readers) == 0 {
		return nil
	}
	if len(readers) >= 2 {
		fmt.Fprintf(os.Stderr,
			"警告: 複数のリーダーが見つかりました。最初のものを使います\n")
	}

	reader := new(Reader)
	reader.ctx = ctx
	reader.c = c
	reader.name = readers[0]
	reader.card = nil
	return reader
}

func (self *Reader) Finalize() {
	self.ctx.Release()
}

func (self *Reader) GetCard() *scard.Card {
	card, _ := self.ctx.Connect(
		self.name, scard.ShareExclusive, scard.ProtocolAny)
	self.card = card
	return card
}

func (self *Reader) WaitForCard() error {
	rs := make([]scard.ReaderState, 1)
	rs[0].Reader = self.name
	rs[0].CurrentState = scard.StateUnaware
	for i := 0; i < 5; i++ {
		err := self.ctx.GetStatusChange(rs, -1)
		if err != nil {
			return fmt.Errorf("エラー: %s\n", err)
		}
		if rs[0].EventState&scard.StatePresent != 0 {
			card, err := self.ctx.Connect(
				self.name, scard.ShareExclusive, scard.ProtocolAny)
			if err == nil {
				self.card = card
				return nil
			}
		}
		fmt.Fprintf(os.Stderr, "wait for card...\n")
		time.Sleep(1 * time.Second)
	}
	return errors.New("カードが見つかりません")
}

func (self *Reader) SelectAP(aid string) bool {
	return self.SelectDF(aid)
}

func (self *Reader) SelectCardAP() bool {
	return self.SelectDF("D3 92 10 00 31 00 01 01 04 08")
}

func (self *Reader) SelectJPKIAP() bool {
	return self.SelectDF("D3 92 f0 00 26 01 00 00 00 01")
}

func (self *Reader) SelectDF(id string) bool {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Select DF\n")
	}
	bid := ToBytes(id)
	apdu := "00 A4 04 0C" + fmt.Sprintf(" %02X % X", len(bid), bid)
	sw1, sw2, _ := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return true
	} else {
		return false
	}
}

func (self *Reader) SelectEF(id string) (uint8, uint8) {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Select EF\n")
	}
	bid := ToBytes(id)
	apdu := fmt.Sprintf("00 A4 02 0C %02X % X", len(bid), bid)
	sw1, sw2, _ := self.Tx(apdu)
	return sw1, sw2
}

func (self *Reader) LookupPin() int {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Lookup PIN\n")
	}
	sw1, sw2, _ := self.Tx("00 20 00 80")
	if sw1 == 0x63 {
		return int(sw2 & 0x0F)
	} else {
		return -1
	}
}

func (self *Reader) Verify(pin string) (uint8, uint8) {
	var apdu string
	if pin == "" {
		if self.c.GlobalBool("debug") {
			fmt.Fprintf(os.Stderr, "# Lookup PIN\n")
		}
		apdu = "00 20 00 80"
		sw1, sw2, _ := self.Tx(apdu)
		return sw1, sw2
	} else {
		if self.c.GlobalBool("debug") {
			fmt.Fprintf(os.Stderr, "# Verify PIN\n")
		}
		bpin := []byte(pin)
		apdu = fmt.Sprintf("00 20 00 80 %02X % X", len(bpin), bpin)
		sw1, sw2, _ := self.Tx(apdu)
		return sw1, sw2
	}
}

func (self *Reader) ChangePin(pin string) bool {
	var apdu string
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Change PIN\n")
	}
	bpin := []byte(pin)
	apdu = fmt.Sprintf("00 24 01 80 %02X % X", len(bpin), bpin)
	sw1, sw2, _ := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return true
	} else {
		return false
	}
}

func dumpBinary(bin []byte) {
	for i := 0; i < len(bin); i++ {
		if i%0x10 == 0 {
			fmt.Fprintf(os.Stderr, ">")
		}
		fmt.Fprintf(os.Stderr, " %02X", bin[i])
		if i%0x10 == 0x0f {
			fmt.Println()
		}
	}
	fmt.Println()
}

func (self *Reader) Tx(apdu string) (uint8, uint8, []byte) {
	card := self.card
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "< %v\n", apdu)
	}
	cmd := ToBytes(apdu)
	res, err := card.Transmit(cmd)
	if err != nil {
		fmt.Fprintf(os.Stderr, "err: %s\n", err)
		return 0, 0, nil
	}

	if self.c.GlobalBool("debug") {
		dumpBinary(res)
	}

	l := len(res)
	if l == 2 {
		return res[0], res[1], nil
	} else if l > 2 {
		return res[l-2], res[l-1], res[:l-2]
	}
	return 0, 0, nil
}

func (self *Reader) ReadBinary(size uint16) []byte {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Read Binary\n")
	}

	var l uint8
	var apdu string
	var pos uint16
	pos = 0
	var res []byte

	for pos < size {
		if size-pos > 0xFF {
			l = 0
		} else {
			l = uint8(size - pos)
		}
		apdu = fmt.Sprintf("00 B0 %02X %02X %02X",
			pos>>8&0xFF, pos&0xFF, l)
		sw1, sw2, data := self.Tx(apdu)
		if sw1 != 0x90 || sw2 != 0x00 {
			return nil
		}
		res = append(res, data...)
		pos += uint16(len(data))
	}
	return res
}

func (self *Reader) Signature(data []byte) ([]byte, error) {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Signature ")
	}

	apdu := fmt.Sprintf("80 2a 00 80 %02X % X 00", len(data), data)
	sw1, sw2, res := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return res, nil
	} else {
		return nil, fmt.Errorf("署名エラー(%0X, %0X)", sw1, sw2)
	}
}
<commit_msg>fix log formating<commit_after>package libmyna

import (
	"errors"
	"fmt"
	"github.com/ebfe/scard"
	"github.com/urfave/cli"
	"os"
	"time"
)

type Reader struct {
	ctx  *scard.Context
	c    *cli.Context
	name string
	card *scard.Card
}

func NewReader(c *cli.Context) *Reader {
	ctx, err := scard.EstablishContext()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		return nil
	}

	readers, err := ctx.ListReaders()
	if err != nil || len(readers) == 0 {
		return nil
	}
	if len(readers) >= 2 {
		fmt.Fprintf(os.Stderr,
			"警告: 複数のリーダーが見つかりました。最初のものを使います\n")
	}

	reader := new(Reader)
	reader.ctx = ctx
	reader.c = c
	reader.name = readers[0]
	reader.card = nil
	return reader
}

func (self *Reader) Finalize() {
	self.ctx.Release()
}

func (self *Reader) GetCard() *scard.Card {
	card, _ := self.ctx.Connect(
		self.name, scard.ShareExclusive, scard.ProtocolAny)
	self.card = card
	return card
}

func (self *Reader) WaitForCard() error {
	rs := make([]scard.ReaderState, 1)
	rs[0].Reader = self.name
	rs[0].CurrentState = scard.StateUnaware
	for i := 0; i < 5; i++ {
		err := self.ctx.GetStatusChange(rs, -1)
		if err != nil {
			return fmt.Errorf("エラー: %s\n", err)
		}
		if rs[0].EventState&scard.StatePresent != 0 {
			card, err := self.ctx.Connect(
				self.name, scard.ShareExclusive, scard.ProtocolAny)
			if err == nil {
				self.card = card
				return nil
			}
		}
		fmt.Fprintf(os.Stderr, "wait for card...\n")
		time.Sleep(1 * time.Second)
	}
	return errors.New("カードが見つかりません")
}

func (self *Reader) SelectAP(aid string) bool {
	return self.SelectDF(aid)
}

func (self *Reader) SelectCardAP() bool {
	return self.SelectDF("D3 92 10 00 31 00 01 01 04 08")
}

func (self *Reader) SelectJPKIAP() bool {
	return self.SelectDF("D3 92 f0 00 26 01 00 00 00 01")
}

func (self *Reader) SelectDF(id string) bool {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Select DF\n")
	}
	bid := ToBytes(id)
	apdu := "00 A4 04 0C" + fmt.Sprintf(" %02X % X", len(bid), bid)
	sw1, sw2, _ := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return true
	} else {
		return false
	}
}

func (self *Reader) SelectEF(id string) (uint8, uint8) {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Select EF\n")
	}
	bid := ToBytes(id)
	apdu := fmt.Sprintf("00 A4 02 0C %02X % X", len(bid), bid)
	sw1, sw2, _ := self.Tx(apdu)
	return sw1, sw2
}

func (self *Reader) LookupPin() int {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Lookup PIN\n")
	}
	sw1, sw2, _ := self.Tx("00 20 00 80")
	if sw1 == 0x63 {
		return int(sw2 & 0x0F)
	} else {
		return -1
	}
}

func (self *Reader) Verify(pin string) (uint8, uint8) {
	var apdu string
	if pin == "" {
		if self.c.GlobalBool("debug") {
			fmt.Fprintf(os.Stderr, "# Lookup PIN\n")
		}
		apdu = "00 20 00 80"
		sw1, sw2, _ := self.Tx(apdu)
		return sw1, sw2
	} else {
		if self.c.GlobalBool("debug") {
			fmt.Fprintf(os.Stderr, "# Verify PIN\n")
		}
		bpin := []byte(pin)
		apdu = fmt.Sprintf("00 20 00 80 %02X % X", len(bpin), bpin)
		sw1, sw2, _ := self.Tx(apdu)
		return sw1, sw2
	}
}

func (self *Reader) ChangePin(pin string) bool {
	var apdu string
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Change PIN\n")
	}
	bpin := []byte(pin)
	apdu = fmt.Sprintf("00 24 01 80 %02X % X", len(bpin), bpin)
	sw1, sw2, _ := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return true
	} else {
		return false
	}
}

func dumpBinary(bin []byte) {
	for i := 0; i < len(bin); i++ {
		if i%0x10 == 0 {
			fmt.Fprintf(os.Stderr, ">")
		}
		fmt.Fprintf(os.Stderr, " %02X", bin[i])
		if i%0x10 == 0x0f {
			fmt.Fprintln(os.Stderr)
		}
	}
	fmt.Fprintln(os.Stderr)
}

func (self *Reader) Tx(apdu string) (uint8, uint8, []byte) {
	card := self.card
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "< %v\n", apdu)
	}
	cmd := ToBytes(apdu)
	res, err := card.Transmit(cmd)
	if err != nil {
		fmt.Fprintf(os.Stderr, "err: %s\n", err)
		return 0, 0, nil
	}

	if self.c.GlobalBool("debug") {
		dumpBinary(res)
	}

	l := len(res)
	if l == 2 {
		return res[0], res[1], nil
	} else if l > 2 {
		return res[l-2], res[l-1], res[:l-2]
	}
	return 0, 0, nil
}

func (self *Reader) ReadBinary(size uint16) []byte {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Read Binary\n")
	}

	var l uint8
	var apdu string
	var pos uint16
	pos = 0
	var res []byte

	for pos < size {
		if size-pos > 0xFF {
			l = 0
		} else {
			l = uint8(size - pos)
		}
		apdu = fmt.Sprintf("00 B0 %02X %02X %02X",
			pos>>8&0xFF, pos&0xFF, l)
		sw1, sw2, data := self.Tx(apdu)
		if sw1 != 0x90 || sw2 != 0x00 {
			return nil
		}
		res = append(res, data...)
		pos += uint16(len(data))
	}
	return res
}

func (self *Reader) Signature(data []byte) ([]byte, error) {
	if self.c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "# Signature\n")
	}

	apdu := fmt.Sprintf("80 2a 00 80 %02X % X 00", len(data), data)
	sw1, sw2, res := self.Tx(apdu)
	if sw1 == 0x90 && sw2 == 0x00 {
		return res, nil
	} else {
		return nil, fmt.Errorf("署名エラー(%0X, %0X)", sw1, sw2)
	}
}
<|endoftext|>


<commit_before>package main

type ability interface {
	perform()
	satisfiedRequirements(u *unit) bool
}

type partialAbility struct {
	disableTypes []disableType
}

// perform does nothing
func (p *partialAbility) perform() {}

// satisfiedRequirements returns true iff the ability satisfy activation requirements
func (p *partialAbility) satisfiedRequirements(u *unit) bool {
	for o := range u.operators {
		switch o := o.(type) {
		case *cooldown:
			if _, ok := o.ability.(*partialAbility); !ok {
				continue
			}
			if p == o.ability.(*partialAbility) {
				return false
			}
		case *disable:
			for d := range p.disableTypes {
				if disableType(d) == o.disableType {
					return false
				}
			}
		}
	}
	// todo check cost
	return true
}
<commit_msg>Check ability cost<commit_after>package main

type ability interface {
	perform()
	satisfiedRequirements(u *unit) bool
}

type partialAbility struct {
	disableTypes []disableType
	cost         int32
}

// perform does nothing
func (p *partialAbility) perform() {}

// satisfiedRequirements returns true iff the ability satisfy activation requirements
func (p *partialAbility) satisfiedRequirements(u *unit) bool {
	if u.mana() < p.cost {
		return false
	}
	for o := range u.operators {
		switch o := o.(type) {
		case *cooldown:
			if _, ok := o.ability.(*partialAbility); !ok {
				continue
			}
			if p == o.ability.(*partialAbility) {
				return false
			}
		case *disable:
			for d := range p.disableTypes {
				if disableType(d) == o.disableType {
					return false
				}
			}
		}
	}
	return true
}
<|endoftext|>


<commit_before>// lineserver emulates a line-based UDP server
package lineserver

import (
	"bufio"
	"fmt"
	"launchpad.net/tomb"
	"net"
)

// LineServer is a line-based UDP server à la `nc -u -l`. Ch channel
// will receive incoming lines from all clients.
type LineServer struct {
	Ch        chan string
	conn      *net.UDPConn
	tomb.Tomb // provides: Done, Kill, Dying
}

func NewLineServer(addr string) (*LineServer, error) {
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return nil, err
	}
	conn, err := net.ListenUDP("udp", laddr)
	if err != nil {
		return nil, err
	}
	var ls LineServer
	ls.Ch = make(chan string)
	ls.conn = conn
	return &ls, nil
}

func (srv *LineServer) GetAddr() (*net.UDPAddr, error) {
	return net.ResolveUDPAddr("udp", srv.conn.LocalAddr().String())
}

// Start starts the server. Call as a goroutine.
func (srv *LineServer) Start() {
	defer srv.conn.Close()
	defer srv.Done()
	defer fmt.Println("LineServer exiting")

	fmt.Println("LineServer starting")

	scanner := &AsyncScanner{
		make(chan bool),
		bufio.NewScanner(srv.conn),
	}
	go scanner.Run()

	// Scanned tokens are limited in max size (64 * 1024); see
	// pkg/bufio/scan.go:MaxScanTokenSize in Go source tree.
	for {
		select {
		case _, ok := <-scanner.ReadyCh:
			if ok {
				select {
				case srv.Ch <- scanner.Text():
				case <-srv.Dying():
					return
				}
			}else{
				if err := scanner.Err(); err != nil {
					srv.Kill(err)
				}
			}
		case <-srv.Dying():
			return
		}
	}
}
<commit_msg>lineserver: close read channel on exit<commit_after>// lineserver emulates a line-based UDP server
package lineserver

import (
	"bufio"
	"fmt"
	"launchpad.net/tomb"
	"net"
)

// LineServer is a line-based UDP server à la `nc -u -l`. Ch channel
// will receive incoming lines from all clients.
type LineServer struct {
	Ch        chan string
	conn      *net.UDPConn
	tomb.Tomb // provides: Done, Kill, Dying
}

func NewLineServer(addr string) (*LineServer, error) {
	laddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return nil, err
	}
	conn, err := net.ListenUDP("udp", laddr)
	if err != nil {
		return nil, err
	}
	var ls LineServer
	ls.Ch = make(chan string)
	ls.conn = conn
	return &ls, nil
}

func (srv *LineServer) GetAddr() (*net.UDPAddr, error) {
	return net.ResolveUDPAddr("udp", srv.conn.LocalAddr().String())
}

// Start starts the server. Call as a goroutine.
func (srv *LineServer) Start() {
	defer srv.conn.Close()
	defer close(srv.Ch)
	defer srv.Done()
	defer fmt.Println("LineServer exiting")

	fmt.Println("LineServer starting")

	scanner := &AsyncScanner{
		make(chan bool),
		bufio.NewScanner(srv.conn),
	}
	go scanner.Run()

	// Scanned tokens are limited in max size (64 * 1024); see
	// pkg/bufio/scan.go:MaxScanTokenSize in Go source tree.
	for {
		select {
		case _, ok := <-scanner.ReadyCh:
			if ok {
				select {
				case srv.Ch <- scanner.Text():
				case <-srv.Dying():
					return
				}
			}else{
				if err := scanner.Err(); err != nil {
					srv.Kill(err)
				}
			}
		case <-srv.Dying():
			return
		}
	}
}
<|endoftext|>


<commit_before>package ircbot

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

type ActionFunc func(b *IrcBot, m *IrcMsg)

type Action struct {
	command string
	do      ActionFunc
}

func Pong(b *IrcBot, m *IrcMsg) {

	b.Out <- &IrcMsg{
		command: "PONG",
		args:    m.args,
	}
}

func Join(b *IrcBot, m *IrcMsg) {
	if m.nick == b.Nick {
		b.joined = true
		return
	}

	s := fmt.Sprintf("%s :Salut %s", b.Channel[0], m.nick)
	b.Out <- &IrcMsg{
		command: "PRIVMSG",
		args:    []string{s},
	}
}

func Respond(b *IrcBot, m *IrcMsg) {
	response := []string{
		"oui ?",
		"on parle de moi ?",
		"Je suis pas là",
	}

	s := strings.Join(m.args, " ")

	if strings.Contains(s, b.Nick) {
		nbr := rand.Intn(len(response))
		line := fmt.Sprintf("%s :%s", b.Channel[0], response[nbr])
		b.Out <- &IrcMsg{
			command: "PRIVMSG",
			args:    []string{line},
		}
	}
}
<commit_msg>fix ping pong<commit_after>package ircbot

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

type ActionFunc func(b *IrcBot, m *IrcMsg)

type Action struct {
	command string
	do      ActionFunc
}

func Pong(b *IrcBot, m *IrcMsg) {

	s := fmt.Sprintf("%s", strings.Join(m.args, " "))
	b.Out <- &IrcMsg{
		command: "PONG",
		args:    []string{s},
	}
}

func Join(b *IrcBot, m *IrcMsg) {
	if m.nick == b.Nick {
		b.joined = true
		return
	}

	s := fmt.Sprintf("%s :Salut %s", b.Channel[0], m.nick)
	b.Out <- &IrcMsg{
		command: "PRIVMSG",
		args:    []string{s},
	}
}

func Respond(b *IrcBot, m *IrcMsg) {
	response := []string{
		"oui ?",
		"on parle de moi ?",
		"Je suis pas là",
	}

	s := strings.Join(m.args, " ")

	if strings.Contains(s, b.Nick) {
		nbr := rand.Intn(len(response))
		line := fmt.Sprintf("%s :%s", b.Channel[0], response[nbr])
		b.Out <- &IrcMsg{
			command: "PRIVMSG",
			args:    []string{line},
		}
	}
}
<|endoftext|>


<commit_before>package slack

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

// Adapter ...
type Adapter struct {
	cnf *Config
}

// NewAdapter starts a new Adapter instance
func NewAdapter(cnf *Config) *Adapter {
	return &Adapter{
		cnf: cnf,
	}
}

// SendMessage pushes a message to one of Slack's channels
func (a *Adapter) SendMessage(channel, username, text, emoji string) error {
	payload := map[string]string{
		"channel":  channel,
		"username": username,
		"text":     text,
		"emoji":    emoji,
	}
	payloadJSON, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	resp, err := http.PostForm(
		a.cnf.IncomingWebhook,
		url.Values{
			"payload": {string(payloadJSON)},
		},
	)
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("Send Slack Message Error: %s", string(body))
	}
	return nil
}
<commit_msg>Update adapter.go<commit_after>package slack

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

// Adapter ...
type Adapter struct {
	cnf *Config
}

// NewAdapter starts a new Adapter instance
func NewAdapter(cnf *Config) *Adapter {
	return &Adapter{
		cnf: cnf,
	}
}

// SendMessage pushes a message to one of Slack's channels
func (a *Adapter) SendMessage(channel, username, text, emoji string) error {
	payload := map[string]string{
		"channel":  channel,
		"username": username,
		"text":     text,
		"emoji":    emoji,
	}
	payloadJSON, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	resp, err := http.PostForm(
		a.cnf.IncomingWebhook,
		url.Values{
			"payload": {string(payloadJSON)},
		},
	)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("Send Slack Message Error: %s", string(body))
	}
	return nil
}
<|endoftext|>


<commit_before>package ads111x

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"fmt"

	"golang.org/x/exp/io/i2c"
)

// Resolution is the resolution of the ADC.
const Resolution = 1 << 16

// I2CAddress represents one of the possible I2C bus addresses.
type I2CAddress uint8

const (
	Addr48 I2CAddress = 0x48
	Addr49            = 0x49
	Addr4A            = 0x4A
	Addr4B            = 0x4B
)

const (
	// ConversionReg is the address of the conversion register.
	ConversionReg byte = iota
	// ConfigReg is the address of the config register.
	ConfigReg
	// LoThresReg is the address of the Lo_thresh register.
	LoThreshReg
	// HiThreshReg is the address of the Hi_thresh register.
	HiThreshReg
)

type Status uint16

const (
	Status_LSB  uint8  = 15
	Status_Mask uint16 = ^uint16(1 << Status_LSB)
)

const (
	// Busy means a conversion is currently being performed.
	Busy = iota << Status_LSB
	// Idle means a conversion is not currently being performed.
	Idle
)

type AIN uint16

const (
	AIN_LSB  uint8  = 12
	AIN_Mask uint16 = uint16(7 << AIN_LSB)
)

const (
	// AIN_0_1 is used to select AIN0 (pos) & AIN1 (neg) inputs (default).
	AIN_0_1 AIN = iota << AIN_LSB
	// AIN_0_3 is used to select AIN0 (pos) & AIN3 (neg) inputs.
	AIN_0_3
	// AIN_1_3 is used to select AIN1 (pos) & AIN3 (neg) inputs.
	AIN_1_3
	// AIN_2_3 is used to select AIN2 (pos) & AIN3 (neg) inputs.
	AIN_2_3
	// AIN_0_GND is used to select AIN0 (pos) & GND (neg) inputs.
	AIN_0_GND
	// AIN_1_GND is used to select AIN1 (pos) & GND (neg) inputs.
	AIN_1_GND
	// AIN_2_GND is used to select AIN2 (pos) & GND (neg) inputs.
	AIN_2_GND
	// AIN_3_GND is used to select AIN3 (pos) & GND (neg) inputs.
	AIN_3_GND
)

type FS uint16

const (
	FS_LSB  uint8  = 9
	FS_Mask uint16 = uint16(7 << FS_LSB)
)

const (
	// FS_6_144V is used to set full scale range to +/- 6.144V.
	FS_6_144V FS = iota << FS_LSB
	// FS_4_096V is used to set full scale range to +/- 4.096V.
	FS_4_096V
	// FS_2_048V is used to set full scale range to +/- 2.048V (default).
	FS_2_048V
	// FS_1_024V is used to set full scale range to +/- 1.024V.
	FS_1_024V
	// FS_0_512V is used to set full scale range to +/- 0.512V.
	FS_0_512V
	// FS_0_256V is used to set full scale range to +/- 0.256V.
	FS_0_256V
)

// FSMinMax returns the min and max voltages for the given full scale value.
func FSMinMax(fs FS) (min, max float64) {
	switch fs {
	case FS_6_144V:
		return -6.144, 6.144
	case FS_4_096V:
		return -4.096, 4.096
	case FS_2_048V:
		return -2.048, 2.048
	case FS_1_024V:
		return -1.024, 1.024
	case FS_0_512V:
		return -0.512, 0.512
	case FS_0_256V:
		return -0.256, 0.256
	default:
		panic("invalid fs value")
	}
}

// FSRange returns the difference between max and min for the full scale value.
func FSRange(fs FS) float64 {
	min, max := FSMinMax(fs)
	return max - min
}

type Mode uint16

const (
	Mode_LSB  uint8  = 8
	Mode_Mask uint16 = uint16(1 << Mode_LSB)
)

const (
	// Continuous is used to set continuous conversion mode.
	Continuous Mode = iota << Mode_LSB
	// Single is used to set Power-down single-shot mode (default).
	Single
)

type DataRate uint16

const (
	DataRate_LSB  uint8  = 5
	DataRate_Mask uint16 = uint16(7 << DataRate_LSB)
)

const (
	// DR_8SPS is used to set the data rate to 8 samples per second.
	DR_8SPS DataRate = iota << DataRate_LSB
	// DR_16SPS is used to set the data rate to 16 samples per second.
	DR_16SPS
	// DR_32SPS is used to set the data rate to 32 samples per second.
	DR_32SPS
	// DR_64SPS is used to set the data rate to 64 samples per second.
	DR_64SPS
	// DR_128SPS is used to set the data rate to 128 samples per second (default).
	DR_128SPS
	// DR_250SPS is used to set the data rate to 250 samples per second.
	DR_250SPS
	// DR_475SPS is used to set the data rate to 475 samples per second.
	DR_475SPS
	// DR_860SPS is used to set the data rate to 860 samples per second.
	DR_860SPS
)

type ComparatorMode uint16

const (
	ComparatorMode_LSB  uint8  = 4
	ComparatorMode_Mask uint16 = uint16(1 << ComparatorMode_LSB)
)

const (
	// Traditional is used to set traditional comparator with histeresis (default).
	Traditional ComparatorMode = iota << ComparatorMode_LSB
	// Window is used to set window comparator mode.
	Window
)

type ComparatorPolarity uint16

const (
	ComparatorPolarity_LSB  uint8  = 3
	ComparatorPolarity_Mask uint16 = uint16(1 << ComparatorPolarity_LSB)
)

const (
	// ActiveLow is used to set polarity of ALERT/RDY pin to active low (default).
	ActiveLow ComparatorPolarity = iota << ComparatorPolarity_LSB
	// ActiveHigh is used to set polarity of ALERT/RDY pin to active high.
	ActiveHigh
)

type ComparatorLatching uint16

const (
	ComparatorLatching_LSB  uint8  = 2
	ComparatorLatching_Mask uint16 = uint16(1 << ComparatorLatching_LSB)
)

const (
	// Off is used to set the comparator to non-latching (default).
	Off ComparatorLatching = iota << ComparatorLatching_LSB
	//On is used to set the comparator to latching.
	On
)

type ComparatorQueue uint16

const (
	ComparatorQueue_LSB  uint8  = 0
	ComparatorQueue_Mask uint16 = uint16(1 << ComparatorQueue_LSB)
)

const (
	// CQ_AfterOne is used to set number of successive conversions exceeding upper or lower
	// thresholds before asserting ALERT/RDY pin.
	AfterOne ComparatorQueue = iota << ComparatorQueue_LSB
	AfterTwo
	AfterFour
	Disable
)

// ADC represents an ADS1113, ADS1114, or ADS1115 analog to digital converter.
type ADC struct {
	i2c    *i2c.Device
	open   bool
	config uint16 // current device config
}

// Open returns a new ADC initialized and ready for use.
// dev is the I2C bus device, e.g., /dev/i2c-1
func Open(dev string, addr I2CAddress) (*ADC, error) {
	d, err := i2c.Open(&i2c.Devfs{Dev: dev}, int(addr))
	if err != nil {
		return nil, err
	}

	adc := &ADC{
		i2c: d,
	}

	if _, err := adc.Config(); err != nil {
		return nil, err
	}

	adc.open = true

	return adc, nil
}

// Close closes the ADC connection.
func (adc *ADC) Close() error {
	return adc.i2c.Close()
}

// Mode returns the mode config setting.
func (adc *ADC) Mode() (Mode, error) {
	return Mode(adc.config & Mode_Mask), nil
}

// SetMode sets the mode of operation (continuous or single).
func (adc *ADC) SetMode(m Mode) error {
	cfg := adc.config & ^Mode_Mask
	cfg |= uint16(m)
	return adc.WriteConfig(cfg)
}

// FullScale returns the full scale config setting.
func (adc *ADC) FullScale() (FS, error) {
	return FS(adc.config & FS_Mask), nil
}

// SetFullScale sets the full scale range.
func (adc *ADC) SetFullScale(fs FS) error {
	cfg := adc.config & ^FS_Mask
	cfg |= uint16(fs)
	return adc.WriteConfig(cfg)
}

// Config returns the device config.
func (adc *ADC) Config() (uint16, error) {
	if adc.open {
		return adc.config, nil
	}

	if err := adc.WriteReg(ConfigReg, []byte{}); err != nil {
		return 0, err
	}

	var buf [2]byte
	if err := adc.Read(buf[:]); err != nil {
		return 0, err
	}

	println("Config() read...")
	println(hex.Dump(buf[:]))

	config, err := leUint16(buf[:])
	if err != nil {
		return 0, err
	}

	adc.config = config

	return config, nil
}

// WriteConfig writes a new config to the device.
func (adc *ADC) WriteConfig(cfg uint16) error {
	println("writing config...")
	println(cfg)
	if err := adc.WriteReg(ConfigReg, cfg); err != nil {
		return err
	}
	adc.config = cfg
	return nil
}

// ReadVolts reads the voltage from the specified input.
func (adc *ADC) ReadVolts(input AIN) (float64, error) {
	cnt, err := adc.ReadAIN(input)
	if err != nil {
		return 0, err
	}

	fmt.Printf("FS_Mask = %v\n", FS_Mask)
	fmt.Printf("adc.config = %v\n", adc.config)
	println(FS(adc.config & FS_Mask))

	fsrange := FSRange(FS(adc.config & FS_Mask))
	voltsPerCnt := fsrange / Resolution

	return float64(cnt) * voltsPerCnt, nil
}

// ReadAIN reads the value from the specified input.
func (adc *ADC) ReadAIN(input AIN) (uint16, error) {
	// If the input isn't currently selected, select it.
	currentInput := AIN(adc.config & AIN_Mask)
	if input != currentInput {
		// Clear input select bits.
		newConfig := adc.config & ^AIN_Mask
		// Set new input select bits.
		newConfig |= uint16(input)
		// Write new config.
		if err := adc.WriteConfig(newConfig); err != nil {
			return 0, err
		}
	}

	// Read value from the conversion register.
	var buf [2]byte
	if err := adc.ReadReg(ConversionReg, buf[:]); err != nil {
		return 0, err
	}

	val, err := toUint16(buf[:])
	if err != nil {
		return 0, err
	}

	return val, nil
}

// Read reads from the device.
func (adc *ADC) Read(buf []byte) error {
	return adc.i2c.Read(buf)
}

// ReadReg reads a register.
func (adc *ADC) ReadReg(reg byte, buf []byte) error {
	fmt.Printf("ReadReg(reg = %v)\n", reg)
	err := adc.i2c.ReadReg(reg, buf)
	println(hex.Dump(buf))
	return err
}

// Write writes bytes to the device.
func (adc *ADC) Write(buf []byte) error {
	return adc.i2c.Write(buf)
}

// WriteReg writes a value to a register on the device.
func (adc *ADC) WriteReg(reg byte, data interface{}) error {
	b, err := toBytes(data)
	if err != nil {
		return err
	}
	return adc.i2c.WriteReg(reg, b)
}

// toBytes converts data to a []byte suitable to send to the device.
func toBytes(data interface{}) ([]byte, error) {
	buf := &bytes.Buffer{}
	err := binary.Write(buf, binary.BigEndian, data)
	return buf.Bytes(), err
}

// toUint16 converts []byte to a uint16.
func toUint16(b []byte) (uint16, error) {
	var v uint16
	err := binary.Read(bytes.NewReader(b), binary.BigEndian, &v)
	return v, err
}

func leUint16(b []byte) (uint16, error) {
	var v uint16
	err := binary.Read(bytes.NewReader(b), binary.LittleEndian, &v)
	return v, err
}
<commit_msg>more debugging fixes<commit_after>package ads111x

import (
	"bytes"
	"encoding/binary"

	"golang.org/x/exp/io/i2c"
)

// Resolution is the resolution of the ADC.
const Resolution = 1 << 16

// I2CAddress represents one of the possible I2C bus addresses.
type I2CAddress uint8

const (
	Addr48 I2CAddress = 0x48
	Addr49            = 0x49
	Addr4A            = 0x4A
	Addr4B            = 0x4B
)

const (
	// ConversionReg is the address of the conversion register.
	ConversionReg byte = iota
	// ConfigReg is the address of the config register.
	ConfigReg
	// LoThresReg is the address of the Lo_thresh register.
	LoThreshReg
	// HiThreshReg is the address of the Hi_thresh register.
	HiThreshReg
)

// DefaultConfig is the configuration the device boots with.
const DefaultConfig = uint16(0x8583)

type Status uint16

const (
	Status_LSB  uint8  = 15
	Status_Mask uint16 = ^uint16(1 << Status_LSB)
)

const (
	// Busy means a conversion is currently being performed.
	Busy = iota << Status_LSB
	// Idle means a conversion is not currently being performed.
	Idle
)

type AIN uint16

const (
	AIN_LSB  uint8  = 12
	AIN_Mask uint16 = uint16(7 << AIN_LSB)
)

const (
	// AIN_0_1 is used to select AIN0 (pos) & AIN1 (neg) inputs (default).
	AIN_0_1 AIN = iota << AIN_LSB
	// AIN_0_3 is used to select AIN0 (pos) & AIN3 (neg) inputs.
	AIN_0_3
	// AIN_1_3 is used to select AIN1 (pos) & AIN3 (neg) inputs.
	AIN_1_3
	// AIN_2_3 is used to select AIN2 (pos) & AIN3 (neg) inputs.
	AIN_2_3
	// AIN_0_GND is used to select AIN0 (pos) & GND (neg) inputs.
	AIN_0_GND
	// AIN_1_GND is used to select AIN1 (pos) & GND (neg) inputs.
	AIN_1_GND
	// AIN_2_GND is used to select AIN2 (pos) & GND (neg) inputs.
	AIN_2_GND
	// AIN_3_GND is used to select AIN3 (pos) & GND (neg) inputs.
	AIN_3_GND
)

type FS uint16

const (
	FS_LSB  uint8  = 9
	FS_Mask uint16 = uint16(7 << FS_LSB)
)

const (
	// FS_6_144V is used to set full scale range to +/- 6.144V.
	FS_6_144V FS = iota << FS_LSB
	// FS_4_096V is used to set full scale range to +/- 4.096V.
	FS_4_096V
	// FS_2_048V is used to set full scale range to +/- 2.048V (default).
	FS_2_048V
	// FS_1_024V is used to set full scale range to +/- 1.024V.
	FS_1_024V
	// FS_0_512V is used to set full scale range to +/- 0.512V.
	FS_0_512V
	// FS_0_256V is used to set full scale range to +/- 0.256V.
	FS_0_256V
)

// FSMinMax returns the min and max voltages for the given full scale value.
func FSMinMax(fs FS) (min, max float64) {
	switch fs {
	case FS_6_144V:
		return -6.144, 6.144
	case FS_4_096V:
		return -4.096, 4.096
	case FS_2_048V:
		return -2.048, 2.048
	case FS_1_024V:
		return -1.024, 1.024
	case FS_0_512V:
		return -0.512, 0.512
	case FS_0_256V:
		return -0.256, 0.256
	default:
		panic("invalid fs value")
	}
}

// FSRange returns the difference between max and min for the full scale value.
func FSRange(fs FS) float64 {
	min, max := FSMinMax(fs)
	return max - min
}

type Mode uint16

const (
	Mode_LSB  uint8  = 8
	Mode_Mask uint16 = uint16(1 << Mode_LSB)
)

const (
	// Continuous is used to set continuous conversion mode.
	Continuous Mode = iota << Mode_LSB
	// Single is used to set Power-down single-shot mode (default).
	Single
)

type DataRate uint16

const (
	DataRate_LSB  uint8  = 5
	DataRate_Mask uint16 = uint16(7 << DataRate_LSB)
)

const (
	// DR_8SPS is used to set the data rate to 8 samples per second.
	DR_8SPS DataRate = iota << DataRate_LSB
	// DR_16SPS is used to set the data rate to 16 samples per second.
	DR_16SPS
	// DR_32SPS is used to set the data rate to 32 samples per second.
	DR_32SPS
	// DR_64SPS is used to set the data rate to 64 samples per second.
	DR_64SPS
	// DR_128SPS is used to set the data rate to 128 samples per second (default).
	DR_128SPS
	// DR_250SPS is used to set the data rate to 250 samples per second.
	DR_250SPS
	// DR_475SPS is used to set the data rate to 475 samples per second.
	DR_475SPS
	// DR_860SPS is used to set the data rate to 860 samples per second.
	DR_860SPS
)

type ComparatorMode uint16

const (
	ComparatorMode_LSB  uint8  = 4
	ComparatorMode_Mask uint16 = uint16(1 << ComparatorMode_LSB)
)

const (
	// Traditional is used to set traditional comparator with histeresis (default).
	Traditional ComparatorMode = iota << ComparatorMode_LSB
	// Window is used to set window comparator mode.
	Window
)

type ComparatorPolarity uint16

const (
	ComparatorPolarity_LSB  uint8  = 3
	ComparatorPolarity_Mask uint16 = uint16(1 << ComparatorPolarity_LSB)
)

const (
	// ActiveLow is used to set polarity of ALERT/RDY pin to active low (default).
	ActiveLow ComparatorPolarity = iota << ComparatorPolarity_LSB
	// ActiveHigh is used to set polarity of ALERT/RDY pin to active high.
	ActiveHigh
)

type ComparatorLatching uint16

const (
	ComparatorLatching_LSB  uint8  = 2
	ComparatorLatching_Mask uint16 = uint16(1 << ComparatorLatching_LSB)
)

const (
	// Off is used to set the comparator to non-latching (default).
	Off ComparatorLatching = iota << ComparatorLatching_LSB
	//On is used to set the comparator to latching.
	On
)

type ComparatorQueue uint16

const (
	ComparatorQueue_LSB  uint8  = 0
	ComparatorQueue_Mask uint16 = uint16(1 << ComparatorQueue_LSB)
)

const (
	// CQ_AfterOne is used to set number of successive conversions exceeding upper or lower
	// thresholds before asserting ALERT/RDY pin.
	AfterOne ComparatorQueue = iota << ComparatorQueue_LSB
	AfterTwo
	AfterFour
	Disable
)

type i2cdevice interface {
	Close() error
	Read([]byte) error
	ReadReg(reg byte, buf []byte) error
	Write(buf []byte) (err error)
	WriteReg(reg byte, buf []byte) (err error)
}

// ADC represents an ADS1113, ADS1114, or ADS1115 analog to digital converter.
type ADC struct {
	i2c i2cdevice
}

// Open returns a new ADC initialized and ready for use.
// dev is the I2C bus device, e.g., /dev/i2c-1
func Open(dev string, addr I2CAddress) (*ADC, error) {
	d, err := i2c.Open(&i2c.Devfs{Dev: dev}, int(addr))
	if err != nil {
		return nil, err
	}

	return &ADC{
		i2c: d,
	}, nil
}

// Close closes the ADC connection.
func (adc *ADC) Close() error {
	return adc.i2c.Close()
}

// Mode returns the mode config setting.
func (adc *ADC) Mode() (Mode, error) {
	cfg, err := adc.Config()
	if err != nil {
		return Continuous, err
	}
	return Mode(cfg & Mode_Mask), nil
}

// SetMode sets the mode of operation (continuous or single).
func (adc *ADC) SetMode(m Mode) error {
	cfg, err := adc.Config()
	if err != nil {
		return err
	}
	cfg &= ^Mode_Mask
	cfg |= uint16(m)
	return adc.WriteConfig(cfg)
}

// FullScale returns the full scale config setting.
func (adc *ADC) FullScale() (FS, error) {
	cfg, err := adc.Config()
	if err != nil {
		return FS_0_256V, err
	}
	return FS(cfg & FS_Mask), nil
}

// SetFullScale sets the full scale range.
func (adc *ADC) SetFullScale(fs FS) error {
	cfg, err := adc.Config()
	if err != nil {
		return err
	}
	cfg &= ^FS_Mask
	cfg |= uint16(fs)
	return adc.WriteConfig(cfg)
}

// Config returns the device config.
func (adc *ADC) Config() (uint16, error) {
	buf := make([]byte, 2)
	if err := adc.ReadReg(ConfigReg, buf); err != nil {
		return 0, err
	}

	var cfg uint16
	if err := binary.Read(bytes.NewReader(buf), binary.BigEndian, &cfg); err != nil {
		return 0, err
	}

	return cfg, nil
}

// WriteConfig writes a new config to the device.
func (adc *ADC) WriteConfig(cfg uint16) error {
	return adc.WriteReg(ConfigReg, cfg)
}

// ReadVolts reads the voltage from the specified input.
func (adc *ADC) ReadVolts(input AIN) (float64, error) {
	cfg, err := adc.Config()
	if err != nil {
		return 0.0, err
	}
	cnt, err := adc.ReadAIN(input)
	if err != nil {
		return 0, err
	}

	fsrange := FSRange(FS(cfg & FS_Mask))
	voltsPerCnt := fsrange / Resolution

	return float64(cnt) * voltsPerCnt, nil
}

// ReadAIN reads the value from the specified input.
func (adc *ADC) ReadAIN(input AIN) (uint16, error) {
	cfg, err := adc.Config()
	if err != nil {
		return 0, err
	}
	// If the input isn't currently selected, select it.
	currentInput := AIN(cfg & AIN_Mask)
	if input != currentInput {
		// Clear input select bits.
		newConfig := cfg & ^AIN_Mask
		// Set new input select bits.
		newConfig |= uint16(input)
		// Write new config.
		if err := adc.WriteConfig(newConfig); err != nil {
			return 0, err
		}
	}

	// Read value from the conversion register.
	buf := make([]byte, 2)
	if err := adc.ReadReg(ConversionReg, buf); err != nil {
		return 0, err
	}

	var n uint16
	if err := binary.Read(bytes.NewReader(buf), binary.BigEndian, &n); err != nil {
		return 0, err
	}

	return n, nil
}

// Read reads from the device.
func (adc *ADC) Read(buf []byte) error {
	return adc.i2c.Read(buf)
}

// ReadReg reads a register.
func (adc *ADC) ReadReg(reg byte, buf []byte) error {
	if err := adc.i2c.ReadReg(reg, buf); err != nil {
		return err
	}
	//fmt.Printf("ReadReg(0x%x) = {0x%x, 0x%x}\n", reg, buf[0], buf[1])
	return nil
}

// Write writes bytes to the device.
func (adc *ADC) Write(buf []byte) error {
	return adc.i2c.Write(buf)
}

// WriteReg writes a value to a register on the device.
func (adc *ADC) WriteReg(reg byte, data uint16) error {
	b, err := toBytes(data)
	if err != nil {
		return err
	}
	//fmt.Printf("WriteReg(0x%x, {0x%x, 0x%x})\n", reg, b[0], b[1])
	//println(hex.Dump(b))
	return adc.i2c.WriteReg(reg, b)
}

// toBytes converts data to a []byte suitable to send to the device.
func toBytes(data uint16) ([]byte, error) {
	buf := &bytes.Buffer{}
	err := binary.Write(buf, binary.BigEndian, data)
	return buf.Bytes(), err
}
<|endoftext|>


<commit_before>package ast

import (
	"errors"
	"fmt"
	"github.com/matttproud/prometheus/model"
	"time"
)

type Function struct {
	name       string
	argTypes   []ExprType
	returnType ExprType
	callFn     func(timestamp *time.Time, args []Node) interface{}
}

func (function *Function) CheckArgTypes(args []Node) error {
	if len(function.argTypes) != len(args) {
		return errors.New(
			fmt.Sprintf("Wrong number of arguments to function %v(): %v expected, %v given",
				function.name, len(function.argTypes), len(args)))
	}
	for idx, argType := range function.argTypes {
		invalidType := false
		var expectedType string
		if _, ok := args[idx].(ScalarNode); argType == SCALAR && !ok {
			invalidType = true
			expectedType = "scalar"
		}
		if _, ok := args[idx].(VectorNode); argType == VECTOR && !ok {
			invalidType = true
			expectedType = "vector"
		}
		if _, ok := args[idx].(MatrixNode); argType == MATRIX && !ok {
			invalidType = true
			expectedType = "matrix"
		}
		if _, ok := args[idx].(StringNode); argType == STRING && !ok {
			invalidType = true
			expectedType = "string"
		}

		if invalidType {
			return errors.New(
				fmt.Sprintf("Wrong type for argument %v in function %v(), expected %v",
					idx, function.name, expectedType))
		}
	}
	return nil
}

// === time() ===
func timeImpl(timestamp *time.Time, args []Node) interface{} {
	return model.SampleValue(time.Now().Unix())
}

// === count(vector VectorNode) ===
func countImpl(timestamp *time.Time, args []Node) interface{} {
	return model.SampleValue(len(args[0].(VectorNode).Eval(timestamp)))
}

// === delta(matrix MatrixNode, isCounter ScalarNode) ===
func deltaImpl(timestamp *time.Time, args []Node) interface{} {
	matrixNode := args[0].(MatrixNode)
	isCounter := int(args[1].(ScalarNode).Eval(timestamp))
	resultVector := Vector{}

	// If we treat these metrics as counters, we need to fetch all values
	// in the interval to find breaks in the timeseries' monotonicity.
	// I.e. if a counter resets, we want to ignore that reset.
	var matrixValue Matrix
	if isCounter > 0 {
		matrixValue = matrixNode.Eval(timestamp)
	} else {
		matrixValue = matrixNode.EvalBoundaries(timestamp)
	}
	for _, samples := range matrixValue {
		counterCorrection := model.SampleValue(0)
		lastValue := model.SampleValue(0)
		for _, sample := range samples.Values {
			currentValue := sample.Value
			if currentValue < lastValue {
				counterCorrection += lastValue - currentValue
			}
			lastValue = currentValue
		}
		resultValue := lastValue - samples.Values[0].Value + counterCorrection
		resultSample := &model.Sample{
			Metric:    samples.Metric,
			Value:     resultValue,
			Timestamp: *timestamp,
		}
		resultVector = append(resultVector, resultSample)
	}
	return resultVector
}

// === rate(node *MatrixNode) ===
func rateImpl(timestamp *time.Time, args []Node) interface{} {
	args = append(args, &ScalarLiteral{value: 1})
	return deltaImpl(timestamp, args)
}

// === sampleVectorImpl() ===
func sampleVectorImpl(timestamp *time.Time, args []Node) interface{} {
	return Vector{
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "0",
			},
			Value:     10,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "1",
			},
			Value:     20,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "2",
			},
			Value:     30,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "canary",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "2",
				"group":    "canary",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "mytest",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "mytest",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
	}
}

var functions = map[string]*Function{
	"time": {
		name:       "time",
		argTypes:   []ExprType{},
		returnType: SCALAR,
		callFn:     timeImpl,
	},
	"count": {
		name:       "count",
		argTypes:   []ExprType{VECTOR},
		returnType: SCALAR,
		callFn:     countImpl,
	},
	"delta": {
		name:       "delta",
		argTypes:   []ExprType{MATRIX, SCALAR},
		returnType: VECTOR,
		callFn:     deltaImpl,
	},
	"rate": {
		name:       "rate",
		argTypes:   []ExprType{MATRIX},
		returnType: VECTOR,
		callFn:     rateImpl,
	},
	"sampleVector": {
		name:       "sampleVector",
		argTypes:   []ExprType{},
		returnType: VECTOR,
		callFn:     sampleVectorImpl,
	},
}

func GetFunction(name string) (*Function, error) {
	function, ok := functions[name]
	if !ok {
		return nil, errors.New(fmt.Sprintf("Couldn't find function %v()", name))
	}
	return function, nil
}
<commit_msg>Implement per-second rate behavior for rate().<commit_after>package ast

import (
	"errors"
	"fmt"
	"github.com/matttproud/prometheus/model"
	"time"
)

type Function struct {
	name       string
	argTypes   []ExprType
	returnType ExprType
	callFn     func(timestamp *time.Time, args []Node) interface{}
}

func (function *Function) CheckArgTypes(args []Node) error {
	if len(function.argTypes) != len(args) {
		return errors.New(
			fmt.Sprintf("Wrong number of arguments to function %v(): %v expected, %v given",
				function.name, len(function.argTypes), len(args)))
	}
	for idx, argType := range function.argTypes {
		invalidType := false
		var expectedType string
		if _, ok := args[idx].(ScalarNode); argType == SCALAR && !ok {
			invalidType = true
			expectedType = "scalar"
		}
		if _, ok := args[idx].(VectorNode); argType == VECTOR && !ok {
			invalidType = true
			expectedType = "vector"
		}
		if _, ok := args[idx].(MatrixNode); argType == MATRIX && !ok {
			invalidType = true
			expectedType = "matrix"
		}
		if _, ok := args[idx].(StringNode); argType == STRING && !ok {
			invalidType = true
			expectedType = "string"
		}

		if invalidType {
			return errors.New(
				fmt.Sprintf("Wrong type for argument %v in function %v(), expected %v",
					idx, function.name, expectedType))
		}
	}
	return nil
}

// === time() ===
func timeImpl(timestamp *time.Time, args []Node) interface{} {
	return model.SampleValue(time.Now().Unix())
}

// === count(vector VectorNode) ===
func countImpl(timestamp *time.Time, args []Node) interface{} {
	return model.SampleValue(len(args[0].(VectorNode).Eval(timestamp)))
}

// === delta(matrix MatrixNode, isCounter ScalarNode) ===
func deltaImpl(timestamp *time.Time, args []Node) interface{} {
	matrixNode := args[0].(MatrixNode)
	isCounter := int(args[1].(ScalarNode).Eval(timestamp))
	resultVector := Vector{}

	// If we treat these metrics as counters, we need to fetch all values
	// in the interval to find breaks in the timeseries' monotonicity.
	// I.e. if a counter resets, we want to ignore that reset.
	var matrixValue Matrix
	if isCounter > 0 {
		matrixValue = matrixNode.Eval(timestamp)
	} else {
		matrixValue = matrixNode.EvalBoundaries(timestamp)
	}
	for _, samples := range matrixValue {
		counterCorrection := model.SampleValue(0)
		lastValue := model.SampleValue(0)
		for _, sample := range samples.Values {
			currentValue := sample.Value
			if currentValue < lastValue {
				counterCorrection += lastValue - currentValue
			}
			lastValue = currentValue
		}
		resultValue := lastValue - samples.Values[0].Value + counterCorrection
		resultSample := &model.Sample{
			Metric:    samples.Metric,
			Value:     resultValue,
			Timestamp: *timestamp,
		}
		resultVector = append(resultVector, resultSample)
	}
	return resultVector
}

// === rate(node *MatrixNode) ===
func rateImpl(timestamp *time.Time, args []Node) interface{} {
	args = append(args, &ScalarLiteral{value: 1})
	vector := deltaImpl(timestamp, args).(Vector)

	// TODO: could be other type of MatrixNode in the future (right now, only
	// MatrixLiteral exists). Find a better way of getting the duration of a
	// matrix, such as looking at the samples themselves.
	interval := args[0].(*MatrixLiteral).interval
	for _, sample := range vector {
		sample.Value /= model.SampleValue(interval / time.Second)
	}
	return vector
}

// === sampleVectorImpl() ===
func sampleVectorImpl(timestamp *time.Time, args []Node) interface{} {
	return Vector{
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "0",
			},
			Value:     10,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "1",
			},
			Value:     20,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "2",
			},
			Value:     30,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "canary",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "2",
				"group":    "canary",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "mytest",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
		&model.Sample{
			Metric: model.Metric{
				"name":     "http_requests",
				"job":      "api-server",
				"instance": "3",
				"group":    "mytest",
			},
			Value:     40,
			Timestamp: *timestamp,
		},
	}
}

var functions = map[string]*Function{
	"time": {
		name:       "time",
		argTypes:   []ExprType{},
		returnType: SCALAR,
		callFn:     timeImpl,
	},
	"count": {
		name:       "count",
		argTypes:   []ExprType{VECTOR},
		returnType: SCALAR,
		callFn:     countImpl,
	},
	"delta": {
		name:       "delta",
		argTypes:   []ExprType{MATRIX, SCALAR},
		returnType: VECTOR,
		callFn:     deltaImpl,
	},
	"rate": {
		name:       "rate",
		argTypes:   []ExprType{MATRIX},
		returnType: VECTOR,
		callFn:     rateImpl,
	},
	"sampleVector": {
		name:       "sampleVector",
		argTypes:   []ExprType{},
		returnType: VECTOR,
		callFn:     sampleVectorImpl,
	},
}

func GetFunction(name string) (*Function, error) {
	function, ok := functions[name]
	if !ok {
		return nil, errors.New(fmt.Sprintf("Couldn't find function %v()", name))
	}
	return function, nil
}
<|endoftext|>