<commit_before>package syslog

import (
	"fmt"
	"log/syslog"
	"os"
	"path"
	"sync"

	"github.com/docker/docker/daemon/logger"
)

type Syslog struct {
	writer *syslog.Writer
	tag    string
	mu     sync.Mutex
}

func New(tag string) (logger.Logger, error) {
	log, err := syslog.New(syslog.LOG_USER, path.Base(os.Args[0]))
	if err != nil {
		return nil, err
	}
	return &Syslog{
		writer: log,
		tag:    tag,
	}, nil
}

func (s *Syslog) Log(msg *logger.Message) error {
	logMessage := fmt.Sprintf("%s: %s", s.tag, string(msg.Line))
	if msg.Source == "stderr" {
		return s.writer.Err(logMessage)
	}
	return s.writer.Info(logMessage)
}

func (s *Syslog) Close() error {
	return s.writer.Close()
}

func (s *Syslog) Name() string {
	return "Syslog"
}
<commit_msg>Syslog.Log - Remove redundant cast of msg.Line []byte to string as<commit_after>package syslog

import (
	"fmt"
	"log/syslog"
	"os"
	"path"
	"sync"

	"github.com/docker/docker/daemon/logger"
)

type Syslog struct {
	writer *syslog.Writer
	tag    string
	mu     sync.Mutex
}

func New(tag string) (logger.Logger, error) {
	log, err := syslog.New(syslog.LOG_USER, path.Base(os.Args[0]))
	if err != nil {
		return nil, err
	}
	return &Syslog{
		writer: log,
		tag:    tag,
	}, nil
}

func (s *Syslog) Log(msg *logger.Message) error {
	logMessage := fmt.Sprintf("%s: %s", s.tag, msg.Line)
	if msg.Source == "stderr" {
		return s.writer.Err(logMessage)
	}
	return s.writer.Info(logMessage)
}

func (s *Syslog) Close() error {
	return s.writer.Close()
}

func (s *Syslog) Name() string {
	return "Syslog"
}
<|endoftext|>


<commit_before>package getprofile

import (
    "regexp"
    "os/exec"
    "path"
    "path/filepath"
    "os"
    "errors"
    "fmt"
)

type gitSyncer struct{}

var gitSyncerInstance *gitSyncer = &gitSyncer{}

func (sync *gitSyncer) Supports(repoUrl string) bool {
    if matched, err := regexp.MatchString(".+@.+:.+", repoUrl); err != nil {
        dbgf("Error checking gitSyncer.Supports(%v)", repoUrl)
        return false
    } else {
        return matched
    }
}

func (sync *gitSyncer) Init() error {
    if repoUrl, err := getConfig(); err != nil {
        return err
    } else if _, err := os.Stat(path.Join(repoPath, ".git")); os.IsNotExist(err) {
        return exec.Command("git", "clone", repoUrl, path.Join(basePath, "repo")).Run()
    } else {
        return nil // Already cloned
    }
}

func (sync *gitSyncer) Track(absPath, relPath string) error {
    copyToRepo(absPath, relPath)

    cmd := exec.Command("git", "add", relPath)
    cmd.Dir = repoPath
    return cmd.Run()
}

func (sync *gitSyncer) Untrack(relPath string) error {
    cmd := exec.Command("git", "rm", "-f", relPath)
    cmd.Dir = repoPath
    return cmd.Run()
}

func (sync *gitSyncer) Out() error {
    inf("Sending updates out")
    if err := filepath.Walk(repoPath, makeWalkFunc(copyToRepo)); err != nil {
        return err
    } else {
        repoPath := path.Join(basePath, "repo")

        dbg("Command:", "git", "diff", "HEAD", "--quiet")
        cmd := exec.Command("git", "diff", "HEAD", "--quiet")
        cmd.Dir = repoPath
        if err := cmd.Run(); err != nil {
            if execExitStatus(err, 128) {
                dbg("New git repo. Will try to continue.")
            } else {
                return err
            }
        }

        if cmd.ProcessState.Success() {
            return nil // No changes
        } else if _, err := gitRepoExec("git", "add", "-u"); err != nil {
            return err
        } else if _, err := gitRepoExec("git", "commit", "-m", "auto-commit"); err != nil {
            return err
        } else {
            _, err = gitRepoExec("git", "push")
            return err
        }
    }
}

func (sync *gitSyncer) In() error {
    inf("Copying updates in")
    if prevSha, err := gitSha(); err != nil {
        return err
    } else if _, err := gitRepoExec("git", "pull"); err != nil {
        return err
    } else if nowSha, err := gitSha(); err != nil {
        return err
    } else if prevSha == nowSha {
        return nil
    } else {
        return filepath.Walk(path.Join(basePath, "repo"), makeWalkFunc(copyToLocal))
    }
}

func makeWalkFunc(processor func(absPath, relPath string) error) filepath.WalkFunc {
    return func(absPath string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        } else if info.IsDir() {
            return nil
        } else if relPath, err := filepath.Rel(repoPath, absPath); err != nil {
            return err
        } else if !filepath.HasPrefix(relPath, ".git/") {
            return processor(absPath, relPath)
        } else {
            return nil
        }
    }
}

func gitRepoExec(cmdToks ...string) (string, error) {
    dbgf("Command: %v", cmdToks)
    cmd := exec.Command(cmdToks[0], cmdToks[1:]...)
    cmd.Dir = repoPath
    if bytes, err := cmd.Output(); err != nil {
        return string(bytes), err
    } else {
        return string(bytes), nil
    }
}

func gitSha() (string, error) {
    return gitRepoExec("git", "rev-parse", "HEAD")
}

func copyToRepo(absPath, relPath string) error {
    inf("Copy to repo:", relPath)
    src := path.Join(homePath, relPath)
    dest := path.Join(repoPath, relPath)
    if err := os.MkdirAll(path.Dir(dest), 0700); err != nil {
        return err
    }

    cmd := fmt.Sprintf("[ -e '%v' ] && cp '%v' '%v'", src, src, dest)
    dbg("Command:", cmd)
    return exec.Command("bash", "-c", cmd).Run()
}

func copyToLocal(absPath, relPath string) error {
    inf("Copy to local:", relPath)
    return errors.New("TODO") // TODO
}

<commit_msg>don't leak error exit from existence check<commit_after>package getprofile

import (
    "regexp"
    "os/exec"
    "path"
    "path/filepath"
    "os"
    "errors"
    "fmt"
)

type gitSyncer struct{}

var gitSyncerInstance *gitSyncer = &gitSyncer{}

func (sync *gitSyncer) Supports(repoUrl string) bool {
    if matched, err := regexp.MatchString(".+@.+:.+", repoUrl); err != nil {
        dbgf("Error checking gitSyncer.Supports(%v)", repoUrl)
        return false
    } else {
        return matched
    }
}

func (sync *gitSyncer) Init() error {
    if repoUrl, err := getConfig(); err != nil {
        return err
    } else if _, err := os.Stat(path.Join(repoPath, ".git")); os.IsNotExist(err) {
        return exec.Command("git", "clone", repoUrl, path.Join(basePath, "repo")).Run()
    } else {
        return nil // Already cloned
    }
}

func (sync *gitSyncer) Track(absPath, relPath string) error {
    copyToRepo(absPath, relPath)

    cmd := exec.Command("git", "add", relPath)
    cmd.Dir = repoPath
    return cmd.Run()
}

func (sync *gitSyncer) Untrack(relPath string) error {
    cmd := exec.Command("git", "rm", "-f", relPath)
    cmd.Dir = repoPath
    return cmd.Run()
}

func (sync *gitSyncer) Out() error {
    inf("Sending updates out")
    if err := filepath.Walk(repoPath, makeWalkFunc(copyToRepo)); err != nil {
        return err
    } else {
        repoPath := path.Join(basePath, "repo")

        dbg("Command:", "git", "diff", "HEAD", "--quiet")
        cmd := exec.Command("git", "diff", "HEAD", "--quiet")
        cmd.Dir = repoPath
        if err := cmd.Run(); err != nil {
            if execExitStatus(err, 128) {
                dbg("New git repo. Will try to continue.")
            } else {
                return err
            }
        }

        if cmd.ProcessState.Success() {
            return nil // No changes
        } else if _, err := gitRepoExec("git", "add", "-u"); err != nil {
            return err
        } else if _, err := gitRepoExec("git", "commit", "-m", "auto-commit"); err != nil {
            return err
        } else {
            _, err = gitRepoExec("git", "push")
            return err
        }
    }
}

func (sync *gitSyncer) In() error {
    inf("Copying updates in")
    if prevSha, err := gitSha(); err != nil {
        return err
    } else if _, err := gitRepoExec("git", "pull"); err != nil {
        return err
    } else if nowSha, err := gitSha(); err != nil {
        return err
    } else if prevSha == nowSha {
        return nil
    } else {
        return filepath.Walk(path.Join(basePath, "repo"), makeWalkFunc(copyToLocal))
    }
}

func makeWalkFunc(processor func(absPath, relPath string) error) filepath.WalkFunc {
    return func(absPath string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        } else if info.IsDir() {
            return nil
        } else if relPath, err := filepath.Rel(repoPath, absPath); err != nil {
            return err
        } else if !filepath.HasPrefix(relPath, ".git/") {
            return processor(absPath, relPath)
        } else {
            return nil
        }
    }
}

func gitRepoExec(cmdToks ...string) (string, error) {
    dbgf("Command: %v", cmdToks)
    cmd := exec.Command(cmdToks[0], cmdToks[1:]...)
    cmd.Dir = repoPath
    if bytes, err := cmd.Output(); err != nil {
        return string(bytes), err
    } else {
        return string(bytes), nil
    }
}

func gitSha() (string, error) {
    return gitRepoExec("git", "rev-parse", "HEAD")
}

func copyToRepo(absPath, relPath string) error {
    inf("Copy to repo:", relPath)
    src := path.Join(homePath, relPath)
    dest := path.Join(repoPath, relPath)
    if err := os.MkdirAll(path.Dir(dest), 0700); err != nil {
        return err
    }

    cmd := fmt.Sprintf("[ -e '%v' ] && cp '%v' '%v' || exit 0", src, src, dest)
    dbg("Command:", cmd)
    return exec.Command("bash", "-c", cmd).Run()
}

func copyToLocal(absPath, relPath string) error {
    inf("Copy to local:", relPath)
    return errors.New("TODO") // TODO
}

<|endoftext|>


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

package ggstat

import (
	"math"

	"github.com/aclements/go-gg/generic"
	"github.com/aclements/go-gg/table"
	"github.com/aclements/go-moremath/stats"
	"github.com/aclements/go-moremath/vec"
)

// TODO: Default to first (and second) column for X (and Y)?

