<commit_before>package datadog

import (
	"github.com/openzipkin-contrib/zipkin-go-opentracing/thrift/gen-go/zipkincore"
	"github.com/pkg/errors"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
	"reflect"
	"time"
	"unsafe"
)

func Initialize(addr string) {
	// sets the global instance
	tracer.Start(tracer.WithAgentAddr(addr))
}

func sinkSpan(span *zipkincore.Span) tracer.Span {
	startTime := time.Unix(0, span.GetTimestamp()*int64(time.Microsecond))
	finishTime := startTime.Add(time.Duration(span.GetDuration()) * time.Microsecond)

	tags := map[string]interface{}{}
	for _, an := range span.BinaryAnnotations {
		value := string(an.Value)

		switch an.Key {
		case "dd.name":
			tags[ext.SpanName] = value

		case "dd.service":
			tags[ext.ServiceName] = value

		case "dd.resource":
			tags[ext.ResourceName] = value

		default:
			tags[an.Key] = string(an.Value)
		}
	}

	var ddSpan ddtrace.Span = tracer.StartSpan(span.Name, func(cfg *ddtrace.StartSpanConfig) {
		cfg.StartTime = startTime
		cfg.SpanID = uint64(span.ID)
		cfg.Tags = tags
	})

	var context ddtrace.SpanContext = ddSpan.Context()

	refSpan := reflect.ValueOf(ddSpan)

	// validate type
	refSpanType := refSpan.Type()
	if refSpanType.Kind() != reflect.Ptr || refSpanType.String() != "*tracer.span" {
		panic(errors.Errorf("Expected Span of type *tracer.span, got '%s'", refSpanType.String()))
	}

	// dereference the pointer value
	refSpan = refSpan.Elem()

	refSpan.FieldByName("TraceID").SetUint(uint64(span.TraceID))

	if span.ParentID != nil {
		refSpan.FieldByName("ParentID").SetUint(uint64(*span.ParentID))
	}

	refContext := reflect.ValueOf(context).Elem()
	setUnexportetFieldValue(refContext.FieldByName("traceID"), uint64(span.TraceID))
	setUnexportetFieldValue(refContext.FieldByName("spanID"), uint64(span.ID))

	ddSpan.Finish(tracer.FinishTime(finishTime))

	return ddSpan
}

func setUnexportetFieldValue(target reflect.Value, value uint64) {
	if target.Kind() != reflect.Uint64 {
		panic(errors.Errorf("Expect type uint64, got %s", target.Kind()))
	}

	ptr := unsafe.Pointer(target.UnsafeAddr())
	*(*uint64)(ptr) = value
}

// Reads all zipkin spans from the given channel, converts them to datadog spans using the given converter
// and write them into another channel.
func Sink(zipkinSpans <-chan *zipkincore.Span) {
	for span := range zipkinSpans {
		sinkSpan(span)
	}
}
<commit_msg>Always add a name to the span.<commit_after>package datadog

import (
	"github.com/openzipkin-contrib/zipkin-go-opentracing/thrift/gen-go/zipkincore"
	"github.com/pkg/errors"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
	"reflect"
	"time"
	"unsafe"
)

func Initialize(addr string) {
	// sets the global instance
	tracer.Start(tracer.WithAgentAddr(addr))
}

func sinkSpan(span *zipkincore.Span) tracer.Span {
	startTime := time.Unix(0, span.GetTimestamp()*int64(time.Microsecond))
	finishTime := startTime.Add(time.Duration(span.GetDuration()) * time.Microsecond)

	tags := map[string]interface{}{}
	for _, an := range span.BinaryAnnotations {
		value := string(an.Value)

		switch an.Key {
		case "dd.name":
			tags[ext.SpanName] = value

		case "dd.service":
			tags[ext.ServiceName] = value

		case "dd.resource":
			tags[ext.ResourceName] = value

		default:
			tags[an.Key] = string(an.Value)
		}
	}

	name := span.Name
	if name == "" {
		name = "unknown"
	}

	var ddSpan ddtrace.Span = tracer.StartSpan(name, func(cfg *ddtrace.StartSpanConfig) {
		cfg.StartTime = startTime
		cfg.SpanID = uint64(span.ID)
		cfg.Tags = tags
	})

	var context ddtrace.SpanContext = ddSpan.Context()

	refSpan := reflect.ValueOf(ddSpan)

	// validate type
	refSpanType := refSpan.Type()
	if refSpanType.Kind() != reflect.Ptr || refSpanType.String() != "*tracer.span" {
		panic(errors.Errorf("Expected Span of type *tracer.span, got '%s'", refSpanType.String()))
	}

	// dereference the pointer value
	refSpan = refSpan.Elem()

	refSpan.FieldByName("TraceID").SetUint(uint64(span.TraceID))

	if span.ParentID != nil {
		refSpan.FieldByName("ParentID").SetUint(uint64(*span.ParentID))
	}

	refContext := reflect.ValueOf(context).Elem()
	setUnexportetFieldValue(refContext.FieldByName("traceID"), uint64(span.TraceID))
	setUnexportetFieldValue(refContext.FieldByName("spanID"), uint64(span.ID))

	ddSpan.Finish(tracer.FinishTime(finishTime))

	return ddSpan
}

func setUnexportetFieldValue(target reflect.Value, value uint64) {
	if target.Kind() != reflect.Uint64 {
		panic(errors.Errorf("Expect type uint64, got %s", target.Kind()))
	}

	ptr := unsafe.Pointer(target.UnsafeAddr())
	*(*uint64)(ptr) = value
}

// Reads all zipkin spans from the given channel, converts them to datadog spans using the given converter
// and write them into another channel.
func Sink(zipkinSpans <-chan *zipkincore.Span) {
	for span := range zipkinSpans {
		sinkSpan(span)
	}
}
<|endoftext|>


<commit_before>package decomposition

import (
	"errors"

	"github.com/ready-steady/linear/matrix"
)

// CovPCA performs principal component analysis on an m-by-m covariance matrix
// Σ. The principal components U and their variances Λ are returned in
// descending order of the variances. By definition, the variances should be
// nonnegative. Due to finite-precision arithmetics, however, some close-to-zero
// variances might turn out to be negative. If the absolute value of a negative
// variance is smaller than the tolerance ε, the function nullifies that
// variance and proceeds without any errors; otherwise, an error is returned.
func CovPCA(Σ []float64, m uint, ε float64) (U []float64, Λ []float64, err error) {
	U = make([]float64, m*m)
	Λ = make([]float64, m)

	if err = matrix.SymmetricEigen(Σ, U, Λ, m); err != nil {
		return nil, nil, err
	}

	for i := uint(0); i < m; i++ {
		if Λ[i] < 0 {
			if -Λ[i] < ε {
				Λ[i] = 0.0
			} else {
				return nil, nil, errors.New("the matrix should be positive semidefinite")
			}
		}
	}

	// NOTE: Λ is in ascending order. Reverse!
	for i, j := uint(0), m-1; i < j; i, j = i+1, j-1 {
		Λ[i], Λ[j] = Λ[j], Λ[i]
		for k := uint(0); k < m; k++ {
			U[i*m+k], U[j*m+k] = U[j*m+k], U[i*m+k]
		}
	}

	return
}
<commit_msg>decomposition: update the usage of linear/decomposition<commit_after>package decomposition

import (
	"errors"

	"github.com/ready-steady/linear/decomposition"
)

// CovPCA performs principal component analysis on an m-by-m covariance matrix
// Σ. The principal components U and their variances Λ are returned in the
// descending order of the variances.
//
// By definition, the variances should be nonnegative. Due to finite-precision
// arithmetics, however, some close-to-zero variances might turn out to be
// negative. If the absolute value of a negative variance is smaller than the
// tolerance ε, the function nullifies that variance and proceeds without any
// errors; otherwise, an error is returned.
func CovPCA(Σ []float64, m uint, ε float64) (U []float64, Λ []float64, err error) {
	U = make([]float64, m*m)
	Λ = make([]float64, m)

	if err = decomposition.SymmetricEigen(Σ, U, Λ, m); err != nil {
		return nil, nil, err
	}

	for i := uint(0); i < m; i++ {
		if Λ[i] < 0 {
			if -Λ[i] < ε {
				Λ[i] = 0.0
			} else {
				return nil, nil, errors.New("the matrix should be positive semidefinite")
			}
		}
	}

	// Λ is in the ascending order. Reverse!
	for i, j := uint(0), m-1; i < j; i, j = i+1, j-1 {
		Λ[i], Λ[j] = Λ[j], Λ[i]
		for k := uint(0); k < m; k++ {
			U[i*m+k], U[j*m+k] = U[j*m+k], U[i*m+k]
		}
	}

	return
}
<|endoftext|>


<commit_before>package webserver

import (
	"log"

	"github.com/gin-gonic/contrib/static"
	"github.com/gin-gonic/gin"
	cors "github.com/tommy351/gin-cors"
)

func Run(listen string) {
	gin.SetMode(gin.DebugMode)

	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(cors.Middleware(cors.Options{
		AllowOrigins: []string{"*"},
		AllowHeaders: []string{"x-auth-token", "content-type"},
	}))

	apiEndpoints := r.Group("/api/v1")
	{
		apiEndpoints.GET("/puzzles", puzzlesByPositionAndDistance)
		apiEndpoints.GET("/remaining-time", remainingTime)
		apiEndpoints.PUT("/start", startGame)
		apiEndpoints.PUT("/abort", abortGame)
		apiEndpoints.PUT("/finish", finishGame)
	}

	r.Use(static.Serve("/", static.LocalFile("static", false)))

	if error := r.Run(listen); error != nil {
		log.Fatal(error)
	}
}
<commit_msg>Fix path for static files<commit_after>package webserver

import (
	"log"

	"github.com/gin-gonic/contrib/static"
	"github.com/gin-gonic/gin"
	cors "github.com/tommy351/gin-cors"
)

func Run(listen string) {
	gin.SetMode(gin.DebugMode)

	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(cors.Middleware(cors.Options{
		AllowOrigins: []string{"*"},
		AllowHeaders: []string{"x-auth-token", "content-type"},
	}))

	apiEndpoints := r.Group("/api/v1")
	{
		apiEndpoints.GET("/puzzles", puzzlesByPositionAndDistance)
		apiEndpoints.GET("/remaining-time", remainingTime)
		apiEndpoints.PUT("/start", startGame)
		apiEndpoints.PUT("/abort", abortGame)
		apiEndpoints.PUT("/finish", finishGame)
	}

	r.Use(static.Serve("/", static.LocalFile("frontend/dist", false)))

	if error := r.Run(listen); error != nil {
		log.Fatal(error)
	}
}
<|endoftext|>


<commit_before>package asciidocgo

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"os"
)

var _ = Describe("the path_resolver module", func() {
	Context("initialization", func() {
		It("can be created using the default config", func() {
			Expect(NewPathResolver(0, "")).ToNot(BeNil())
		})

		It("should use a system path separator by default", func() {
			//Expect(NewPathResolver(0, "").FileSeparator()).To(Equal(os.PathSeparator))
			Expect(NewPathResolver('/', "").FileSeparator()).To(BeNumerically("==", '/'))
			Expect(NewPathResolver('\\', "").FileSeparator()).To(BeNumerically("==", '\\'))
		})

		It("should be set to the current working path by default", func() {
			pwd, _ := os.Getwd()

			Expect(NewPathResolver(0, "").WorkingDir()).To(Equal(pwd))
			Expect(NewPathResolver(0, `/`).WorkingDir()).To(Equal(`/`))
			Expect(NewPathResolver(0, "test").WorkingDir()).To(Equal(pwd + string(os.PathSeparator) + "test"))
		})
	})

	Context("web path", func() {
		It("can test for a web path", func() {
			Expect(IsWebRoot("")).To(BeFalse())
			Expect(IsWebRoot("a")).To(BeFalse())
			Expect(IsWebRoot(`\a\b/c`)).To(BeFalse())

			Expect(IsWebRoot(`/a/b/c`)).To(BeTrue())
		})
	})

	Context("posixify", func() {
		It("should not adjust an empty path", func() {
			Expect(Posixfy((""))).To(Equal(""))
		})

		It("should be idempotent", func() {
			Expect(Posixfy(Posixfy(("/hello/world")))).To(Equal("/hello/world"))
		})

		It("should be replace backslashes with slashes", func() {
			Expect(Posixfy((`a\b\c`))).To(Equal("a/b/c"))
		})
	})

	Context("webroot check", func() {
		It("should report false for a path not beginning with /", func() {
			Expect(IsWebRoot("")).To(BeFalse())
			Expect(IsWebRoot("C:\\")).To(BeFalse())
			Expect(IsWebRoot("\\")).To(BeFalse())
		})

		It("should report true for a path beginning with /", func() {
			Expect(IsWebRoot("/")).To(BeTrue())
			Expect(IsWebRoot("/a/b/")).To(BeTrue())
			Expect(IsWebRoot("/a\\b/./c")).To(BeTrue())
			Expect(IsWebRoot("/a/b/./c")).To(BeTrue())
		})
	})

	Context("expand path", func() {
		It("should return an empty string when expanding an empty path", func() {
			Expect(ExpandPath("")).To(Equal(""))
		})

		It("should return a posix path when provided with a weird mash", func() {
			Expect(ExpandPath(`c:\a/.\b/../c`)).To(Equal("c:/a/b/../c"))
		})
	})

	Context("path partitioning", func() {
		//TODO
	})
})
<commit_msg>Fix path test on Windows<commit_after>package asciidocgo

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"os"
	"path/filepath"
)

