<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

const port string = ":8080"
const htmlPage = "static/index.html"
const jsPage = "static/js/initialize.js"
const cssPage = "static/css/style.css"
const d3 = "static/js/d3/d3.js"

const (
	delete = iota
	update = iota
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

/*-----------------------------------------------------------------*/

func test(updates chan interface{}) {
	for {
		time.Sleep(1000000000)
		log.Println("test")
		updates <- "salut"
	}

}

/*-----------------------------------------------------------------*/

//MCUpdates multicast updates sent by the routine comminicating with the routers
func MCUpdates(updates chan interface{}, g *Listenergroupe) { //TODO changer string par le bon type
	for {
		update, quit := <-updates
		if quit == false {
			log.Println("closing all chanels")
			close(globalClose)
			return
		}
		g.Iter(func(l *Listener) {
			l.conduct <- update
		})

	}
}

//GetMess gets messages sent by the client and redirect them to the mess chanel
func GetMess(conn *websocket.Conn, mess chan []byte) {
	_, message, err := conn.ReadMessage()
	if err != nil {
		log.Println(err)
		return
	}
	mess <- message

}

//HandleMessage handle messages receved from the client
func HandleMessage(mess []byte) {
	//TODO gere les message du client
	return
}

/*-----------------------------------------------------------------*/

//RootHandler load the html file when someone connect to the root of the server
func RootHandler(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(htmlPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//RootHandcss load the CSS file when someone connect to the root of the server
func RootHandcss(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(cssPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//RootHandinitialize load js file when someone connect to the root of the server
func RootHandinitialize(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(jsPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}
func d3Handler(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(d3)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//WsHandler manage the websockets
func WsHandler(l *Listenergroupe) http.Handler { //TODO interface et non routeinfo
	fn := func(w http.ResponseWriter, r *http.Request) {

		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println("Could not create the socket.", err)
			return
		}
		//TODO parcourt la base de donné et envois tout au client

		log.Println("New connection to a websocket")
		updates := NewListener()
		l.Push(updates)
		defer l.Quit(updates)
		mess := make(chan []byte, chanelSize)
		go GetMess(conn, mess)
		for {
			//we wait for a new message from the client or from our chanel
			select {
			case lastUp := <-updates.conduct: //we got a new update on the chanel
				log.Println(lastUp)
				err := conn.WriteJSON(lastUp)
				if err != nil {
					log.Println(err)
				}

			case _, q := <-updates.quit:
				if q == false {
					return
				}

			case clientMessage := <-mess: //we got a message from the client
				log.Println(clientMessage)
				HandleMessage(clientMessage)

			}
		}
	}
	return http.HandlerFunc(fn)
}

/*-----------------------------------------------------------------*/

func wsManager(updates chan interface{}) {
	//creation du chanel pour communiquer avec le reste du serv
	log.Println("test")
	go test(updates)
	bcastGrp := NewListenerGroupe()
	go MCUpdates(updates, bcastGrp)
	ws := WsHandler(bcastGrp)
	http.HandleFunc("/", RootHandler)
	http.HandleFunc("/style.css", RootHandcss)
	http.HandleFunc("/initialize.js", RootHandinitialize)
	http.HandleFunc("/d3/d3.js", d3Handler)

	http.Handle("/ws", ws)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		return
	}

}
<commit_msg>quite manager for ws<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/websocket"
)

const port string = ":8080"
const htmlPage = "static/index.html"
const jsPage = "static/js/initialize.js"
const cssPage = "static/css/style.css"
const d3 = "static/js/d3/d3.js"

const (
	delete = iota
	update = iota
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

/*-----------------------------------------------------------------*/

func test(updates chan interface{}) {
	for {
		time.Sleep(1000000000)
		log.Println("test")
		updates <- "salut"
	}

}

/*-----------------------------------------------------------------*/

//MCUpdates multicast updates sent by the routine comminicating with the routers
func MCUpdates(updates chan interface{}, g *Listenergroupe) { //TODO changer string par le bon type
	for {
		update, quit := <-updates
		if quit == false {
			log.Println("closing all chanels")
			close(globalClose)
			return
		}
		g.Iter(func(l *Listener) {
			l.conduct <- update
		})

	}
}

//GetMess gets messages sent by the client and redirect them to the mess chanel
func GetMess(conn *websocket.Conn, mess chan []byte) {
	_, message, err := conn.ReadMessage()
	if err != nil {
		close(mess)
		log.Println(err)
		return
	}
	mess <- message

}

//HandleMessage handle messages receved from the client
func HandleMessage(mess []byte) {
	//TODO gere les message du client
	return
}

/*-----------------------------------------------------------------*/

//RootHandler load the html file when someone connect to the root of the server
func RootHandler(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(htmlPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//RootHandcss load the CSS file when someone connect to the root of the server
func RootHandcss(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(cssPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//RootHandinitialize load js file when someone connect to the root of the server
func RootHandinitialize(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(jsPage)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}
func d3Handler(w http.ResponseWriter, r *http.Request) {
	content, err := ioutil.ReadFile(d3)
	if err != nil {
		log.Println("Could not open file.", err)
	}
	fmt.Fprintf(w, "%s", content)
}

//WsHandler manage the websockets
func WsHandler(l *Listenergroupe) http.Handler { //TODO interface et non routeinfo
	fn := func(w http.ResponseWriter, r *http.Request) {

		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println("Could not create the socket.", err)
			return
		}
		//TODO parcourt la base de donné et envois tout au client

		log.Println("New connection to a websocket")
		updates := NewListener()
		l.Push(updates)
		defer l.Quit(updates)
		mess := make(chan []byte, chanelSize)
		go GetMess(conn, mess)
		for {
			//we wait for a new message from the client or from our chanel
			select {
			case lastUp := <-updates.conduct: //we got a new update on the chanel
				log.Println(lastUp)
				err := conn.WriteJSON(lastUp)
				if err != nil {
					log.Println(err)
				}

			case _, q := <-updates.quit:
				if q == false {
					return
				}

			case clientMessage, q := <-mess: //we got a message from the client
				if q == false {
					return
				}

				log.Println(clientMessage)

				HandleMessage(clientMessage)

			}
		}
	}
	return http.HandlerFunc(fn)
}

/*-----------------------------------------------------------------*/

func wsManager(updates chan interface{}) {
	//creation du chanel pour communiquer avec le reste du serv
	log.Println("test")
	go test(updates)
	bcastGrp := NewListenerGroupe()
	go MCUpdates(updates, bcastGrp)
	ws := WsHandler(bcastGrp)
	http.HandleFunc("/", RootHandler)
	http.HandleFunc("/style.css", RootHandcss)
	http.HandleFunc("/initialize.js", RootHandinitialize)
	http.HandleFunc("/d3/d3.js", d3Handler)

	http.Handle("/ws", ws)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		return
	}

}
<|endoftext|>


<commit_before>package wuxia

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/robertkrimen/otto"
	"github.com/spf13/afero"
)

const (
	scriptsDir = "scripts"
	initDir    = "init"
	planDir    = "plan"
	configFile = "config.json"
	indexFile  = "index.js"
)

type buildStage int

const (
	stageInit buildStage = iota
	stageConfig
	stagePlan
	stageExec
)

func (s buildStage) String() string {
	var rst string
	switch s {
	case stageInit:
		rst = "init"
	case stageConfig:
		rst = "config"
	case stagePlan:
		rst = "plan"
	case stageExec:
		rst = "exec"
	default:
		rst = "unkown stage"
	}
	return rst
}

//buildError error returned when building the static website. The error string
//returned is a json string that encodes the build stage and the message.
type buildError struct {
	Stage   string `json:"stage"`
	Message string `json:"msg"`
}

func buildErr(stage buildStage, msg string) error {
	return &buildError{Stage: stage.String(), Message: msg}
}

func (b *buildError) Error() string {
	o, err := json.Marshal(b)
	if err != nil {
		return err.Error()
	}
	return string(o)
}

//Generator provides the static website generation capabilities.This is heavily
//integrated with the otto javascript runtime.
type Generator struct {
	vm  *otto.Otto
	sys *System
	fs  afero.Fs

	// This is the absolute path to the root of the project from which the
	// Generator will be operating.
	workDir string
}

//NewGenerator retrunes a new  Generator.
func NewGenerator(vm *otto.Otto, sys *System, fs afero.Fs) *Generator {
	return &Generator{
		vm:  vm,
		sys: sys,
		fs:  fs,
	}
}

//Build builds a project.
func (g *Generator) Build() error {
	steps := []struct {
		stage buildStage
		exec  func() error
	}{
		{stageConfig, g.config},
		{stageInit, g.init},
		{stagePlan, g.plan},
		{stageExec, g.exec},
	}
	var err error
	for _, buildStep := range steps {
		err = buildStep.exec()
		if err != nil {
			return err
		}
	}
	return nil
}

//initializes the build process. Any stages after this will have the generator
//already bootstraped.
//
// It is possible to bootstrap the generator from the project( User's side) by
// providing an entry javascript file in the default path of
// scripts/init/index.js which will be executed and you can overide the default
// entry script which is evaluated internally
//
// Initialzation is offloaded to the javascript runtine of the generator..Any
// error returned is a build error.
func (g *Generator) init() error {

	_ = g.vm.Set("sys", func(call otto.FunctionCall) otto.Value {
		data, err := json.Marshal(g.sys)
		if err != nil {
			panicOtto(err)
		}
		val, err := call.Otto.Call("JSON.parse", nil, string(data))
		if err != nil {
			panicOtto(err)
		}
		return val
	})
	_, err := g.vm.Eval(entryScript())
	if err != nil {
		return buildErr(stageInit, err.Error())
	}

	_ = g.vm.Set("fileTree", fileTree(g.fs, g.workDir))

	// evaluate project provided entry script if provided. We ignore if the file
	// is not provided but any errors arsing from evaluating a provided script is
	// a built error.
	entryFile := filepath.Join(scriptsDir, initDir, indexFile)
	err = g.evaluateFile(entryFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(stageInit, err.Error())
		}
	}

	return nil
}

//fileTree provides an array of all files found in the root( which is suppose to
//be the working directory.
//
//The file index is built only once and evaluated once too, then it is cached.
//This operates in the otto runtime.
func fileTree(fs afero.Fs, root string) func(otto.FunctionCall) otto.Value {
	var tree []string
	var v otto.Value
	return func(call otto.FunctionCall) otto.Value {
		if tree != nil {
			return v
		}
		ferr := afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if !info.IsDir() {
				tree = append(tree, path)
			}
			return nil
		})
		if ferr != nil {
			tree = nil
			panicOtto(ferr.Error())
		}
		v, _ = call.Otto.ToValue(tree)
		return v
	}
}

func defaultSystem() *System {
	return &System{
		Boot: &Boot{
			ConfigiFile: configFile,
			PlanFile:    "index.js",
		},
	}
}

// opens the file in the specified path and evaluates it withing the context of
// the javascript runtine.
//
// The evaluated javascript code can mutate the global state. Use execFile to
// execute the javascript without mutating the state of the generato'r
// javascript runtime.
//
// TODO: (gernest) implement callFile if necessary
func (g *Generator) evaluateFile(path string) error {
	f, err := g.fs.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()
	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}
	_, err = g.vm.Eval(data)
	if err != nil {
		return err
	}
	return nil
}

func defaultVM(sys *System) *otto.Otto {
	return otto.New()
}

func (g *Generator) config() error {
	if g.sys == nil {
		g.sys = defaultSystem()
	}
	if g.vm == nil {
		g.vm = defaultVM(g.sys)
	}
	// Properly set working directory/
	if g.workDir == "" {
		wd, err := os.Getwd()
		if err != nil {
			return buildErr(stageInit, err.Error())
		}
		g.workDir = wd
	}

	// ensure everything is relative to the working directory
	g.fs = afero.NewBasePathFs(g.fs, g.workDir)
	af := afero.Afero{g.fs}
	data, err := af.ReadFile(configFile)
	if err != nil {
		return buildErr(stageInit, err.Error())
	}
	cfg := &Config{}
	err = json.Unmarshal(data, cfg)
	if err != nil {
		return buildErr(stageInit, err.Error())
	}
	g.sys.Config = cfg
	return nil
}

func (g *Generator) plan() error {
	return nil
}
func (g *Generator) exec() error {
	return nil
}
func (g *Generator) down() error {
	return nil
}
<commit_msg>Make gen.init and gen.Config Public<commit_after>package wuxia

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/robertkrimen/otto"
	"github.com/spf13/afero"
)

const (
	scriptsDir = "scripts"
	initDir    = "init"
	planDir    = "plan"
	configFile = "config.json"
	indexFile  = "index.js"
)

type buildStage int

const (
	stageInit buildStage = iota
	stageConfig
	stagePlan
	stageExec
)

func (s buildStage) String() string {
	var rst string
	switch s {
	case stageInit:
		rst = "init"
	case stageConfig:
		rst = "config"
	case stagePlan:
		rst = "plan"
	case stageExec:
		rst = "exec"
	default:
		rst = "unkown stage"
	}
	return rst
}

//buildError error returned when building the static website. The error string
//returned is a json string that encodes the build stage and the message.
type buildError struct {
	Stage   string `json:"stage"`
	Message string `json:"msg"`
}

func buildErr(stage buildStage, msg string) error {
	return &buildError{Stage: stage.String(), Message: msg}
}

func (b *buildError) Error() string {
	o, err := json.Marshal(b)
	if err != nil {
		return err.Error()
	}
	return string(o)
}

//Generator provides the static website generation capabilities.This is heavily
//integrated with the otto javascript runtime.
type Generator struct {
	vm  *otto.Otto
	sys *System
	fs  afero.Fs

	// This is the absolute path to the root of the project from which the
	// Generator will be operating.
	workDir string
}

//NewGenerator retrunes a new  Generator.
func NewGenerator(vm *otto.Otto, sys *System, fs afero.Fs) *Generator {
	return &Generator{
		vm:  vm,
		sys: sys,
		fs:  fs,
	}
}

//Build builds a project.
func (g *Generator) Build() error {
	steps := []struct {
		stage buildStage
		exec  func() error
	}{
		{stageConfig, g.Config},
		{stageInit, g.Init},
		{stagePlan, g.plan},
		{stageExec, g.exec},
	}
	var err error
	for _, buildStep := range steps {
		err = buildStep.exec()
		if err != nil {
			return err
		}
	}
	return nil
}

//Init initializes the build process. Any stages after this will have the generator
//already bootstraped.
//
// It is possible to bootstrap the generator from the project( User's side) by
// providing an entry javascript file in the default path of
// scripts/init/index.js which will be executed and you can overide the default
// entry script which is evaluated internally
//
// Initialzation is offloaded to the javascript runtine of the generator..Any
// error returned is a build error.
func (g *Generator) Init() error {

	_ = g.vm.Set("sys", func(call otto.FunctionCall) otto.Value {
		data, err := json.Marshal(g.sys)
		if err != nil {
			panicOtto(err)
		}
		val, err := call.Otto.Call("JSON.parse", nil, string(data))
		if err != nil {
			panicOtto(err)
		}
		return val
	})
	_, err := g.vm.Eval(entryScript())
	if err != nil {
		return buildErr(stageInit, err.Error())
	}

	_ = g.vm.Set("fileTree", fileTree(g.fs, g.workDir))

	// evaluate project provided entry script if provided. We ignore if the file
	// is not provided but any errors arsing from evaluating a provided script is
	// a built error.
	entryFile := filepath.Join(scriptsDir, initDir, indexFile)
	err = g.evaluateFile(entryFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(stageInit, err.Error())
		}
	}

	return nil
}