// Density constructs a probability density estimate from a set of
// samples using kernel density estimation.
//
// X is the only required field. All other fields have reasonable
// default zero values.
//
// The result of Density has two columns in addition to constant
// columns from the input:
//
// - Column X is the points at which the density estimate is sampled.
//
// - If Cumulative is false, column "probability density" is the
//   density estimate. If Cumulative is true, column "cumulative
//   density" is the cumulative density estimate.
type Density struct {
	// X is the name of the column to use for samples.
	X string

	// W is the optional name of the column to use for sample
	// weights. It may be "" to uniformly weight samples.
	W string

	// N is the number of points to sample the KDE at. If N is 0,
	// a reasonable default is used.
	//
	// TODO: This is particularly sensitive to the scale
	// transform.
	N int

	// Widen controls the domain of the returned density estimate.
	// If Widen is < 0, the domain is the range of the data.
	// Otherwise, the domain will be expanded by Widen*Bandwidth
	// (which may be the computed bandwidth). If Widen is 0, it is
	// replaced with a default value of 3.
	//
	// TODO: This is different from ECDF and LeastSquares. Make
	// them consistent.
	Widen float64

	// SplitGroups indicates that each group in the table should
	// have separate bounds based on the data in that group alone.
	// The default, false, indicates that the density function
	// should use the bounds of all of the data combined. This
	// makes it possible to stack KDEs and easier to compare KDEs
	// across groups.
	SplitGroups bool

	// Cumulative indicates that Density should produce a
	// cumulative density estimate rather than a probability
	// density estimate.
	Cumulative bool

	// Kernel is the kernel to use for the KDE.
	Kernel stats.KDEKernel

	// Bandwidth is the bandwidth to use for the KDE.
	//
	// If this is zero, the bandwidth is computed from the data
	// using a default bandwidth estimator (currently
	// stats.BandwidthScott).
	Bandwidth float64

	// BoundaryMethod is the boundary correction method to use for
	// the KDE. The default value is BoundaryReflect; however, the
	// default bounds are effectively +/-inf, which is equivalent
	// to performing no boundary correction.
	BoundaryMethod stats.KDEBoundaryMethod

	// [BoundaryMin, BoundaryMax) specify a bounded support for
	// the KDE. If both are 0 (their default values), they are
	// treated as +/-inf.
	//
	// To specify a half-bounded support, set Min to math.Inf(-1)
	// or Max to math.Inf(1).
	BoundaryMin float64
	BoundaryMax float64
}

func (d Density) F(g table.Grouping) table.Grouping {
	kde := stats.KDE{
		Kernel:         d.Kernel,
		Bandwidth:      d.Bandwidth,
		BoundaryMethod: d.BoundaryMethod,
		BoundaryMin:    d.BoundaryMin,
		BoundaryMax:    d.BoundaryMax,
	}
	if d.N == 0 {
		d.N = 200
	}
	if d.Widen == 0 {
		d.Widen = 3
	}
	resp := "probability density"
	if d.Cumulative {
		resp = "cumulative density"
	}

	// Gather samples.
	samples := map[table.GroupID]stats.Sample{}
	for _, gid := range g.Tables() {
		t := g.Table(gid)
		var sample stats.Sample
		generic.ConvertSlice(&sample.Xs, t.MustColumn(d.X))
		if d.W != "" {
			generic.ConvertSlice(&sample.Weights, t.MustColumn(d.W))
		}
		samples[gid] = sample
	}

	min, max := math.NaN(), math.NaN()
	if !d.SplitGroups {
		// Compute combined bounds.
		for _, sample := range samples {
			smin, smax := sample.Bounds()
			if math.IsNaN(smin) {
				continue
			}

			bandwidth := d.Bandwidth
			if d.Bandwidth == 0 {
				bandwidth = stats.BandwidthScott(sample)
			}

			smin, smax = smin-d.Widen*bandwidth, smax+d.Widen*bandwidth
			if smin < min || math.IsNaN(min) {
				min = smin
			}
			if smax > max || math.IsNaN(max) {
				max = smax
			}
		}
	}

	return table.MapTables(func(gid table.GroupID, t *table.Table) *table.Table {
		kde.Sample = samples[gid]

		if kde.Sample.Weight() == 0 {
			return new(table.Table).Add(d.X, []float64{}).Add(resp, []float64{})
		}

		if d.Bandwidth == 0 {
			kde.Bandwidth = stats.BandwidthScott(kde.Sample)
		}

		if d.SplitGroups {
			// Compute group bounds.
			min, max = kde.Sample.Bounds()
			min, max = min-d.Widen*kde.Bandwidth, max+d.Widen*kde.Bandwidth
		}

		ss := vec.Linspace(min, max, d.N)
		nt := new(table.Table).Add(d.X, ss)
		if d.Cumulative {
			nt = nt.Add(resp, vec.Map(kde.CDF, ss))
		} else {
			nt = nt.Add(resp, vec.Map(kde.PDF, ss))
		}
		return preserveConsts(nt, t)
	}, g)
}
<commit_msg>ggstat: produce both PDF and CDF from Density<commit_after>// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ggstat

import (
	"math"

	"github.com/aclements/go-gg/generic"
	"github.com/aclements/go-gg/table"
	"github.com/aclements/go-moremath/stats"
	"github.com/aclements/go-moremath/vec"
)

// TODO: Default to first (and second) column for X (and Y)?

// Density constructs a probability density estimate from a set of
// samples using kernel density estimation.
//
// X is the only required field. All other fields have reasonable
// default zero values.
//
// The result of Density has three columns in addition to constant
// columns from the input:
//
// - Column X is the points at which the density estimate is sampled.
//
// - Column "probability density" is the density estimate.
//
// - Column "cumulative density" is the cumulative density estimate.
type Density struct {
	// X is the name of the column to use for samples.
	X string

	// W is the optional name of the column to use for sample
	// weights. It may be "" to uniformly weight samples.
	W string

	// N is the number of points to sample the KDE at. If N is 0,
	// a reasonable default is used.
	//
	// TODO: This is particularly sensitive to the scale
	// transform.
	N int

	// Widen controls the domain of the returned density estimate.
	// If Widen is < 0, the domain is the range of the data.
	// Otherwise, the domain will be expanded by Widen*Bandwidth
	// (which may be the computed bandwidth). If Widen is 0, it is
	// replaced with a default value of 3.
	//
	// TODO: This is different from ECDF and LeastSquares. Make
	// them consistent.
	Widen float64

	// SplitGroups indicates that each group in the table should
	// have separate bounds based on the data in that group alone.
	// The default, false, indicates that the density function
	// should use the bounds of all of the data combined. This
	// makes it possible to stack KDEs and easier to compare KDEs
	// across groups.
	SplitGroups bool

	// Kernel is the kernel to use for the KDE.
	Kernel stats.KDEKernel

	// Bandwidth is the bandwidth to use for the KDE.
	//
	// If this is zero, the bandwidth is computed from the data
	// using a default bandwidth estimator (currently
	// stats.BandwidthScott).
	Bandwidth float64

	// BoundaryMethod is the boundary correction method to use for
	// the KDE. The default value is BoundaryReflect; however, the
	// default bounds are effectively +/-inf, which is equivalent
	// to performing no boundary correction.
	BoundaryMethod stats.KDEBoundaryMethod

	// [BoundaryMin, BoundaryMax) specify a bounded support for
	// the KDE. If both are 0 (their default values), they are
	// treated as +/-inf.
	//
	// To specify a half-bounded support, set Min to math.Inf(-1)
	// or Max to math.Inf(1).
	BoundaryMin float64
	BoundaryMax float64
}

func (d Density) F(g table.Grouping) table.Grouping {
	kde := stats.KDE{
		Kernel:         d.Kernel,
		Bandwidth:      d.Bandwidth,
		BoundaryMethod: d.BoundaryMethod,
		BoundaryMin:    d.BoundaryMin,
		BoundaryMax:    d.BoundaryMax,
	}
	if d.N == 0 {
		d.N = 200
	}
	if d.Widen == 0 {
		d.Widen = 3
	}
	dname, cname := "probability density", "cumulative density"

	// Gather samples.
	samples := map[table.GroupID]stats.Sample{}
	for _, gid := range g.Tables() {
		t := g.Table(gid)
		var sample stats.Sample
		generic.ConvertSlice(&sample.Xs, t.MustColumn(d.X))
		if d.W != "" {
			generic.ConvertSlice(&sample.Weights, t.MustColumn(d.W))
		}
		samples[gid] = sample
	}

	min, max := math.NaN(), math.NaN()
	if !d.SplitGroups {
		// Compute combined bounds.
		for _, sample := range samples {
			smin, smax := sample.Bounds()
			if math.IsNaN(smin) {
				continue
			}

			bandwidth := d.Bandwidth
			if d.Bandwidth == 0 {
				bandwidth = stats.BandwidthScott(sample)
			}

			smin, smax = smin-d.Widen*bandwidth, smax+d.Widen*bandwidth
			if smin < min || math.IsNaN(min) {
				min = smin
			}
			if smax > max || math.IsNaN(max) {
				max = smax
			}
		}
	}

	return table.MapTables(func(gid table.GroupID, t *table.Table) *table.Table {
		kde.Sample = samples[gid]

		if kde.Sample.Weight() == 0 {
			return new(table.Table).Add(d.X, []float64{}).Add(dname, []float64{}).Add(cname, []float64{})
		}

		if d.Bandwidth == 0 {
			kde.Bandwidth = stats.BandwidthScott(kde.Sample)
		}

		if d.SplitGroups {
			// Compute group bounds.
			min, max = kde.Sample.Bounds()
			min, max = min-d.Widen*kde.Bandwidth, max+d.Widen*kde.Bandwidth
		}

		ss := vec.Linspace(min, max, d.N)
		nt := new(table.Table).Add(d.X, ss)
		nt = nt.Add(dname, vec.Map(kde.PDF, ss))
		nt = nt.Add(cname, vec.Map(kde.CDF, ss))
		return preserveConsts(nt, t)
	}, g)
}
<|endoftext|>


<commit_before>package isolated