var _ = Describe("the path_resolver module", func() {
	Context("initialization", func() {
		It("can be created using the default config", func() {
			Expect(NewPathResolver(0, "")).ToNot(BeNil())
		})

		It("should use a system path separator by default", func() {
			//Expect(NewPathResolver(0, "").FileSeparator()).To(Equal(os.PathSeparator))
			Expect(NewPathResolver('/', "").FileSeparator()).To(BeNumerically("==", '/'))
			Expect(NewPathResolver('\\', "").FileSeparator()).To(BeNumerically("==", '\\'))
		})

		It("should be set to the current working path by default", func() {
			pwd, _ := os.Getwd()

			Expect(NewPathResolver(0, "").WorkingDir()).To(Equal(pwd))
			Expect(NewPathResolver(0, filepath.FromSlash("/")).WorkingDir()).To(Equal(filepath.FromSlash("/")))
			Expect(NewPathResolver(0, "test").WorkingDir()).To(Equal(pwd + string(os.PathSeparator) + "test"))
		})
	})

	Context("web path", func() {
		It("can test for a web path", func() {
			Expect(IsWebRoot("")).To(BeFalse())
			Expect(IsWebRoot("a")).To(BeFalse())
			Expect(IsWebRoot(`\a\b/c`)).To(BeFalse())

			Expect(IsWebRoot(`/a/b/c`)).To(BeTrue())
		})
	})

	Context("posixify", func() {
		It("should not adjust an empty path", func() {
			Expect(Posixfy((""))).To(Equal(""))
		})

		It("should be idempotent", func() {
			Expect(Posixfy(Posixfy(("/hello/world")))).To(Equal("/hello/world"))
		})

		It("should be replace backslashes with slashes", func() {
			Expect(Posixfy((`a\b\c`))).To(Equal("a/b/c"))
		})
	})

	Context("webroot check", func() {
		It("should report false for a path not beginning with /", func() {
			Expect(IsWebRoot("")).To(BeFalse())
			Expect(IsWebRoot("C:\\")).To(BeFalse())
			Expect(IsWebRoot("\\")).To(BeFalse())
		})

		It("should report true for a path beginning with /", func() {
			Expect(IsWebRoot("/")).To(BeTrue())
			Expect(IsWebRoot("/a/b/")).To(BeTrue())
			Expect(IsWebRoot("/a\\b/./c")).To(BeTrue())
			Expect(IsWebRoot("/a/b/./c")).To(BeTrue())
		})
	})

	Context("expand path", func() {
		It("should return an empty string when expanding an empty path", func() {
			Expect(ExpandPath("")).To(Equal(""))
		})

		It("should return a posix path when provided with a weird mash", func() {
			Expect(ExpandPath(`c:\a/.\b/../c`)).To(Equal("c:/a/b/../c"))
		})
	})

	Context("path partitioning", func() {
		//TODO
	})
})
<|endoftext|>


<commit_before>package socialkite

import (
	"sync"

	"koding/kites/kloud/stack"
	"koding/socialapi"
)

// Kite is an interface for kite.Kite, that is used
// to make RPC calls.
type Kite interface {
	Call(method string, req, resp interface{}) error
}

// KloudAuth provides socialapi.AuthFunc that is
// backed by kite RPC.
type KloudAuth struct {
	Kite    Kite              // kite transport to use; required
	Storage socialapi.Storage // storage for cache to use; optional

	once sync.Once
	auth socialapi.AuthFunc
}

func (ka *KloudAuth) init() {
	ka.once.Do(ka.initAuth)
}

func (ka *KloudAuth) initAuth() {
	if ka.Storage != nil {
		cache := socialapi.NewCache(ka.rpcAuth)
		cache.Storage = ka.Storage
		ka.auth = cache.Auth
	} else {
		ka.auth = ka.rpcAuth
	}
}

// Auth obtains user session by calling "auth.login" method over Kite transport.
func (ka *KloudAuth) Auth(opts *socialapi.AuthOptions) (*socialapi.Session, error) {
	ka.init()
	return ka.auth(opts)
}

func (ka *KloudAuth) rpcAuth(opts *socialapi.AuthOptions) (*socialapi.Session, error) {
	var req = &stack.LoginRequest{GroupName: opts.Session.Team}
	var resp stack.LoginResponse

	if err := ka.Kite.Call("auth.login", req, &resp); err != nil {
		return nil, err
	}

	return &socialapi.Session{
		ClientID: resp.ClientID,
		// TODO(rjeczalik): add Username field to stack.LoginResponse
		// Username: resp.Username,
		Username: opts.Session.Username,
		Team:     resp.GroupName,
	}, nil
}
<commit_msg>socialapi/socialkite: add Storage wrapper for socialapi.Storage backed by BoltDB<commit_after>package socialkite

import (
	"sync"

	"koding/kites/config"
	"koding/kites/kloud/stack"
	"koding/socialapi"
)

// Kite is an interface for kite.Kite, that is used
// to make RPC calls.
type Kite interface {
	Call(method string, req, resp interface{}) error
}

// KloudAuth provides socialapi.AuthFunc that is
// backed by kite RPC.
type KloudAuth struct {
	Kite    Kite              // kite transport to use; required
	Storage socialapi.Storage // storage for cache to use; optional

	once sync.Once
	auth socialapi.AuthFunc
}

var _ socialapi.AuthFunc = (&KloudAuth{}).Auth

func (ka *KloudAuth) init() {
	ka.once.Do(ka.initAuth)
}

func (ka *KloudAuth) initAuth() {
	if ka.Storage != nil {
		cache := socialapi.NewCache(ka.rpcAuth)
		cache.Storage = ka.Storage
		ka.auth = cache.Auth
	} else {
		ka.auth = ka.rpcAuth
	}
}

// Auth obtains user session by calling "auth.login" method over Kite transport.
func (ka *KloudAuth) Auth(opts *socialapi.AuthOptions) (*socialapi.Session, error) {
	ka.init()
	return ka.auth(opts)
}

func (ka *KloudAuth) rpcAuth(opts *socialapi.AuthOptions) (*socialapi.Session, error) {
	var req = &stack.LoginRequest{GroupName: opts.Session.Team}
	var resp stack.LoginResponse

	if err := ka.Kite.Call("auth.login", req, &resp); err != nil {
		return nil, err
	}

	return &socialapi.Session{
		ClientID: resp.ClientID,
		// TODO(rjeczalik): add Username field to stack.LoginResponse
		// Username: resp.Username,
		Username: opts.Session.Username,
		Team:     resp.GroupName,
	}, nil
}

// Storage is wrapper for config.Cache that implements socialapi.Storage.
type Storage struct {
	Cache *config.Cache
}

var _ socialapi.Storage = (*Storage)(nil)

// Get implements the socialapi.Storage interface.
func (st *Storage) Get(s *socialapi.Session) error {
	var sessions map[string]socialapi.Session

	if err := st.Cache.GetValue("auth.sessions", &sessions); err != nil {
		return err
	}

	session, ok := sessions[s.Key()]
	if !ok {
		return socialapi.ErrSessionNotFound
	}

	*s = session

	return nil
}

// Set implements the socialapi.Storage interface.
func (st *Storage) Set(s *socialapi.Session) error {
	sessions := make(map[string]socialapi.Session)

	if err := st.Cache.GetValue("auth.sessions", &sessions); err != nil {
		return err
	}

	sessions[s.Key()] = *s

	return st.Cache.SetValue("auth.sessions", sessions)
}

// Delete implements the socialapi.Storage interface.
func (st *Storage) Delete(s *socialapi.Session) error {
	sessions := make(map[string]socialapi.Session)

	if err := st.Cache.GetValue("auth.sessions", &sessions); err != nil {
		return err
	}

	delete(sessions, s.Key())

	return st.Cache.SetValue("auth.sessions", sessions)
}
<|endoftext|>


<commit_before>package flowpathmapper

import (
	"github.com/dfeyer/flow-debugproxy/config"
	"github.com/dfeyer/flow-debugproxy/errorhandler"
	"github.com/dfeyer/flow-debugproxy/logger"
	"github.com/dfeyer/flow-debugproxy/pathmapping"

	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"
)

const (
	h                = "%s"
	cachePathPattern = "@base@/Data/Temporary/@context@/Cache/Code/Flow_Object_Classes/@filename@.php"
)

var (
	regexpPhpFile         = regexp.MustCompile(`(?://)?(/[^ ]*\.php)`)
	regexpFilename        = regexp.MustCompile(`filename=["]?file://(\S+)/Data/Temporary/[^/]*/Cache/Code/Flow_Object_Classes/([^"]*)\.php`)
	regexpPathAndFilename = regexp.MustCompile(`(?m)^# PathAndFilename: (.*)$`)
	regexpPackageClass    = regexp.MustCompile(`(.*?)/Packages/(.*?)/Classes/(.*).php`)
	regexpDot             = regexp.MustCompile(`[\./]`)
)

// PathMapper handle the mapping between real code and proxy
type PathMapper struct {
	Config      *config.Config
	Logger      *logger.Logger
	PathMapping *pathmapping.PathMapping
}

// ApplyMappingToTextProtocol change file path in xDebug text protocol
func (p *PathMapper) ApplyMappingToTextProtocol(message []byte) []byte {
	return p.doTextPathMapping(message)
}

// ApplyMappingToXML change file path in xDebug XML protocol
func (p *PathMapper) ApplyMappingToXML(message []byte) []byte {
	message = p.doXMLPathMapping(message)

	// update xml length count
	s := strings.Split(string(message), "\x00")
	i, err := strconv.Atoi(s[0])
	errorhandler.PanicHandling(err, p.Logger)
	l := len(s[1])
	if i != l {
		message = bytes.Replace(message, []byte(strconv.Itoa(i)), []byte(strconv.Itoa(l)), 1)
	}

	return message
}

func (p *PathMapper) doTextPathMapping(message []byte) []byte {
	var processedMapping = map[string]string{}
	for _, match := range regexpPhpFile.FindAllStringSubmatch(string(message), -1) {
		originalPath := match[1]
		path := p.mapPath(originalPath)
		p.Logger.Debug("doTextPathMapping %s >>> %s", path, originalPath)
		processedMapping[path] = originalPath
	}

	for path, originalPath := range processedMapping {
		message = bytes.Replace(message, []byte(p.getRealFilename(originalPath)), []byte(p.getRealFilename(path)), -1)
	}

	return message
}

func (p *PathMapper) getCachePath(base, filename string) string {
	cachePath := strings.Replace(cachePathPattern, "@base@", base, 1)
	cachePath = strings.Replace(cachePath, "@context@", p.Config.Context, 1)
	return strings.Replace(cachePath, "@filename@", filename, 1)
}

func (p *PathMapper) doXMLPathMapping(b []byte) []byte {
	var processedMapping = map[string]string{}
	for _, match := range regexpFilename.FindAllStringSubmatch(string(b), -1) {
		path := p.getCachePath(match[1], match[2])
		if _, ok := processedMapping[path]; ok == false {
			if originalPath, exist := p.PathMapping.Get(path); exist {
				if p.Config.VeryVerbose {
					p.Logger.Info("Umpa Lumpa can help you, he know the mapping\n%s\n%s\n", p.Logger.Colorize(">>> "+fmt.Sprintf(h, path), "yellow"), p.Logger.Colorize(">>> "+fmt.Sprintf(h, p.getRealFilename(originalPath)), "green"))
				}
				processedMapping[path] = originalPath
				p.Logger.Debug("doXMLPathMapping mapping exist %s >>> %s", path, originalPath)
			} else {
				originalPath = p.readOriginalPathFromCache(path)
				processedMapping[path] = originalPath
				p.Logger.Debug("doXMLPathMapping missing mapping %s >>> %s", path, originalPath)
			}
		}
	}

	for path, originalPath := range processedMapping {
		path = p.getRealFilename(path)
		originalPath = p.getRealFilename(originalPath)
		b = bytes.Replace(b, []byte(path), []byte(originalPath), -1)
	}

	return b
}

// getRealFilename removes file:// protocol from the given path
func (p *PathMapper) getRealFilename(path string) string {
	return strings.TrimPrefix(path, "file://")
}

func (p *PathMapper) mapPath(originalPath string) string {
	if strings.Contains(originalPath, "/Packages/") {
		p.Logger.Debug("Path %s is a Flow Package file", originalPath)
		cachePath := p.getCachePath(p.buildClassNameFromPath(originalPath))
		realPath := p.getRealFilename(cachePath)
		if _, err := os.Stat(realPath); err == nil {
			return p.registerPathMapping(realPath, originalPath)
		}
	}

	return originalPath
}

func (p *PathMapper) registerPathMapping(path string, originalPath string) string {
	dat, err := ioutil.ReadFile(path)
	errorhandler.PanicHandling(err, p.Logger)
	// check if file contains flow annotation
	if strings.Contains(string(dat), "@Flow\\") {
		if p.Config.Verbose {
			p.Logger.Info("%s", "Our Umpa Lumpa take care of your mapping and they did a great job, they found a proxy for you:")
			p.Logger.Info(">>> %s\n", path)
		}

		if p.PathMapping.Has(path) == false {
			p.PathMapping.Set(path, originalPath)
		}
		return path
	}
	return originalPath
}