//fileTree provides an array of all files found in the root( which is suppose to
//be the working directory.
//
//The file index is built only once and evaluated once too, then it is cached.
//This operates in the otto runtime.
func fileTree(fs afero.Fs, root string) func(otto.FunctionCall) otto.Value {
	var tree []string
	var v otto.Value
	return func(call otto.FunctionCall) otto.Value {
		if tree != nil {
			return v
		}
		ferr := afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if !info.IsDir() {
				tree = append(tree, path)
			}
			return nil
		})
		if ferr != nil {
			tree = nil
			panicOtto(ferr.Error())
		}
		v, _ = call.Otto.ToValue(tree)
		return v
	}
}

func defaultSystem() *System {
	return &System{
		Boot: &Boot{
			ConfigiFile: configFile,
			PlanFile:    "index.js",
		},
	}
}

// opens the file in the specified path and evaluates it withing the context of
// the javascript runtine.
//
// The evaluated javascript code can mutate the global state. Use execFile to
// execute the javascript without mutating the state of the generato'r
// javascript runtime.
//
// TODO: (gernest) implement callFile if necessary
func (g *Generator) evaluateFile(path string) error {
	f, err := g.fs.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()
	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}
	_, err = g.vm.Eval(data)
	if err != nil {
		return err
	}
	return nil
}

func defaultVM(sys *System) *otto.Otto {
	return otto.New()
}

//Config configures the generator.
func (g *Generator) Config() error {
	if g.sys == nil {
		g.sys = defaultSystem()
	}
	if g.vm == nil {
		g.vm = defaultVM(g.sys)
	}
	// Properly set working directory/
	if g.workDir == "" {
		wd, err := os.Getwd()
		if err != nil {
			return buildErr(stageInit, err.Error())
		}
		g.workDir = wd
	}

	// ensure everything is relative to the working directory
	g.fs = afero.NewBasePathFs(g.fs, g.workDir)
	af := afero.Afero{Fs: g.fs}
	data, err := af.ReadFile(configFile)
	if err != nil {
		return buildErr(stageInit, err.Error())
	}
	cfg := &Config{}
	err = json.Unmarshal(data, cfg)
	if err != nil {
		return buildErr(stageInit, err.Error())
	}
	g.sys.Config = cfg
	return nil
}

func (g *Generator) plan() error {
	return nil
}
func (g *Generator) exec() error {
	return nil
}
func (g *Generator) down() error {
	return nil
}
<|endoftext|>


<commit_before>package humanlog

import (
	"bytes"
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"text/tabwriter"
	"time"

	"github.com/aybabtme/rgbterm"
)

// JSONHandler can handle logs emmited by logrus.TextFormatter loggers.
type JSONHandler struct {
	buf     *bytes.Buffer
	out     *tabwriter.Writer
	truncKV int

	Opts *HandlerOptions

	Level   string
	Time    time.Time
	Message string
	Fields  map[string]string

	last map[string]string
}

func (h *JSONHandler) clear() {
	h.Level = ""
	h.Time = time.Time{}
	h.Message = ""
	h.last = h.Fields
	h.Fields = make(map[string]string)
	if h.buf != nil {
		h.buf.Reset()
	}
}

// TryHandle tells if this line was handled by this handler.
func (h *JSONHandler) TryHandle(d []byte) bool {
	if !bytes.Contains(d, []byte(`"time":"`)) {
		return false
	}
	err := h.UnmarshalJSON(d)
	if err != nil {
		h.clear()
		return false
	}
	return true
}

// UnmarshalJSON sets the fields of the handler.
func (h *JSONHandler) UnmarshalJSON(data []byte) error {
	raw := make(map[string]interface{})
	err := json.Unmarshal(data, &raw)
	if err != nil {
		return err
	}

	timeStr, ok := raw["time"].(string)
	if ok {
		h.Time, ok = tryParseTime(timeStr)
		if !ok {
			return fmt.Errorf("field time is not a known timestamp: %v", timeStr)
		}
	}
	delete(raw, "time")
	h.Message, _ = raw["msg"].(string)
	delete(raw, "msg")

	h.Level, ok = raw["level"].(string)
	if !ok {
		h.Level, ok = raw["lvl"].(string)
		delete(raw, "lvl")
		if !ok {
			h.Level = "???"
		}
	} else {
		delete(raw, "level")
	}

	if h.Fields == nil {
		h.Fields = make(map[string]string)
	}

	for key, val := range raw {
		h.Fields[key] = fmt.Sprintf("%v", val)
	}

	return nil
}

// Prettify the output in a logrus like fashion.
func (h *JSONHandler) Prettify(skipUnchanged bool) []byte {
	defer h.clear()
	if h.out == nil {
		if h.Opts == nil {
			h.Opts = DefaultOptions
		}
		h.buf = bytes.NewBuffer(nil)
		h.out = tabwriter.NewWriter(h.buf, 0, 1, 0, '\t', 0)
	}

	var msg string
	if h.Message == "" {
		msg = rgbterm.FgString("<no msg>", 190, 190, 190)
	} else {
		msg = rgbterm.FgString(h.Message, 255, 255, 255)
	}

	lvl := strings.ToUpper(h.Level)[:imin(4, len(h.Level))]
	var level string
	switch h.Level {
	case "debug":
		level = rgbterm.FgString(lvl, 221, 28, 119)
	case "info":
		level = rgbterm.FgString(lvl, 20, 172, 190)
	case "warn", "warning":
		level = rgbterm.FgString(lvl, 255, 245, 32)
	case "error":
		level = rgbterm.FgString(lvl, 255, 0, 0)
	case "fatal", "panic":
		level = rgbterm.BgString(lvl, 255, 0, 0)
	default:
		level = rgbterm.FgString(lvl, 221, 28, 119)
	}

	_, _ = fmt.Fprintf(h.out, "%s |%s| %s\t %s",
		rgbterm.FgString(h.Time.Format(time.Stamp), 99, 99, 99),
		level,
		msg,
		strings.Join(h.joinKVs(skipUnchanged, "="), "\t "),
	)

	_ = h.out.Flush()

	return h.buf.Bytes()
}

func (h *JSONHandler) joinKVs(skipUnchanged bool, sep string) []string {

	kv := make([]string, 0, len(h.Fields))
	for k, v := range h.Fields {
		if !h.Opts.shouldShowKey(k) {
			continue
		}

		if skipUnchanged {
			if lastV, ok := h.last[k]; ok && lastV == v {
				continue
			}
		}

		kstr := rgbterm.FgString(k, h.Opts.KeyRGB.R, h.Opts.KeyRGB.G, h.Opts.KeyRGB.B)

		var vstr string
		if h.Opts.Truncates && len(v) > h.Opts.TruncateLength {
			vstr = v[:h.Opts.TruncateLength] + "..."
		} else {
			vstr = v
		}
		vstr = rgbterm.FgString(vstr, h.Opts.ValRGB.R, h.Opts.ValRGB.G, h.Opts.ValRGB.B)
		kv = append(kv, kstr+sep+vstr)
	}

	sort.Strings(kv)

	if h.Opts.SortLongest {
		sort.Stable(byLongest(kv))
	}

	return kv
}
<commit_msg>dont print integers as floats<commit_after>package humanlog

import (
	"bytes"
	"encoding/json"
	"fmt"
	"math"
	"sort"
	"strings"
	"text/tabwriter"
	"time"

	"github.com/aybabtme/rgbterm"
)

// JSONHandler can handle logs emmited by logrus.TextFormatter loggers.
type JSONHandler struct {
	buf     *bytes.Buffer
	out     *tabwriter.Writer
	truncKV int

	Opts *HandlerOptions

	Level   string
	Time    time.Time
	Message string
	Fields  map[string]string

	last map[string]string
}

func (h *JSONHandler) clear() {
	h.Level = ""
	h.Time = time.Time{}
	h.Message = ""
	h.last = h.Fields
	h.Fields = make(map[string]string)
	if h.buf != nil {
		h.buf.Reset()
	}
}

// TryHandle tells if this line was handled by this handler.
func (h *JSONHandler) TryHandle(d []byte) bool {
	if !bytes.Contains(d, []byte(`"time":"`)) {
		return false
	}
	err := h.UnmarshalJSON(d)
	if err != nil {
		h.clear()
		return false
	}
	return true
}

// UnmarshalJSON sets the fields of the handler.
func (h *JSONHandler) UnmarshalJSON(data []byte) error {
	raw := make(map[string]interface{})
	err := json.Unmarshal(data, &raw)
	if err != nil {
		return err
	}

	timeStr, ok := raw["time"].(string)
	if ok {
		h.Time, ok = tryParseTime(timeStr)
		if !ok {
			return fmt.Errorf("field time is not a known timestamp: %v", timeStr)
		}
	}
	delete(raw, "time")
	h.Message, _ = raw["msg"].(string)
	delete(raw, "msg")

	h.Level, ok = raw["level"].(string)
	if !ok {
		h.Level, ok = raw["lvl"].(string)
		delete(raw, "lvl")
		if !ok {
			h.Level = "???"
		}
	} else {
		delete(raw, "level")
	}

	if h.Fields == nil {
		h.Fields = make(map[string]string)
	}

	for key, val := range raw {
		switch v := val.(type) {
		case float64:
			if v-math.Floor(v) < 0.000001 && v < 1e9 {
				// looks like an integer that's not too large
				h.Fields[key] = fmt.Sprintf("%d", int(v))
			} else {
				h.Fields[key] = fmt.Sprintf("%g", v)
			}
		case string:
			h.Fields[key] = fmt.Sprintf("%q", v)
		default:
			h.Fields[key] = fmt.Sprintf("%v", v)
		}
	}

	return nil
}

// Prettify the output in a logrus like fashion.
func (h *JSONHandler) Prettify(skipUnchanged bool) []byte {
	defer h.clear()
	if h.out == nil {
		if h.Opts == nil {
			h.Opts = DefaultOptions
		}
		h.buf = bytes.NewBuffer(nil)
		h.out = tabwriter.NewWriter(h.buf, 0, 1, 0, '\t', 0)
	}

	var msg string
	if h.Message == "" {
		msg = rgbterm.FgString("<no msg>", 190, 190, 190)
	} else {
		msg = rgbterm.FgString(h.Message, 255, 255, 255)
	}

	lvl := strings.ToUpper(h.Level)[:imin(4, len(h.Level))]
	var level string
	switch h.Level {
	case "debug":
		level = rgbterm.FgString(lvl, 221, 28, 119)
	case "info":
		level = rgbterm.FgString(lvl, 20, 172, 190)
	case "warn", "warning":
		level = rgbterm.FgString(lvl, 255, 245, 32)
	case "error":
		level = rgbterm.FgString(lvl, 255, 0, 0)
	case "fatal", "panic":
		level = rgbterm.BgString(lvl, 255, 0, 0)
	default:
		level = rgbterm.FgString(lvl, 221, 28, 119)
	}

	_, _ = fmt.Fprintf(h.out, "%s |%s| %s\t %s",
		rgbterm.FgString(h.Time.Format(time.Stamp), 99, 99, 99),
		level,
		msg,
		strings.Join(h.joinKVs(skipUnchanged, "="), "\t "),
	)

	_ = h.out.Flush()

	return h.buf.Bytes()
}