import (
	"fmt"
	"net/http"
	"os/exec"
	"strings"

	. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("logs Command", func() {
	Describe("help", func() {
		When("--help flag is set", func() {
			It("appears in cf help -a", func() {
				session := helpers.CF("help", "-a")
				Eventually(session).Should(Exit(0))
				Expect(session).To(HaveCommandInCategoryWithDescription("logs", "APPS", "Tail or show recent logs for an app"))
			})

			It("displays command usage to output", func() {
				session := helpers.CF("logs", "--help")
				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("logs - Tail or show recent logs for an app"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf logs APP_NAME"))
				Eventually(session).Should(Say("OPTIONS:"))
				Eventually(session).Should(Say(`--recent\s+Dump recent logs instead of tailing`))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, apps, ssh"))
				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "logs", "app-name")
		})
	})

	When("the environment is set up correctly", func() {
		var (
			orgName   string
			spaceName string
		)

		BeforeEach(func() {
			orgName = helpers.NewOrgName()
			spaceName = helpers.NewSpaceName()
			helpers.SetupCF(orgName, spaceName)
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		When("input is invalid", func() {
			Context("because no app name is provided", func() {
				It("gives an incorrect usage message", func() {
					session := helpers.CF("logs")
					Eventually(session.Err).Should(Say("Incorrect Usage: the required argument `APP_NAME` was not provided"))
					Eventually(session).Should(Say("NAME:"))
					Eventually(session).Should(Say("logs - Tail or show recent logs for an app"))
					Eventually(session).Should(Say("USAGE:"))
					Eventually(session).Should(Say("cf logs APP_NAME"))
					Eventually(session).Should(Say("OPTIONS:"))
					Eventually(session).Should(Say(`--recent\s+Dump recent logs instead of tailing`))
					Eventually(session).Should(Say("SEE ALSO:"))
					Eventually(session).Should(Say("app, apps, ssh"))
					Eventually(session).Should(Exit(1))
				})
			})

			Context("because the app does not exist", func() {
				It("fails with an app not found message", func() {
					session := helpers.CF("logs", "dora")
					Eventually(session).Should(Say("FAILED"))
					Eventually(session.Err).Should(Say("App 'dora' not found"))
					Eventually(session).Should(Exit(1))
				})
			})
		})

		When("the specified app exists", func() {
			var appName string

			BeforeEach(func() {
				appName = helpers.PrefixedRandomName("app")
				helpers.WithHelloWorldApp(func(appDir string) {
					Eventually(helpers.CF("push", appName, "-p", appDir, "-b", "staticfile_buildpack", "-u", "http", "--endpoint", "/")).Should(Exit(0))
				})
			})

			Context("without the --recent flag", func() {
				It("streams logs out to the screen", func() {
					session := helpers.CF("logs", appName)
					defer session.Terminate()
					userName, _ := helpers.GetCredentials()
					Eventually(session).Should(Say("Retrieving logs for app %s in org %s / space %s as %s...", appName, orgName, spaceName, userName))

					response, err := http.Get(fmt.Sprintf("http://%s.%s", appName, helpers.DefaultSharedDomain()))
					Expect(err).NotTo(HaveOccurred())
					Expect(response.StatusCode).To(Equal(http.StatusOK))
					Eventually(session).Should(Say(`%s \[APP/PROC/WEB/0\]\s+OUT .*? \"GET / HTTP/1.1\" 200 \d+`, helpers.ISO8601Regex))
				})
			})

			Context("with the --recent flag", func() {
				It("displays the most recent logs and closes the stream", func() {
					session := helpers.CF("logs", appName, "--recent")
					userName, _ := helpers.GetCredentials()
					Eventually(session).Should(Say("Retrieving logs for app %s in org %s / space %s as %s...", appName, orgName, spaceName, userName))
					Eventually(session).Should(Say(`%s \[API/\d+\]\s+OUT Created app with guid %s`, helpers.ISO8601Regex, helpers.GUIDRegex))
					Eventually(session).Should(Exit(0))
				})

				XIt("it can get at least 1000 recent log messages", func() {
					route := fmt.Sprintf("%s.%s", appName, helpers.DefaultSharedDomain())
					// 3 lines of logs for each call to curl + a few lines during the push
					for i := 0; i < 333; i += 1 {
						command := exec.Command("curl", route)
						session, err := Start(command, GinkgoWriter, GinkgoWriter)
						Expect(err).NotTo(HaveOccurred())
						Eventually(session).Should(Exit(0))
					}
					Eventually(func() int {
						session := helpers.CF("logs", appName, "--recent")
						Eventually(session).Should(Exit(0))
						output := session.Out.Contents()
						return strings.Count(string(output), "\n")
					}.Should(BeNumerically(">=", 1000)))
				})
			})
		})
	})
})
<commit_msg>Finally, this test passes locally<commit_after>package isolated

import (
	"fmt"
	"net/http"
	"os/exec"
	"strings"

	. "code.cloudfoundry.org/cli/cf/util/testhelpers/matchers"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("logs Command", func() {
	Describe("help", func() {
		When("--help flag is set", func() {
			It("appears in cf help -a", func() {
				session := helpers.CF("help", "-a")
				Eventually(session).Should(Exit(0))
				Expect(session).To(HaveCommandInCategoryWithDescription("logs", "APPS", "Tail or show recent logs for an app"))
			})

			It("displays command usage to output", func() {
				session := helpers.CF("logs", "--help")
				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("logs - Tail or show recent logs for an app"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf logs APP_NAME"))
				Eventually(session).Should(Say("OPTIONS:"))
				Eventually(session).Should(Say(`--recent\s+Dump recent logs instead of tailing`))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, apps, ssh"))
				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "logs", "app-name")
		})
	})

	When("the environment is set up correctly", func() {
		var (
			orgName   string
			spaceName string
		)

		BeforeEach(func() {
			orgName = helpers.NewOrgName()
			spaceName = helpers.NewSpaceName()
			helpers.SetupCF(orgName, spaceName)
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		When("input is invalid", func() {
			Context("because no app name is provided", func() {
				It("gives an incorrect usage message", func() {
					session := helpers.CF("logs")
					Eventually(session.Err).Should(Say("Incorrect Usage: the required argument `APP_NAME` was not provided"))
					Eventually(session).Should(Say("NAME:"))
					Eventually(session).Should(Say("logs - Tail or show recent logs for an app"))
					Eventually(session).Should(Say("USAGE:"))
					Eventually(session).Should(Say("cf logs APP_NAME"))
					Eventually(session).Should(Say("OPTIONS:"))
					Eventually(session).Should(Say(`--recent\s+Dump recent logs instead of tailing`))
					Eventually(session).Should(Say("SEE ALSO:"))
					Eventually(session).Should(Say("app, apps, ssh"))
					Eventually(session).Should(Exit(1))
				})
			})

			Context("because the app does not exist", func() {
				It("fails with an app not found message", func() {
					session := helpers.CF("logs", "dora")
					Eventually(session).Should(Say("FAILED"))
					Eventually(session.Err).Should(Say("App 'dora' not found"))
					Eventually(session).Should(Exit(1))
				})
			})
		})

		When("the specified app exists", func() {
			var appName string

			BeforeEach(func() {
				appName = helpers.PrefixedRandomName("app")
				helpers.WithHelloWorldApp(func(appDir string) {
					Eventually(helpers.CF("push", appName, "-p", appDir, "-b", "staticfile_buildpack", "-u", "http", "--endpoint", "/")).Should(Exit(0))
				})
			})

			Context("without the --recent flag", func() {
				It("streams logs out to the screen", func() {
					session := helpers.CF("logs", appName)
					defer session.Terminate()
					userName, _ := helpers.GetCredentials()
					Eventually(session).Should(Say("Retrieving logs for app %s in org %s / space %s as %s...", appName, orgName, spaceName, userName))

					response, err := http.Get(fmt.Sprintf("http://%s.%s", appName, helpers.DefaultSharedDomain()))
					Expect(err).NotTo(HaveOccurred())
					Expect(response.StatusCode).To(Equal(http.StatusOK))
					Eventually(session).Should(Say(`%s \[APP/PROC/WEB/0\]\s+OUT .*? \"GET / HTTP/1.1\" 200 \d+`, helpers.ISO8601Regex))
				})
			})

			Context("with the --recent flag", func() {
				It("displays the most recent logs and closes the stream", func() {
					session := helpers.CF("logs", appName, "--recent")
					userName, _ := helpers.GetCredentials()
					Eventually(session).Should(Say("Retrieving logs for app %s in org %s / space %s as %s...", appName, orgName, spaceName, userName))
					Eventually(session).Should(Say(`%s \[API/\d+\]\s+OUT Created app with guid %s`, helpers.ISO8601Regex, helpers.GUIDRegex))
					Eventually(session).Should(Exit(0))
				})

				It("it can get at least 1000 recent log messages", func() {
					route := fmt.Sprintf("%s.%s", appName, helpers.DefaultSharedDomain())
					// 3 lines of logs for each call to curl + a few lines during the push
					for i := 0; i < 333; i += 1 {
						command := exec.Command("curl", route)
						session, err := Start(command, GinkgoWriter, GinkgoWriter)
						Expect(err).NotTo(HaveOccurred())
						Eventually(session).Should(Exit(0))
					}
					Eventually(func() int {
						session := helpers.CF("logs", appName, "--recent")
						Eventually(session).Should(Exit(0))
						output := session.Out.Contents()
						return strings.Count(string(output), "\n")
					}).Should(BeNumerically(">=", 1000))
				})
			})
		})
	})
})
<|endoftext|>


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

package shader

import (
	"github.com/hajimehoshi/ebiten/internal/opengl"
)

var (
	programTexture opengl.Program
	programRect    opengl.Program
)

const quadsMaxNum = 65536 / 6

// unsafe.SizeOf can't be used because unsafe doesn't work with GopherJS.
const int16Size = 2

func initialize(c *opengl.Context) error {
	shaderVertexNative, err := c.NewShader(c.VertexShader, shader(c, shaderVertex))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderVertexNative)

	shaderVertexColorNative, err := c.NewShader(c.VertexShader, shader(c, shaderVertexColor))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderVertexColorNative)

	shaderFragmentTextureNative, err := c.NewShader(c.FragmentShader, shader(c, shaderFragmentTexture))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderFragmentTextureNative)

	shaderFragmentRectNative, err := c.NewShader(c.FragmentShader, shader(c, shaderFragmentRect))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderFragmentRectNative)

	programTexture, err = c.NewProgram([]opengl.Shader{
		shaderVertexNative,
		shaderFragmentTextureNative,
	})
	if err != nil {
		return err
	}

	programRect, err = c.NewProgram([]opengl.Shader{
		shaderVertexColorNative,
		shaderFragmentRectNative,
	})
	if err != nil {
		return err
	}

	const stride = int16Size * 8 // 8 = (2 for vertex) + (2 for texture) + (4 for color)
	c.NewBuffer(c.ArrayBuffer, 4*stride*quadsMaxNum, c.DynamicDraw)

	indices := make([]uint16, 6*quadsMaxNum)
	for i := uint16(0); i < quadsMaxNum; i++ {
		indices[6*i+0] = 4*i + 0
		indices[6*i+1] = 4*i + 1
		indices[6*i+2] = 4*i + 2
		indices[6*i+3] = 4*i + 1
		indices[6*i+4] = 4*i + 2
		indices[6*i+5] = 4*i + 3
	}
	c.NewBuffer(c.ElementArrayBuffer, indices, c.StaticDraw)

	return nil
}

var lastProgram opengl.Program

type programFinisher func()

func (p programFinisher) FinishProgram() {
	p()
}

func useProgramTexture(c *opengl.Context, projectionMatrix []float32, texture opengl.Texture, geo Matrix, color Matrix) programFinisher {
	if !lastProgram.Equals(programTexture) {
		c.UseProgram(programTexture)
		lastProgram = programTexture
	}
	program := programTexture

	c.UniformFloats(program, "projection_matrix", projectionMatrix)

	ma := float32(geo.Element(0, 0))
	mb := float32(geo.Element(0, 1))
	mc := float32(geo.Element(1, 0))
	md := float32(geo.Element(1, 1))
	tx := float32(geo.Element(0, 2))
	ty := float32(geo.Element(1, 2))
	glModelviewMatrix := []float32{
		ma, mc, 0, 0,
		mb, md, 0, 0,
		0, 0, 1, 0,
		tx, ty, 0, 1,
	}
	c.UniformFloats(program, "modelview_matrix", glModelviewMatrix)
	c.UniformInt(program, "texture", 0)

	e := [4][5]float32{}
	for i := 0; i < 4; i++ {
		for j := 0; j < 5; j++ {
			e[i][j] = float32(color.Element(i, j))
		}
	}

	glColorMatrix := []float32{
		e[0][0], e[1][0], e[2][0], e[3][0],
		e[0][1], e[1][1], e[2][1], e[3][1],
		e[0][2], e[1][2], e[2][2], e[3][2],
		e[0][3], e[1][3], e[2][3], e[3][3],
	}
	c.UniformFloats(program, "color_matrix", glColorMatrix)
	glColorMatrixTranslation := []float32{
		e[0][4], e[1][4], e[2][4], e[3][4],
	}
	c.UniformFloats(program, "color_matrix_translation", glColorMatrixTranslation)

	// We don't have to call gl.ActiveTexture here: GL_TEXTURE0 is the default active texture
	// See also: https://www.opengl.org/sdk/docs/man2/xhtml/glActiveTexture.xml
	c.BindTexture(texture)

	c.EnableVertexAttribArray(program, "vertex")
	c.EnableVertexAttribArray(program, "tex_coord")

	c.VertexAttribPointer(program, "vertex", true, false, int16Size*4, 2, uintptr(int16Size*0))
	c.VertexAttribPointer(program, "tex_coord", true, true, int16Size*4, 2, uintptr(int16Size*2))

	return func() {
		c.DisableVertexAttribArray(program, "tex_coord")
		c.DisableVertexAttribArray(program, "vertex")
	}
}

func useProgramRect(c *opengl.Context, projectionMatrix []float32) programFinisher {
	if lastProgram != programRect {
		c.UseProgram(programRect)
		lastProgram = programRect
	}
	program := programRect

	c.UniformFloats(program, "projection_matrix", projectionMatrix)

	c.EnableVertexAttribArray(program, "vertex")
	c.EnableVertexAttribArray(program, "color")

	c.VertexAttribPointer(program, "vertex", true, false, int16Size*6, 2, uintptr(int16Size*0))
	c.VertexAttribPointer(program, "color", false, true, int16Size*6, 4, uintptr(int16Size*2))

	return func() {
		c.DisableVertexAttribArray(program, "color")
		c.DisableVertexAttribArray(program, "vertex")
	}
}
<commit_msg>example:shapes Bug fix: Structs containing js.Object can't be compared again<commit_after>// Copyright 2014 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shader

import (
	"github.com/hajimehoshi/ebiten/internal/opengl"
)

var (
	programTexture opengl.Program
	programRect    opengl.Program
)

const quadsMaxNum = 65536 / 6

// unsafe.SizeOf can't be used because unsafe doesn't work with GopherJS.
const int16Size = 2

func initialize(c *opengl.Context) error {
	shaderVertexNative, err := c.NewShader(c.VertexShader, shader(c, shaderVertex))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderVertexNative)

	shaderVertexColorNative, err := c.NewShader(c.VertexShader, shader(c, shaderVertexColor))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderVertexColorNative)

	shaderFragmentTextureNative, err := c.NewShader(c.FragmentShader, shader(c, shaderFragmentTexture))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderFragmentTextureNative)

	shaderFragmentRectNative, err := c.NewShader(c.FragmentShader, shader(c, shaderFragmentRect))
	if err != nil {
		return err
	}
	defer c.DeleteShader(shaderFragmentRectNative)

	programTexture, err = c.NewProgram([]opengl.Shader{
		shaderVertexNative,
		shaderFragmentTextureNative,
	})
	if err != nil {
		return err
	}

	programRect, err = c.NewProgram([]opengl.Shader{
		shaderVertexColorNative,
		shaderFragmentRectNative,
	})
	if err != nil {
		return err
	}

	const stride = int16Size * 8 // 8 = (2 for vertex) + (2 for texture) + (4 for color)
	c.NewBuffer(c.ArrayBuffer, 4*stride*quadsMaxNum, c.DynamicDraw)

	indices := make([]uint16, 6*quadsMaxNum)
	for i := uint16(0); i < quadsMaxNum; i++ {
		indices[6*i+0] = 4*i + 0
		indices[6*i+1] = 4*i + 1
		indices[6*i+2] = 4*i + 2
		indices[6*i+3] = 4*i + 1
		indices[6*i+4] = 4*i + 2
		indices[6*i+5] = 4*i + 3
	}
	c.NewBuffer(c.ElementArrayBuffer, indices, c.StaticDraw)

	return nil
}

var lastProgram opengl.Program

type programFinisher func()

func (p programFinisher) FinishProgram() {
	p()
}

func useProgramTexture(c *opengl.Context, projectionMatrix []float32, texture opengl.Texture, geo Matrix, color Matrix) programFinisher {
	if !lastProgram.Equals(programTexture) {
		c.UseProgram(programTexture)
		lastProgram = programTexture
	}
	program := programTexture

	c.UniformFloats(program, "projection_matrix", projectionMatrix)

	ma := float32(geo.Element(0, 0))
	mb := float32(geo.Element(0, 1))
	mc := float32(geo.Element(1, 0))
	md := float32(geo.Element(1, 1))
	tx := float32(geo.Element(0, 2))
	ty := float32(geo.Element(1, 2))
	glModelviewMatrix := []float32{
		ma, mc, 0, 0,
		mb, md, 0, 0,
		0, 0, 1, 0,
		tx, ty, 0, 1,
	}
	c.UniformFloats(program, "modelview_matrix", glModelviewMatrix)
	c.UniformInt(program, "texture", 0)

	e := [4][5]float32{}
	for i := 0; i < 4; i++ {
		for j := 0; j < 5; j++ {
			e[i][j] = float32(color.Element(i, j))
		}
	}

	glColorMatrix := []float32{
		e[0][0], e[1][0], e[2][0], e[3][0],
		e[0][1], e[1][1], e[2][1], e[3][1],
		e[0][2], e[1][2], e[2][2], e[3][2],
		e[0][3], e[1][3], e[2][3], e[3][3],
	}
	c.UniformFloats(program, "color_matrix", glColorMatrix)
	glColorMatrixTranslation := []float32{
		e[0][4], e[1][4], e[2][4], e[3][4],
	}
	c.UniformFloats(program, "color_matrix_translation", glColorMatrixTranslation)

	// We don't have to call gl.ActiveTexture here: GL_TEXTURE0 is the default active texture
	// See also: https://www.opengl.org/sdk/docs/man2/xhtml/glActiveTexture.xml
	c.BindTexture(texture)

	c.EnableVertexAttribArray(program, "vertex")
	c.EnableVertexAttribArray(program, "tex_coord")

	c.VertexAttribPointer(program, "vertex", true, false, int16Size*4, 2, uintptr(int16Size*0))
	c.VertexAttribPointer(program, "tex_coord", true, true, int16Size*4, 2, uintptr(int16Size*2))

	return func() {
		c.DisableVertexAttribArray(program, "tex_coord")
		c.DisableVertexAttribArray(program, "vertex")
	}
}

func useProgramRect(c *opengl.Context, projectionMatrix []float32) programFinisher {
	if !lastProgram.Equals(programRect) {
		c.UseProgram(programRect)
		lastProgram = programRect
	}
	program := programRect

	c.UniformFloats(program, "projection_matrix", projectionMatrix)

	c.EnableVertexAttribArray(program, "vertex")
	c.EnableVertexAttribArray(program, "color")

	c.VertexAttribPointer(program, "vertex", true, false, int16Size*6, 2, uintptr(int16Size*0))
	c.VertexAttribPointer(program, "color", false, true, int16Size*6, 4, uintptr(int16Size*2))

	return func() {
		c.DisableVertexAttribArray(program, "color")
		c.DisableVertexAttribArray(program, "vertex")
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package github

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strconv"
	"time"
)

// CreateRelease creates a release for a tag
func CreateRelease(token string, repo string, tag string, name string) error {
	params := ReleaseCreate{
		TagName: tag,
		Name:    name,
	}

	payload, err := json.Marshal(params)
	if err != nil {
		return fmt.Errorf("can't encode release creation params, %v", err)
	}
	reader := bytes.NewReader(payload)

	uri := fmt.Sprintf("/repos/keybase/%s/releases", repo)
	resp, err := DoAuthRequest("POST", githubAPIURL+uri, "application/json", token, nil, reader)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return fmt.Errorf("while submitting %v, %v", string(payload), err)
	}
	if resp.StatusCode != http.StatusCreated {
		if resp.StatusCode == 422 {
			return fmt.Errorf("github returned %v (this is probably because the release already exists)",
				resp.Status)
		}
		return fmt.Errorf("github returned %v", resp.Status)
	}
	return nil
}

// Upload uploads a file to a tagged repo
func Upload(token string, repo string, tag string, name string, file string) error {
	release, err := ReleaseOfTag("keybase", repo, tag, token)
	if err != nil {
		return err
	}
	v := url.Values{}
	v.Set("name", name)
	url := release.CleanUploadURL() + "?" + v.Encode()
	osfile, err := os.Open(file)
	if err != nil {
		return err
	}
	resp, err := DoAuthRequest("POST", url, "application/octet-stream", token, nil, osfile)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusCreated {
		if resp.StatusCode == 422 {
			return fmt.Errorf("github returned %v (this is probably because the release already exists)",
				resp.Status)
		}
		return fmt.Errorf("github returned %v", resp.Status)
	}
	return nil
}

// DownloadSource dowloads source from repo tag
func DownloadSource(token string, repo string, tag string) error {
	url := githubAPIURL + fmt.Sprintf("/repos/keybase/%s/tarball/%s", repo, tag)
	name := fmt.Sprintf("%s-%s.tar.gz", repo, tag)
	log.Printf("Url: %s", url)
	return Download(token, url, name)
}

// DownloadAsset downloads an asset from Github that matches name
func DownloadAsset(token string, repo string, tag string, name string) error {
	release, err := ReleaseOfTag("keybase", repo, tag, token)
	if err != nil {
		return err
	}

	assetID := 0
	for _, asset := range release.Assets {
		if asset.Name == name {
			assetID = asset.ID
		}
	}

	if assetID == 0 {
		return fmt.Errorf("could not find asset named %s", name)
	}

	url := githubAPIURL + fmt.Sprintf(assetDownloadURI, "keybase", repo, assetID)
	return Download(token, url, name)
}

// Download from Github
func Download(token string, url string, name string) error {
	resp, err := DoAuthRequest("GET", url, "", token, map[string]string{
		"Accept": "application/octet-stream",
	}, nil)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return fmt.Errorf("could not fetch releases, %v", err)
	}

	contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("github did not respond with 200 OK but with %v", resp.Status)
	}

	out, err := os.Create(name)
	if err != nil {
		return fmt.Errorf("could not create file %s", name)
	}
	defer func() { _ = out.Close() }()

	n, err := io.Copy(out, resp.Body)
	if n != contentLength {
		return fmt.Errorf("downloaded data did not match content length %d != %d", contentLength, n)
	}
	return err
}

// LatestCommit returns a latest commit for all statuses matching state and contexts
func LatestCommit(token string, repo string, contexts []string) (*Commit, error) {
	commits, err := Commits("keybase", repo, token)
	if err != nil {
		return nil, err
	}

	for _, commit := range commits {
		log.Printf("Checking %s", commit.SHA)
		statuses, err := Statuses("keybase", repo, commit.SHA, token)
		if err != nil {
			return nil, err
		}
		matching := map[string]Status{}
		for _, status := range statuses {
			if stringInSlice(status.Context, contexts) {
				switch status.State {
				case "failure":
					log.Printf("%s (failure)", status.Context)
				case "success":
					log.Printf("%s (success)", status.Context)
					matching[status.Context] = status
				}
			}
		}
		// If we match all contexts then we've found the commit
		if len(contexts) == len(matching) {
			return &commit, nil
		}
	}
	return nil, nil
}

func stringInSlice(str string, list []string) bool {
	for _, s := range list {
		if s == str {
			return true
		}
	}
	return false
}

// WaitForCI waits for commit in repo to pass CI contexts
func WaitForCI(token string, repo string, commit string, contexts []string, delay time.Duration, timeout time.Duration) error {
	start := time.Now()
	re := regexp.MustCompile("(.*)(/label=.*)")
	for time.Since(start) < timeout {
		log.Printf("Checking status for %s (%s)", contexts, commit)
		statuses, err := Statuses("keybase", repo, commit, token)
		if err != nil {
			return err
		}
		const success = "success"
		const failure = "failure"
		matching := map[string]Status{}
		// for _, status := range statuses {
		// 	log.Printf("\t%s (%s)", status.Context, status.State)
		// }
		for _, status := range statuses {
			context := re.ReplaceAllString(status.Context, "$1")
			if stringInSlice(context, contexts) {
				switch status.State {
				case failure:
					if matching[context].State != success {
						log.Printf("\t%s (failure)", context)
						return fmt.Errorf("Failure in CI for %s", context)
					}
					log.Printf("\t%s (ignoring previous failure)", context)
				case success:
					log.Printf("\t%s (success)", context)
					matching[context] = status
				}
			}
		}
		// If we match all contexts then we've passed
		if len(contexts) == len(matching) {
			return nil
		}

		log.Printf("Waiting %s", delay)
		time.Sleep(delay)
	}
	return fmt.Errorf("Timed out")
}
<commit_msg>Debug log for status messages<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package github

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strconv"
	"time"
)