func (p *PathMapper) readOriginalPathFromCache(path string) string {
	dat, err := ioutil.ReadFile(path)
	errorhandler.PanicHandling(err, p.Logger)
	match := regexpPathAndFilename.FindStringSubmatch(string(dat))
	p.Logger.Debug("readOriginalPathFromCache %s", path)
	if len(match) == 2 {
		originalPath := match[1]
		if p.Config.VeryVerbose {
			p.Logger.Info("Umpa Lumpa need to work harder, need to reverse this one\n>>> %s\n>>> %s\n", p.Logger.Colorize(fmt.Sprintf(h, path), "yellow"), p.Logger.Colorize(fmt.Sprintf(h, originalPath), "green"))
		}
		p.Logger.Debug("readOriginalPathFromCache %s >>> %s", path, originalPath)
		p.registerPathMapping(path, originalPath)
		return originalPath
	}
	return path
}

func (p *PathMapper) buildClassNameFromPath(path string) (string, string) {
	// todo add support for PSR4
	match := regexpPackageClass.FindStringSubmatch(path)
	basePath := match[1]
	className := regexpDot.ReplaceAllString(match[3], "_")
	return basePath, className
}
<commit_msg>[TASK] Avoid duplicate file cache read<commit_after>package flowpathmapper

import (
	"github.com/dfeyer/flow-debugproxy/config"
	"github.com/dfeyer/flow-debugproxy/errorhandler"
	"github.com/dfeyer/flow-debugproxy/logger"
	"github.com/dfeyer/flow-debugproxy/pathmapping"

	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"
)

const (
	h                = "%s"
	cachePathPattern = "@base@/Data/Temporary/@context@/Cache/Code/Flow_Object_Classes/@filename@.php"
)

var (
	regexpPhpFile         = regexp.MustCompile(`(?://)?(/[^ ]*\.php)`)
	regexpFilename        = regexp.MustCompile(`filename=["]?file://(\S+)/Data/Temporary/[^/]*/Cache/Code/Flow_Object_Classes/([^"]*)\.php`)
	regexpPathAndFilename = regexp.MustCompile(`(?m)^# PathAndFilename: (.*)$`)
	regexpPackageClass    = regexp.MustCompile(`(.*?)/Packages/(.*?)/Classes/(.*).php`)
	regexpDot             = regexp.MustCompile(`[\./]`)
)

// PathMapper handle the mapping between real code and proxy
type PathMapper struct {
	Config      *config.Config
	Logger      *logger.Logger
	PathMapping *pathmapping.PathMapping
}

// ApplyMappingToTextProtocol change file path in xDebug text protocol
func (p *PathMapper) ApplyMappingToTextProtocol(message []byte) []byte {
	return p.doTextPathMapping(message)
}

// ApplyMappingToXML change file path in xDebug XML protocol
func (p *PathMapper) ApplyMappingToXML(message []byte) []byte {
	message = p.doXMLPathMapping(message)

	// update xml length count
	s := strings.Split(string(message), "\x00")
	i, err := strconv.Atoi(s[0])
	errorhandler.PanicHandling(err, p.Logger)
	l := len(s[1])
	if i != l {
		message = bytes.Replace(message, []byte(strconv.Itoa(i)), []byte(strconv.Itoa(l)), 1)
	}

	return message
}

func (p *PathMapper) doTextPathMapping(message []byte) []byte {
	var processedMapping = map[string]string{}
	for _, match := range regexpPhpFile.FindAllStringSubmatch(string(message), -1) {
		originalPath := match[1]
		path := p.mapPath(originalPath)
		p.Logger.Debug("doTextPathMapping %s >>> %s", path, originalPath)
		processedMapping[path] = originalPath
	}

	for path, originalPath := range processedMapping {
		message = bytes.Replace(message, []byte(p.getRealFilename(originalPath)), []byte(p.getRealFilename(path)), -1)
	}

	return message
}

func (p *PathMapper) getCachePath(base, filename string) string {
	cachePath := strings.Replace(cachePathPattern, "@base@", base, 1)
	cachePath = strings.Replace(cachePath, "@context@", p.Config.Context, 1)
	return strings.Replace(cachePath, "@filename@", filename, 1)
}

func (p *PathMapper) doXMLPathMapping(b []byte) []byte {
	var processedMapping = map[string]string{}
	for _, match := range regexpFilename.FindAllStringSubmatch(string(b), -1) {
		path := p.getCachePath(match[1], match[2])
		if _, ok := processedMapping[path]; ok == false {
			if originalPath, exist := p.PathMapping.Get(path); exist {
				if p.Config.VeryVerbose {
					p.Logger.Info("Umpa Lumpa can help you, he know the mapping\n%s\n%s\n", p.Logger.Colorize(">>> "+fmt.Sprintf(h, path), "yellow"), p.Logger.Colorize(">>> "+fmt.Sprintf(h, p.getRealFilename(originalPath)), "green"))
				}
				processedMapping[path] = originalPath
				p.Logger.Debug("doXMLPathMapping mapping exist %s >>> %s", path, originalPath)
			} else {
				originalPath = p.readOriginalPathFromCache(path)
				processedMapping[path] = originalPath
				p.Logger.Debug("doXMLPathMapping missing mapping %s >>> %s", path, originalPath)
			}
		}
	}

	for path, originalPath := range processedMapping {
		path = p.getRealFilename(path)
		originalPath = p.getRealFilename(originalPath)
		b = bytes.Replace(b, []byte(path), []byte(originalPath), -1)
	}

	return b
}

// getRealFilename removes file:// protocol from the given path
func (p *PathMapper) getRealFilename(path string) string {
	return strings.TrimPrefix(path, "file://")
}

func (p *PathMapper) mapPath(originalPath string) string {
	if strings.Contains(originalPath, "/Packages/") {
		p.Logger.Debug("Path %s is a Flow Package file", originalPath)
		cachePath := p.getCachePath(p.buildClassNameFromPath(originalPath))
		realPath := p.getRealFilename(cachePath)
		if _, err := os.Stat(realPath); err == nil {
			return p.registerPathMapping(realPath, originalPath)
		}
	}

	return originalPath
}

func (p *PathMapper) registerPathMapping(path string, originalPath string) string {
	dat, err := ioutil.ReadFile(path)
	errorhandler.PanicHandling(err, p.Logger)
	return p.setPathMapping(path, originalPath, dat)
}

func (p *PathMapper) setPathMapping(path string, originalPath string, dat []byte) string {
	// check if file contains flow annotation
	if strings.Contains(string(dat), "@Flow\\") {
		if p.Config.Verbose {
			p.Logger.Info("%s", "Our Umpa Lumpa take care of your mapping and they did a great job, they found a proxy for you:")
			p.Logger.Info(">>> %s\n", path)
		}

		if p.PathMapping.Has(path) == false {
			p.PathMapping.Set(path, originalPath)
		}
		return path
	}
	return originalPath
}

func (p *PathMapper) readOriginalPathFromCache(path string) string {
	dat, err := ioutil.ReadFile(path)
	errorhandler.PanicHandling(err, p.Logger)
	match := regexpPathAndFilename.FindStringSubmatch(string(dat))
	p.Logger.Debug("readOriginalPathFromCache %s", path)
	if len(match) == 2 {
		originalPath := match[1]
		if p.Config.VeryVerbose {
			p.Logger.Info("Umpa Lumpa need to work harder, need to reverse this one\n>>> %s\n>>> %s\n", p.Logger.Colorize(fmt.Sprintf(h, path), "yellow"), p.Logger.Colorize(fmt.Sprintf(h, originalPath), "green"))
		}
		p.Logger.Debug("readOriginalPathFromCache %s >>> %s", path, originalPath)
		p.setPathMapping(path, originalPath, dat)
		return originalPath
	}
	return path
}

func (p *PathMapper) buildClassNameFromPath(path string) (string, string) {
	// todo add support for PSR4
	match := regexpPackageClass.FindStringSubmatch(path)
	basePath := match[1]
	className := regexpDot.ReplaceAllString(match[3], "_")
	return basePath, className
}
<|endoftext|>


<commit_before>package ble

import (
  "errors"
  "time"
  "io"
  "os"
)

type ManagerRequest struct {
  msg []byte
  device *Device
}

type Manager struct {
  Devices []*Device
  globalHandleOffset int
  associations map[int][]int
  requestChan chan ManagerRequest
  hciSock     *os.File
  log         *os.File
}

func NewManager(hciSock *os.File) (*Manager) {
  f, _ := os.Create("log.csv")
  return &Manager{make([]*Device, 0), 0, make(map[int][]int),
    make(chan ManagerRequest), hciSock, f}
}

func (this *Manager) ConnectTo(addr string) error {
  remoteAddr, err := Str2Ba(addr)
  if err != nil {
    return err
  }

  f, err := NewBLE(NewL2Sockaddr(4, remoteAddr, BDADDR_LE_RANDOM), addr)
  if err != nil {
    return err
  }

  ci := GetConnInfo(f)

  this.AddDeviceForConn(addr, f, ci)

  return nil
}

func (this *Manager) ConnUpdate(device *Device, interval uint16) int {
  if device.connInfo != nil {
    return HCIConnUpdate(this.hciSock, device.connInfo.HCIHandle, interval, interval, 0, 0x0C80)
  } else {
    return 0
  }
}

func (this *Manager) AddDeviceForConn(addr string, f io.ReadWriteCloser, ci *ConnInfo) (*Device) {
  device := NewDevice(addr, this.requestChan, f, ci)
  this.Devices = append(this.Devices, device)
  return device
}

func (this *Manager) StartNoDiscover(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }

  device := this.Devices[idx]
  return this.StartDeviceNoDiscover(device)
}

func (this *Manager) StartDeviceNoDiscover(device *Device) error {
  device.Start()
  return nil
}

func (this *Manager) Start(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }
  device := this.Devices[idx]
  return this.StartDevice(device)
}

func (this *Manager) StartDevice(device *Device) error {
  device.Start()

  handles, err := DiscoverHandles(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  device.handleOffset = this.globalHandleOffset
  this.globalHandleOffset += len(handles)

  for _, handle := range handles {
    h := &Handle{*handle, time.Now(), nil, nil}
    device.handles[handle.handle] = h
  }

  groupVals, err := DiscoverServices(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  for _,v := range groupVals {
    device.handles[v.handle].cachedValue = v.value
    device.handles[v.handle].endGroup = v.endGroup
  }

  handleVals, err := DiscoverCharacteristics(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  for _,v := range handleVals {
    device.handles[v.handle].cachedValue = v.value
  }

  return nil
}

func (this *Manager) DisconnectFrom(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }

  device := this.Devices[idx]

  err := device.fd.Close()
  if err != nil {
    return err
  }

  this.Devices = append(this.Devices[0:idx], this.Devices[idx + 1:]...)
  delete(this.associations, idx)
  for cl,lst := range this.associations {
    for i,v := range lst {
      if v == idx {
        this.associations[cl] = append(lst[0:i], lst[i + 1:]...)
        break
      }
    }
    if len(this.associations) == 0 {
      delete(this.associations, cl)
    }
  }
  return nil
}

func (this *Manager) ServeTo(serverIdx, clientIdx int) error {
  if clientIdx >= len(this.Devices) || serverIdx >= len(this.Devices) {
    return errors.New("No such device")
  }

  if lst,ok := this.associations[clientIdx]; ok {
    this.associations[clientIdx] = append(lst, serverIdx)
  } else {
    this.associations[clientIdx] = []int {serverIdx}
  }

  return nil
}

<commit_msg>Use public BLE address for scans (works with more peripherals).<commit_after>package ble

import (
  "errors"
  "time"
  "io"
  "os"
)

type ManagerRequest struct {
  msg []byte
  device *Device
}

type Manager struct {
  Devices []*Device
  globalHandleOffset int
  associations map[int][]int
  requestChan chan ManagerRequest
  hciSock     *os.File
  log         *os.File
}

func NewManager(hciSock *os.File) (*Manager) {
  f, _ := os.Create("log.csv")
  return &Manager{make([]*Device, 0), 0, make(map[int][]int),
    make(chan ManagerRequest), hciSock, f}
}

func (this *Manager) ConnectTo(addr string) error {
  remoteAddr, err := Str2Ba(addr)
  if err != nil {
    return err
  }

  f, err := NewBLE(NewL2Sockaddr(4, remoteAddr, BDADDR_LE_PUBLIC), addr)
  if err != nil {
    return err
  }

  ci := GetConnInfo(f)

  this.AddDeviceForConn(addr, f, ci)

  return nil
}

func (this *Manager) ConnUpdate(device *Device, interval uint16) int {
  if device.connInfo != nil {
    return HCIConnUpdate(this.hciSock, device.connInfo.HCIHandle, interval, interval, 0, 0x0C80)
  } else {
    return 0
  }
}

func (this *Manager) AddDeviceForConn(addr string, f io.ReadWriteCloser, ci *ConnInfo) (*Device) {
  device := NewDevice(addr, this.requestChan, f, ci)
  this.Devices = append(this.Devices, device)
  return device
}

func (this *Manager) StartNoDiscover(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }

  device := this.Devices[idx]
  return this.StartDeviceNoDiscover(device)
}

func (this *Manager) StartDeviceNoDiscover(device *Device) error {
  device.Start()
  return nil
}

func (this *Manager) Start(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }
  device := this.Devices[idx]
  return this.StartDevice(device)
}