func (h *JSONHandler) joinKVs(skipUnchanged bool, sep string) []string {

	kv := make([]string, 0, len(h.Fields))
	for k, v := range h.Fields {
		if !h.Opts.shouldShowKey(k) {
			continue
		}

		if skipUnchanged {
			if lastV, ok := h.last[k]; ok && lastV == v {
				continue
			}
		}

		kstr := rgbterm.FgString(k, h.Opts.KeyRGB.R, h.Opts.KeyRGB.G, h.Opts.KeyRGB.B)

		var vstr string
		if h.Opts.Truncates && len(v) > h.Opts.TruncateLength {
			vstr = v[:h.Opts.TruncateLength] + "..."
		} else {
			vstr = v
		}
		vstr = rgbterm.FgString(vstr, h.Opts.ValRGB.R, h.Opts.ValRGB.G, h.Opts.ValRGB.B)
		kv = append(kv, kstr+sep+vstr)
	}

	sort.Strings(kv)

	if h.Opts.SortLongest {
		sort.Stable(byLongest(kv))
	}

	return kv
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Brian Hetro <whee@smaertness.net>
// Use of this source code is governed by the ISC
// license which can be found in the LICENSE file.

package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strconv"
)

type Attributes map[string][]float64
type Weights map[string]int
type Data map[string]interface{}

type Classifier struct {
	Name       string
	ScoreName  string
	Categories map[string]Attributes
	Weights    Weights
}

type Category struct {
	Name  string
	Score int
}

func NewClassifier(file string) (*Classifier, error) {
	configData, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	var c Classifier
	err = json.Unmarshal(configData, &c)
	c.ScoreName = c.Name + " Score"
	return &c, err
}

func (c *Classifier) Classify(d Data) Category {
	var cat Category
	for name, attrs := range c.Categories {
		if s := attrs.Score(d, c.Weights); s > cat.Score {
			cat = Category{name, s}
		}
	}
	return cat
}

func (a Attributes) Score(d Data, w Weights) int {
	var score int
	for attr, i := range a {
		if d[attr] == nil {
			continue
		}
		low, high := i[0], i[1]
		val, ok := d[attr].(float64)
		if !ok {
			var err error
			val, err = strconv.ParseFloat(d[attr].(string), 64)
			if err != nil {
				log.Fatal(err)
			}
		}
		if val >= low && val < high {
			score += w[attr]
		}
	}
	return score
}

func main() {
	if len(os.Args) != 2 {
		log.Fatal("Usage: jsonclassify [configuration file]\n")
	}
	configFile := os.Args[1]
	c, err := NewClassifier(configFile)
	if err != nil {
		log.Fatal(err)
	}

	dec := json.NewDecoder(os.Stdin)
	enc := json.NewEncoder(os.Stdout)

	decoded := make(chan Data, 10)
	scored := make(chan Data, 10)

	go func() {
		defer close(decoded)
		for {
			var jsd Data
			if err := dec.Decode(&jsd); err != nil {
				if err == io.EOF {
					return
				}
				log.Fatal(err)
			}
			decoded <- jsd
		}
	}()

	go func() {
		defer close(scored)
		for d := range decoded {
			category := c.Classify(d)
			d[c.Name] = category.Name
			d[c.ScoreName] = category.Score
			scored <- d
		}
	}()

	for s := range scored {
		if err := enc.Encode(&s); err != nil {
			log.Fatal(err)
		}
	}
}
<commit_msg>Allow and return multiple categories in the event of a tie.<commit_after>// Copyright (c) 2014 Brian Hetro <whee@smaertness.net>
// Use of this source code is governed by the ISC
// license which can be found in the LICENSE file.

package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
)

type Attributes map[string][]float64
type Weights map[string]int
type Data map[string]interface{}

type Classifier struct {
	Name       string
	ScoreName  string
	Categories map[string]Attributes
	Weights    Weights
}

type Category struct {
	Name  []string
	Score int
}

func NewClassifier(file string) (*Classifier, error) {
	configData, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	var c Classifier
	err = json.Unmarshal(configData, &c)
	c.ScoreName = c.Name + " Score"
	return &c, err
}

func (c *Classifier) Classify(d Data) Category {
	var cat Category
	for name, attrs := range c.Categories {
		if s := attrs.Score(d, c.Weights); s >= cat.Score {
			cat.Score = s
			cat.Name = append(cat.Name, name)
		}
	}
	sort.Strings(cat.Name)
	return cat
}

func (a Attributes) Score(d Data, w Weights) int {
	var score int
	for attr, i := range a {
		if d[attr] == nil {
			continue
		}
		low, high := i[0], i[1]
		val, ok := d[attr].(float64)
		if !ok {
			var err error
			val, err = strconv.ParseFloat(d[attr].(string), 64)
			if err != nil {
				log.Fatal(err)
			}
		}
		if val >= low && val < high {
			score += w[attr]
		}
	}
	return score
}

func main() {
	if len(os.Args) != 2 {
		log.Fatal("Usage: jsonclassify [configuration file]\n")
	}
	configFile := os.Args[1]
	c, err := NewClassifier(configFile)
	if err != nil {
		log.Fatal(err)
	}

	dec := json.NewDecoder(os.Stdin)
	enc := json.NewEncoder(os.Stdout)

	decoded := make(chan Data, 10)
	scored := make(chan Data, 10)

	go func() {
		defer close(decoded)
		for {
			var jsd Data
			if err := dec.Decode(&jsd); err != nil {
				if err == io.EOF {
					return
				}
				log.Fatal(err)
			}
			decoded <- jsd
		}
	}()

	go func() {
		defer close(scored)
		for d := range decoded {
			category := c.Classify(d)
			d[c.Name] = strings.Join(category.Name, " & ")
			d[c.ScoreName] = category.Score
			scored <- d
		}
	}()

	for s := range scored {
		if err := enc.Encode(&s); err != nil {
			log.Fatal(err)
		}
	}
}
<|endoftext|>


<commit_before>/**
 * actor reference implementation
 */
package ri

import (
	"code.google.com/p/goprotobuf/proto"
	"fmt"
	"github.com/quexer/kodec"
	"github.com/quexer/tok"
	"log"
	"net/http"
	"time"
)

type Checker interface {
	CheckUp(from interface{}, to string) bool
	CheckDown(target interface{}, v *kodec.Msg) bool
	Dispatch(targets []interface{}, v *kodec.Msg)
	ParseAddr(to string) ([]interface{}, error)
	Auth(r *http.Request) (interface{}, error)
}

type Actor struct {
	checker Checker
}

func (p *Actor) OnReceive(uid interface{}, data []byte) {
	m, err := kodec.Unboxing(data)
	if err != nil {
		log.Println("decode err ", err)
		return
	}

	switch v := m.(type) {
	case *kodec.Msg:
		v.From = proto.Int64(int64(uid.(int)))
		v.Ct = proto.Int64(tick())

		if v.GetTp() != kodec.Msg_SYS {
			from := int(v.GetFrom())
			to := v.GetTo()
			if !p.checker.CheckUp(from, to) {
				log.Println(fmt.Errorf("warning: chat not allow, %d -> %v \n", from, to))
				return
			}
		}
		p.dispatchMsg(v)
	default:
		log.Println(fmt.Errorf("unknown data frame"))
	}
}

func (p *Actor) dispatchMsg(v *kodec.Msg) {
	uids := []interface{}{}
	targets, err := p.checker.ParseAddr(v.GetTo())
	if err != nil {
		log.Println("parse addr err", err)
		return
	}

	from := int(v.GetFrom())
	for _, target := range targets {
		if target == from || !p.checker.CheckDown(target, v) {
			continue
		}
		uids = append(uids, target)
	}

	go p.checker.Dispatch(uids, v)
}

func (p *Actor) Ping() []byte {
	b, err := kodec.Boxing(kodec.BuildCmd(kodec.Cmd_PING, "", tick()))
	if err != nil {
		log.Panic("build ping err", err)
	}
	return b
}

func (p *Actor) Bye(reason string) []byte {
	b, err := kodec.Boxing(kodec.BuildCmd(kodec.Cmd_UNAUTHORIZED, reason, tick()))
	if err != nil {
		log.Panic("build bye err", err)
	}
	return b
}

func (p *Actor) Auth(r *http.Request) (interface{}, error) {
	return p.checker.Auth(r)
}

func (p *Actor) OnClose(uid interface{}, active int) {
	//do nothing
}

func tick() int64 {
	return time.Now().UnixNano() / 1e6
}

func CreateActor(checker Checker) tok.Actor {
	return &Actor{checker: checker}
}
<commit_msg>add empty OnSend<commit_after>/**
 * actor reference implementation
 */
package ri

import (
	"code.google.com/p/goprotobuf/proto"
	"fmt"
	"github.com/quexer/kodec"
	"github.com/quexer/tok"
	"log"
	"net/http"
	"time"
)

type Checker interface {
	CheckUp(from interface{}, to string) bool
	CheckDown(target interface{}, v *kodec.Msg) bool
	Dispatch(targets []interface{}, v *kodec.Msg)
	ParseAddr(to string) ([]interface{}, error)
	Auth(r *http.Request) (interface{}, error)
}

type Actor struct {
	checker Checker
}

func (p *Actor) OnReceive(uid interface{}, data []byte) {
	m, err := kodec.Unboxing(data)
	if err != nil {
		log.Println("decode err ", err)
		return
	}

	switch v := m.(type) {
	case *kodec.Msg:
		v.From = proto.Int64(int64(uid.(int)))
		v.Ct = proto.Int64(tick())

		if v.GetTp() != kodec.Msg_SYS {
			from := int(v.GetFrom())
			to := v.GetTo()
			if !p.checker.CheckUp(from, to) {
				log.Println(fmt.Errorf("warning: chat not allow, %d -> %v \n", from, to))
				return
			}
		}
		p.dispatchMsg(v)
	default:
		log.Println(fmt.Errorf("unknown data frame"))
	}
}

func (p *Actor) dispatchMsg(v *kodec.Msg) {
	uids := []interface{}{}
	targets, err := p.checker.ParseAddr(v.GetTo())
	if err != nil {
		log.Println("parse addr err", err)
		return
	}

	from := int(v.GetFrom())
	for _, target := range targets {
		if target == from || !p.checker.CheckDown(target, v) {
			continue
		}
		uids = append(uids, target)
	}

	go p.checker.Dispatch(uids, v)
}

func (p *Actor) OnSent(uid interface{}, data []byte, count int) {
	//do nothing
}

func (p *Actor) Ping() []byte {
	b, err := kodec.Boxing(kodec.BuildCmd(kodec.Cmd_PING, "", tick()))
	if err != nil {
		log.Panic("build ping err", err)
	}
	return b
}

func (p *Actor) Bye(reason string) []byte {
	b, err := kodec.Boxing(kodec.BuildCmd(kodec.Cmd_UNAUTHORIZED, reason, tick()))
	if err != nil {
		log.Panic("build bye err", err)
	}
	return b
}

func (p *Actor) Auth(r *http.Request) (interface{}, error) {
	return p.checker.Auth(r)
}

func (p *Actor) OnClose(uid interface{}, active int) {
	//do nothing
}

func tick() int64 {
	return time.Now().UnixNano() / 1e6
}

func CreateActor(checker Checker) tok.Actor {
	return &Actor{checker: checker}
}
<|endoftext|>


<commit_before>package polygen

import (
	"image"
	"log"
	"sort"
	"math/rand"
	"time"
)

func SimulateAnnealing(maxGen int, referenceImg image.Image, destFile string, safeImages []*SafeImage) {
	refImgRGBA := ConvertToRGBA(referenceImg)

	w := refImgRGBA.Bounds().Dx()
	h := refImgRGBA.Bounds().Dy()

	mostFit := RandomCandidate(w, h)
	evaluateCandidate(mostFit, refImgRGBA)

	candidates := make([]*Candidate, PopulationCount)
	candidates[0] = mostFit

	startTime := time.Now()

	generationsSinceChange := 0

	for gen := 0; gen < maxGen; gen++ {

		for i := 1; i < PopulationCount; i++ {
			copy := mostFit.CopyOf()
			copy.MutateInPlace()
			evaluateCandidate(copy, refImgRGBA)
			candidates[i] = copy
		}

		// after sort, the best will be at [0], worst will be at [len() - 1]
		sort.Sort(ByFitness(candidates))

		if gen % 10 == 0 {
			printStats(candidates, gen, generationsSinceChange, startTime)
		}

		for i := 0; i < len(safeImages); i++ {
			safeImages[i].Update(candidates[i].img)
		}

		prev := mostFit
		mostFit = candidates[0]

		if mostFit.Fitness < prev.Fitness {
			generationsSinceChange = 0
		} else {
			generationsSinceChange++
		}
	}

	mostFit.DrawAndSave(destFile)
	log.Printf("after %d generations, fitness is: %d, saved to %s", maxGen, mostFit.Fitness, destFile)
}