// CreateRelease creates a release for a tag
func CreateRelease(token string, repo string, tag string, name string) error {
	params := ReleaseCreate{
		TagName: tag,
		Name:    name,
	}

	payload, err := json.Marshal(params)
	if err != nil {
		return fmt.Errorf("can't encode release creation params, %v", err)
	}
	reader := bytes.NewReader(payload)

	uri := fmt.Sprintf("/repos/keybase/%s/releases", repo)
	resp, err := DoAuthRequest("POST", githubAPIURL+uri, "application/json", token, nil, reader)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return fmt.Errorf("while submitting %v, %v", string(payload), err)
	}
	if resp.StatusCode != http.StatusCreated {
		if resp.StatusCode == 422 {
			return fmt.Errorf("github returned %v (this is probably because the release already exists)",
				resp.Status)
		}
		return fmt.Errorf("github returned %v", resp.Status)
	}
	return nil
}

// Upload uploads a file to a tagged repo
func Upload(token string, repo string, tag string, name string, file string) error {
	release, err := ReleaseOfTag("keybase", repo, tag, token)
	if err != nil {
		return err
	}
	v := url.Values{}
	v.Set("name", name)
	url := release.CleanUploadURL() + "?" + v.Encode()
	osfile, err := os.Open(file)
	if err != nil {
		return err
	}
	resp, err := DoAuthRequest("POST", url, "application/octet-stream", token, nil, osfile)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusCreated {
		if resp.StatusCode == 422 {
			return fmt.Errorf("github returned %v (this is probably because the release already exists)",
				resp.Status)
		}
		return fmt.Errorf("github returned %v", resp.Status)
	}
	return nil
}