func (this *Manager) StartDevice(device *Device) error {
  device.Start()

  handles, err := DiscoverHandles(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  device.handleOffset = this.globalHandleOffset
  this.globalHandleOffset += len(handles)

  for _, handle := range handles {
    h := &Handle{*handle, time.Now(), nil, nil}
    device.handles[handle.handle] = h
  }

  groupVals, err := DiscoverServices(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  for _,v := range groupVals {
    device.handles[v.handle].cachedValue = v.value
    device.handles[v.handle].endGroup = v.endGroup
  }

  handleVals, err := DiscoverCharacteristics(device)
  if err != nil {
    device.fd.Close()
    return err
  }

  for _,v := range handleVals {
    device.handles[v.handle].cachedValue = v.value
  }

  return nil
}

func (this *Manager) DisconnectFrom(idx int) error {
  if idx >= len(this.Devices) || idx < 0 {
    return errors.New("No such device")
  }

  device := this.Devices[idx]

  err := device.fd.Close()
  if err != nil {
    return err
  }

  this.Devices = append(this.Devices[0:idx], this.Devices[idx + 1:]...)
  delete(this.associations, idx)
  for cl,lst := range this.associations {
    for i,v := range lst {
      if v == idx {
        this.associations[cl] = append(lst[0:i], lst[i + 1:]...)
        break
      }
    }
    if len(this.associations) == 0 {
      delete(this.associations, cl)
    }
  }
  return nil
}

func (this *Manager) ServeTo(serverIdx, clientIdx int) error {
  if clientIdx >= len(this.Devices) || serverIdx >= len(this.Devices) {
    return errors.New("No such device")
  }

  if lst,ok := this.associations[clientIdx]; ok {
    this.associations[clientIdx] = append(lst, serverIdx)
  } else {
    this.associations[clientIdx] = []int {serverIdx}
  }

  return nil
}

<|endoftext|>


<commit_before>package client

import (
	"context"
	"fmt"

	"github.com/keybase/cli"
	"github.com/keybase/client/go/chat/utils"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/chat1"
	"github.com/keybase/client/go/protocol/keybase1"
)

type CmdChatRenameChannel struct {
	g *libkb.GlobalContext

	resolvingRequest chatConversationResolvingRequest
	setTopicName     string
	nonBlock         bool
	team             bool
}

func NewCmdChatRenameChannelRunner(g *libkb.GlobalContext) *CmdChatRenameChannel {
	return &CmdChatRenameChannel{
		g: g,
	}
}

func newCmdChatRenameChannel(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:         "rename-channel",
		Usage:        "Rename a conversation channel",
		ArgumentHelp: "[conversation [new channel name]]",
		Action: func(c *cli.Context) {
			cl.ChooseCommand(NewCmdChatRenameChannelRunner(g), "rename-channel", c)
		},
		Flags: append(getConversationResolverFlags(),
			mustGetChatFlags("set-channel", "nonblock")...),
	}
}

func (c *CmdChatRenameChannel) Run() error {
	c.g.StartStandaloneChat()
	return chatSend(context.TODO(), c.g, ChatSendArg{
		resolvingRequest: c.resolvingRequest,
		setTopicName:     c.setTopicName,
		nonBlock:         c.nonBlock,
		team:             true,
		message:          "",
		setHeadline:      "",
		clearHeadline:    false,
		hasTTY:           true,
	})
}

func (c *CmdChatRenameChannel) ParseArgv(ctx *cli.Context) (err error) {
	c.setTopicName = utils.SanitizeTopicName(ctx.String("set-channel"))
	c.nonBlock = ctx.Bool("nonblock")

	var tlfName string
	if len(ctx.Args()) >= 1 {
		tlfName = ctx.Args().Get(0)
	} else {
		return fmt.Errorf("Must supply team name.")
	}
	if c.resolvingRequest, err = parseConversationResolvingRequest(ctx, tlfName); err != nil {
		return err
	}
	c.resolvingRequest.MembersType = chat1.ConversationMembersType_TEAM
	if c.resolvingRequest.Visibility == keybase1.TLFVisibility_ANY {
		c.resolvingRequest.Visibility = keybase1.TLFVisibility_PRIVATE
	}
	if c.setTopicName == "" {
		return fmt.Errorf("Must supply non-empty channel name.")
	}
	if len(ctx.Args()) > 1 {
		return fmt.Errorf("cannot send text message and set channel name simultaneously")
	}

	return nil
}

func (c *CmdChatRenameChannel) GetUsage() libkb.Usage {
	return libkb.Usage{
		Config: true,
		API:    true,
	}
}
<commit_msg>Contextify<commit_after>package client

import (
	"context"
	"fmt"

	"github.com/keybase/cli"
	"github.com/keybase/client/go/chat/utils"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/chat1"
	"github.com/keybase/client/go/protocol/keybase1"
)

type CmdChatRenameChannel struct {
	libkb.Contextified

	resolvingRequest chatConversationResolvingRequest
	setTopicName     string
	nonBlock         bool
	team             bool
}

func NewCmdChatRenameChannelRunner(g *libkb.GlobalContext) *CmdChatRenameChannel {
	return &CmdChatRenameChannel{Contextified: libkb.NewContextified(g)}
}

func newCmdChatRenameChannel(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
	return cli.Command{
		Name:         "rename-channel",
		Usage:        "Rename a conversation channel",
		ArgumentHelp: "[conversation [new channel name]]",
		Action: func(c *cli.Context) {
			cl.ChooseCommand(NewCmdChatRenameChannelRunner(g), "rename-channel", c)
		},
		Flags: append(getConversationResolverFlags(),
			mustGetChatFlags("set-channel", "nonblock")...),
	}
}

func (c *CmdChatRenameChannel) Run() error {
	c.G().StartStandaloneChat()
	return chatSend(context.TODO(), c.G(), ChatSendArg{
		resolvingRequest: c.resolvingRequest,
		setTopicName:     c.setTopicName,
		nonBlock:         c.nonBlock,
		team:             true,
		message:          "",
		setHeadline:      "",
		clearHeadline:    false,
		hasTTY:           true,
	})
}

func (c *CmdChatRenameChannel) ParseArgv(ctx *cli.Context) (err error) {
	c.setTopicName = utils.SanitizeTopicName(ctx.String("set-channel"))
	c.nonBlock = ctx.Bool("nonblock")

	var tlfName string
	if len(ctx.Args()) >= 1 {
		tlfName = ctx.Args().Get(0)
	} else {
		return fmt.Errorf("Must supply team name.")
	}
	if c.resolvingRequest, err = parseConversationResolvingRequest(ctx, tlfName); err != nil {
		return err
	}
	c.resolvingRequest.MembersType = chat1.ConversationMembersType_TEAM
	if c.resolvingRequest.Visibility == keybase1.TLFVisibility_ANY {
		c.resolvingRequest.Visibility = keybase1.TLFVisibility_PRIVATE
	}
	if c.setTopicName == "" {
		return fmt.Errorf("Must supply non-empty channel name.")
	}
	if len(ctx.Args()) > 1 {
		return fmt.Errorf("cannot send text message and set channel name simultaneously")
	}

	return nil
}

func (c *CmdChatRenameChannel) GetUsage() libkb.Usage {
	return libkb.Usage{
		Config: true,
		API:    true,
	}
}
<|endoftext|>


<commit_before>package instructions

var (
    _aload_0 = &aload_0{}
    _aload_1 = &aload_1{}
    _aload_2 = &aload_2{}
    _aload_3 = &aload_3{}
    _arraylength = &arraylength{}
    _astore_0 = &astore_0{}
    _astore_1 = &astore_1{}
    _astore_2 = &astore_2{}
    _astore_3 = &astore_3{}
    _athrow = &athrow{}
    _d2f = &d2f{}
    _d2i = &d2i{}
    _d2l = &d2l{}
    _dcmpg = &dcmpg{}
    _dcmpl = &dcmpl{}
    _dload_0 = &dload_0{}
    _dload_1 = &dload_1{}
    _dload_2 = &dload_2{}
    _dload_3 = &dload_3{}
    _dstore_0 = &dstore_0{}
    _dstore_1 = &dstore_1{}
    _dstore_2 = &dstore_2{}
    _dstore_3 = &dstore_3{}
    _dup = &dup{}
    _dup_x1 = &dup_x1{}
    _dup_x2 = &dup_x2{}
    _dup2 = &dup2{}
    _dup2_x1 = &dup2_x1{}
    _dup2_x2 = &dup2_x2{}
)

func Decode(bcr *BytecodeReader) (Instruction) {
    opcode := bcr.readUint8()
    instruction := newInstruction(opcode)
    instruction.fetchOperands(bcr)
    return instruction
}

func newInstruction(opcode byte) (Instruction) {
    switch opcode {
    case 0x00: return &nop{}
    case 0x01: return &aconst_null{}
    case 0x02: return &iconst_m1{}
    case 0x03: return &iconst_0{}
    case 0x04: return &iconst_1{}
    case 0x05: return &iconst_2{}
    case 0x06: return &iconst_3{}
    case 0x07: return &iconst_4{}
    case 0x08: return &iconst_5{}
    case 0x09: return &lconst_0{}
    case 0x0a: return &lconst_1{}
    case 0x0b: return &fconst_0{}
    case 0x0c: return &fconst_1{}
    case 0x0d: return &fconst_2{}
    case 0x0e: return &dconst_0{}
    case 0x0f: return &dconst_1{}
    case 0x10: return &bipush{}
    case 0x11: return &sipush{}
    case 0x12: return &ldc{}
    case 0x13: return &ldc_w{}
    case 0x14: return &ldc2_w{}
    case 0x15: return &iload{}
    case 0x16: return &lload{}
    case 0x17: return &fload{}
    case 0x18: return &dload{}
    case 0x19: return &aload{}
    case 0x1a: return &iload_0{}
    case 0x1b: return &iload_1{}
    case 0x1c: return &iload_2{}
    case 0x1d: return &iload_3{}
    case 0x1e: return &lload_0{}
    case 0x1f: return &lload_1{}
    case 0x20: return &lload_2{}
    case 0x21: return &lload_3{}
    case 0x22: return &fload_0{}
    case 0x23: return &fload_1{}
    case 0x24: return &fload_2{}
    case 0x25: return &fload_3{}
    case 0x26: return _dload_0
    case 0x27: return _dload_1
    case 0x28: return _dload_2
    case 0x29: return _dload_3
    case 0x2a: return _aload_0
    case 0x2b: return _aload_1
    case 0x2c: return _aload_2
    case 0x2d: return _aload_3
    case 0x2e: return &iaload{}
    case 0x2f: return &laload{}
    case 0x30: return &faload{}
    case 0x31: return &daload{}
    case 0x32: return &aaload{}
    case 0x33: return &baload{}
    case 0x34: return &caload{}
    case 0x35: return &saload{}
    case 0x36: return &istore{}
    case 0x37: return &lstore{}
    case 0x38: return &fstore{}
    case 0x39: return &dstore{}
    case 0x3a: return &astore{}
    case 0x3b: return &istore_0{}
    case 0x3c: return &istore_1{}
    case 0x3d: return &istore_2{}
    case 0x3e: return &istore_3{}
    case 0x3f: return &lstore_0{}
    case 0x40: return &lstore_1{}
    case 0x41: return &lstore_2{}
    case 0x42: return &lstore_3{}
    case 0x43: return &fstore_0{}
    case 0x44: return &fstore_1{}
    case 0x45: return &fstore_2{}
    case 0x46: return &fstore_3{}
    case 0x47: return _dstore_0
    case 0x48: return _dstore_1
    case 0x49: return _dstore_2
    case 0x4a: return _dstore_3
    case 0x4b: return _astore_0
    case 0x4c: return _astore_1
    case 0x4d: return _astore_2
    case 0x4e: return _astore_3
    case 0x4f: return &iastore{}
    case 0x50: return &lastore{}
    case 0x51: return &fastore{}
    case 0x52: return &dastore{}
    case 0x53: return &aastore{}
    case 0x54: return &bastore{}
    case 0x55: return &castore{}
    case 0x56: return &sastore{}
    case 0x57: return &pop{}
    case 0x58: return &pop2{}
    case 0x59: return _dup
    case 0x5a: return _dup_x1
    case 0x5b: return _dup_x2
    case 0x5c: return _dup2
    case 0x5d: return _dup2_x1
    case 0x5e: return _dup2_x2
    case 0x5f: return &swap{}
    case 0x60: return &iadd{}
    case 0x61: return &ladd{}
    case 0x62: return &fadd{}
    case 0x63: return &dadd{}
    case 0x64: return &isub{}
    case 0x65: return &lsub{}
    case 0x66: return &fsub{}
    case 0x67: return &dsub{}
    case 0x68: return &imul{}
    case 0x69: return &lmul{}
    case 0x6a: return &fmul{}
    case 0x6b: return &dmul{}
    case 0x6c: return &idiv{}
    case 0x6d: return &ldiv{}
    case 0x6e: return &fdiv{}
    case 0x6f: return &ddiv{}
    case 0x70: return &irem{}
    case 0x71: return &lrem{}
    case 0x72: return &frem{}
    case 0x73: return &drem{}
    case 0x74: return &ineg{}
    case 0x75: return &lneg{}
    case 0x76: return &fneg{}
    case 0x77: return &dneg{}
    case 0x78: return &ishl{}
    case 0x79: return &lshl{}
    case 0x7a: return &ishr{}
    case 0x7b: return &lshr{}
    case 0x7c: return &iushr{}
    case 0x7d: return &lushr{}
    case 0x7e: return &iand{}
    case 0x7f: return &land{}
    case 0x80: return &ior{}
    case 0x81: return &lor{}
    case 0x82: return &ixor{}
    case 0x83: return &lxor{}
    case 0x84: return &iinc{}
    case 0x85: return &i2l{}
    case 0x86: return &i2f{}
    case 0x87: return &i2d{}
    case 0x88: return &l2i{}
    case 0x89: return &l2f{}
    case 0x8a: return &l2d{}
    case 0x8b: return &f2i{}
    case 0x8c: return &f2l{}
    case 0x8d: return &f2d{}
    case 0x8e: return _d2i
    case 0x8f: return _d2l
    case 0x90: return _d2f
    case 0x91: return &i2b{}
    case 0x92: return &i2c{}
    case 0x93: return &i2s{}
    case 0x94: return &lcmp{}
    case 0x95: return &fcmpl{}
    case 0x96: return &fcmpg{}
    case 0x97: return _dcmpl
    case 0x98: return _dcmpg
    case 0x99: return &ifeq{}
    case 0x9a: return &ifne{}
    case 0x9b: return &iflt{}
    case 0x9c: return &ifge{}
    case 0x9d: return &ifgt{}
    case 0x9e: return &ifle{}
    case 0x9f: return &if_icmpeq{}
    case 0xa0: return &if_icmpne{}
    case 0xa1: return &if_icmplt{}
    case 0xa2: return &if_icmpge{}
    case 0xa3: return &if_icmpgt{}
    case 0xa4: return &if_icmple{}
    case 0xa5: return &if_acmpeq{}
    case 0xa6: return &if_acmpne{}
    case 0xa7: return &_goto{}
  //case 0xa8: return &jsr{}
  //case 0xa9: return &ret{}
    case 0xaa: return &tableswitch{}
    case 0xab: return &lookupswitch{}
    case 0xac: return &ireturn{}
    case 0xad: return &lreturn{}
    case 0xae: return &freturn{}
    case 0xaf: return &dreturn{}
    case 0xb0: return &areturn{}
    case 0xb1: return &_return{}
    case 0xb2: return &getstatic{}
    case 0xb3: return &putstatic{}
    case 0xb4: return &getfield{}
    case 0xb5: return &putfield{}
    case 0xb6: return &invokevirtual{}
    case 0xb7: return &invokespecial{}
    case 0xb8: return &invokestatic{}
    case 0xb9: return &invokeinterface{}
    case 0xba: return &invokedynamic{}
    case 0xbb: return &_new{}
    case 0xbc: return &newarray{}
    case 0xbd: return &anewarray{}
    case 0xbe: return _arraylength
    case 0xbf: return _athrow
    case 0xc0: return &checkcast{}
    case 0xc1: return &instanceof{}
    case 0xc2: return &monitorenter{}
    case 0xc3: return &monitorexit{}
    case 0xc5: return &multianewarray{}
    case 0xc6: return &ifnull{}
    case 0xc7: return &ifnonnull{}
    case 0xc8: return &goto_w{}
  //case 0xc9: return &jsr_w{}
  //case 0xca: return &breakpoint{}
  //case 0xfe: return &impdep1{}
  //case 0xff: return &impdep2{}
    // todo
    default: panic("BAD opcode!")
    }
}
<commit_msg>optimize<commit_after>package instructions

var (
    _aload_0 = &aload_0{}
    _aload_1 = &aload_1{}
    _aload_2 = &aload_2{}
    _aload_3 = &aload_3{}
    _arraylength = &arraylength{}
    _astore_0 = &astore_0{}
    _astore_1 = &astore_1{}
    _astore_2 = &astore_2{}
    _astore_3 = &astore_3{}
    _athrow = &athrow{}
    _d2f = &d2f{}
    _d2i = &d2i{}
    _d2l = &d2l{}
    _dcmpg = &dcmpg{}
    _dcmpl = &dcmpl{}
    _dload_0 = &dload_0{}
    _dload_1 = &dload_1{}
    _dload_2 = &dload_2{}
    _dload_3 = &dload_3{}
    _dstore_0 = &dstore_0{}
    _dstore_1 = &dstore_1{}
    _dstore_2 = &dstore_2{}
    _dstore_3 = &dstore_3{}
    _dup = &dup{}
    _dup_x1 = &dup_x1{}
    _dup_x2 = &dup_x2{}
    _dup2 = &dup2{}
    _dup2_x1 = &dup2_x1{}
    _dup2_x2 = &dup2_x2{}
    _f2d = &f2d{}
    _f2i = &f2i{}
    _f2l = &f2l{}
)

func Decode(bcr *BytecodeReader) (Instruction) {
    opcode := bcr.readUint8()
    instruction := newInstruction(opcode)
    instruction.fetchOperands(bcr)
    return instruction
}

func newInstruction(opcode byte) (Instruction) {
    switch opcode {
    case 0x00: return &nop{}
    case 0x01: return &aconst_null{}
    case 0x02: return &iconst_m1{}
    case 0x03: return &iconst_0{}
    case 0x04: return &iconst_1{}
    case 0x05: return &iconst_2{}
    case 0x06: return &iconst_3{}
    case 0x07: return &iconst_4{}
    case 0x08: return &iconst_5{}
    case 0x09: return &lconst_0{}
    case 0x0a: return &lconst_1{}
    case 0x0b: return &fconst_0{}
    case 0x0c: return &fconst_1{}
    case 0x0d: return &fconst_2{}
    case 0x0e: return &dconst_0{}
    case 0x0f: return &dconst_1{}
    case 0x10: return &bipush{}
    case 0x11: return &sipush{}
    case 0x12: return &ldc{}
    case 0x13: return &ldc_w{}
    case 0x14: return &ldc2_w{}
    case 0x15: return &iload{}
    case 0x16: return &lload{}
    case 0x17: return &fload{}
    case 0x18: return &dload{}
    case 0x19: return &aload{}
    case 0x1a: return &iload_0{}
    case 0x1b: return &iload_1{}
    case 0x1c: return &iload_2{}
    case 0x1d: return &iload_3{}
    case 0x1e: return &lload_0{}
    case 0x1f: return &lload_1{}
    case 0x20: return &lload_2{}
    case 0x21: return &lload_3{}
    case 0x22: return &fload_0{}
    case 0x23: return &fload_1{}
    case 0x24: return &fload_2{}
    case 0x25: return &fload_3{}
    case 0x26: return _dload_0
    case 0x27: return _dload_1
    case 0x28: return _dload_2
    case 0x29: return _dload_3
    case 0x2a: return _aload_0
    case 0x2b: return _aload_1
    case 0x2c: return _aload_2
    case 0x2d: return _aload_3
    case 0x2e: return &iaload{}
    case 0x2f: return &laload{}
    case 0x30: return &faload{}
    case 0x31: return &daload{}
    case 0x32: return &aaload{}
    case 0x33: return &baload{}
    case 0x34: return &caload{}
    case 0x35: return &saload{}
    case 0x36: return &istore{}
    case 0x37: return &lstore{}
    case 0x38: return &fstore{}
    case 0x39: return &dstore{}
    case 0x3a: return &astore{}
    case 0x3b: return &istore_0{}
    case 0x3c: return &istore_1{}
    case 0x3d: return &istore_2{}
    case 0x3e: return &istore_3{}
    case 0x3f: return &lstore_0{}
    case 0x40: return &lstore_1{}
    case 0x41: return &lstore_2{}
    case 0x42: return &lstore_3{}
    case 0x43: return &fstore_0{}
    case 0x44: return &fstore_1{}
    case 0x45: return &fstore_2{}
    case 0x46: return &fstore_3{}
    case 0x47: return _dstore_0
    case 0x48: return _dstore_1
    case 0x49: return _dstore_2
    case 0x4a: return _dstore_3
    case 0x4b: return _astore_0
    case 0x4c: return _astore_1
    case 0x4d: return _astore_2
    case 0x4e: return _astore_3
    case 0x4f: return &iastore{}
    case 0x50: return &lastore{}
    case 0x51: return &fastore{}
    case 0x52: return &dastore{}
    case 0x53: return &aastore{}
    case 0x54: return &bastore{}
    case 0x55: return &castore{}
    case 0x56: return &sastore{}
    case 0x57: return &pop{}
    case 0x58: return &pop2{}
    case 0x59: return _dup
    case 0x5a: return _dup_x1
    case 0x5b: return _dup_x2
    case 0x5c: return _dup2
    case 0x5d: return _dup2_x1
    case 0x5e: return _dup2_x2
    case 0x5f: return &swap{}
    case 0x60: return &iadd{}
    case 0x61: return &ladd{}
    case 0x62: return &fadd{}
    case 0x63: return &dadd{}
    case 0x64: return &isub{}
    case 0x65: return &lsub{}
    case 0x66: return &fsub{}
    case 0x67: return &dsub{}
    case 0x68: return &imul{}
    case 0x69: return &lmul{}
    case 0x6a: return &fmul{}
    case 0x6b: return &dmul{}
    case 0x6c: return &idiv{}
    case 0x6d: return &ldiv{}
    case 0x6e: return &fdiv{}
    case 0x6f: return &ddiv{}
    case 0x70: return &irem{}
    case 0x71: return &lrem{}
    case 0x72: return &frem{}
    case 0x73: return &drem{}
    case 0x74: return &ineg{}
    case 0x75: return &lneg{}
    case 0x76: return &fneg{}
    case 0x77: return &dneg{}
    case 0x78: return &ishl{}
    case 0x79: return &lshl{}
    case 0x7a: return &ishr{}
    case 0x7b: return &lshr{}
    case 0x7c: return &iushr{}
    case 0x7d: return &lushr{}
    case 0x7e: return &iand{}
    case 0x7f: return &land{}
    case 0x80: return &ior{}
    case 0x81: return &lor{}
    case 0x82: return &ixor{}
    case 0x83: return &lxor{}
    case 0x84: return &iinc{}
    case 0x85: return &i2l{}
    case 0x86: return &i2f{}
    case 0x87: return &i2d{}
    case 0x88: return &l2i{}
    case 0x89: return &l2f{}
    case 0x8a: return &l2d{}
    case 0x8b: return _f2i
    case 0x8c: return _f2l
    case 0x8d: return _f2d
    case 0x8e: return _d2i
    case 0x8f: return _d2l
    case 0x90: return _d2f
    case 0x91: return &i2b{}
    case 0x92: return &i2c{}
    case 0x93: return &i2s{}
    case 0x94: return &lcmp{}
    case 0x95: return &fcmpl{}
    case 0x96: return &fcmpg{}
    case 0x97: return _dcmpl
    case 0x98: return _dcmpg
    case 0x99: return &ifeq{}
    case 0x9a: return &ifne{}
    case 0x9b: return &iflt{}
    case 0x9c: return &ifge{}
    case 0x9d: return &ifgt{}
    case 0x9e: return &ifle{}
    case 0x9f: return &if_icmpeq{}
    case 0xa0: return &if_icmpne{}
    case 0xa1: return &if_icmplt{}
    case 0xa2: return &if_icmpge{}
    case 0xa3: return &if_icmpgt{}
    case 0xa4: return &if_icmple{}
    case 0xa5: return &if_acmpeq{}
    case 0xa6: return &if_acmpne{}
    case 0xa7: return &_goto{}
  //case 0xa8: return &jsr{}
  //case 0xa9: return &ret{}
    case 0xaa: return &tableswitch{}
    case 0xab: return &lookupswitch{}
    case 0xac: return &ireturn{}
    case 0xad: return &lreturn{}
    case 0xae: return &freturn{}
    case 0xaf: return &dreturn{}
    case 0xb0: return &areturn{}
    case 0xb1: return &_return{}
    case 0xb2: return &getstatic{}
    case 0xb3: return &putstatic{}
    case 0xb4: return &getfield{}
    case 0xb5: return &putfield{}
    case 0xb6: return &invokevirtual{}
    case 0xb7: return &invokespecial{}
    case 0xb8: return &invokestatic{}
    case 0xb9: return &invokeinterface{}
    case 0xba: return &invokedynamic{}
    case 0xbb: return &_new{}
    case 0xbc: return &newarray{}
    case 0xbd: return &anewarray{}
    case 0xbe: return _arraylength
    case 0xbf: return _athrow
    case 0xc0: return &checkcast{}
    case 0xc1: return &instanceof{}
    case 0xc2: return &monitorenter{}
    case 0xc3: return &monitorexit{}
    case 0xc5: return &multianewarray{}
    case 0xc6: return &ifnull{}
    case 0xc7: return &ifnonnull{}
    case 0xc8: return &goto_w{}
  //case 0xc9: return &jsr_w{}
  //case 0xca: return &breakpoint{}
  //case 0xfe: return &impdep1{}
  //case 0xff: return &impdep2{}
    // todo
    default: panic("BAD opcode!")
    }
}
<|endoftext|>


<commit_before>package arn

import (
	"errors"

	"github.com/aerogo/nano"
)

// Company represents an anime studio, producer or licensor.
type Company struct {
	Name        CompanyName `json:"name" editable:"true"`
	Description string      `json:"description" editable:"true" type:"textarea"`
	Links       []*Link     `json:"links" editable:"true"`

	// Mixins
	HasID
	HasMappings
	HasLikes
	HasDraft

	// Other editable fields
	Location *Location `json:"location" editable:"true"`
	Tags     []string  `json:"tags" editable:"true"`

	// Editing dates
	HasCreator
	HasEditor
}

// NewCompany creates a new company.
func NewCompany() *Company {
	return &Company{
		HasID: HasID{
			ID: GenerateID("Company"),
		},
		Name:  CompanyName{},
		Links: []*Link{},
		Tags:  []string{},
		HasCreator: HasCreator{
			Created: DateTimeUTC(),
		},
		HasLikes: HasLikes{
			Likes: []string{},
		},
		HasMappings: HasMappings{
			Mappings: []*Mapping{},
		},
	}
}

// Link returns a single company.
func (company *Company) Link() string {
	return "/company/" + company.ID
}

// Creator returns the user who created this company.
func (company *Company) Creator() *User {
	user, _ := GetUser(company.CreatedBy)
	return user
}

// Anime returns the anime connected with this company.
func (company *Company) Anime() (studioAnime []*Anime, producedAnime []*Anime, licensedAnime []*Anime) {
	for anime := range StreamAnime() {
		if Contains(anime.StudioIDs, company.ID) {
			studioAnime = append(studioAnime, anime)
		}

		if Contains(anime.ProducerIDs, company.ID) {
			producedAnime = append(producedAnime, anime)
		}

		if Contains(anime.LicensorIDs, company.ID) {
			licensedAnime = append(licensedAnime, anime)
		}
	}

	SortAnimeByQuality(studioAnime)
	SortAnimeByQuality(producedAnime)
	SortAnimeByQuality(licensedAnime)

	return studioAnime, producedAnime, licensedAnime
}

// Publish publishes the company draft.
func (company *Company) Publish() error {
	// No title
	if company.Name.English == "" {
		return errors.New("No English company name")
	}

	return publish(company)
}

// Unpublish turns the company into a draft.
func (company *Company) Unpublish() error {
	return unpublish(company)
}

// String implements the default string serialization.
func (company *Company) String() string {
	return company.Name.English
}

// GetCompany returns a single company.
func GetCompany(id string) (*Company, error) {
	obj, err := DB.Get("Company", id)

	if err != nil {
		return nil, err
	}

	return obj.(*Company), nil
}

// StreamCompanies returns a stream of all companies.
func StreamCompanies() chan *Company {
	channel := make(chan *Company, nano.ChannelBufferSize)

	go func() {
		for obj := range DB.All("Company") {
			channel <- obj.(*Company)
		}

		close(channel)
	}()

	return channel
}

// FilterCompanies filters all companies by a custom function.
func FilterCompanies(filter func(*Company) bool) []*Company {
	var filtered []*Company

	channel := DB.All("Company")

	for obj := range channel {
		realObject := obj.(*Company)

		if filter(realObject) {
			filtered = append(filtered, realObject)
		}
	}

	return filtered
}

// AllCompanies returns a slice of all companies.
func AllCompanies() []*Company {
	var all []*Company

	stream := StreamCompanies()

	for obj := range stream {
		all = append(all, obj)
	}

	return all
}
<commit_msg>Add editable email field to Company<commit_after>package arn

import (
	"errors"

	"github.com/aerogo/nano"
)

// Company represents an anime studio, producer or licensor.
type Company struct {
	Name        CompanyName `json:"name" editable:"true"`
	Description string      `json:"description" editable:"true" type:"textarea"`
	Links       []*Link     `json:"links" editable:"true"`

	// Mixins
	HasID
	HasMappings
	HasLikes
	HasDraft

	// Other editable fields
	Location *Location `json:"location" editable:"true"`
	Tags     []string  `json:"tags" editable:"true"`
	Email    string    `json:"email" editable:"true"`

	// Editing dates
	HasCreator
	HasEditor
}

// NewCompany creates a new company.
func NewCompany() *Company {
	return &Company{
		HasID: HasID{
			ID: GenerateID("Company"),
		},
		Name:  CompanyName{},
		Links: []*Link{},
		Tags:  []string{},
		HasCreator: HasCreator{
			Created: DateTimeUTC(),
		},
		HasLikes: HasLikes{
			Likes: []string{},
		},
		HasMappings: HasMappings{
			Mappings: []*Mapping{},
		},
	}
}

// Link returns a single company.
func (company *Company) Link() string {
	return "/company/" + company.ID
}

// Creator returns the user who created this company.
func (company *Company) Creator() *User {
	user, _ := GetUser(company.CreatedBy)
	return user
}

// Anime returns the anime connected with this company.
func (company *Company) Anime() (studioAnime []*Anime, producedAnime []*Anime, licensedAnime []*Anime) {
	for anime := range StreamAnime() {
		if Contains(anime.StudioIDs, company.ID) {
			studioAnime = append(studioAnime, anime)
		}

		if Contains(anime.ProducerIDs, company.ID) {
			producedAnime = append(producedAnime, anime)
		}

		if Contains(anime.LicensorIDs, company.ID) {
			licensedAnime = append(licensedAnime, anime)
		}
	}

	SortAnimeByQuality(studioAnime)
	SortAnimeByQuality(producedAnime)
	SortAnimeByQuality(licensedAnime)

	return studioAnime, producedAnime, licensedAnime
}

// Publish publishes the company draft.
func (company *Company) Publish() error {
	// No title
	if company.Name.English == "" {
		return errors.New("No English company name")
	}

	return publish(company)
}

// Unpublish turns the company into a draft.
func (company *Company) Unpublish() error {
	return unpublish(company)
}

// String implements the default string serialization.
func (company *Company) String() string {
	return company.Name.English
}

// GetCompany returns a single company.
func GetCompany(id string) (*Company, error) {
	obj, err := DB.Get("Company", id)

	if err != nil {
		return nil, err
	}

	return obj.(*Company), nil
}

// StreamCompanies returns a stream of all companies.
func StreamCompanies() chan *Company {
	channel := make(chan *Company, nano.ChannelBufferSize)

	go func() {
		for obj := range DB.All("Company") {
			channel <- obj.(*Company)
		}

		close(channel)
	}()

	return channel
}

// FilterCompanies filters all companies by a custom function.
func FilterCompanies(filter func(*Company) bool) []*Company {
	var filtered []*Company

	channel := DB.All("Company")

	for obj := range channel {
		realObject := obj.(*Company)

		if filter(realObject) {
			filtered = append(filtered, realObject)
		}
	}

	return filtered
}

// AllCompanies returns a slice of all companies.
func AllCompanies() []*Company {
	var all []*Company

	stream := StreamCompanies()

	for obj := range stream {
		all = append(all, obj)
	}

	return all
}
<|endoftext|>


<commit_before>package xmmsclient

import (
	"bytes"
	"encoding/hex"
	"reflect"
	"testing"
)

func checkBuffer(t *testing.T, expected []byte, actual []byte) {
	if !reflect.DeepEqual(expected, actual) {
		t.Fatalf("\nwant:\n%s\nhave:\n%s", hex.Dump(expected), hex.Dump(actual))
	}
}

func TestSerializeInt(t *testing.T) {
	var expected = []byte{
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a,
	}
	var buffer bytes.Buffer

	var err = SerializeXmmsValue(XmmsInt(42), &buffer)
	if err != nil {
		t.Fatal(err)
	}

	checkBuffer(t, expected, buffer.Bytes())
}
<commit_msg>Add more tests.<commit_after>package xmmsclient

import (
	"bytes"
	"encoding/hex"
	"reflect"
	"testing"
)

func checkBuffer(t *testing.T, expected []byte, actual []byte) {
	if !reflect.DeepEqual(expected, actual) {
		t.Fatalf("\nwant:\n%s\nhave:\n%s", hex.Dump(expected), hex.Dump(actual))
	}
}

func TestSerializeInt(t *testing.T) {
	var expected = []byte{
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a,
	}
	var buffer bytes.Buffer

	var err = SerializeXmmsValue(XmmsInt(42), &buffer)
	if err != nil {
		t.Fatal(err)
	}

	checkBuffer(t, expected, buffer.Bytes())
}

func TestSerializeString(t *testing.T) {
	var expected = []byte{
		0x00, 0x00, 0x00, 0x03,
		0x00, 0x00, 0x00, 0x05,
		0x74, 0x65, 0x73, 0x74, 0x00,
	}
	var buffer bytes.Buffer

	var err = SerializeXmmsValue(XmmsString("test"), &buffer)
	if err != nil {
		t.Fatal(err)
	}

	checkBuffer(t, expected, buffer.Bytes())
}

func TestSerializeList(t *testing.T) {
	var expected = []byte{
		0x00, 0x00, 0x00, 0x06,
		0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a,
		0x00, 0x00, 0x00, 0x03,
		0x00, 0x00, 0x00, 0x05,
		0x74, 0x65, 0x73, 0x74, 0x00,
	}
	var buffer bytes.Buffer

	var err = SerializeXmmsValue(NewXmmsList(XmmsInt(42), XmmsString("test")), &buffer)
	if err != nil {
		t.Fatal(err)
	}

	checkBuffer(t, expected, buffer.Bytes())
}

/* No sorted map in Go, need some other testing strategy
func TestSerializeDict(t *testing.T) {
	var expected = []byte{
		0x00, 0x00, 0x00, 0x07,
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x04,
		0x69, 0x6e, 0x74, 0x00,
		0x00, 0x00, 0x00, 0x02,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a,
		0x00, 0x00, 0x00, 0x04,
		0x73, 0x74, 0x72, 0x00,
		0x00, 0x00, 0x00, 0x03,
		0x00, 0x00, 0x00, 0x05,
		0x74, 0x65, 0x73, 0x74, 0x00,
	}
	var buffer bytes.Buffer

	var err = SerializeXmmsValue(XmmsDict{"int": XmmsInt(42), "str": XmmsString("test")}, &buffer)
	if err != nil {
		t.Fatal(err)
	}

	checkBuffer(t, expected, buffer.Bytes())
}
*/
<|endoftext|>


<commit_before>// Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package img

import (
	"errors"
)

func flashWindows(imgPath, disk string) error {
	return errors.New("Flash() is not implemented on Windows")
}

func mountWindows(disk string, n int) (string, error) {
	return "", errors.New("Mount() is not implemented on Windows")
}

func umountWindows(disk string) error {
	return errors.New("Umount() is not implemented on Windows")
}

func listSDCardsWindows() []string {
	return nil
}
<commit_msg>img: Implement listSDCardsWindows() on Windows<commit_after>// Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package img

import (
	"errors"
	"strings"
)

func flashWindows(imgPath, disk string) error {
	return errors.New("Flash() is not implemented on Windows")
}

func mountWindows(disk string, n int) (string, error) {
	return "", errors.New("Mount() is not implemented on Windows")
}

func umountWindows(disk string) error {
	return errors.New("Umount() is not implemented on Windows")
}

func listSDCardsWindows() []string {
	var out []string
	for _, disk := range wmicListDisks() {
		if disk["MediaLoaded"] == "TRUE" && disk["MediaType"] == "Removable Media" {
			out = append(out, disk["DeviceID"])
		}
	}
	return out
}

func wmicListDisks() []map[string]string {
	// TODO(maruel): It'd be nicer to use the Win32 APIs but shelling out will be
	// good enough for now. Shelling out permits to not have to do COM/WMI.
	// In theory, /format:xml would produce an output meant to be mechanically
	// parsed, in practice the output is suboptimal.
	b, err := capture("", "wmic", "diskdrive", "list")
	if err != nil || len(b) == 0 {
		return nil
	}
	s := strings.Replace(string(b), "\r", "", -1)
	lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
	type col struct {
		start, end int
		name       string
	}
	var cols []col
	l := lines[0]
	for i := 0; i < len(l); {
		end := strings.IndexByte(l[i:], ' ')
		if end == -1 {
			// Last column.
			end = len(l)
		} else {
			for end += i; end < len(l) && l[end] == ' '; end++ {
			}
		}
		name := strings.TrimSpace(l[i:end])
		if name == "" {
			break
		}
		cols = append(cols, col{i, end, name})
		i = end
	}
	var out []map[string]string
	for i := 1; i < len(lines); i++ {
		m := map[string]string{}
		for _, c := range cols {
			m[c.name] = strings.TrimSpace(lines[i][c.start:c.end])
		}
		out = append(out, m)
	}
	return out
}
<|endoftext|>


<commit_before>package influxql

import (
	"fmt"
	"sort"
	"strconv"
	"time"

	"github.com/influxdata/flux"
	"github.com/influxdata/flux/execute"
	"github.com/influxdata/flux/values"
)

// responseIterator implements flux.ResultIterator for a Response.
type responseIterator struct {
	response  *Response
	resultIdx int
}

// NewresponseIterator constructs a responseIterator from a flux.ResultIterator.
func NewResponseIterator(r *Response) flux.ResultIterator {
	return &responseIterator{
		response: r,
	}
}

// More returns true if there are results left to iterate through.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) More() bool {
	return r.resultIdx < len(r.response.Results)
}