func evaluateCandidate(c *Candidate, referenceImg *image.RGBA) {
//	diff, err := Compare(referenceImg, c.img)
	diff, err := FastCompare(referenceImg, c.img)

	if err != nil {
		log.Fatalf("error comparing images: %s", err)
	}

	c.Fitness = diff
}

func shufflePopulation(population []*Candidate) {
	for i := range population {
		j := rand.Intn(i + 1)
		population[i], population[j] = population[j], population[i]
	}
}

func printStats(sortedPop []*Candidate, generations, generationsSinceChange int, startTime time.Time) {
	dur := time.Since(startTime)
	best := sortedPop[0].Fitness
	worst := sortedPop[len(sortedPop)-1].Fitness

	log.Printf("dur: %s, gen: %d, since change: %d, best: %d, worst: %d", dur, generations, generationsSinceChange, best, worst)
}
<commit_msg>make evolver concurrent<commit_after>package polygen

import (
	"image"
	"log"
	"sort"
	"math/rand"
	"time"
	"sync"
)

func SimulateAnnealing(maxGen int, referenceImg image.Image, destFile string, safeImages []*SafeImage) {
	refImgRGBA := ConvertToRGBA(referenceImg)

	w := refImgRGBA.Bounds().Dx()
	h := refImgRGBA.Bounds().Dy()

	mostFit := RandomCandidate(w, h)
	evaluateCandidate(mostFit, refImgRGBA)

	candidates := make([]*Candidate, PopulationCount)
	candidates[0] = mostFit

	startTime := time.Now()

	generationsSinceChange := 0

	for gen := 0; gen < maxGen; gen++ {

		c := make(chan *Candidate, PopulationCount)
		var wg sync.WaitGroup

		processCandidate := func(cand *Candidate) {
			cand.MutateInPlace()
			evaluateCandidate(cand, refImgRGBA)
			c <- cand
			wg.Done()
		}

		wg.Add(PopulationCount - 1)

		for i := 1; i < PopulationCount; i++ {
			go processCandidate(mostFit.CopyOf())
		}

		wg.Wait()

		for i := 1; i < PopulationCount; i++ {
			candidates[i] = <- c
		}

		// after sort, the best will be at [0], worst will be at [len() - 1]
		sort.Sort(ByFitness(candidates))

		if gen % 10 == 0 {
			printStats(candidates, gen, generationsSinceChange, startTime)
		}

		for i := 0; i < len(safeImages); i++ {
			safeImages[i].Update(candidates[i].img)
		}

		currBest := candidates[0]

		if currBest.Fitness < mostFit.Fitness {
			generationsSinceChange = 0
			mostFit = currBest
		} else {
			generationsSinceChange++
		}
	}

	mostFit.DrawAndSave(destFile)
	log.Printf("after %d generations, fitness is: %d, saved to %s", maxGen, mostFit.Fitness, destFile)
}

func evaluateCandidate(c *Candidate, referenceImg *image.RGBA) {
//	diff, err := Compare(referenceImg, c.img)
	diff, err := FastCompare(referenceImg, c.img)

	if err != nil {
		log.Fatalf("error comparing images: %s", err)
	}

	c.Fitness = diff
}

func shufflePopulation(population []*Candidate) {
	for i := range population {
		j := rand.Intn(i + 1)
		population[i], population[j] = population[j], population[i]
	}
}

func printStats(sortedPop []*Candidate, generations, generationsSinceChange int, startTime time.Time) {
	dur := time.Since(startTime)
	best := sortedPop[0].Fitness
	worst := sortedPop[len(sortedPop)-1].Fitness

	log.Printf("dur: %s, gen: %d, since change: %d, best: %d, worst: %d", dur, generations, generationsSinceChange, best, worst)
}
<|endoftext|>


<commit_before>package rfm69

import (
	"fmt"
	"log"
	"unsafe"
)

const (
	bitrate   = 16384  // baud
	channelBw = 250000 // Hz
)

func (config *RfConfiguration) Bytes() []byte {
	return (*[RegTemp2 - RegOpMode + 1]byte)(unsafe.Pointer(config))[:]
}

func (r *Radio) ReadConfiguration() *RfConfiguration {
	if r.Error() != nil {
		return nil
	}
	regs := r.hw.ReadBurst(RegOpMode, RegTemp2-RegOpMode+1)
	return (*RfConfiguration)(unsafe.Pointer(&regs[0]))
}

func (r *Radio) WriteConfiguration(config *RfConfiguration) {
	r.hw.WriteBurst(RegOpMode, config.Bytes())
}

func (r *Radio) InitRF(frequency uint32) {
	rf := DefaultRfConfiguration
	fb := frequencyToRegisters(frequency)
	br := bitrateToRegisters(bitrate)
	bw := channelBwToRegister(channelBw)

	rf.RegDataModul = PacketMode | ModulationTypeOOK | 2<<ModulationShapingShift

	rf.RegBitrateMsb = br[0]
	rf.RegBitrateLsb = br[1]

	rf.RegFrfMsb = fb[0]
	rf.RegFrfMid = fb[1]
	rf.RegFrfLsb = fb[2]

	// Use PA1 with 13 dbM output power.
	rf.RegPaLevel = Pa1On | 0x1F<<OutputPowerShift

	// Default != reset value
	rf.RegLna = LnaZin | 1<<LnaCurrentGainShift | 0<<LnaGainSelectShift

	rf.RegRxBw = 2<<DccFreqShift | bw
	rf.RegAfcBw = 4<<DccFreqShift | bw

	// Interrupt when Sync word is seen.
	// Cleared when leaving Rx or FIFO is emptied.
	rf.RegDioMapping1 = 2 << Dio0MappingShift

	// Default != reset value.
	rf.RegDioMapping2 = 7 << ClkOutShift

	// Default != reset value.
	rf.RegRssiThresh = 0xE4

	// Make sure enough preamble bytes are sent.
	rf.RegPreambleMsb = 0x00
	rf.RegPreambleLsb = 0x10

	// Use 4 bytes for Sync word.
	rf.RegSyncConfig = SyncOn | 3<<SyncSizeShift

	// Sync word
	rf.RegSyncValue1 = 0xFF
	rf.RegSyncValue2 = 0x00
	rf.RegSyncValue3 = 0xFF
	rf.RegSyncValue4 = 0x00

	// Use unlimited length packet format (data sheet section 5.5.2.3).
	rf.RegPacketConfig1 = FixedLength
	rf.RegPayloadLength = 0x00
	rf.RegFifoThresh = TxStartFifoNotEmpty | fifoThreshold<<FifoThresholdShift
	rf.RegPacketConfig2 = AutoRxRestartOff

	r.WriteConfiguration(&rf)

	// Default != reset value.
	r.hw.WriteRegister(RegTestDagc, 0x30)
}

func (r *Radio) Frequency() uint32 {
	return registersToFrequency(r.hw.ReadBurst(RegFrfMsb, 3))
}

func registersToFrequency(frf []byte) uint32 {
	f := uint32(frf[0])<<16 + uint32(frf[1])<<8 + uint32(frf[2])
	return uint32(uint64(f) * FXOSC >> 19)
}

func (r *Radio) SetFrequency(freq uint32) {
	r.hw.WriteBurst(RegFrfMsb, frequencyToRegisters(freq))
}

func frequencyToRegisters(freq uint32) []byte {
	f := (uint64(freq)<<19 + FXOSC/2) / FXOSC
	return []byte{byte(f >> 16), byte(f >> 8), byte(f)}
}

func (r *Radio) ReadRSSI() int {
	rssi := r.hw.ReadRegister(RegRssiValue)
	return -int(rssi) / 2
}

func (r *Radio) Bitrate() uint32 {
	return registersToBitrate(r.hw.ReadBurst(RegBitrateMsb, 2))
}

// See data sheet section 3.3.2 and table 9.
func registersToBitrate(br []byte) uint32 {
	d := uint32(br[0])<<8 + uint32(br[1])
	return (FXOSC + d/2) / d
}

func bitrateToRegisters(br uint32) []byte {
	b := (FXOSC + br/2) / br
	return []byte{byte(b >> 8), byte(b)}
}

func (r *Radio) ReadModulationType() byte {
	return r.hw.ReadRegister(RegDataModul) & ModulationTypeMask
}

func (r *Radio) ChannelBw() uint32 {
	bw := r.hw.ReadRegister(RegRxBw)
	m := r.ReadModulationType()
	return registerToChannelBw(bw, m)
}

func registerToChannelBw(bw byte, modType byte) uint32 {
	mant := 0
	switch bw & RxBwMantMask {
	case RxBwMant16:
		mant = 16
	case RxBwMant20:
		mant = 20
	case RxBwMant24:
		mant = 24
	default:
		log.Panicf("unknown RX bandwidth mantissa (%X)", bw&RxBwMantMask)
	}
	e := bw & RxBwExpMask
	switch modType {
	case ModulationTypeFSK:
		return uint32(FXOSC) / (uint32(mant) << (e + 2))
	case ModulationTypeOOK:
		return uint32(FXOSC) / (uint32(mant) << (e + 3))
	default:
		log.Panicf("unknown modulation mode (%X)", modType)
	}
	panic("unreachable")
}

func (r *Radio) SetChannelBw(bw uint32) {
	v := channelBwToRegister(bw)
	r.hw.WriteRegister(RegRxBw, 2<<DccFreqShift|v)
	r.hw.WriteRegister(RegAfcBw, 4<<DccFreqShift|v)
}

// Channel BW = FXOSC / (RxBwMant * 2^(RxBwExp + 3), assuming OOK modulation.
// The caller must add the desired DccFreq field to the result.
func channelBwToRegister(bw uint32) byte {
	bb := uint32(1302) // lowest possible channel bandwidth
	rr := byte(RxBwMant24 | 7<<RxBwExpShift)
	if bw < bb {
		return rr
	}
	for i := 0; i < 8; i++ {
		e := byte(7 - i)
		for j := 0; j < 3; j++ {
			m := byte((6 - j) * 4)
			b := uint32(FXOSC) / (uint32(m) << (e + 3))
			r := byte(2-j)<<RxBwMantShift | e<<RxBwExpShift
			if b >= bw {
				if b-bw < bw-bb {
					return r
				} else {
					return rr
				}
			}
			bb = b
			rr = r
		}
	}
	return rr
}

func (r *Radio) mode() byte {
	return r.hw.ReadRegister(RegOpMode) & ModeMask
}

func (r *Radio) setMode(mode uint8) {
	r.SetError(nil)
	cur := r.hw.ReadRegister(RegOpMode)
	if cur&ModeMask == mode {
		return
	}
	if verbose {
		log.Printf("change from %s to %s", stateName(cur&ModeMask), stateName(mode))
	}
	r.hw.WriteRegister(RegOpMode, cur&^ModeMask|mode)
	for r.Error() == nil && r.mode() != mode {
		if verbose {
			log.Printf("  %s", r.State())
		}
	}
}

func (r *Radio) Sleep() {
	r.setMode(SleepMode)
}

func stateName(mode uint8) string {
	switch mode {
	case SleepMode:
		return "Sleep"
	case StandbyMode:
		return "Standby"
	case FreqSynthMode:
		return "Frequency Synthesizer"
	case TransmitterMode:
		return "Transmitter"
	case ReceiverMode:
		return "Receiver"
	default:
		return fmt.Sprintf("Unknown operating mode (%X)", mode)
	}
}

func (r *Radio) State() string {
	return stateName(r.mode())
}
<commit_msg>Reduce packet loss<commit_after>package rfm69

import (
	"fmt"
	"log"
	"unsafe"
)

const (
	bitrate   = 16384  // baud
	channelBw = 250000 // Hz
)

func (config *RfConfiguration) Bytes() []byte {
	return (*[RegTemp2 - RegOpMode + 1]byte)(unsafe.Pointer(config))[:]
}

func (r *Radio) ReadConfiguration() *RfConfiguration {
	if r.Error() != nil {
		return nil
	}
	regs := r.hw.ReadBurst(RegOpMode, RegTemp2-RegOpMode+1)
	return (*RfConfiguration)(unsafe.Pointer(&regs[0]))
}

func (r *Radio) WriteConfiguration(config *RfConfiguration) {
	r.hw.WriteBurst(RegOpMode, config.Bytes())
}