// DownloadSource dowloads source from repo tag
func DownloadSource(token string, repo string, tag string) error {
	url := githubAPIURL + fmt.Sprintf("/repos/keybase/%s/tarball/%s", repo, tag)
	name := fmt.Sprintf("%s-%s.tar.gz", repo, tag)
	log.Printf("Url: %s", url)
	return Download(token, url, name)
}

// DownloadAsset downloads an asset from Github that matches name
func DownloadAsset(token string, repo string, tag string, name string) error {
	release, err := ReleaseOfTag("keybase", repo, tag, token)
	if err != nil {
		return err
	}

	assetID := 0
	for _, asset := range release.Assets {
		if asset.Name == name {
			assetID = asset.ID
		}
	}

	if assetID == 0 {
		return fmt.Errorf("could not find asset named %s", name)
	}

	url := githubAPIURL + fmt.Sprintf(assetDownloadURI, "keybase", repo, assetID)
	return Download(token, url, name)
}

// Download from Github
func Download(token string, url string, name string) error {
	resp, err := DoAuthRequest("GET", url, "", token, map[string]string{
		"Accept": "application/octet-stream",
	}, nil)
	if resp != nil {
		defer func() { _ = resp.Body.Close() }()
	}
	if err != nil {
		return fmt.Errorf("could not fetch releases, %v", err)
	}

	contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("github did not respond with 200 OK but with %v", resp.Status)
	}

	out, err := os.Create(name)
	if err != nil {
		return fmt.Errorf("could not create file %s", name)
	}
	defer func() { _ = out.Close() }()

	n, err := io.Copy(out, resp.Body)
	if n != contentLength {
		return fmt.Errorf("downloaded data did not match content length %d != %d", contentLength, n)
	}
	return err
}

// LatestCommit returns a latest commit for all statuses matching state and contexts
func LatestCommit(token string, repo string, contexts []string) (*Commit, error) {
	commits, err := Commits("keybase", repo, token)
	if err != nil {
		return nil, err
	}

	for _, commit := range commits {
		log.Printf("Checking %s", commit.SHA)
		statuses, err := Statuses("keybase", repo, commit.SHA, token)
		if err != nil {
			return nil, err
		}
		matching := map[string]Status{}
		for _, status := range statuses {
			if stringInSlice(status.Context, contexts) {
				switch status.State {
				case "failure":
					log.Printf("%s (failure)", status.Context)
				case "success":
					log.Printf("%s (success)", status.Context)
					matching[status.Context] = status
				}
			}
		}
		// If we match all contexts then we've found the commit
		if len(contexts) == len(matching) {
			return &commit, nil
		}
	}
	return nil, nil
}

func stringInSlice(str string, list []string) bool {
	for _, s := range list {
		if s == str {
			return true
		}
	}
	return false
}

// WaitForCI waits for commit in repo to pass CI contexts
func WaitForCI(token string, repo string, commit string, contexts []string, delay time.Duration, timeout time.Duration) error {
	start := time.Now()
	re := regexp.MustCompile("(.*)(/label=.*)")
	for time.Since(start) < timeout {
		log.Printf("Checking status for %s (%s)", contexts, commit)
		statuses, err := Statuses("keybase", repo, commit, token)
		if err != nil {
			return err
		}
		const success = "success"
		const failure = "failure"
		matching := map[string]Status{}
		log.Println("\tStatuses:")
		for _, status := range statuses {
			log.Printf("\t%s (%s)", status.Context, status.State)
		}
		log.Println("\t")
		log.Println("\tMatch:")
		for _, status := range statuses {
			context := re.ReplaceAllString(status.Context, "$1")
			if stringInSlice(context, contexts) {
				switch status.State {
				case failure:
					if matching[context].State != success {
						log.Printf("\t%s (failure)", context)
						return fmt.Errorf("Failure in CI for %s", context)
					}
					log.Printf("\t%s (ignoring previous failure)", context)
				case success:
					log.Printf("\t%s (success)", context)
					matching[context] = status
				}
			}
		}
		log.Println("\t")
		// If we match all contexts then we've passed
		if len(contexts) == len(matching) {
			return nil
		}

		log.Printf("Waiting %s", delay)
		time.Sleep(delay)
	}
	return fmt.Errorf("Timed out")
}
<|endoftext|>


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

package main

const adapterTemplate = `// Code generated by adapter-generator. DO NOT EDIT.

package adapter

import (
	"fmt"
	"github.com/ligato/cn-infra/datasync"
	. "github.com/ligato/cn-infra/kvscheduler/api"
	. "github.com/ligato/cn-infra/kvscheduler/value/protoval"

    {{- range $i, $path := .Imports }}
	"{{ $path }}"
	{{- end }}
)

////////// type-safe key-value pair with metadata //////////

type {{ .DescriptorName }}KVWithMetadata struct {
	Key      string
	Value    {{ .ValueT }}
	Metadata {{ .MetadataT }}
	Origin   ValueOrigin
}

////////// type-safe Descriptor interface //////////

type {{ .DescriptorName }}DescriptorAPI interface {
	GetName() string
	KeySelector(key string) bool
	NBKeyPrefixes() []string
	WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory)
{{- if .IsProtoValue }}
	Build(key string, valueData {{ .ValueDataT }}) (value ProtoValue, err error)
{{- else }}
	Build(key string, valueData {{ .ValueDataT }}) (value {{ .ValueT }}, err error)
{{- end }}
	Add(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error)
	Delete(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Modify(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error)
	ModifyHasToRecreate(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool
	Update(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Dependencies(key string, value {{ .ValueT }}) []Dependency
	DerivedValues(key string, value {{ .ValueT }}) []KeyValuePair
	Dump(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error)
	DumpDependencies() []string
}

////////// Descriptor base implementation //////////

// {{ .DescriptorName }}DescriptorBase provides default(=empty) implementations
// for all the methods to extend from.
type {{ .DescriptorName }}DescriptorBase struct {
}

func (db *{{ .DescriptorName }}DescriptorBase) GetName() string {
	return "base"
}

func (db *{{ .DescriptorName }}DescriptorBase) KeySelector(key string) bool {
	return false
}

func (db *{{ .DescriptorName }}DescriptorBase) NBKeyPrefixes() []string {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory) {
	return false, nil
}

{{ if .IsProtoValue -}}
func (db *{{ .DescriptorName }}DescriptorBase) Build(key string, valueData {{ .ValueDataT }}) (value ProtoValue, err error) {
{{- if .FromDatasync }}
	// You can override specific methods of ProtoValue using embedding:
	//
	//	type MyProtoValue struct {
	//		ProtoValue
	//      typedMsg {{ .ValueDataT }}
	//	}
	//
	//	// ... (override some methods)
	//
	//  return &MyProtoValue{ProtoValue: NewProtoValue(valueData), typedMsg: valueData}	, nil
	return NewProtoValue(valueData), nil
{{- else }}
	return nil, nil
{{- end }}
}
{{- else }}
func (db *{{ .DescriptorName }}DescriptorBase) Build(key string, valueData {{ .ValueDataT }}) (value {{ .ValueT }}, err error) {
	return nil, nil
}
{{- end }}

func (db *{{ .DescriptorName }}DescriptorBase) Add(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error) {
	fmt.Printf("Create for key=%s is not implemented\n", key)
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Delete(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error {
	fmt.Printf("Delete for key=%s is not implemented\n", key)
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Modify(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error) {
	fmt.Printf("Modify for key=%s is not implemented\n", key)
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) ModifyHasToRecreate(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool {
	return false
}

func (db *{{ .DescriptorName }}DescriptorBase) Update(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error {
	fmt.Printf("Modify for key=%s is not implemented\n", key)
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Dependencies(key string, value {{ .ValueT }}) []Dependency {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) DerivedValues(key string, value {{ .ValueT }}) []KeyValuePair {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Dump(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error) {
	fmt.Println("Dump is not implemented")
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) DumpDependencies() []string {
	return nil
}

////////// Descriptor adapter //////////

type {{ .DescriptorName }}DescriptorAdapter struct {
	descriptor {{ .DescriptorName }}DescriptorAPI
}

func New{{ .DescriptorName }}Descriptor(impl {{ .DescriptorName }}DescriptorAPI) KVDescriptor {
	return &{{ .DescriptorName }}DescriptorAdapter{descriptor: impl}
}

func (da *{{ .DescriptorName }}DescriptorAdapter) GetName() string {
	return da.descriptor.GetName()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) KeySelector(key string) bool {
	return da.descriptor.KeySelector(key)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) NBKeyPrefixes() []string {
	return da.descriptor.NBKeyPrefixes()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory) {
	return da.descriptor.WithMetadata()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Build(key string, valueData interface{}) (value Value, err error) {
	typedValueData, err := cast{{ .DescriptorName }}ValueData(key, valueData)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Build(key, typedValueData)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Add(key string, value Value) (metadata Metadata, err error) {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Add(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Modify(key string, oldValue, newValue Value, oldMetadata Metadata) (newMetadata Metadata, err error) {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return nil, err
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return nil, err
	}
	typedOldMetadata, err := cast{{ .DescriptorName }}Metadata(key, oldMetadata)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Modify(key, oldTypedValue, newTypedValue, typedOldMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Delete(key string, value Value, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Delete(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ModifyHasToRecreate(key string, oldValue, newValue Value, metadata Metadata) bool {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return true
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return true
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return true
	}
	return da.descriptor.ModifyHasToRecreate(key, oldTypedValue, newTypedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Update(key string, value Value, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Update(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dependencies(key string, value Value) []Dependency {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.Dependencies(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DerivedValues(key string, value Value) []KeyValuePair {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.DerivedValues(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dump(correlate []KVWithMetadata) ([]KVWithMetadata, error) {
	var correlateWithType []{{ .DescriptorName }}KVWithMetadata
	for _, kvpair := range correlate {
		typedValue, err := cast{{ .DescriptorName }}Value(kvpair.Key, kvpair.Value)
		if err != nil {
			continue
		}
		typedMetadata, err := cast{{ .DescriptorName }}Metadata(kvpair.Key, kvpair.Metadata)
		if err != nil {
			continue
		}
		correlateWithType = append(correlateWithType,
			{{ .DescriptorName }}KVWithMetadata{
				Key:      kvpair.Key,
				Value:    typedValue,
				Metadata: typedMetadata,
				Origin:   kvpair.Origin,
			})
	}

	typedDump, err := da.descriptor.Dump(correlateWithType)
	if err != nil {
		return nil, err
	}
	var dump []KVWithMetadata
	for _, typedKVWithMetadata := range typedDump {
		kvWithMetadata := KVWithMetadata{
			Key:      typedKVWithMetadata.Key,
			Metadata: typedKVWithMetadata.Metadata,
			Origin:   typedKVWithMetadata.Origin,
			}
		{{- if .IsProtoValue }}
		kvWithMetadata.Value = NewProtoValue(typedKVWithMetadata.Value)
		{{- else }}
		kvWithMetadata.Value = typedKVWithMetadata.Value
		{{- end }}
		dump = append(dump, kvWithMetadata)
	}
	return dump, err
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DumpDependencies() []string {
	return da.descriptor.DumpDependencies()
}

////////// Helper methods //////////

func cast{{ .DescriptorName }}ValueData(key string, valueData interface{}) ({{ .ValueDataT }}, error) {
{{- if .FromDatasync }}
	changeValue, isChange := valueData.(datasync.ChangeValue)
	if !isChange {
		return nil, ErrInvalidValueDataType(key)
	}
	protoMessage := &{{ .ValueDataBaseT }}{}
	err := changeValue.GetValue(protoMessage)
	if err != nil {
		return nil, err
	}
	return protoMessage, nil
{{- else }}
	typedValueData, ok := valueData.({{ .ValueDataT }})
	if !ok {
		return nil, ErrInvalidValueDataType(key)
	}
	return typedValueData, nil
{{- end }}
}

func cast{{ .DescriptorName }}Value(key string, value Value) ({{ .ValueT }}, error) {
{{- if .IsProtoValue }}
	protoValue, isProto := value.(ProtoValue)
	if !isProto {
		return nil, ErrInvalidValueType(key, value)
	}
	protoWithType, ok := protoValue.GetProtoMessage().({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return protoWithType, nil
{{- else }}
	typedValue, ok := value.({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return typedValue, nil
{{- end }}
}

func cast{{ .DescriptorName }}Metadata(key string, metadata Metadata) ({{ .MetadataT }}, error) {
	if metadata == nil {
		return nil, nil
	}
	typedMetadata, ok := metadata.({{ .MetadataT }})
	if !ok {
		return nil, ErrInvalidMetadataType(key)
	}
	return typedMetadata, nil
}
`
<commit_msg>Fix adapter-generator template.<commit_after>// Copyright (c) 2018 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