// Next retrieves the next flux.Result.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Next() flux.Result {
	res := r.response.Results[r.resultIdx]
	r.resultIdx++
	return newQueryResult(&res)
}

// Release is a noop.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Release() {}

// Err returns an error if the response contained an error.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Err() error {
	if r.response.Err != "" {
		return fmt.Errorf(r.response.Err)
	}

	return nil
}

// seriesIterator is a simple wrapper for Result that implements flux.Result and flux.TableIterator.
type seriesIterator struct {
	result *Result
}

func newQueryResult(r *Result) *seriesIterator {
	return &seriesIterator{
		result: r,
	}
}

// Name returns the results statement id.
// It is used to implement flux.Result.
func (r *seriesIterator) Name() string {
	return strconv.Itoa(r.result.StatementID)
}

// Tables returns the original as a flux.TableIterator.
// It is used to implement flux.Result.
func (r *seriesIterator) Tables() flux.TableIterator {
	return r
}

// Do iterates through the series of a Result.
// It is used to implement flux.TableIterator.
func (r *seriesIterator) Do(f func(flux.Table) error) error {
	for _, row := range r.result.Series {
		t, err := newQueryTable(row)
		if err != nil {
			return err
		}
		if err := f(t); err != nil {
			return err
		}
	}

	return nil
}