func (r *Radio) InitRF(frequency uint32) {
	rf := DefaultRfConfiguration
	fb := frequencyToRegisters(frequency)
	br := bitrateToRegisters(bitrate)
	bw := channelBwToRegister(channelBw)

	rf.RegDataModul = PacketMode | ModulationTypeOOK | 0<<ModulationShapingShift

	rf.RegBitrateMsb = br[0]
	rf.RegBitrateLsb = br[1]

	rf.RegFrfMsb = fb[0]
	rf.RegFrfMid = fb[1]
	rf.RegFrfLsb = fb[2]

	// Use PA1 with 13 dbM output power.
	rf.RegPaLevel = Pa1On | 0x1F<<OutputPowerShift

	// Default != reset value
	rf.RegLna = LnaZin | 1<<LnaCurrentGainShift | 0<<LnaGainSelectShift

	rf.RegRxBw = 2<<DccFreqShift | bw
	rf.RegAfcBw = 4<<DccFreqShift | bw

	// Interrupt when Sync word is seen.
	// Cleared when leaving Rx or FIFO is emptied.
	rf.RegDioMapping1 = 2 << Dio0MappingShift

	// Default != reset value.
	rf.RegDioMapping2 = 7 << ClkOutShift

	// Default != reset value.
	rf.RegRssiThresh = 0xE4

	// Make sure enough preamble bytes are sent.
	rf.RegPreambleMsb = 0x00
	rf.RegPreambleLsb = 0x18

	// Use 4 bytes for Sync word.
	rf.RegSyncConfig = SyncOn | 3<<SyncSizeShift

	// Sync word
	rf.RegSyncValue1 = 0xFF
	rf.RegSyncValue2 = 0x00
	rf.RegSyncValue3 = 0xFF
	rf.RegSyncValue4 = 0x00

	// Use unlimited length packet format (data sheet section 5.5.2.3).
	rf.RegPacketConfig1 = FixedLength
	rf.RegPayloadLength = 0x00
	rf.RegFifoThresh = TxStartFifoNotEmpty | fifoThreshold<<FifoThresholdShift
	rf.RegPacketConfig2 = AutoRxRestartOff

	r.WriteConfiguration(&rf)

	// Default != reset value.
	r.hw.WriteRegister(RegTestDagc, 0x30)
}

func (r *Radio) Frequency() uint32 {
	return registersToFrequency(r.hw.ReadBurst(RegFrfMsb, 3))
}

func registersToFrequency(frf []byte) uint32 {
	f := uint32(frf[0])<<16 + uint32(frf[1])<<8 + uint32(frf[2])
	return uint32(uint64(f) * FXOSC >> 19)
}

func (r *Radio) SetFrequency(freq uint32) {
	r.hw.WriteBurst(RegFrfMsb, frequencyToRegisters(freq))
}

func frequencyToRegisters(freq uint32) []byte {
	f := (uint64(freq)<<19 + FXOSC/2) / FXOSC
	return []byte{byte(f >> 16), byte(f >> 8), byte(f)}
}

func (r *Radio) ReadRSSI() int {
	rssi := r.hw.ReadRegister(RegRssiValue)
	return -int(rssi) / 2
}

func (r *Radio) Bitrate() uint32 {
	return registersToBitrate(r.hw.ReadBurst(RegBitrateMsb, 2))
}

// See data sheet section 3.3.2 and table 9.
func registersToBitrate(br []byte) uint32 {
	d := uint32(br[0])<<8 + uint32(br[1])
	return (FXOSC + d/2) / d
}

func bitrateToRegisters(br uint32) []byte {
	b := (FXOSC + br/2) / br
	return []byte{byte(b >> 8), byte(b)}
}

func (r *Radio) ReadModulationType() byte {
	return r.hw.ReadRegister(RegDataModul) & ModulationTypeMask
}

func (r *Radio) ChannelBw() uint32 {
	bw := r.hw.ReadRegister(RegRxBw)
	m := r.ReadModulationType()
	return registerToChannelBw(bw, m)
}

func registerToChannelBw(bw byte, modType byte) uint32 {
	mant := 0
	switch bw & RxBwMantMask {
	case RxBwMant16:
		mant = 16
	case RxBwMant20:
		mant = 20
	case RxBwMant24:
		mant = 24
	default:
		log.Panicf("unknown RX bandwidth mantissa (%X)", bw&RxBwMantMask)
	}
	e := bw & RxBwExpMask
	switch modType {
	case ModulationTypeFSK:
		return uint32(FXOSC) / (uint32(mant) << (e + 2))
	case ModulationTypeOOK:
		return uint32(FXOSC) / (uint32(mant) << (e + 3))
	default:
		log.Panicf("unknown modulation mode (%X)", modType)
	}
	panic("unreachable")
}

func (r *Radio) SetChannelBw(bw uint32) {
	v := channelBwToRegister(bw)
	r.hw.WriteRegister(RegRxBw, 2<<DccFreqShift|v)
	r.hw.WriteRegister(RegAfcBw, 4<<DccFreqShift|v)
}

// Channel BW = FXOSC / (RxBwMant * 2^(RxBwExp + 3), assuming OOK modulation.
// The caller must add the desired DccFreq field to the result.
func channelBwToRegister(bw uint32) byte {
	bb := uint32(1302) // lowest possible channel bandwidth
	rr := byte(RxBwMant24 | 7<<RxBwExpShift)
	if bw < bb {
		return rr
	}
	for i := 0; i < 8; i++ {
		e := byte(7 - i)
		for j := 0; j < 3; j++ {
			m := byte((6 - j) * 4)
			b := uint32(FXOSC) / (uint32(m) << (e + 3))
			r := byte(2-j)<<RxBwMantShift | e<<RxBwExpShift
			if b >= bw {
				if b-bw < bw-bb {
					return r
				} else {
					return rr
				}
			}
			bb = b
			rr = r
		}
	}
	return rr
}

func (r *Radio) mode() byte {
	return r.hw.ReadRegister(RegOpMode) & ModeMask
}

func (r *Radio) setMode(mode uint8) {
	r.SetError(nil)
	cur := r.hw.ReadRegister(RegOpMode)
	if cur&ModeMask == mode {
		return
	}
	if verbose {
		log.Printf("change from %s to %s", stateName(cur&ModeMask), stateName(mode))
	}
	r.hw.WriteRegister(RegOpMode, cur&^ModeMask|mode)
	for r.Error() == nil {
		s := r.mode()
		if s == mode && r.modeReady() {
			break
		}
		if verbose {
			log.Printf("  %s", stateName(s))
		}
	}
}

func (r *Radio) modeReady() bool {
	return r.hw.ReadRegister(RegIrqFlags1)&ModeReady != 0
}

func (r *Radio) Sleep() {
	r.setMode(SleepMode)
}

func stateName(mode uint8) string {
	switch mode {
	case SleepMode:
		return "Sleep"
	case StandbyMode:
		return "Standby"
	case FreqSynthMode:
		return "Frequency Synthesizer"
	case TransmitterMode:
		return "Transmitter"
	case ReceiverMode:
		return "Receiver"
	default:
		return fmt.Sprintf("Unknown operating mode (%X)", mode)
	}
}

func (r *Radio) State() string {
	return stateName(r.mode())
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
)

func MarshalJSON(i interface{}) (res []byte, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = errors.New(fmt.Sprintf("MarshalJSON error: %s\n", e))
		}
	}()

	buffer := bytes.NewBuffer([]byte("{"))

	rtype := reflect.TypeOf(i).Elem()
	rval := reflect.ValueOf(i).Elem()
	count := rtype.NumField()

	result := make([][]byte, 0)

	for i := range make([]struct{}, count) {
		key := rtype.Field(i)
		value := rval.Field(i)
		if val, ok := value.Interface().(driver.Valuer); ok {
			if v, err := val.Value(); v != nil && err == nil {
				if vJson, err := json.Marshal(v); err == nil {
					res := []byte(`"`)
					res = append(res, []byte(key.Name)...)
					res = append(res, []byte(`":`)...)
					res = append(res, vJson...)
					result = append(result, res)
				}
			}
		} else if value.Kind() == reflect.Slice && value.Len() > 0 {
			if vJson, err := json.Marshal(value.Interface()); err == nil {
				res := []byte(`"`)
				res = append(res, []byte(key.Name)...)
				res = append(res, []byte(`":`)...)
				res = append(res, vJson...)
				result = append(result, res)
			}
		}
	}

	jsonData := bytes.Join(result, []byte(","))
	if _, err = buffer.Write(jsonData); err != nil {
		return
	}

	if _, err = buffer.Write([]byte(`}`)); err != nil {
		return
	}

	return buffer.Bytes(), err
}
<commit_msg>[kami] Remove helpers<commit_after><|endoftext|>


<commit_before>package rkt

import (
	"path/filepath"

	"github.com/coreos/go-systemd/dbus"
)

const (
	stage1Dir   = "/stage1"
	stage1Init  = stage1Dir + "/init"
	stage2Dir   = stage1Dir + "/opt/stage2"
	servicesDir = stage1Dir + "/run/systemd/system"
	wantsDir    = servicesDir + "/default.target.wants"
)

// Stage1RootfsPath returns the directory in root containing the rootfs for stage1
func Stage1RootfsPath(root string) string {
	return filepath.Join(root, stage1Dir)
}

// Stage1InitPath returns the path to the file in root that is the stage1 init process
func Stage1InitPath(root string) string {
	return filepath.Join(root, stage1Init)
}

// ContainerManifestPath returns the path in root to the Container Runtime Manifest
func ContainerManifestPath(root string) string {
	return filepath.Join(root, "container")
}

// AppImagePath returns the path where an app image (i.e. RAF) is rooted (i.e.
// where its contents are extracted during stage0), based on the app image ID.
func AppImagePath(root string, id string) string {
	return filepath.Join(root, stage2Dir, id)
}

// AppRootfsPath returns the path to an app's rootfs.
// id should be the app image ID.
func AppRootfsPath(root string, id string) string {
	return filepath.Join(AppImagePath(root, id), "rootfs")
}

// AppManifestPath returns the path to the app's manifest file inside the RAF.
// id should be the app image ID.
func AppManifestPath(root string, imageID string) string {
	return filepath.Join(AppImagePath(root, imageID), "manifest")
}

// WantsPath returns the systemd "wantd" directory in root
func WantsPath(root string) string {
	return filepath.Join(root, wantsDir)
}

// ServicesPath returns the systemd "services" directory in root
func ServicesPath(root string) string {
	return filepath.Join(root, servicesDir)
}

// ServiceName returns a sanitized (escaped) systemd service name
// for the given app name
func ServiceName(appname string) string {
	return dbus.PathBusEscape(appname) + ".service"
}

// ServiceFilePath returns the path to the systemd service file
// path for the named app
func ServiceFilePath(root, name string) string {
	return filepath.Join(root, servicesDir, ServiceName(name))
}

// WantLinkPath returns the systemd "want" symlink path for the
// named app
func WantLinkPath(root, name string) string {
	return filepath.Join(root, wantsDir, ServiceName(name))
}
<commit_msg>rkt: move service files into /usr<commit_after>package rkt

import (
	"path/filepath"

	"github.com/coreos/go-systemd/dbus"
)

const (
	stage1Dir   = "/stage1"
	stage1Init  = stage1Dir + "/init"
	stage2Dir   = stage1Dir + "/opt/stage2"
	servicesDir = stage1Dir + "/usr/lib/systemd/system"
	wantsDir    = servicesDir + "/default.target.wants"
)

// Stage1RootfsPath returns the directory in root containing the rootfs for stage1
func Stage1RootfsPath(root string) string {
	return filepath.Join(root, stage1Dir)
}

// Stage1InitPath returns the path to the file in root that is the stage1 init process
func Stage1InitPath(root string) string {
	return filepath.Join(root, stage1Init)
}

// ContainerManifestPath returns the path in root to the Container Runtime Manifest
func ContainerManifestPath(root string) string {
	return filepath.Join(root, "container")
}

// AppImagePath returns the path where an app image (i.e. RAF) is rooted (i.e.
// where its contents are extracted during stage0), based on the app image ID.
func AppImagePath(root string, id string) string {
	return filepath.Join(root, stage2Dir, id)
}

// AppRootfsPath returns the path to an app's rootfs.
// id should be the app image ID.
func AppRootfsPath(root string, id string) string {
	return filepath.Join(AppImagePath(root, id), "rootfs")
}

// AppManifestPath returns the path to the app's manifest file inside the RAF.
// id should be the app image ID.
func AppManifestPath(root string, imageID string) string {
	return filepath.Join(AppImagePath(root, imageID), "manifest")
}

// WantsPath returns the systemd "wantd" directory in root
func WantsPath(root string) string {
	return filepath.Join(root, wantsDir)
}

// ServicesPath returns the systemd "services" directory in root
func ServicesPath(root string) string {
	return filepath.Join(root, servicesDir)
}

// ServiceName returns a sanitized (escaped) systemd service name
// for the given app name
func ServiceName(appname string) string {
	return dbus.PathBusEscape(appname) + ".service"
}

// ServiceFilePath returns the path to the systemd service file
// path for the named app
func ServiceFilePath(root, name string) string {
	return filepath.Join(root, servicesDir, ServiceName(name))
}