const adapterTemplate = `// Code generated by adapter-generator. DO NOT EDIT.

package adapter

import (
	"fmt"
	"github.com/ligato/cn-infra/datasync"
	. "github.com/ligato/cn-infra/kvscheduler/api"
	. "github.com/ligato/cn-infra/kvscheduler/value/protoval"

    {{- range $i, $path := .Imports }}
	"{{ $path }}"
	{{- end }}
)

////////// type-safe key-value pair with metadata //////////

type {{ .DescriptorName }}KVWithMetadata struct {
	Key      string
	Value    {{ .ValueT }}
	Metadata {{ .MetadataT }}
	Origin   ValueOrigin
}

////////// type-safe Descriptor interface //////////

type {{ .DescriptorName }}DescriptorAPI interface {
	GetName() string
	KeySelector(key string) bool
	NBKeyPrefixes() []string
	WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory)
{{- if .IsProtoValue }}
	Build(key string, valueData {{ .ValueDataT }}) (value ProtoValue, err error)
{{- else }}
	Build(key string, valueData {{ .ValueDataT }}) (value {{ .ValueT }}, err error)
{{- end }}
	Add(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error)
	Delete(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Modify(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error)
	ModifyHasToRecreate(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool
	Update(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error
	Dependencies(key string, value {{ .ValueT }}) []Dependency
	DerivedValues(key string, value {{ .ValueT }}) []KeyValuePair
	Dump(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error)
	DumpDependencies() []string
}

////////// Descriptor base implementation //////////

// {{ .DescriptorName }}DescriptorBase provides default(=empty) implementations
// for all the methods to extend from.
type {{ .DescriptorName }}DescriptorBase struct {
}

func (db *{{ .DescriptorName }}DescriptorBase) GetName() string {
	return "base"
}

func (db *{{ .DescriptorName }}DescriptorBase) KeySelector(key string) bool {
	return false
}

func (db *{{ .DescriptorName }}DescriptorBase) NBKeyPrefixes() []string {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory) {
	return false, nil
}

{{ if .IsProtoValue -}}
func (db *{{ .DescriptorName }}DescriptorBase) Build(key string, valueData {{ .ValueDataT }}) (value ProtoValue, err error) {
{{- if .FromDatasync }}
	// You can override specific methods of ProtoValue using embedding:
	//
	//	type MyProtoValue struct {
	//		ProtoValue
	//      typedMsg {{ .ValueDataT }}
	//	}
	//
	//	// ... (override some methods)
	//
	//  return &MyProtoValue{ProtoValue: NewProtoValue(valueData), typedMsg: valueData}	, nil
	return NewProtoValue(valueData), nil
{{- else }}
	return nil, nil
{{- end }}
}
{{- else }}
func (db *{{ .DescriptorName }}DescriptorBase) Build(key string, valueData {{ .ValueDataT }}) (value {{ .ValueT }}, err error) {
	return nil, nil
}
{{- end }}

func (db *{{ .DescriptorName }}DescriptorBase) Add(key string, value {{ .ValueT }}) (metadata {{ .MetadataT }}, err error) {
	fmt.Printf("Create for key=%s is not implemented\n", key)
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Delete(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error {
	fmt.Printf("Delete for key=%s is not implemented\n", key)
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Modify(key string, oldValue, newValue {{ .ValueT }}, oldMetadata {{ .MetadataT }}) (newMetadata {{ .MetadataT }}, err error) {
	fmt.Printf("Modify for key=%s is not implemented\n", key)
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) ModifyHasToRecreate(key string, oldValue, newValue {{ .ValueT }}, metadata {{ .MetadataT }}) bool {
	return false
}

func (db *{{ .DescriptorName }}DescriptorBase) Update(key string, value {{ .ValueT }}, metadata {{ .MetadataT }}) error {
	fmt.Printf("Update for key=%s is not implemented\n", key)
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Dependencies(key string, value {{ .ValueT }}) []Dependency {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) DerivedValues(key string, value {{ .ValueT }}) []KeyValuePair {
	return nil
}

func (db *{{ .DescriptorName }}DescriptorBase) Dump(correlate []{{ .DescriptorName }}KVWithMetadata) ([]{{ .DescriptorName }}KVWithMetadata, error) {
	fmt.Println("Dump is not implemented")
	return nil, nil
}

func (db *{{ .DescriptorName }}DescriptorBase) DumpDependencies() []string {
	return nil
}

////////// Descriptor adapter //////////

type {{ .DescriptorName }}DescriptorAdapter struct {
	descriptor {{ .DescriptorName }}DescriptorAPI
}

func New{{ .DescriptorName }}Descriptor(impl {{ .DescriptorName }}DescriptorAPI) KVDescriptor {
	return &{{ .DescriptorName }}DescriptorAdapter{descriptor: impl}
}

func (da *{{ .DescriptorName }}DescriptorAdapter) GetName() string {
	return da.descriptor.GetName()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) KeySelector(key string) bool {
	return da.descriptor.KeySelector(key)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) NBKeyPrefixes() []string {
	return da.descriptor.NBKeyPrefixes()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) WithMetadata() (withMeta bool, customMapFactory MetadataMapFactory) {
	return da.descriptor.WithMetadata()
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Build(key string, valueData interface{}) (value Value, err error) {
	typedValueData, err := cast{{ .DescriptorName }}ValueData(key, valueData)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Build(key, typedValueData)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Add(key string, value Value) (metadata Metadata, err error) {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Add(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Modify(key string, oldValue, newValue Value, oldMetadata Metadata) (newMetadata Metadata, err error) {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return nil, err
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return nil, err
	}
	typedOldMetadata, err := cast{{ .DescriptorName }}Metadata(key, oldMetadata)
	if err != nil {
		return nil, err
	}
	return da.descriptor.Modify(key, oldTypedValue, newTypedValue, typedOldMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Delete(key string, value Value, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Delete(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) ModifyHasToRecreate(key string, oldValue, newValue Value, metadata Metadata) bool {
	oldTypedValue, err := cast{{ .DescriptorName }}Value(key, oldValue)
	if err != nil {
		return true
	}
	newTypedValue, err := cast{{ .DescriptorName }}Value(key, newValue)
	if err != nil {
		return true
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return true
	}
	return da.descriptor.ModifyHasToRecreate(key, oldTypedValue, newTypedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Update(key string, value Value, metadata Metadata) error {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return err
	}
	typedMetadata, err := cast{{ .DescriptorName }}Metadata(key, metadata)
	if err != nil {
		return err
	}
	return da.descriptor.Update(key, typedValue, typedMetadata)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dependencies(key string, value Value) []Dependency {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.Dependencies(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DerivedValues(key string, value Value) []KeyValuePair {
	typedValue, err := cast{{ .DescriptorName }}Value(key, value)
	if err != nil {
		return nil
	}
	return da.descriptor.DerivedValues(key, typedValue)
}

func (da *{{ .DescriptorName }}DescriptorAdapter) Dump(correlate []KVWithMetadata) ([]KVWithMetadata, error) {
	var correlateWithType []{{ .DescriptorName }}KVWithMetadata
	for _, kvpair := range correlate {
		typedValue, err := cast{{ .DescriptorName }}Value(kvpair.Key, kvpair.Value)
		if err != nil {
			continue
		}
		typedMetadata, err := cast{{ .DescriptorName }}Metadata(kvpair.Key, kvpair.Metadata)
		if err != nil {
			continue
		}
		correlateWithType = append(correlateWithType,
			{{ .DescriptorName }}KVWithMetadata{
				Key:      kvpair.Key,
				Value:    typedValue,
				Metadata: typedMetadata,
				Origin:   kvpair.Origin,
			})
	}

	typedDump, err := da.descriptor.Dump(correlateWithType)
	if err != nil {
		return nil, err
	}
	var dump []KVWithMetadata
	for _, typedKVWithMetadata := range typedDump {
		kvWithMetadata := KVWithMetadata{
			Key:      typedKVWithMetadata.Key,
			Metadata: typedKVWithMetadata.Metadata,
			Origin:   typedKVWithMetadata.Origin,
			}
		{{- if .IsProtoValue }}
		value, err := da.descriptor.Build(typedKVWithMetadata.Key, typedKVWithMetadata.Value)
		if err != nil {
			return nil, err
		}
		kvWithMetadata.Value = value
		{{- else }}
		kvWithMetadata.Value = typedKVWithMetadata.Value
		{{- end }}
		dump = append(dump, kvWithMetadata)
	}
	return dump, err
}

func (da *{{ .DescriptorName }}DescriptorAdapter) DumpDependencies() []string {
	return da.descriptor.DumpDependencies()
}

////////// Helper methods //////////

func cast{{ .DescriptorName }}ValueData(key string, valueData interface{}) ({{ .ValueDataT }}, error) {
{{- if .FromDatasync }}
	changeValue, isChange := valueData.(datasync.ChangeValue)
	if !isChange {
		return nil, ErrInvalidValueDataType(key)
	}
	protoMessage := &{{ .ValueDataBaseT }}{}
	err := changeValue.GetValue(protoMessage)
	if err != nil {
		return nil, err
	}
	return protoMessage, nil
{{- else }}
	typedValueData, ok := valueData.({{ .ValueDataT }})
	if !ok {
		return nil, ErrInvalidValueDataType(key)
	}
	return typedValueData, nil
{{- end }}
}

func cast{{ .DescriptorName }}Value(key string, value Value) ({{ .ValueT }}, error) {
{{- if .IsProtoValue }}
	protoValue, isProto := value.(ProtoValue)
	if !isProto {
		return nil, ErrInvalidValueType(key, value)
	}
	protoWithType, ok := protoValue.GetProtoMessage().({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return protoWithType, nil
{{- else }}
	typedValue, ok := value.({{ .ValueT }})
	if !ok {
		return nil, ErrInvalidValueType(key, value)
	}
	return typedValue, nil
{{- end }}
}

func cast{{ .DescriptorName }}Metadata(key string, metadata Metadata) ({{ .MetadataT }}, error) {
	if metadata == nil {
		return nil, nil
	}
	typedMetadata, ok := metadata.({{ .MetadataT }})
	if !ok {
		return nil, ErrInvalidMetadataType(key)
	}
	return typedMetadata, nil
}
`
<|endoftext|>


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