// queryTable implements flux.Table and flux.ColReader.
type queryTable struct {
	row      *Row
	groupKey flux.GroupKey
	colMeta  []flux.ColMeta
	cols     []interface{}
}

func newQueryTable(r *Row) (*queryTable, error) {
	t := &queryTable{
		row: r,
	}
	if err := t.translateRowsToColumns(); err != nil {
		return nil, err
	}
	return t, nil
}

// Data in a column is laid out in the following way:
//   [ r.row.Columns... , r.tagKeys()... , r.row.Name ]
func (t *queryTable) translateRowsToColumns() error {
	cols := t.Cols()
	t.cols = make([]interface{}, len(cols))
	for i, col := range cols {
		switch col.Type {
		case flux.TFloat:
			t.cols[i] = make([]float64, 0, t.Len())
		case flux.TInt:
			t.cols[i] = make([]int64, 0, t.Len())
		case flux.TUInt:
			t.cols[i] = make([]uint64, 0, t.Len())
		case flux.TString:
			t.cols[i] = make([]string, 0, t.Len())
		case flux.TBool:
			t.cols[i] = make([]bool, 0, t.Len())
		case flux.TTime:
			t.cols[i] = make([]values.Time, 0, t.Len())
		}
	}
	for _, els := range t.row.Values {
		for i, el := range els {
			col := cols[i]
			switch col.Type {
			case flux.TFloat:
				val, ok := el.(float64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]float64), val)
			case flux.TInt:
				val, ok := el.(int64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]int64), val)
			case flux.TUInt:
				val, ok := el.(uint64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]uint64), val)
			case flux.TString:
				val, ok := el.(string)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]string), val)
			case flux.TBool:
				val, ok := el.(bool)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]bool), val)
			case flux.TTime:
				switch val := el.(type) {
				case int64:
					t.cols[i] = append(t.cols[i].([]values.Time), values.Time(val))
				case float64:
					t.cols[i] = append(t.cols[i].([]values.Time), values.Time(val))
				case string:
					tm, err := time.Parse(time.RFC3339, val)
					if err != nil {
						return fmt.Errorf("could not parse string %q as time: %v", val, err)
					}
					t.cols[i] = append(t.cols[i].([]values.Time), values.ConvertTime(tm))
				default:
					return fmt.Errorf("unsupported type %T found in column %s", val, col.Label)
				}
			default:
				return fmt.Errorf("invalid type %T found in column %s", el, col.Label)
			}
		}

		j := len(t.row.Columns)
		for j < len(t.row.Columns)+len(t.row.Tags) {
			col := cols[j]
			t.cols[j] = append(t.cols[j].([]string), t.row.Tags[col.Label])
			j++
		}

		t.cols[j] = append(t.cols[j].([]string), t.row.Name)
	}

	return nil
}