// WantLinkPath returns the systemd "want" symlink path for the
// named app
func WantLinkPath(root, name string) string {
	return filepath.Join(root, wantsDir, ServiceName(name))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"sync"
	"syscall"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	keybase1 "github.com/keybase/client/protocol/go"
	"github.com/keybase/kbfs/libkbfs"
	"golang.org/x/net/context"
)

// Folder represents KBFS top-level folders
type Folder struct {
	fs *FS
	id libkbfs.DirID
	dh *libkbfs.DirHandle

	// Protects all Dir.pathNode and File.pathNode instances.
	mu sync.RWMutex
}

// Dir represents KBFS subdirectories.
type Dir struct {
	fs.NodeRef

	folder   *Folder
	parent   *Dir
	pathNode libkbfs.PathNode
}

var _ fs.Node = (*Dir)(nil)

// Attr implements the fs.Node interface for Dir.
func (d *Dir) Attr(ctx context.Context, a *fuse.Attr) error {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	a.Mode = os.ModeDir | 0700
	if d.folder.id.IsPublic() || d.folder.dh.IsPublic() {
		a.Mode |= 0055
	}
	return nil
}

// getPath returns the Path for the current directory.
//
// Caller is responsible for locking.
func (d *Dir) getPathLocked() libkbfs.Path {
	p := libkbfs.Path{
		TopDir: d.folder.id,
	}
	for cur := d; cur != nil; cur = cur.parent {
		p.Path = append(p.Path, cur.pathNode)
	}
	// reverse
	for i := len(p.Path)/2 - 1; i >= 0; i-- {
		opp := len(p.Path) - 1 - i
		p.Path[i], p.Path[opp] = p.Path[opp], p.Path[i]
	}
	return p
}

// Update the PathNode stored here, and in parents.
//
// Caller is responsible for locking.
func (d *Dir) updatePathLocked(p libkbfs.Path) {
	for dir, path := d, p.Path; dir != nil; dir, path = dir.parent, path[:len(path)-1] {
		pNode := path[len(path)-1]
		if dir.pathNode.Name != pNode.Name {
			break
		}
		dir.pathNode = pNode
	}
}

var _ fs.NodeRequestLookuper = (*Dir)(nil)

// Lookup implements the fs.NodeRequestLookuper interface for Dir.
func (d *Dir) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (fs.Node, error) {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	p := d.getPathLocked()

	if req.Name == libkbfs.PublicName &&
		p.HasPublic() &&
		d.folder.dh.HasPublic() {
		dhPub := &libkbfs.DirHandle{
			Writers: d.folder.dh.Writers,
			Readers: []keybase1.UID{keybase1.PublicUID},
		}
		md, err := d.folder.fs.config.KBFSOps().GetRootMDForHandle(dhPub)
		if err != nil {
			return nil, err
		}
		pubFolder := &Folder{
			fs: d.folder.fs,
			id: md.ID,
			dh: dhPub,
		}
		child := &Dir{
			folder: pubFolder,
			pathNode: libkbfs.PathNode{
				BlockPointer: md.Data().Dir.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil
	}

	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return nil, err
	}
	de, ok := dirBlock.Children[req.Name]
	if !ok {
		return nil, fuse.ENOENT
	}

	switch de.Type {
	default:
		return nil, fmt.Errorf("unhandled entry type: %v", de.Type)

	case libkbfs.File, libkbfs.Exec:
		child := &File{
			parent: d,
			pathNode: libkbfs.PathNode{
				BlockPointer: de.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil

	case libkbfs.Dir:
		child := &Dir{
			folder: d.folder,
			parent: d,
			pathNode: libkbfs.PathNode{
				BlockPointer: de.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil

	case libkbfs.Sym:
		child := &Symlink{
			parent: d,
			pathNode: libkbfs.PathNode{
				// use a null block pointer for symlinks
				Name: req.Name,
			},
		}
		return child, nil
	}
}

var _ fs.NodeCreater = (*Dir)(nil)

// Create implements the fs.NodeCreater interface for Dir.
func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	isExec := (req.Mode.Perm() & 0100) != 0
	pChild, de, err := d.folder.fs.config.KBFSOps().CreateFile(d.getPathLocked(), req.Name, isExec)
	if err != nil {
		return nil, nil, err
	}
	d.updatePathLocked(*pChild.ParentPath())
	// TODO update mtime, ctime, size?

	child := &File{
		parent: d,
		pathNode: libkbfs.PathNode{
			BlockPointer: de.BlockPointer,
			Name:         req.Name,
		},
	}
	return child, child, nil
}

var _ fs.NodeMkdirer = (*Dir)(nil)

// Mkdir implements the fs.NodeMkdirer interface for Dir.
func (d *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	pChild, de, err := d.folder.fs.config.KBFSOps().CreateDir(d.getPathLocked(), req.Name)
	if err != nil {
		return nil, err
	}
	d.updatePathLocked(*pChild.ParentPath())
	// TODO update mtime, ctime, size?

	child := &Dir{
		folder: d.folder,
		parent: d,
		pathNode: libkbfs.PathNode{
			BlockPointer: de.BlockPointer,
			Name:         req.Name,
		},
	}
	return child, nil
}

var _ fs.NodeSymlinker = (*Dir)(nil)

// Symlink implements the fs.NodeSymlinker interface for Dir.
func (d *Dir) Symlink(ctx context.Context, req *fuse.SymlinkRequest) (fs.Node, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	p, _, err := d.folder.fs.config.KBFSOps().CreateLink(d.getPathLocked(), req.NewName, req.Target)
	if err != nil {
		return nil, err
	}
	d.updatePathLocked(p)
	// TODO update mtime, ctime, size?

	child := &Symlink{
		parent: d,
		pathNode: libkbfs.PathNode{
			// use a null block pointer for symlinks
			Name: req.NewName,
		},
	}
	return child, nil
}

var _ fs.NodeRenamer = (*Dir)(nil)

// Rename implements the fs.NodeRenamer interface for Dir.
func (d *Dir) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	newDir2, ok := newDir.(*Dir)
	if !ok {
		// The destination is not a Dir instance, probably because
		// it's Root (or some other node type added later). The kernel
		// won't let a rename newDir point to a non-directory.
		//
		// We have no cheap atomic rename across folders, so we can't
		// serve this. EXDEV makes `mv` do a copy+delete, and the
		// Lookup on the destination path will decide whether the it's
		// legal.
		return fuse.Errno(syscall.EXDEV)
	}
	if d.folder != newDir2.folder {
		// Check this explicitly, not just trusting KBFSOps.Rename to
		// return an error, because we rely on it for locking
		// correctness.
		return fuse.Errno(syscall.EXDEV)
	}

	oldParent := d.getPathLocked()
	newParent := newDir2.getPathLocked()

	pOld, pNew, err := d.folder.fs.config.KBFSOps().Rename(oldParent, req.OldName, newParent, req.NewName)
	if err != nil {
		return err
	}
	// TODO why can't i trigger a test failure if these are missing
	d.updatePathLocked(pOld)
	newDir2.updatePathLocked(pNew)
	// TODO update mtime, ctime, size?

	return nil
}

var _ fs.NodeRemover = (*Dir)(nil)

// Remove implements the fs.NodeRemover interface for Dir.
func (d *Dir) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	p := d.getPathLocked()
	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return err
	}

	de, ok := dirBlock.Children[req.Name]
	if !ok {
		return fuse.ENOENT
	}

	p.Path = append(p.Path, libkbfs.PathNode{
		BlockPointer: de.BlockPointer,
		Name:         req.Name,
	})

	switch {
	case !req.Dir && de.Type == libkbfs.Dir:
		return fuse.Errno(syscall.EISDIR)
	case req.Dir && de.Type != libkbfs.Dir:
		return fuse.Errno(syscall.ENOTDIR)
	}

	var p2 libkbfs.Path
	if req.Dir {
		p2, err = d.folder.fs.config.KBFSOps().RemoveDir(p)
	} else {
		p2, err = d.folder.fs.config.KBFSOps().RemoveEntry(p)
	}
	if err != nil {
		return err
	}

	d.updatePathLocked(p2)
	return nil
}

var _ fs.Handle = (*Dir)(nil)

var _ fs.HandleReadDirAller = (*Dir)(nil)

// ReadDirAll implements the fs.NodeReadDirAller interface for Dir.
func (d *Dir) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	var res []fuse.Dirent
	p := d.getPathLocked()
	hasPublic := p.HasPublic() && d.folder.dh.HasPublic()
	if hasPublic {
		res = append(res, fuse.Dirent{
			Name: libkbfs.PublicName,
			Type: fuse.DT_Dir,
		})
	}

	if d.folder.id == libkbfs.NullDirID {
		// It's a dummy folder for the purposes of exposing public.
		return res, nil
	}

	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return nil, err
	}

	for name, de := range dirBlock.Children {
		fde := fuse.Dirent{
			Name: name,
		}
		switch de.Type {
		case libkbfs.File, libkbfs.Exec:
			fde.Type = fuse.DT_File
		case libkbfs.Dir:
			fde.Type = fuse.DT_Dir
		case libkbfs.Sym:
			fde.Type = fuse.DT_Link
		}
		res = append(res, fde)
	}
	return res, nil
}
<commit_msg>FUSE: Fill attributes like size for directories<commit_after>package main

import (
	"fmt"
	"os"
	"sync"
	"syscall"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	keybase1 "github.com/keybase/client/protocol/go"
	"github.com/keybase/kbfs/libkbfs"
	"golang.org/x/net/context"
)

// Folder represents KBFS top-level folders
type Folder struct {
	fs *FS
	id libkbfs.DirID
	dh *libkbfs.DirHandle

	// Protects all Dir.pathNode and File.pathNode instances.
	mu sync.RWMutex
}

// Dir represents KBFS subdirectories.
type Dir struct {
	fs.NodeRef

	folder   *Folder
	parent   *Dir
	pathNode libkbfs.PathNode
}

var _ fs.Node = (*Dir)(nil)

// Attr implements the fs.Node interface for Dir.
func (d *Dir) Attr(ctx context.Context, a *fuse.Attr) error {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	switch {
	case d.folder.id == libkbfs.NullDirID:
		// It's a made-up folder, e.g. to show u/public when caller
		// has no access to u; no DirEntry.

	case d.parent == nil:
		// Top-level folder
		md, err := d.folder.fs.config.KBFSOps().GetRootMDForHandle(d.folder.dh)
		if err != nil {
			return err
		}
		de := &md.Data().Dir
		fillAttr(de, a)

	default:
		// Not a top-level folder => GetDir is safe.
		de, err := statPath(d.folder.fs.config.KBFSOps(), d.getPathLocked())
		if err != nil {
			return err
		}
		fillAttr(de, a)
	}

	a.Mode = os.ModeDir | 0700
	if d.folder.id.IsPublic() || d.folder.dh.IsPublic() {
		a.Mode |= 0055
	}
	return nil
}

// getPath returns the Path for the current directory.
//
// Caller is responsible for locking.
func (d *Dir) getPathLocked() libkbfs.Path {
	p := libkbfs.Path{
		TopDir: d.folder.id,
	}
	for cur := d; cur != nil; cur = cur.parent {
		p.Path = append(p.Path, cur.pathNode)
	}
	// reverse
	for i := len(p.Path)/2 - 1; i >= 0; i-- {
		opp := len(p.Path) - 1 - i
		p.Path[i], p.Path[opp] = p.Path[opp], p.Path[i]
	}
	return p
}

// Update the PathNode stored here, and in parents.
//
// Caller is responsible for locking.
func (d *Dir) updatePathLocked(p libkbfs.Path) {
	for dir, path := d, p.Path; dir != nil; dir, path = dir.parent, path[:len(path)-1] {
		pNode := path[len(path)-1]
		if dir.pathNode.Name != pNode.Name {
			break
		}
		dir.pathNode = pNode
	}
}

var _ fs.NodeRequestLookuper = (*Dir)(nil)