package gm

import (
	"github.com/cpmech/gosl/chk"
	"github.com/cpmech/gosl/fun"
	"github.com/cpmech/gosl/la"
	"github.com/cpmech/gosl/plt"
)

// Transfinite maps a reference square [-1,1]×[-1,1] into a curve-bounded quadrilateral
//
//                                   B1(s) _,B
//       c———————b                C--.___-'  |
//       |       |                 \         | B0(r)
//   s   |       |      y     B2(r) \        |
//   ↑   |       |      ↑           /      __A
//   |   d———————a      |          / ____,'
//   |                  |         D-'   B3(s)
//   +————→r            +————→x
//
type Transfinite struct {
	Ndim int         // space dimension
	B    []fun.Vs    // the boundary functions
	Bd   []fun.Vs    // derivatives of boundary functions
	C    []la.Vector // "corner" points
	X    []la.Vector // points at arbitrary positions along edges/faces
	Xd   []la.Vector // derivatives at arbitrary positions along edges/faces
}

// NewTransfinite allocates a new structure
//  B  -- boundary functions x(s) = B(s)
//  Bd -- derivative functions dxds(s) = B'(s)
func NewTransfinite(ndim int, B, Bd []fun.Vs) (o *Transfinite) {
	o = new(Transfinite)
	o.Ndim = ndim
	o.B = B
	o.Bd = Bd
	if o.Ndim == 2 {
		if len(B) != 4 || len(Bd) != 4 {
			chk.Panic("in 2D, four boundary functions B are required\n")
		}
		o.C = make([]la.Vector, 4)
		o.X = make([]la.Vector, 4)
		o.Xd = make([]la.Vector, 4)
		for i := 0; i < len(o.C); i++ {
			o.C[i] = la.NewVector(o.Ndim)
			o.X[i] = la.NewVector(o.Ndim)
			o.Xd[i] = la.NewVector(o.Ndim)
		}
		o.B[0](o.C[0], -1)
		o.B[0](o.C[1], +1)
		o.B[2](o.C[2], +1)
		o.B[2](o.C[3], -1)
	} else if o.Ndim == 3 {
		if len(B) != 6 {
			chk.Panic("in 3D, six boundary functions B are required\n")
		}
	} else {
		chk.Panic("space dimension (ndim) must be 2 or 3\n")
	}
	return
}

// Point computes "real" position x(r,s,t)
//  Input:
//    u -- the "reference" coordinates {r,s,t} ϵ [-1,+1]×[-1,+1]×[-1,+1]
//  Output:
//    x -- the "real" coordinates {x,y,z}
func (o *Transfinite) Point(x, u la.Vector) {
	if o.Ndim == 2 {
		r, s := u[0], u[1]
		A, B, C, D := o.X[0], o.X[1], o.X[2], o.X[3]
		m, n, p, q := o.C[0], o.C[1], o.C[2], o.C[3]
		o.B[0](A, r)
		o.B[1](B, s)
		o.B[2](C, r)
		o.B[3](D, s)
		for i := 0; i < o.Ndim; i++ {
			x[i] = 0.5*((1-s)*A[i]+(1+r)*B[i]+(1+s)*C[i]+(1-r)*D[i]) -
				0.25*((1-r)*((1-s)*m[i]+(1+s)*q[i])+(1+r)*((1-s)*n[i]+(1+s)*p[i]))
		}
		return
	}
	chk.Panic("Point function is not ready for 3D yet\n")
}

// Derivs calculates derivatives (=metric terms) @ u={r,s,t}
//  Input:
//    u -- the "reference" coordinates {r,s,t} ϵ [-1,+1]×[-1,+1]×[-1,+1]
//  Output:
//    dxdu -- the derivatives [dx/du]ij = dxi/duj
//    x    -- the "real" coordinates {x,y,z}
func (o *Transfinite) Derivs(dxdu *la.Matrix, x, u la.Vector) {
	if o.Ndim == 2 {
		r, s := u[0], u[1]
		A, B, C, D := o.X[0], o.X[1], o.X[2], o.X[3]
		a, b, c, d := o.Xd[0], o.Xd[1], o.Xd[2], o.Xd[3]
		m, n, p, q := o.C[0], o.C[1], o.C[2], o.C[3]
		o.B[0](A, r)
		o.B[1](B, s)
		o.B[2](C, r)
		o.B[3](D, s)
		o.Bd[0](a, r)
		o.Bd[1](b, s)
		o.Bd[2](c, r)
		o.Bd[3](d, s)
		var dxidr, dxids float64
		for i := 0; i < o.Ndim; i++ {

			x[i] = 0.5*((1-s)*A[i]+(1+r)*B[i]+(1+s)*C[i]+(1-r)*D[i]) -
				0.25*((1-r)*((1-s)*m[i]+(1+s)*q[i])+(1+r)*((1-s)*n[i]+(1+s)*p[i]))

			dxidr = 0.5*((1-s)*a[i]+B[i]+(1+s)*c[i]-D[i]) -
				0.25*((1-s)*(n[i]-m[i])+(1+s)*(p[i]-q[i]))

			dxids = 0.5*(-A[i]+(1+r)*b[i]+C[i]+(1-r)*d[i]) -
				0.25*((1-r)*(q[i]-m[i])+(1+r)*(p[i]-n[i]))

			dxdu.Set(i, 0, dxidr)
			dxdu.Set(i, 1, dxids)
		}
		return
	}
	chk.Panic("Derivs function is not ready for 3D yet\n")
}

// Draw draws figure formed by B
func (o *Transfinite) Draw(npts []int, args, argsBry *plt.A) {

	// auxiliary
	if len(npts) != o.Ndim {
		npts = make([]int, o.Ndim)
	}
	for i := 0; i < o.Ndim; i++ {
		if npts[i] < 3 {
			npts[i] = 3
		}
	}
	if args == nil {
		args = &plt.A{C: plt.C(0, 0), NoClip: true}
	}
	if argsBry == nil {
		argsBry = &plt.A{C: plt.C(0, 0), Lw: 2, NoClip: true}
	}
	x := la.NewVector(o.Ndim)
	u := la.NewVector(o.Ndim)

	// draw 0-lines
	x0 := make([]float64, npts[0])
	y0 := make([]float64, npts[0])
	for j := 0; j < npts[1]; j++ {
		u[1] = -1 + 2*float64(j)/float64(npts[1]-1)
		for i := 0; i < npts[0]; i++ {
			u[0] = -1 + 2*float64(i)/float64(npts[0]-1)
			o.Point(x, u)
			x0[i] = x[0]
			y0[i] = x[1]
		}
		plt.Plot(x0, y0, args)
	}

	// draw 1-lines
	x1 := make([]float64, npts[1])
	y1 := make([]float64, npts[1])
	for i := 0; i < npts[0]; i++ {
		u[0] = -1 + 2*float64(i)/float64(npts[0]-1)
		for j := 0; j < npts[1]; j++ {
			u[1] = -1 + 2*float64(j)/float64(npts[1]-1)
			o.Point(x, u)
			x1[j] = x[0]
			y1[j] = x[1]
		}
		plt.Plot(x1, y1, args)
	}

	// draw B0(r)
	for i := 0; i < npts[0]; i++ {
		r := -1 + 2*float64(i)/float64(npts[0]-1)
		o.B[0](x, r)
		x0[i] = x[0]
		y0[i] = x[1]
	}
	plt.Plot(x0, y0, argsBry)

	// draw B1(s)
	for j := 0; j < npts[1]; j++ {
		s := -1 + 2*float64(j)/float64(npts[1]-1)
		o.B[1](x, s)
		x1[j] = x[0]
		y1[j] = x[1]
	}
	plt.Plot(x1, y1, argsBry)

	// draw B2(r)
	for i := 0; i < npts[0]; i++ {
		r := -1 + 2*float64(i)/float64(npts[0]-1)
		o.B[2](x, r)
		x0[i] = x[0]
		y0[i] = x[1]
	}
	plt.Plot(x0, y0, argsBry)

	// draw B3(s)
	for j := 0; j < npts[1]; j++ {
		s := -1 + 2*float64(j)/float64(npts[1]-1)
		o.B[3](x, s)
		x1[j] = x[0]
		y1[j] = x[1]
	}
	plt.Plot(x1, y1, argsBry)
}
<commit_msg>Improve figure<commit_after>// Copyright 2016 The Gosl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gm

import (
	"github.com/cpmech/gosl/chk"
	"github.com/cpmech/gosl/fun"
	"github.com/cpmech/gosl/la"
	"github.com/cpmech/gosl/plt"
)

// Transfinite maps a reference square [-1,+1]×[-1,+1] into a curve-bounded quadrilateral
//
//                                             B[2](r(x,y)) _,'\
//              B[2](r)                                  _,'    \ B[1](s(x,y))
//             ┌───────┐                              _,'        \
//             │       │                             \            \
//      B[3](s)│       │B[1](s)     ⇒                 \         _,'
//   s         │       │                  B[3](s(x,y)) \     _,'
//   │         └───────┘               y                \ _,'  B[0](r(x,y))
//   └──r       B[0](r)                │                 '
//                                     └──x
type Transfinite struct {

	// input
	Ndim int         // space dimension
	B    []fun.Vs    // the boundary functions
	Bd   []fun.Vs    // derivatives of boundary functions
	C    []la.Vector // "corner" points

	// workspase
	xface  []la.Vector // points at arbitrary positions along edges/faces
	dxface []la.Vector // derivatives at arbitrary positions along edges/faces
}

// NewTransfinite allocates a new structure
//  B  -- boundary functions x(s) = B(s)
//  Bd -- derivative functions dxds(s) = B'(s)
func NewTransfinite(ndim int, B, Bd []fun.Vs) (o *Transfinite) {
	o = new(Transfinite)
	o.Ndim = ndim
	o.B = B
	o.Bd = Bd
	if o.Ndim == 2 {
		if len(B) != 4 || len(Bd) != 4 {
			chk.Panic("in 2D, four boundary functions B are required\n")
		}
		o.C = make([]la.Vector, 4)
		o.xface = make([]la.Vector, 4)
		o.dxface = make([]la.Vector, 4)
		for i := 0; i < len(o.C); i++ {
			o.C[i] = la.NewVector(o.Ndim)
			o.xface[i] = la.NewVector(o.Ndim)
			o.dxface[i] = la.NewVector(o.Ndim)
		}
		o.B[0](o.C[0], -1)
		o.B[0](o.C[1], +1)
		o.B[2](o.C[2], +1)
		o.B[2](o.C[3], -1)
	} else if o.Ndim == 3 {
		if len(B) != 6 {
			chk.Panic("in 3D, six boundary functions B are required\n")
		}
	} else {
		chk.Panic("space dimension (ndim) must be 2 or 3\n")
	}
	return
}