// Key constructs the flux.GroupKey for a Row from the rows
// tags and measurement.
// It is used to implement flux.Table and flux.ColReader.
func (r *queryTable) Key() flux.GroupKey {
	if r.groupKey == nil {
		cols := make([]flux.ColMeta, len(r.row.Tags)+1) // plus one is for measurement
		vs := make([]values.Value, len(r.row.Tags)+1)
		kvs := make([]interface{}, len(r.row.Tags)+1)
		colMeta := r.Cols()
		labels := append(r.tagKeys(), "_measurement")
		for j, label := range labels {
			idx := execute.ColIdx(label, colMeta)
			if idx < 0 {
				panic(fmt.Errorf("table invalid: missing group column %q", label))
			}
			cols[j] = colMeta[idx]
			kvs[j] = "string"
			v := values.New(kvs[j])
			if v == values.InvalidValue {
				panic(fmt.Sprintf("unsupported value kind %T", kvs[j]))
			}
			vs[j] = v
		}
		r.groupKey = execute.NewGroupKey(cols, vs)
	}

	return r.groupKey
}

// tags returns the tag keys for a Row.
func (r *queryTable) tagKeys() []string {
	tags := []string{}
	for t := range r.row.Tags {
		tags = append(tags, t)
	}
	sort.Strings(tags)
	return tags
}

// Cols returns the columns for a row where the data is laid out in the following way:
//   [ r.row.Columns... , r.tagKeys()... , r.row.Name ]
// It is used to implement flux.Table and flux.ColReader.
func (r *queryTable) Cols() []flux.ColMeta {
	if r.colMeta == nil {
		colMeta := make([]flux.ColMeta, len(r.row.Columns)+len(r.row.Tags)+1)
		for i, col := range r.row.Columns {
			colMeta[i] = flux.ColMeta{
				Label: col,
				Type:  flux.TInvalid,
			}
			if col == "time" {
				// rename the time column
				colMeta[i].Label = "_time"
				colMeta[i].Type = flux.TTime
			}
		}

		if len(r.row.Values) < 1 {
			panic("must have at least one value")
		}
		data := r.row.Values[0]
		for i := range r.row.Columns {
			v := data[i]
			if colMeta[i].Label == "_time" {
				continue
			}
			switch v.(type) {
			case float64:
				colMeta[i].Type = flux.TFloat
			case int64:
				colMeta[i].Type = flux.TInt
			case uint64:
				colMeta[i].Type = flux.TUInt
			case bool:
				colMeta[i].Type = flux.TBool
			case string:
				colMeta[i].Type = flux.TString
			}
		}

		tags := r.tagKeys()

		leng := len(r.row.Columns)
		for i, tag := range tags {
			colMeta[leng+i] = flux.ColMeta{
				Label: tag,
				Type:  flux.TString,
			}
		}

		leng = leng + len(tags)
		colMeta[leng] = flux.ColMeta{
			Label: "_measurement",
			Type:  flux.TString,
		}
		r.colMeta = colMeta
	}

	return r.colMeta
}

// Do applies f to itself. This is because Row is a flux.ColReader.
// It is used to implement flux.Table.
func (r *queryTable) Do(f func(flux.ColReader) error) error {
	return f(r)
}

// RefCount is a noop.
// It is used to implement flux.ColReader.
func (r *queryTable) RefCount(n int) {}

// Empty returns true if a Row has no values.
// It is used to implement flux.Table.
func (r *queryTable) Empty() bool { return r.Len() == 0 }

// Len returns the length or r.row.Values
// It is used to implement flux.ColReader.
func (r *queryTable) Len() int {
	return len(r.row.Values)
}

// Bools returns the values in column index j as bools.
// It will panic if the column is not a []bool.
// It is used to implement flux.ColReader.
func (r *queryTable) Bools(j int) []bool {
	return r.cols[j].([]bool)
}

// Ints returns the values in column index j as ints.
// It will panic if the column is not a []int64.
// It is used to implement flux.ColReader.
func (r *queryTable) Ints(j int) []int64 {
	return r.cols[j].([]int64)
}

// UInts returns the values in column index j as ints.
// It will panic if the column is not a []uint64.
// It is used to implement flux.ColReader.
func (r *queryTable) UInts(j int) []uint64 {
	return r.cols[j].([]uint64)
}

// Floats returns the values in column index j as floats.
// It will panic if the column is not a []float64.
// It is used to implement flux.ColReader.
func (r *queryTable) Floats(j int) []float64 {
	return r.cols[j].([]float64)
}

// Strings returns the values in column index j as strings.
// It will panic if the column is not a []string.
// It is used to implement flux.ColReader.
func (r *queryTable) Strings(j int) []string {
	return r.cols[j].([]string)
}

// Times returns the values in column index j as values.Times.
// It will panic if the column is not a []values.Time.
// It is used to implement flux.ColReader.
func (r *queryTable) Times(j int) []values.Time {
	return r.cols[j].([]values.Time)
}
<commit_msg>update transpiler result iterators with new Statistics method<commit_after>package influxql

import (
	"fmt"
	"sort"
	"strconv"
	"time"

	"github.com/influxdata/flux"
	"github.com/influxdata/flux/execute"
	"github.com/influxdata/flux/values"
)

// responseIterator implements flux.ResultIterator for a Response.
type responseIterator struct {
	response  *Response
	resultIdx int
}

// NewresponseIterator constructs a responseIterator from a flux.ResultIterator.
func NewResponseIterator(r *Response) flux.ResultIterator {
	return &responseIterator{
		response: r,
	}
}

// More returns true if there are results left to iterate through.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) More() bool {
	return r.resultIdx < len(r.response.Results)
}

// Next retrieves the next flux.Result.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Next() flux.Result {
	res := r.response.Results[r.resultIdx]
	r.resultIdx++
	return newQueryResult(&res)
}

// Release is a noop.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Release() {}

// Err returns an error if the response contained an error.
// It is used to implement flux.ResultIterator.
func (r *responseIterator) Err() error {
	if r.response.Err != "" {
		return fmt.Errorf(r.response.Err)
	}

	return nil
}

func (r *responseIterator) Statistics() flux.Statistics {
	return flux.Statistics{}
}

// seriesIterator is a simple wrapper for Result that implements flux.Result and flux.TableIterator.
type seriesIterator struct {
	result *Result
}

func newQueryResult(r *Result) *seriesIterator {
	return &seriesIterator{
		result: r,
	}
}

// Name returns the results statement id.
// It is used to implement flux.Result.
func (r *seriesIterator) Name() string {
	return strconv.Itoa(r.result.StatementID)
}

// Tables returns the original as a flux.TableIterator.
// It is used to implement flux.Result.
func (r *seriesIterator) Tables() flux.TableIterator {
	return r
}

// Do iterates through the series of a Result.
// It is used to implement flux.TableIterator.
func (r *seriesIterator) Do(f func(flux.Table) error) error {
	for _, row := range r.result.Series {
		t, err := newQueryTable(row)
		if err != nil {
			return err
		}
		if err := f(t); err != nil {
			return err
		}
	}

	return nil
}

func (r *seriesIterator) Statistics() flux.Statistics {
	return flux.Statistics{}
}

// queryTable implements flux.Table and flux.ColReader.
type queryTable struct {
	row      *Row
	groupKey flux.GroupKey
	colMeta  []flux.ColMeta
	cols     []interface{}
}

func newQueryTable(r *Row) (*queryTable, error) {
	t := &queryTable{
		row: r,
	}
	if err := t.translateRowsToColumns(); err != nil {
		return nil, err
	}
	return t, nil
}

func (t *queryTable) Statistics() flux.Statistics {
	return flux.Statistics{}
}

// Data in a column is laid out in the following way:
//   [ r.row.Columns... , r.tagKeys()... , r.row.Name ]
func (t *queryTable) translateRowsToColumns() error {
	cols := t.Cols()
	t.cols = make([]interface{}, len(cols))
	for i, col := range cols {
		switch col.Type {
		case flux.TFloat:
			t.cols[i] = make([]float64, 0, t.Len())
		case flux.TInt:
			t.cols[i] = make([]int64, 0, t.Len())
		case flux.TUInt:
			t.cols[i] = make([]uint64, 0, t.Len())
		case flux.TString:
			t.cols[i] = make([]string, 0, t.Len())
		case flux.TBool:
			t.cols[i] = make([]bool, 0, t.Len())
		case flux.TTime:
			t.cols[i] = make([]values.Time, 0, t.Len())
		}
	}
	for _, els := range t.row.Values {
		for i, el := range els {
			col := cols[i]
			switch col.Type {
			case flux.TFloat:
				val, ok := el.(float64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]float64), val)
			case flux.TInt:
				val, ok := el.(int64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]int64), val)
			case flux.TUInt:
				val, ok := el.(uint64)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]uint64), val)
			case flux.TString:
				val, ok := el.(string)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]string), val)
			case flux.TBool:
				val, ok := el.(bool)
				if !ok {
					return fmt.Errorf("unsupported type %T found in column %s of type %s", val, col.Label, col.Type)
				}
				t.cols[i] = append(t.cols[i].([]bool), val)
			case flux.TTime:
				switch val := el.(type) {
				case int64:
					t.cols[i] = append(t.cols[i].([]values.Time), values.Time(val))
				case float64:
					t.cols[i] = append(t.cols[i].([]values.Time), values.Time(val))
				case string:
					tm, err := time.Parse(time.RFC3339, val)
					if err != nil {
						return fmt.Errorf("could not parse string %q as time: %v", val, err)
					}
					t.cols[i] = append(t.cols[i].([]values.Time), values.ConvertTime(tm))
				default:
					return fmt.Errorf("unsupported type %T found in column %s", val, col.Label)
				}
			default:
				return fmt.Errorf("invalid type %T found in column %s", el, col.Label)
			}
		}

		j := len(t.row.Columns)
		for j < len(t.row.Columns)+len(t.row.Tags) {
			col := cols[j]
			t.cols[j] = append(t.cols[j].([]string), t.row.Tags[col.Label])
			j++
		}

		t.cols[j] = append(t.cols[j].([]string), t.row.Name)
	}

	return nil
}