// Lookup implements the fs.NodeRequestLookuper interface for Dir.
func (d *Dir) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (fs.Node, error) {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	p := d.getPathLocked()

	if req.Name == libkbfs.PublicName &&
		p.HasPublic() &&
		d.folder.dh.HasPublic() {
		dhPub := &libkbfs.DirHandle{
			Writers: d.folder.dh.Writers,
			Readers: []keybase1.UID{keybase1.PublicUID},
		}
		md, err := d.folder.fs.config.KBFSOps().GetRootMDForHandle(dhPub)
		if err != nil {
			return nil, err
		}
		pubFolder := &Folder{
			fs: d.folder.fs,
			id: md.ID,
			dh: dhPub,
		}
		child := &Dir{
			folder: pubFolder,
			pathNode: libkbfs.PathNode{
				BlockPointer: md.Data().Dir.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil
	}

	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return nil, err
	}
	de, ok := dirBlock.Children[req.Name]
	if !ok {
		return nil, fuse.ENOENT
	}

	switch de.Type {
	default:
		return nil, fmt.Errorf("unhandled entry type: %v", de.Type)

	case libkbfs.File, libkbfs.Exec:
		child := &File{
			parent: d,
			pathNode: libkbfs.PathNode{
				BlockPointer: de.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil

	case libkbfs.Dir:
		child := &Dir{
			folder: d.folder,
			parent: d,
			pathNode: libkbfs.PathNode{
				BlockPointer: de.BlockPointer,
				Name:         req.Name,
			},
		}
		return child, nil

	case libkbfs.Sym:
		child := &Symlink{
			parent: d,
			pathNode: libkbfs.PathNode{
				// use a null block pointer for symlinks
				Name: req.Name,
			},
		}
		return child, nil
	}
}

var _ fs.NodeCreater = (*Dir)(nil)

// Create implements the fs.NodeCreater interface for Dir.
func (d *Dir) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	isExec := (req.Mode.Perm() & 0100) != 0
	pChild, de, err := d.folder.fs.config.KBFSOps().CreateFile(d.getPathLocked(), req.Name, isExec)
	if err != nil {
		return nil, nil, err
	}
	d.updatePathLocked(*pChild.ParentPath())

	child := &File{
		parent: d,
		pathNode: libkbfs.PathNode{
			BlockPointer: de.BlockPointer,
			Name:         req.Name,
		},
	}
	return child, child, nil
}

var _ fs.NodeMkdirer = (*Dir)(nil)

// Mkdir implements the fs.NodeMkdirer interface for Dir.
func (d *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	pChild, de, err := d.folder.fs.config.KBFSOps().CreateDir(d.getPathLocked(), req.Name)
	if err != nil {
		return nil, err
	}
	d.updatePathLocked(*pChild.ParentPath())

	child := &Dir{
		folder: d.folder,
		parent: d,
		pathNode: libkbfs.PathNode{
			BlockPointer: de.BlockPointer,
			Name:         req.Name,
		},
	}
	return child, nil
}

var _ fs.NodeSymlinker = (*Dir)(nil)

// Symlink implements the fs.NodeSymlinker interface for Dir.
func (d *Dir) Symlink(ctx context.Context, req *fuse.SymlinkRequest) (fs.Node, error) {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	p, _, err := d.folder.fs.config.KBFSOps().CreateLink(d.getPathLocked(), req.NewName, req.Target)
	if err != nil {
		return nil, err
	}
	d.updatePathLocked(p)

	child := &Symlink{
		parent: d,
		pathNode: libkbfs.PathNode{
			// use a null block pointer for symlinks
			Name: req.NewName,
		},
	}
	return child, nil
}

var _ fs.NodeRenamer = (*Dir)(nil)

// Rename implements the fs.NodeRenamer interface for Dir.
func (d *Dir) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	newDir2, ok := newDir.(*Dir)
	if !ok {
		// The destination is not a Dir instance, probably because
		// it's Root (or some other node type added later). The kernel
		// won't let a rename newDir point to a non-directory.
		//
		// We have no cheap atomic rename across folders, so we can't
		// serve this. EXDEV makes `mv` do a copy+delete, and the
		// Lookup on the destination path will decide whether the it's
		// legal.
		return fuse.Errno(syscall.EXDEV)
	}
	if d.folder != newDir2.folder {
		// Check this explicitly, not just trusting KBFSOps.Rename to
		// return an error, because we rely on it for locking
		// correctness.
		return fuse.Errno(syscall.EXDEV)
	}

	oldParent := d.getPathLocked()
	newParent := newDir2.getPathLocked()

	pOld, pNew, err := d.folder.fs.config.KBFSOps().Rename(oldParent, req.OldName, newParent, req.NewName)
	if err != nil {
		return err
	}
	// TODO why can't i trigger a test failure if these are missing
	d.updatePathLocked(pOld)
	newDir2.updatePathLocked(pNew)

	return nil
}

var _ fs.NodeRemover = (*Dir)(nil)

// Remove implements the fs.NodeRemover interface for Dir.
func (d *Dir) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
	d.folder.mu.Lock()
	defer d.folder.mu.Unlock()

	p := d.getPathLocked()
	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return err
	}

	de, ok := dirBlock.Children[req.Name]
	if !ok {
		return fuse.ENOENT
	}

	p.Path = append(p.Path, libkbfs.PathNode{
		BlockPointer: de.BlockPointer,
		Name:         req.Name,
	})

	switch {
	case !req.Dir && de.Type == libkbfs.Dir:
		return fuse.Errno(syscall.EISDIR)
	case req.Dir && de.Type != libkbfs.Dir:
		return fuse.Errno(syscall.ENOTDIR)
	}

	var p2 libkbfs.Path
	if req.Dir {
		p2, err = d.folder.fs.config.KBFSOps().RemoveDir(p)
	} else {
		p2, err = d.folder.fs.config.KBFSOps().RemoveEntry(p)
	}
	if err != nil {
		return err
	}

	d.updatePathLocked(p2)
	return nil
}

var _ fs.Handle = (*Dir)(nil)

var _ fs.HandleReadDirAller = (*Dir)(nil)

// ReadDirAll implements the fs.NodeReadDirAller interface for Dir.
func (d *Dir) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
	d.folder.mu.RLock()
	defer d.folder.mu.RUnlock()

	var res []fuse.Dirent
	p := d.getPathLocked()
	hasPublic := p.HasPublic() && d.folder.dh.HasPublic()
	if hasPublic {
		res = append(res, fuse.Dirent{
			Name: libkbfs.PublicName,
			Type: fuse.DT_Dir,
		})
	}

	if d.folder.id == libkbfs.NullDirID {
		// It's a dummy folder for the purposes of exposing public.
		return res, nil
	}

	dirBlock, err := d.folder.fs.config.KBFSOps().GetDir(p)
	if err != nil {
		return nil, err
	}

	for name, de := range dirBlock.Children {
		fde := fuse.Dirent{
			Name: name,
		}
		switch de.Type {
		case libkbfs.File, libkbfs.Exec:
			fde.Type = fuse.DT_File
		case libkbfs.Dir:
			fde.Type = fuse.DT_Dir
		case libkbfs.Sym:
			fde.Type = fuse.DT_Link
		}
		res = append(res, fde)
	}
	return res, nil
}
<|endoftext|>


<commit_before>package config

import (
	"fmt"
	"math"
	"time"
)

const (
	// DefaultRetryAttempts is the default number of maximum retry attempts.
	DefaultRetryAttempts = 5

	// DefaultRetryBackoff is the default base for the exponential backoff
	// algorithm.
	DefaultRetryBackoff = 250 * time.Millisecond
)

// RetryFunc is the signature of a function that supports retries.
type RetryFunc func(int) (bool, time.Duration)

// RetryConfig is a shared configuration for upstreams that support retires on
// failure.
type RetryConfig struct {
	// Attempts is the total number of maximum attempts to retry before letting
	// the error fall through.
	Attempts *int

	// Backoff is the base of the exponentialbackoff. This number will be multipled
	// by the next power of 2 on each iteration.
	Backoff *time.Duration

	// Enabled signals if this retry is enabled.
	Enabled *bool
}

// DefaultRetryConfig returns a configuration that is populated with the
// default values.
func DefaultRetryConfig() *RetryConfig {
	return &RetryConfig{}
}

// Copy returns a deep copy of this configuration.
func (c *RetryConfig) Copy() *RetryConfig {
	if c == nil {
		return nil
	}

	var o RetryConfig

	o.Attempts = c.Attempts

	o.Backoff = c.Backoff

	o.Enabled = c.Enabled

	return &o
}

// Merge combines all values in this configuration with the values in the other
// configuration, with values in the other configuration taking precedence.
// Maps and slices are merged, most other values are overwritten. Complex
// structs define their own merge functionality.
func (c *RetryConfig) Merge(o *RetryConfig) *RetryConfig {
	if c == nil {
		if o == nil {
			return nil
		}
		return o.Copy()
	}

	if o == nil {
		return c.Copy()
	}

	r := c.Copy()

	if o.Attempts != nil {
		r.Attempts = o.Attempts
	}

	if o.Backoff != nil {
		r.Backoff = o.Backoff
	}

	if o.Enabled != nil {
		r.Enabled = o.Enabled
	}

	return r
}

// RetryFunc returns the retry function associated with this configuration.
func (c *RetryConfig) RetryFunc() RetryFunc {
	return func(retry int) (bool, time.Duration) {
		if !BoolVal(c.Enabled) {
			return false, 0
		}

		if IntVal(c.Attempts) > 0 && retry > IntVal(c.Attempts) {
			return false, 0
		}

		base := math.Pow(2, float64(retry))
		sleep := time.Duration(base) * TimeDurationVal(c.Backoff)

		return true, sleep
	}
}

// Finalize ensures there no nil pointers.
func (c *RetryConfig) Finalize() {
	if c.Attempts == nil {
		c.Attempts = Int(DefaultRetryAttempts)
	}

	if c.Backoff == nil {
		c.Backoff = TimeDuration(DefaultRetryBackoff)
	}

	if c.Enabled == nil {
		c.Enabled = Bool(true)
	}
}

// GoString defines the printable version of this struct.
func (c *RetryConfig) GoString() string {
	if c == nil {
		return "(*RetryConfig)(nil)"
	}

	return fmt.Sprintf("&RetryConfig{"+
		"Attempts:%s, "+
		"Backoff:%s, "+
		"Enabled:%s"+
		"}",
		IntGoString(c.Attempts),
		TimeDurationGoString(c.Backoff),
		BoolGoString(c.Enabled),
	)
}
<commit_msg>Off by one in retries<commit_after>package config

import (
	"fmt"
	"math"
	"time"
)

const (
	// DefaultRetryAttempts is the default number of maximum retry attempts.
	DefaultRetryAttempts = 5

	// DefaultRetryBackoff is the default base for the exponential backoff
	// algorithm.
	DefaultRetryBackoff = 250 * time.Millisecond
)

// RetryFunc is the signature of a function that supports retries.
type RetryFunc func(int) (bool, time.Duration)

// RetryConfig is a shared configuration for upstreams that support retires on
// failure.
type RetryConfig struct {
	// Attempts is the total number of maximum attempts to retry before letting
	// the error fall through.
	Attempts *int

	// Backoff is the base of the exponentialbackoff. This number will be multipled
	// by the next power of 2 on each iteration.
	Backoff *time.Duration

	// Enabled signals if this retry is enabled.
	Enabled *bool
}

// DefaultRetryConfig returns a configuration that is populated with the
// default values.
func DefaultRetryConfig() *RetryConfig {
	return &RetryConfig{}
}

// Copy returns a deep copy of this configuration.
func (c *RetryConfig) Copy() *RetryConfig {
	if c == nil {
		return nil
	}

	var o RetryConfig

	o.Attempts = c.Attempts

	o.Backoff = c.Backoff

	o.Enabled = c.Enabled

	return &o
}

// Merge combines all values in this configuration with the values in the other
// configuration, with values in the other configuration taking precedence.
// Maps and slices are merged, most other values are overwritten. Complex
// structs define their own merge functionality.
func (c *RetryConfig) Merge(o *RetryConfig) *RetryConfig {
	if c == nil {
		if o == nil {
			return nil
		}
		return o.Copy()
	}

	if o == nil {
		return c.Copy()
	}

	r := c.Copy()

	if o.Attempts != nil {
		r.Attempts = o.Attempts
	}

	if o.Backoff != nil {
		r.Backoff = o.Backoff
	}

	if o.Enabled != nil {
		r.Enabled = o.Enabled
	}

	return r
}

// RetryFunc returns the retry function associated with this configuration.
func (c *RetryConfig) RetryFunc() RetryFunc {
	return func(retry int) (bool, time.Duration) {
		if !BoolVal(c.Enabled) {
			return false, 0
		}

		if IntVal(c.Attempts) > 0 && retry > IntVal(c.Attempts)-1 {
			return false, 0
		}

		base := math.Pow(2, float64(retry))
		sleep := time.Duration(base) * TimeDurationVal(c.Backoff)

		return true, sleep
	}
}

// Finalize ensures there no nil pointers.
func (c *RetryConfig) Finalize() {
	if c.Attempts == nil {
		c.Attempts = Int(DefaultRetryAttempts)
	}

	if c.Backoff == nil {
		c.Backoff = TimeDuration(DefaultRetryBackoff)
	}

	if c.Enabled == nil {
		c.Enabled = Bool(true)
	}
}

// GoString defines the printable version of this struct.
func (c *RetryConfig) GoString() string {
	if c == nil {
		return "(*RetryConfig)(nil)"
	}

	return fmt.Sprintf("&RetryConfig{"+
		"Attempts:%s, "+
		"Backoff:%s, "+
		"Enabled:%s"+
		"}",
		IntGoString(c.Attempts),
		TimeDurationGoString(c.Backoff),
		BoolGoString(c.Enabled),
	)
}
<|endoftext|>


<commit_before>package main

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

// Roll rolls n dice with values in the range [1,d], and returns
// their values in the order they were rolled.
func roll(n, d int) []int {
	dice := make([]int, n)
	for i := range dice {
		dice[i] = rand.Intn(d) + 1
	}
	return dice
}