// Point computes "real" position x(r,s,t)
//  Input:
//    u -- the "reference" coordinates {r,s,t} ϵ [-1,+1]×[-1,+1]×[-1,+1]
//  Output:
//    x -- the "real" coordinates {x,y,z}
func (o *Transfinite) Point(x, u la.Vector) {
	if o.Ndim == 2 {
		r, s := u[0], u[1]
		A, B, C, D := o.xface[0], o.xface[1], o.xface[2], o.xface[3]
		m, n, p, q := o.C[0], o.C[1], o.C[2], o.C[3]
		o.B[0](A, r)
		o.B[1](B, s)
		o.B[2](C, r)
		o.B[3](D, s)
		for i := 0; i < o.Ndim; i++ {
			x[i] = 0.5*((1-s)*A[i]+(1+r)*B[i]+(1+s)*C[i]+(1-r)*D[i]) -
				0.25*((1-r)*((1-s)*m[i]+(1+s)*q[i])+(1+r)*((1-s)*n[i]+(1+s)*p[i]))
		}
		return
	}
	chk.Panic("Point function is not ready for 3D yet\n")
}

// Derivs calculates derivatives (=metric terms) @ u={r,s,t}
//  Input:
//    u -- the "reference" coordinates {r,s,t} ϵ [-1,+1]×[-1,+1]×[-1,+1]
//  Output:
//    dxdu -- the derivatives [dx/du]ij = dxi/duj
//    x    -- the "real" coordinates {x,y,z}
func (o *Transfinite) Derivs(dxdu *la.Matrix, x, u la.Vector) {
	if o.Ndim == 2 {
		r, s := u[0], u[1]
		A, B, C, D := o.xface[0], o.xface[1], o.xface[2], o.xface[3]
		a, b, c, d := o.dxface[0], o.dxface[1], o.dxface[2], o.dxface[3]
		m, n, p, q := o.C[0], o.C[1], o.C[2], o.C[3]
		o.B[0](A, r)
		o.B[1](B, s)
		o.B[2](C, r)
		o.B[3](D, s)
		o.Bd[0](a, r)
		o.Bd[1](b, s)
		o.Bd[2](c, r)
		o.Bd[3](d, s)
		var dxidr, dxids float64
		for i := 0; i < o.Ndim; i++ {

			x[i] = 0.5*((1-s)*A[i]+(1+r)*B[i]+(1+s)*C[i]+(1-r)*D[i]) -
				0.25*((1-r)*((1-s)*m[i]+(1+s)*q[i])+(1+r)*((1-s)*n[i]+(1+s)*p[i]))

			dxidr = 0.5*((1-s)*a[i]+B[i]+(1+s)*c[i]-D[i]) -
				0.25*((1-s)*(n[i]-m[i])+(1+s)*(p[i]-q[i]))

			dxids = 0.5*(-A[i]+(1+r)*b[i]+C[i]+(1-r)*d[i]) -
				0.25*((1-r)*(q[i]-m[i])+(1+r)*(p[i]-n[i]))

			dxdu.Set(i, 0, dxidr)
			dxdu.Set(i, 1, dxids)
		}
		return
	}
	chk.Panic("Derivs function is not ready for 3D yet\n")
}

// Draw draws figure formed by B
func (o *Transfinite) Draw(npts []int, args, argsBry *plt.A) {

	// auxiliary
	if len(npts) != o.Ndim {
		npts = make([]int, o.Ndim)
	}
	for i := 0; i < o.Ndim; i++ {
		if npts[i] < 3 {
			npts[i] = 3
		}
	}
	if args == nil {
		args = &plt.A{C: plt.C(0, 0), NoClip: true}
	}
	if argsBry == nil {
		argsBry = &plt.A{C: plt.C(0, 0), Lw: 2, NoClip: true}
	}
	x := la.NewVector(o.Ndim)
	u := la.NewVector(o.Ndim)

	// draw 0-lines
	x0 := make([]float64, npts[0])
	y0 := make([]float64, npts[0])
	for j := 0; j < npts[1]; j++ {
		u[1] = -1 + 2*float64(j)/float64(npts[1]-1)
		for i := 0; i < npts[0]; i++ {
			u[0] = -1 + 2*float64(i)/float64(npts[0]-1)
			o.Point(x, u)
			x0[i] = x[0]
			y0[i] = x[1]
		}
		plt.Plot(x0, y0, args)
	}

	// draw 1-lines
	x1 := make([]float64, npts[1])
	y1 := make([]float64, npts[1])
	for i := 0; i < npts[0]; i++ {
		u[0] = -1 + 2*float64(i)/float64(npts[0]-1)
		for j := 0; j < npts[1]; j++ {
			u[1] = -1 + 2*float64(j)/float64(npts[1]-1)
			o.Point(x, u)
			x1[j] = x[0]
			y1[j] = x[1]
		}
		plt.Plot(x1, y1, args)
	}

	// draw B0(r)
	for i := 0; i < npts[0]; i++ {
		r := -1 + 2*float64(i)/float64(npts[0]-1)
		o.B[0](x, r)
		x0[i] = x[0]
		y0[i] = x[1]
	}
	plt.Plot(x0, y0, argsBry)

	// draw B1(s)
	for j := 0; j < npts[1]; j++ {
		s := -1 + 2*float64(j)/float64(npts[1]-1)
		o.B[1](x, s)
		x1[j] = x[0]
		y1[j] = x[1]
	}
	plt.Plot(x1, y1, argsBry)

	// draw B2(r)
	for i := 0; i < npts[0]; i++ {
		r := -1 + 2*float64(i)/float64(npts[0]-1)
		o.B[2](x, r)
		x0[i] = x[0]
		y0[i] = x[1]
	}
	plt.Plot(x0, y0, argsBry)

	// draw B3(s)
	for j := 0; j < npts[1]; j++ {
		s := -1 + 2*float64(j)/float64(npts[1]-1)
		o.B[3](x, s)
		x1[j] = x[0]
		y1[j] = x[1]
	}
	plt.Plot(x1, y1, argsBry)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
)

// Keep this around to simplify things
var G = &libkb.G
var G_UI *UI

func parseArgs() (libkb.CommandLine, libcmdline.Command, error) {

	cl := libcmdline.NewCommandLine(true)
	cmds := []cli.Command{
		NewCmdConfig(cl),
		NewCmdDb(cl),
		NewCmdDevice(cl),
		NewCmdId(cl),
		NewCmdListTrackers(cl),
		NewCmdListTracking(cl),
		NewCmdLogin(cl),
		NewCmdLogout(cl),
		NewCmdMykey(cl),
		NewCmdPGP(cl),
		NewCmdPing(cl),
		NewCmdProve(cl),
		NewCmdResolve(cl),
		NewCmdSibkey(cl),
		NewCmdSigs(cl),
		NewCmdSignup(cl),
		NewCmdTest(cl),
		NewCmdTrack(cl),
		NewCmdVersion(cl),
	}
	cl.AddCommands(cmds)

	cmd, err := cl.Parse(os.Args)
	if err != nil {
		err = fmt.Errorf("Error parsing command line arguments: %s\n", err.Error())
		return nil, nil, err
	}
	return cl, cmd, nil
}

func main() {
	G_UI = &UI{}
	libcmdline.Main(parseArgs, G_UI, true)
}
<commit_msg>removed cmd test<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"
	"github.com/keybase/client/go/libcmdline"
	"github.com/keybase/client/go/libkb"
)

// Keep this around to simplify things
var G = &libkb.G
var G_UI *UI

func parseArgs() (libkb.CommandLine, libcmdline.Command, error) {

	cl := libcmdline.NewCommandLine(true)
	cmds := []cli.Command{
		NewCmdConfig(cl),
		NewCmdDb(cl),
		NewCmdDevice(cl),
		NewCmdId(cl),
		NewCmdListTrackers(cl),
		NewCmdListTracking(cl),
		NewCmdLogin(cl),
		NewCmdLogout(cl),
		NewCmdMykey(cl),
		NewCmdPGP(cl),
		NewCmdPing(cl),
		NewCmdProve(cl),
		NewCmdResolve(cl),
		NewCmdSibkey(cl),
		NewCmdSigs(cl),
		NewCmdSignup(cl),
		NewCmdTrack(cl),
		NewCmdVersion(cl),
	}
	cl.AddCommands(cmds)

	cmd, err := cl.Parse(os.Args)
	if err != nil {
		err = fmt.Errorf("Error parsing command line arguments: %s\n", err.Error())
		return nil, nil, err
	}
	return cl, cmd, nil
}

func main() {
	G_UI = &UI{}
	libcmdline.Main(parseArgs, G_UI, true)
}
<|endoftext|>


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

package gomock

import (
	"errors"
	"fmt"
)

// callSet represents a set of expected calls, indexed by receiver and method
// name.
type callSet map[interface{}]map[string][]*Call

// Add adds a new expected call.
func (cs callSet) Add(call *Call) {
	methodMap, ok := cs[call.receiver]
	if !ok {
		methodMap = make(map[string][]*Call)
		cs[call.receiver] = methodMap
	}
	methodMap[call.method] = append(methodMap[call.method], call)
}

// Remove removes an expected call.
func (cs callSet) Remove(call *Call) {
	methodMap, ok := cs[call.receiver]
	if !ok {
		return
	}
	sl := methodMap[call.method]
	for i, c := range sl {
		if c == call {
			// quick removal; we don't need to maintain call order
			if len(sl) > 1 {
				sl[i] = sl[len(sl)-1]
			}
			methodMap[call.method] = sl[:len(sl)-1]
			break
		}
	}
}

// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) {
	methodMap, ok := cs[receiver]
	if !ok {
		return nil, errors.New("there are no expected method calls for that receiver")
	}
	calls, ok := methodMap[method]
	if !ok {
		return nil, fmt.Errorf("there are no expected calls of the method: %s for that receiver", method)
	}

	// Search through the unordered set of calls expected on a method on a
	// receiver.
	callsErrors := ""
	for _, call := range calls {
		// A call should not normally still be here if exhausted,
		// but it can happen if, for instance, .Times(0) was used.
		// Pretend the call doesn't match.
		if call.exhausted() {
			callsErrors += "\nThe call was exhausted."
			continue
		}
		err := call.matches(args)
		if err != nil {
			callsErrors += "\n" + err.Error()
		} else {
			return call, nil
		}
	}

	return nil, fmt.Errorf(callsErrors)
}
<commit_msg>gomock: fix matcher's degenerate quadratic path.<commit_after>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gomock

import (
	"bytes"
	"errors"
	"fmt"
)

// callSet represents a set of expected calls, indexed by receiver and method
// name.
type callSet map[interface{}]map[string][]*Call

// Add adds a new expected call.
func (cs callSet) Add(call *Call) {
	methodMap, ok := cs[call.receiver]
	if !ok {
		methodMap = make(map[string][]*Call)
		cs[call.receiver] = methodMap
	}
	methodMap[call.method] = append(methodMap[call.method], call)
}

// Remove removes an expected call.
func (cs callSet) Remove(call *Call) {
	methodMap, ok := cs[call.receiver]
	if !ok {
		return
	}
	sl := methodMap[call.method]
	for i, c := range sl {
		if c == call {
			// quick removal; we don't need to maintain call order
			if len(sl) > 1 {
				sl[i] = sl[len(sl)-1]
			}
			methodMap[call.method] = sl[:len(sl)-1]
			break
		}
	}
}

// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) {
	methodMap, ok := cs[receiver]
	if !ok {
		return nil, errors.New("there are no expected method calls for that receiver")
	}
	calls, ok := methodMap[method]
	if !ok {
		return nil, fmt.Errorf("there are no expected calls of the method: %s for that receiver", method)
	}

	// Search through the unordered set of calls expected on a method on a
	// receiver.
	var callsErrors bytes.Buffer
	for _, call := range calls {
		// A call should not normally still be here if exhausted,
		// but it can happen if, for instance, .Times(0) was used.
		// Pretend the call doesn't match.
		if call.exhausted() {
			callsErrors.WriteString("\nThe call was exhausted.")
			continue
		}
		err := call.matches(args)
		if err != nil {
			fmt.Fprintf(&callsErrors, "\n%v", err)
		} else {
			return call, nil
		}
	}

	return nil, fmt.Errorf(callsErrors.String())
}
<|endoftext|>