// Key constructs the flux.GroupKey for a Row from the rows
// tags and measurement.
// It is used to implement flux.Table and flux.ColReader.
func (r *queryTable) Key() flux.GroupKey {
	if r.groupKey == nil {
		cols := make([]flux.ColMeta, len(r.row.Tags)+1) // plus one is for measurement
		vs := make([]values.Value, len(r.row.Tags)+1)
		kvs := make([]interface{}, len(r.row.Tags)+1)
		colMeta := r.Cols()
		labels := append(r.tagKeys(), "_measurement")
		for j, label := range labels {
			idx := execute.ColIdx(label, colMeta)
			if idx < 0 {
				panic(fmt.Errorf("table invalid: missing group column %q", label))
			}
			cols[j] = colMeta[idx]
			kvs[j] = "string"
			v := values.New(kvs[j])
			if v == values.InvalidValue {
				panic(fmt.Sprintf("unsupported value kind %T", kvs[j]))
			}
			vs[j] = v
		}
		r.groupKey = execute.NewGroupKey(cols, vs)
	}

	return r.groupKey
}

// tags returns the tag keys for a Row.
func (r *queryTable) tagKeys() []string {
	tags := []string{}
	for t := range r.row.Tags {
		tags = append(tags, t)
	}
	sort.Strings(tags)
	return tags
}

// Cols returns the columns for a row where the data is laid out in the following way:
//   [ r.row.Columns... , r.tagKeys()... , r.row.Name ]
// It is used to implement flux.Table and flux.ColReader.
func (r *queryTable) Cols() []flux.ColMeta {
	if r.colMeta == nil {
		colMeta := make([]flux.ColMeta, len(r.row.Columns)+len(r.row.Tags)+1)
		for i, col := range r.row.Columns {
			colMeta[i] = flux.ColMeta{
				Label: col,
				Type:  flux.TInvalid,
			}
			if col == "time" {
				// rename the time column
				colMeta[i].Label = "_time"
				colMeta[i].Type = flux.TTime
			}
		}

		if len(r.row.Values) < 1 {
			panic("must have at least one value")
		}
		data := r.row.Values[0]
		for i := range r.row.Columns {
			v := data[i]
			if colMeta[i].Label == "_time" {
				continue
			}
			switch v.(type) {
			case float64:
				colMeta[i].Type = flux.TFloat
			case int64:
				colMeta[i].Type = flux.TInt
			case uint64:
				colMeta[i].Type = flux.TUInt
			case bool:
				colMeta[i].Type = flux.TBool
			case string:
				colMeta[i].Type = flux.TString
			}
		}

		tags := r.tagKeys()

		leng := len(r.row.Columns)
		for i, tag := range tags {
			colMeta[leng+i] = flux.ColMeta{
				Label: tag,
				Type:  flux.TString,
			}
		}

		leng = leng + len(tags)
		colMeta[leng] = flux.ColMeta{
			Label: "_measurement",
			Type:  flux.TString,
		}
		r.colMeta = colMeta
	}

	return r.colMeta
}

// Do applies f to itself. This is because Row is a flux.ColReader.
// It is used to implement flux.Table.
func (r *queryTable) Do(f func(flux.ColReader) error) error {
	return f(r)
}

// RefCount is a noop.
// It is used to implement flux.ColReader.
func (r *queryTable) RefCount(n int) {}

// Empty returns true if a Row has no values.
// It is used to implement flux.Table.
func (r *queryTable) Empty() bool { return r.Len() == 0 }

// Len returns the length or r.row.Values
// It is used to implement flux.ColReader.
func (r *queryTable) Len() int {
	return len(r.row.Values)
}

// Bools returns the values in column index j as bools.
// It will panic if the column is not a []bool.
// It is used to implement flux.ColReader.
func (r *queryTable) Bools(j int) []bool {
	return r.cols[j].([]bool)
}

// Ints returns the values in column index j as ints.
// It will panic if the column is not a []int64.
// It is used to implement flux.ColReader.
func (r *queryTable) Ints(j int) []int64 {
	return r.cols[j].([]int64)
}

// UInts returns the values in column index j as ints.
// It will panic if the column is not a []uint64.
// It is used to implement flux.ColReader.
func (r *queryTable) UInts(j int) []uint64 {
	return r.cols[j].([]uint64)
}

// Floats returns the values in column index j as floats.
// It will panic if the column is not a []float64.
// It is used to implement flux.ColReader.
func (r *queryTable) Floats(j int) []float64 {
	return r.cols[j].([]float64)
}

// Strings returns the values in column index j as strings.
// It will panic if the column is not a []string.
// It is used to implement flux.ColReader.
func (r *queryTable) Strings(j int) []string {
	return r.cols[j].([]string)
}

// Times returns the values in column index j as values.Times.
// It will panic if the column is not a []values.Time.
// It is used to implement flux.ColReader.
func (r *queryTable) Times(j int) []values.Time {
	return r.cols[j].([]values.Time)
}
<|endoftext|>


<commit_before>package buffer

var work_buffer []byte

var cursorPosition int

func Overwrite(offset int, data string) {
	if len(data) + len(work_buffer) > cap(work_buffer) {
		work_buffer = append(work_buffer, make([]byte, 1024)...)
	}

	copy(work_buffer[offset:], []byte(data))
}

func Insert(offset int, data string) {
	if len(data) + len(work_buffer) > cap(work_buffer) {
		work_buffer = append(work_buffer, make([]byte, 1024)...)
	}

	copy(work_buffer[offset+len(data):], work_buffer[offset:])
	Overwrite(offset, data)
}

func Delete(offset int, length int) {
	work_buffer = append(work_buffer[:offset], work_buffer[offset+length:]...)
}

func GetBufferContents(offset int, length int) []byte {
	if length < 1 {
		return work_buffer[offset:]
	}

	return work_buffer[offset:offset + length]
}

func GetBufferSize() int {
	return len(work_buffer)
}

func GetCursorPosition() uint64 {
	return cursorPosition
}

func SetCursorPosition(newpos uint64) {
	cursorPosition = newpos
	//TODO: Call some function to notify output module
}

//Wraps at 80 chars, hardcoded 'cause codeday
//Each element is [length, offset]
func BufferLineSplit() (res [][2]int) {
	res = make([][2]int)
	//The starting position of the line currently being processed
	startpos := 0
	size := GetBufferSize()
	for curpos := 0 ; curpos < size ; curpos++ {
		length = curpos - startpos + 1
		if work_buffer[curpos] == "\n" || length == 80 {
			var a [2]int
			a[0] = curpos - startpos + 1
			a[1] = startpos
			append(res, a)
			startpos = curpos + 1
		}
	}
	return
}

func GetCursorLinePosition() (int, int) {
	l = BufferLineSplit()
	for i, a := range l {
		if a[0] + a[1] >= cursorPosition {
			return i, cursorPosition - a[1]
		}
	}
	return len(work_buffer)
}
<commit_msg>remove dem uint64s<commit_after>package buffer

var work_buffer []byte

var cursorPosition int

func Overwrite(offset int, data string) {
	if len(data) + len(work_buffer) > cap(work_buffer) {
		work_buffer = append(work_buffer, make([]byte, 1024)...)
	}

	copy(work_buffer[offset:], []byte(data))
}

func Insert(offset int, data string) {
	if len(data) + len(work_buffer) > cap(work_buffer) {
		work_buffer = append(work_buffer, make([]byte, 1024)...)
	}

	copy(work_buffer[offset+len(data):], work_buffer[offset:])
	Overwrite(offset, data)
}

func Delete(offset int, length int) {
	work_buffer = append(work_buffer[:offset], work_buffer[offset+length:]...)
}

func GetBufferContents(offset int, length int) []byte {
	if length < 1 {
		return work_buffer[offset:]
	}

	return work_buffer[offset:offset + length]
}

func GetBufferSize() int {
	return len(work_buffer)
}

func GetCursorPosition() int {
	return cursorPosition
}

func SetCursorPosition(newpos int) {
	cursorPosition = newpos
	//TODO: Call some function to notify output module
}

//Wraps at 80 chars, hardcoded 'cause codeday
//Each element is [length, offset]
func BufferLineSplit() (res [][2]int) {
	res = make([][2]int)
	//The starting position of the line currently being processed
	startpos := 0
	size := GetBufferSize()
	for curpos := 0 ; curpos < size ; curpos++ {
		length = curpos - startpos + 1
		if work_buffer[curpos] == "\n" || length == 80 {
			var a [2]int
			a[0] = curpos - startpos + 1
			a[1] = startpos
			append(res, a)
			startpos = curpos + 1
		}
	}
	return
}

func GetCursorLinePosition() (int, int) {
	l = BufferLineSplit()
	for i, a := range l {
		if a[0] + a[1] >= cursorPosition {
			return i, cursorPosition - a[1]
		}
	}
	return len(work_buffer)
}
<|endoftext|>


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

package main

import (
	"bytes"
	"gopkg.in/goyy/goyy.v0/util/files"
	"gopkg.in/goyy/goyy.v0/util/strings"
	"html/template"
	"io/ioutil"
	"path/filepath"
)

func genEntity() {
	for _, p := range conf.projects {
		for _, t := range conf.tables {
			if t.module.project.Id() == p.Id() && t.module.project.generate == "true" && t.module.generate == "true" && t.generate == "true" {
				dir := t.module.rootdir + "/internal/" + t.id + "/"
				dstfile := filepath.Join(dir, "main.domain.go")
				if strings.IsNotBlank(t.master) {
					dir = t.module.rootdir + "/internal/" + t.master + "/"
					dstfile = filepath.Join(dir, "main.domain."+t.slave+".go")
				}
				if files.IsExist(dstfile) {
					continue
				} else {
					files.MkdirAll(dir, 0644)
				}
				buf := bytes.Buffer{}
				tmpl := newTmpl(tmplEntity)
				tmpl.Execute(&buf, t)
				ioutil.WriteFile(dstfile, buf.Bytes(), 0644)
				write(tmplEntityBat, dir+"generate.bat")
				write(tmplEntitySh, dir+"generate.sh")
			}
		}
	}
}

func write(tmpls, dstfile string) {
	if files.IsExist(dstfile) == false {
		buf := bytes.Buffer{}
		tmpl := newTmpl(tmpls)
		tmpl.Execute(&buf, nil)
		ioutil.WriteFile(dstfile, buf.Bytes(), 0644)
	}
}

func newTmpl(s string) *template.Template {
	return template.Must(template.New("T").Funcs(funcs).Parse(s))
}

var (
	funcs = template.FuncMap{
		"supercol": util.IsSuperCol,
		"padname": func(s string, size int) string {
			return strings.PadRight(s, size, " ")
		},
		"blank":    func(s string) bool { return strings.IsBlank(s) },
		"notblank": func(s string) bool { return strings.IsNoneBlank(s) },
		"padright": func(s string, size int) string { return strings.PadRight(s, size, " ") },
		"lower":    func(s string) string { return strings.ToLower(s) },
		"lower1":   func(s string) string { return strings.ToLowerFirst(s) },
		"upper":    func(s string) string { return strings.ToUpper(s) },
		"upper1":   func(s string) string { return strings.ToUpperFirst(s) },
		"camel":    func(s string) string { return strings.Camel(s) },
		"uncamel":  func(s string) string { return strings.UnCamel(s, "_") },
	}
)
<commit_msg>Specification file name<commit_after>// Copyright 2014 The goyy Authors.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"path/filepath"

	"gopkg.in/goyy/goyy.v0/util/files"
	"gopkg.in/goyy/goyy.v0/util/strings"
)

func genEntity() {
	for _, p := range conf.projects {
		for _, t := range conf.tables {
			if t.module.project.Id() == p.Id() && t.module.project.generate == "true" && t.module.generate == "true" && t.generate == "true" {
				dir := t.module.rootdir + "/internal/" + t.id + "/"
				dstfile := filepath.Join(dir, t.id+"_entity.go")
				if strings.IsNotBlank(t.master) {
					dir = t.module.rootdir + "/internal/" + t.master + "/"
					dstfile = filepath.Join(dir, t.slave+"_entity.go")
				}
				if files.IsExist(dstfile) {
					continue
				} else {
					files.MkdirAll(dir, 0644)
				}
				buf := bytes.Buffer{}
				tmpl := newTmpl(tmplEntity)
				tmpl.Execute(&buf, t)
				ioutil.WriteFile(dstfile, buf.Bytes(), 0644)
				write(tmplEntityBat, dir+"generate.bat")
				write(tmplEntitySh, dir+"generate.sh")
			}
		}
	}
}

func write(tmpls, dstfile string) {
	if files.IsExist(dstfile) == false {
		buf := bytes.Buffer{}
		tmpl := newTmpl(tmpls)
		tmpl.Execute(&buf, nil)
		ioutil.WriteFile(dstfile, buf.Bytes(), 0644)
	}
}

func newTmpl(s string) *template.Template {
	return template.Must(template.New("T").Funcs(funcs).Parse(s))
}

var (
	funcs = template.FuncMap{
		"supercol": util.IsSuperCol,
		"padname": func(s string, size int) string {
			return strings.PadRight(s, size, " ")
		},
		"blank":    func(s string) bool { return strings.IsBlank(s) },
		"notblank": func(s string) bool { return strings.IsNoneBlank(s) },
		"padright": func(s string, size int) string { return strings.PadRight(s, size, " ") },
		"lower":    func(s string) string { return strings.ToLower(s) },
		"lower1":   func(s string) string { return strings.ToLowerFirst(s) },
		"upper":    func(s string) string { return strings.ToUpper(s) },
		"upper1":   func(s string) string { return strings.ToUpperFirst(s) },
		"camel":    func(s string) string { return strings.Camel(s) },
		"uncamel":  func(s string) string { return strings.UnCamel(s, "_") },
	}
)
<|endoftext|>