func main() {
	rand.Seed(time.Now().UnixNano())

	if len(os.Args) < 3 {
        println("  Usage:")
        println("      rolldice <num> <faces> [modifier]")
        println("  Rolls <num> dice, each with <faces> number of faces in range [1, <faces>].\n")

        println("  If [modifier] is not given, the dice are printed, one per line.")
        println("  If [modifier] is given, the sum of all the dice, plus the modifier, is")
        println("  printed. The individual rolls will not be printed.\n")

		println("  <num> must be a non-negative integer. <faces> must be a positive integer.")
        println("  [modifier] must be an integer (can be any sign, or zero).")

		return
	}

	n, err := strconv.Atoi(os.Args[1])
	if err != nil || n < 0 {
		println("<num> must be non-negative integer")
		return
	}

	f, err := strconv.Atoi(os.Args[2])
	if err != nil || f <= 0 {
		println("<faces> must be positive integer")
		return
	}

	dice := roll(n, f)

	if len(os.Args) > 3 {
		s, err := strconv.Atoi(os.Args[3])
		if err != nil {
			println("[modifier] must be integer")
			return
		}

		for i := range dice {
			s += dice[i]
		}
		fmt.Println(s)
	} else {
		for i := range dice {
			fmt.Println(dice[i])
		}
	}
}
<commit_msg>Return 1 on failures<commit_after>package main

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

// Roll rolls n dice with values in the range [1,d], and returns
// their values in the order they were rolled.
func roll(n, d int) []int {
	dice := make([]int, n)
	for i := range dice {
		dice[i] = rand.Intn(d) + 1
	}
	return dice
}

func main() {
	rand.Seed(time.Now().UnixNano())

	if len(os.Args) < 3 {
        println("  Usage:")
        println("      rolldice <num> <faces> [modifier]")
        println("  Rolls <num> dice, each with <faces> number of faces in range [1, <faces>].\n")

        println("  If [modifier] is not given, the dice are printed, one per line.")
        println("  If [modifier] is given, the sum of all the dice, plus the modifier, is")
        println("  printed. The individual rolls will not be printed.\n")

		println("  <num> must be a non-negative integer. <faces> must be a positive integer.")
        println("  [modifier] must be an integer (can be any sign, or zero).")

		os.Exit(1)
	}

	n, err := strconv.Atoi(os.Args[1])
	if err != nil || n < 0 {
		println("<num> must be non-negative integer")
		os.Exit(1)
	}

	f, err := strconv.Atoi(os.Args[2])
	if err != nil || f <= 0 {
		println("<faces> must be positive integer")
		os.Exit(1)
	}

	dice := roll(n, f)

	if len(os.Args) > 3 {
		s, err := strconv.Atoi(os.Args[3])
		if err != nil {
			println("[modifier] must be integer")
			os.Exit(1)
		}

		for i := range dice {
			s += dice[i]
		}
		fmt.Println(s)
	} else {
		for i := range dice {
			fmt.Println(dice[i])
		}
	}
}
<|endoftext|>


<commit_before>package rpc

import "encoding/json"
import "github.com/ethereum/go-ethereum/core"

type GetBlockArgs struct {
	BlockNumber int32
	Hash        string
}

func (obj *GetBlockArgs) UnmarshalJSON(b []byte) (err error) {
	argint, argstr := int32(0), ""
	if err = json.Unmarshal(b, &argint); err == nil {
		obj.BlockNumber = argint
		return
	}
	if err = json.Unmarshal(b, &argstr); err == nil {
		obj.Hash = argstr
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (obj *GetBlockArgs) requirements() error {
	if obj.BlockNumber == 0 && obj.Hash == "" {
		return NewErrorResponse("GetBlock requires either a block 'number' or a block 'hash' as argument")
	}
	return nil
}

type NewTxArgs struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Value    string `json:"value"`
	Gas      string `json:"gas"`
	GasPrice string `json:"gasPrice"`
	Data     string `json:"data"`
}

type PushTxArgs struct {
	Tx string `json:"tx"`
}

func (obj *PushTxArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Tx = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *PushTxArgs) requirementsPushTx() error {
	if a.Tx == "" {
		return NewErrorResponse("PushTx requires a 'tx' as argument")
	}
	return nil
}

type GetStorageArgs struct {
	Address string
}

func (obj *GetStorageArgs) UnmarshalJSON(b []byte) (err error) {
	if err = json.Unmarshal(b, &obj.Address); err != nil {
		return NewErrorResponse(ErrorDecodeArgs)
	}
	return
}

func (a *GetStorageArgs) requirements() error {
	if len(a.Address) == 0 {
		return NewErrorResponse("GetStorageAt requires an 'address' value as argument")
	}
	return nil
}

type GetStateArgs struct {
	Address string
	Key     string
}

func (obj *GetStateArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *GetStateArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetStorageAt requires an 'address' value as argument")
	}
	if a.Key == "" {
		return NewErrorResponse("GetStorageAt requires an 'key' value as argument")
	}
	return nil
}

type GetStorageAtRes struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type GetTxCountArgs struct {
	Address string `json:"address"`
}

// type GetTxCountRes struct {
//  Nonce int `json:"nonce"`
// }

func (obj *GetTxCountArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse("Could not determine JSON parameters")
}

func (a *GetTxCountArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetTxCountAt requires an 'address' value as argument")
	}
	return nil
}

// type GetPeerCountRes struct {
//  PeerCount int `json:"peerCount"`
// }

// type GetListeningRes struct {
//  IsListening bool `json:"isListening"`
// }

// type GetCoinbaseRes struct {
//  Coinbase string `json:"coinbase"`
// }

// type GetMiningRes struct {
//  IsMining bool `json:"isMining"`
// }

type GetBalanceArgs struct {
	Address string
}

func (obj *GetBalanceArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse("Could not determine JSON parameters")
}

func (a *GetBalanceArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetBalanceAt requires an 'address' value as argument")
	}
	return nil
}

type BalanceRes struct {
	Balance string `json:"balance"`
	Address string `json:"address"`
}

type GetCodeAtArgs struct {
	Address string
}

func (obj *GetCodeAtArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *GetCodeAtArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetCodeAt requires an 'address' value as argument")
	}
	return nil
}

type Sha3Args struct {
	Data string
}

func (obj *Sha3Args) UnmarshalJSON(b []byte) (err error) {
	if err = json.Unmarshal(b, &obj.Data); err != nil {
		return NewErrorResponse(ErrorDecodeArgs)
	}
	return
}

type FilterOptions struct {
	Earliest int64
	Latest   int64
	Address  string
	Topic    []string
	Skip     int
	Max      int
}

func toFilterOptions(options *FilterOptions) core.FilterOptions {
	var opts core.FilterOptions
	opts.Earliest = options.Earliest
	opts.Latest = options.Latest
	opts.Address = fromHex(options.Address)
	opts.Topics = make([][]byte, len(options.Topic))
	for i, topic := range options.Topic {
		opts.Topics[i] = fromHex(topic)
	}

	return opts
}

type FilterChangedArgs struct {
	n int
}

type DbArgs struct {
	Database string
	Key      string
	Value    string
}

func (a *DbArgs) requirements() error {
	if len(a.Database) == 0 {
		return NewErrorResponse("DbPutArgs requires an 'Database' value as argument")
	}
	if len(a.Key) == 0 {
		return NewErrorResponse("DbPutArgs requires an 'Key' value as argument")
	}
	return nil
}

type WhisperMessageArgs struct {
	Payload  string
	To       string
	From     string
	Topics   []string
	Priority uint32
	Ttl      uint32
}
<commit_msg>Added optional address slice. Closes #326<commit_after>package rpc

import "encoding/json"

import "github.com/ethereum/go-ethereum/core"

type GetBlockArgs struct {
	BlockNumber int32
	Hash        string
}

func (obj *GetBlockArgs) UnmarshalJSON(b []byte) (err error) {
	argint, argstr := int32(0), ""
	if err = json.Unmarshal(b, &argint); err == nil {
		obj.BlockNumber = argint
		return
	}
	if err = json.Unmarshal(b, &argstr); err == nil {
		obj.Hash = argstr
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (obj *GetBlockArgs) requirements() error {
	if obj.BlockNumber == 0 && obj.Hash == "" {
		return NewErrorResponse("GetBlock requires either a block 'number' or a block 'hash' as argument")
	}
	return nil
}

type NewTxArgs struct {
	From     string `json:"from"`
	To       string `json:"to"`
	Value    string `json:"value"`
	Gas      string `json:"gas"`
	GasPrice string `json:"gasPrice"`
	Data     string `json:"data"`
}

type PushTxArgs struct {
	Tx string `json:"tx"`
}

func (obj *PushTxArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Tx = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *PushTxArgs) requirementsPushTx() error {
	if a.Tx == "" {
		return NewErrorResponse("PushTx requires a 'tx' as argument")
	}
	return nil
}

type GetStorageArgs struct {
	Address string
}

func (obj *GetStorageArgs) UnmarshalJSON(b []byte) (err error) {
	if err = json.Unmarshal(b, &obj.Address); err != nil {
		return NewErrorResponse(ErrorDecodeArgs)
	}
	return
}

func (a *GetStorageArgs) requirements() error {
	if len(a.Address) == 0 {
		return NewErrorResponse("GetStorageAt requires an 'address' value as argument")
	}
	return nil
}

type GetStateArgs struct {
	Address string
	Key     string
}

func (obj *GetStateArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *GetStateArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetStorageAt requires an 'address' value as argument")
	}
	if a.Key == "" {
		return NewErrorResponse("GetStorageAt requires an 'key' value as argument")
	}
	return nil
}

type GetStorageAtRes struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type GetTxCountArgs struct {
	Address string `json:"address"`
}

// type GetTxCountRes struct {
//  Nonce int `json:"nonce"`
// }

func (obj *GetTxCountArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse("Could not determine JSON parameters")
}

func (a *GetTxCountArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetTxCountAt requires an 'address' value as argument")
	}
	return nil
}

// type GetPeerCountRes struct {
//  PeerCount int `json:"peerCount"`
// }

// type GetListeningRes struct {
//  IsListening bool `json:"isListening"`
// }

// type GetCoinbaseRes struct {
//  Coinbase string `json:"coinbase"`
// }

// type GetMiningRes struct {
//  IsMining bool `json:"isMining"`
// }

type GetBalanceArgs struct {
	Address string
}

func (obj *GetBalanceArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse("Could not determine JSON parameters")
}

func (a *GetBalanceArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetBalanceAt requires an 'address' value as argument")
	}
	return nil
}

type BalanceRes struct {
	Balance string `json:"balance"`
	Address string `json:"address"`
}

type GetCodeAtArgs struct {
	Address string
}

func (obj *GetCodeAtArgs) UnmarshalJSON(b []byte) (err error) {
	arg0 := ""
	if err = json.Unmarshal(b, &arg0); err == nil {
		obj.Address = arg0
		return
	}
	return NewErrorResponse(ErrorDecodeArgs)
}

func (a *GetCodeAtArgs) requirements() error {
	if a.Address == "" {
		return NewErrorResponse("GetCodeAt requires an 'address' value as argument")
	}
	return nil
}

type Sha3Args struct {
	Data string
}

func (obj *Sha3Args) UnmarshalJSON(b []byte) (err error) {
	if err = json.Unmarshal(b, &obj.Data); err != nil {
		return NewErrorResponse(ErrorDecodeArgs)
	}
	return
}

type FilterOptions struct {
	Earliest int64
	Latest   int64
	Address  interface{}
	Topic    []string
	Skip     int
	Max      int
}

func toFilterOptions(options *FilterOptions) core.FilterOptions {
	var opts core.FilterOptions

	// Convert optional address slice/string to byte slice
	if str, ok := options.Address.(string); ok {
		opts.Address = [][]byte{fromHex(str)}
	} else if slice, ok := options.Address.([]interface{}); ok {
		bslice := make([][]byte, len(slice))
		for i, addr := range slice {
			if saddr, ok := addr.(string); ok {
				bslice[i] = fromHex(saddr)
			}
		}
		opts.Address = bslice
	}

	opts.Earliest = options.Earliest
	opts.Latest = options.Latest
	opts.Topics = make([][]byte, len(options.Topic))
	for i, topic := range options.Topic {
		opts.Topics[i] = fromHex(topic)
	}

	return opts
}

type FilterChangedArgs struct {
	n int
}

type DbArgs struct {
	Database string
	Key      string
	Value    string
}

func (a *DbArgs) requirements() error {
	if len(a.Database) == 0 {
		return NewErrorResponse("DbPutArgs requires an 'Database' value as argument")
	}
	if len(a.Key) == 0 {
		return NewErrorResponse("DbPutArgs requires an 'Key' value as argument")
	}
	return nil
}

type WhisperMessageArgs struct {
	Payload  string
	To       string
	From     string
	Topics   []string
	Priority uint32
	Ttl      uint32
}
<|endoftext|>