<commit_before>package ghg

import (
	"archive/zip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/octokit/go-octokit/octokit"
	"github.com/pkg/errors"
)

type ghg struct {
	binDir  string
	target  string
	version string
	client  *octokit.Client
}

func getOctCli(token string) *octokit.Client {
	var auth octokit.AuthMethod
	if token != "" {
		auth = octokit.TokenAuth{AccessToken: token}
	}
	return octokit.NewClient(auth)
}

func (gh *ghg) install() error {
	owner, repo, err := gh.getRepoAndOwner()
	if err != nil {
		return errors.Wrap(err, "failed to resolve target")
	}
	url, err := octokit.ReleasesLatestURL.Expand(octokit.M{"owner": owner, "repo": repo})
	if err != nil {
		return errors.Wrap(err, "failed to build GitHub URL")
	}
	release, r := gh.client.Releases(url).Latest()
	if r.HasError() {
		return errors.Wrap(r.Err, "failed to fetch latest release")
	}
	tag := release.TagName
	goarch := runtime.GOARCH
	goos := runtime.GOOS
	var urls []string
	for _, asset := range release.Assets {
		name := asset.Name
		if strings.Contains(name, goarch) && strings.Contains(name, goos) {
			urls = append(urls, fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/%s", owner, repo, tag, name))
		}
	}

	for _, url := range urls {
		archivePath, err := download(url)
		if err != nil {
			return errors.Wrap(err, "failed to download")
		}
		workDir := filepath.Join(filepath.Dir(archivePath), "work")
		fmt.Println(workDir)
		err = extract(archivePath, workDir)
		if err != nil {
			return errors.Wrap(err, "failed to extract")
		}
	}
	return nil
}

func download(url string) (fpath string, err error) {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		err = errors.Wrap(err, "failed to create request")
		return
	}
	req.Header.Set("User-Agent", fmt.Sprintf("ghg/%s", version))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		err = errors.Wrap(err, "failed to create request")
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		err = errors.Wrap(err, "failed to read response")
		return
	}
	archiveBase := path.Base(url)
	tempdir, err := ioutil.TempDir("", "ghg-")
	if err != nil {
		err = errors.Wrap(err, "failed to create tempdir")
		return
	}
	defer func() {
		if err != nil {
			os.RemoveAll(tempdir)
		}
	}()
	fpath = filepath.Join(tempdir, archiveBase)
	f, err := os.OpenFile(filepath.Join(tempdir, archiveBase), os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		err = errors.Wrap(err, "failed to open file")
		return
	}
	defer f.Close()
	_, err = f.Write(body)
	if err != nil {
		err = errors.Wrap(err, "failed to read response")
		return
	}
	return fpath, nil
}

func extract(src, dest string) error {
	base := filepath.Base(src)
	if strings.HasSuffix(base, ".zip") {
		return unzip(src, dest)
	}
	return nil
}

func unzip(src, dest string) error {
	r, err := zip.OpenReader(src)
	if err != nil {
		return err
	}
	defer r.Close()

	var move = func(f *zip.File) error {
		rc, err := f.Open()
		if err != nil {
			return err
		}
		defer rc.Close()

		path := filepath.Join(dest, f.Name)
		if f.FileInfo().IsDir() {
			os.MkdirAll(path, f.Mode())
		} else {
			os.MkdirAll(filepath.Dir(path), 0755)
			f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
			if err != nil {
				return errors.Wrap(err, "failed to openfile")
			}
			defer f.Close()
			_, err = io.Copy(f, rc)
			if err != nil {
				return errors.Wrap(err, "failed to copy")
			}
		}
		return nil
	}

	for _, f := range r.File {
		err := move(f)
		if err != nil {
			return err
		}
	}

	return nil
}

func (gh *ghg) getRepoAndOwner() (owner, repo string, err error) {
	arr := strings.SplitN(gh.target, "/", 2)
	if len(arr) < 1 {
		return "", "", fmt.Errorf("target invalid")
	}
	owner = arr[0]
	repo = arr[0]
	if len(arr) > 1 {
		repo = arr[1]
	}
	return
}
<commit_msg>extractTar<commit_after>package ghg

import (
	"archive/tar"
	"archive/zip"
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/octokit/go-octokit/octokit"
	"github.com/pkg/errors"
)

type ghg struct {
	binDir  string
	target  string
	version string
	client  *octokit.Client
}

func getOctCli(token string) *octokit.Client {
	var auth octokit.AuthMethod
	if token != "" {
		auth = octokit.TokenAuth{AccessToken: token}
	}
	return octokit.NewClient(auth)
}

func (gh *ghg) install() error {
	owner, repo, err := gh.getRepoAndOwner()
	if err != nil {
		return errors.Wrap(err, "failed to resolve target")
	}
	url, err := octokit.ReleasesLatestURL.Expand(octokit.M{"owner": owner, "repo": repo})
	if err != nil {
		return errors.Wrap(err, "failed to build GitHub URL")
	}
	release, r := gh.client.Releases(url).Latest()
	if r.HasError() {
		return errors.Wrap(r.Err, "failed to fetch latest release")
	}
	tag := release.TagName
	goarch := runtime.GOARCH
	goos := runtime.GOOS
	var urls []string
	for _, asset := range release.Assets {
		name := asset.Name
		if strings.Contains(name, goarch) && strings.Contains(name, goos) {
			urls = append(urls, fmt.Sprintf("https://github.com/%s/%s/releases/download/%s/%s", owner, repo, tag, name))
		}
	}

	for _, url := range urls {
		archivePath, err := download(url)
		if err != nil {
			return errors.Wrap(err, "failed to download")
		}
		workDir := filepath.Join(filepath.Dir(archivePath), "work")
		err = extract(archivePath, workDir)
		if err != nil {
			return errors.Wrap(err, "failed to extract")
		}
	}
	return nil
}

func download(url string) (fpath string, err error) {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		err = errors.Wrap(err, "failed to create request")
		return
	}
	req.Header.Set("User-Agent", fmt.Sprintf("ghg/%s", version))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		err = errors.Wrap(err, "failed to create request")
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		err = errors.Wrap(err, "failed to read response")
		return
	}
	archiveBase := path.Base(url)
	tempdir, err := ioutil.TempDir("", "ghg-")
	if err != nil {
		err = errors.Wrap(err, "failed to create tempdir")
		return
	}
	defer func() {
		if err != nil {
			os.RemoveAll(tempdir)
		}
	}()
	fpath = filepath.Join(tempdir, archiveBase)
	f, err := os.OpenFile(filepath.Join(tempdir, archiveBase), os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		err = errors.Wrap(err, "failed to open file")
		return
	}
	defer f.Close()
	_, err = f.Write(body)
	if err != nil {
		err = errors.Wrap(err, "failed to read response")
		return
	}
	return fpath, nil
}

func extract(src, dest string) error {
	base := filepath.Base(src)
	if strings.HasSuffix(base, ".zip") {
		return unzip(src, dest)
	}
	if strings.HasSuffix(base, ".tar.gz") || strings.HasSuffix(base, ".tgz") {
		return extractTar(src, dest)
	}
	return nil
}

func unzip(src, dest string) error {
	r, err := zip.OpenReader(src)
	if err != nil {
		return err
	}
	defer r.Close()

	var move = func(f *zip.File) error {
		rc, err := f.Open()
		if err != nil {
			return err
		}
		defer rc.Close()

		path := filepath.Join(dest, f.Name)
		if f.FileInfo().IsDir() {
			os.MkdirAll(path, f.Mode())
		} else {
			os.MkdirAll(filepath.Dir(path), 0755)
			f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
			if err != nil {
				return errors.Wrap(err, "failed to openfile")
			}
			defer f.Close()
			_, err = io.Copy(f, rc)
			if err != nil {
				return errors.Wrap(err, "failed to copy")
			}
		}
		return nil
	}

	for _, f := range r.File {
		err := move(f)
		if err != nil {
			return err
		}
	}

	return nil
}

func extractTar(src, dest string) error {
	file, err := os.Open(src)
	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("failed to open tgz file: %s", src))
	}
	defer file.Close()

	rdr, err := gzip.NewReader(file)
	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("failed to read tgz file: %s", src))
	}
	defer rdr.Close()

	tr := tar.NewReader(rdr)

	var header *tar.Header
	for {
		header, err = tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return errors.Wrap(err, "failed to read tar")
		}

		var buf *bytes.Buffer
		_, err = io.Copy(buf, tr)
		if err != nil {
			return errors.Wrap(err, "failed io.Copy")
		}

		if err = ioutil.WriteFile(filepath.Join(dest, header.Name), buf.Bytes(), 0755); err != nil {
			return errors.Wrap(err, fmt.Sprintf("failed to extract file: %s", src))
		}
	}
	return nil
}

func (gh *ghg) getRepoAndOwner() (owner, repo string, err error) {
	arr := strings.SplitN(gh.target, "/", 2)
	if len(arr) < 1 {
		return "", "", fmt.Errorf("target invalid")
	}
	owner = arr[0]
	repo = arr[0]
	if len(arr) > 1 {
		repo = arr[1]
	}
	return
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/codegangsta/cli"
	"github.com/howeyc/fsnotify"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

var (
	CompileErrors []byte
	Proxy         *httputil.ReverseProxy
	Dirty         = true
)

func main() {
	// set up logs
	log.SetFlags(0)
	log.SetPrefix("[gin] ")

	app := cli.NewApp()
	app.Name = "gin"
	app.Usage = "a Go development server"
	app.Flags = []cli.Flag{
		cli.IntFlag{"p", 5678, "port to run passport on"},
	}
	app.Action = DefaultAction

	app.Run(os.Args)
}

func DefaultAction(c *cli.Context) {
	url, err := url.Parse("http://localhost:3000")
	check(err)
	Proxy = httputil.NewSingleHostReverseProxy(url)

	go watch()
	go checkDirty()

	http.HandleFunc("/", MainHandler)
	port := c.GlobalInt("p")
	log.Printf("listening on port %v", port)
	err = http.ListenAndServe(fmt.Sprintf(":%v", port), nil)
	check(err)
}

func checkDirty() {
	var command *exec.Cmd
	for {
		if Dirty {
			log.Print("Restarting server...")
			build()
			if command != nil {
				command.Process.Kill()
			}
			command = run()
			Dirty = false
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func watch() {
	watcher, err := fsnotify.NewWatcher()
	check(err)

	pwd, err := os.Getwd()
	check(err)

	err = watcher.Watch(pwd)
	check(err)

	defer watcher.Close()

	for {
		select {
		case ev := <-watcher.Event:
			if ev.IsModify() && strings.HasSuffix(ev.Name, ".go") {
				Dirty = true
			}
		case err := <-watcher.Error:
			if err != nil {
				log.Print(err)
			}
		}
	}
}

func MainHandler(res http.ResponseWriter, req *http.Request) {
	if len(CompileErrors) > 0 {
		res.Write(CompileErrors)
	} else {
		Proxy.ServeHTTP(res, req)
	}
}

func build() {
	command := exec.Command("go", "build")

	stderr, err := command.StderrPipe()
	check(err)

	err = command.Start()
	check(err)

	CompileErrors, err = ioutil.ReadAll(stderr)
	check(err)
}

func run() *exec.Cmd {
	wd, err := os.Getwd()
	check(err)

	command := exec.Command(filepath.Join(wd, filepath.Base(wd)))
	stdout, err := command.StdoutPipe()
	check(err)

	err = command.Start()
	check(err)

	go io.Copy(os.Stdout, stdout)

	return command
}

func check(err error) {
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
}
<commit_msg>Playing with some other ways to sync server restarting<commit_after>package main

import (
	"fmt"
	"github.com/codegangsta/cli"
	"github.com/howeyc/fsnotify"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

var (
	CompileErrors []byte
	Proxy         *httputil.ReverseProxy
	Dirty         = true
	once          sync.Once
)

func main() {
	// set up logs
	log.SetFlags(0)
	log.SetPrefix("[gin] ")

	app := cli.NewApp()
	app.Name = "gin"
	app.Usage = "a Go development server"
	app.Flags = []cli.Flag{
		cli.IntFlag{"p", 5678, "port to run passport on"},
	}
	app.Action = DefaultAction

	app.Run(os.Args)
}

func DefaultAction(c *cli.Context) {
	url, err := url.Parse("http://localhost:3000")
	check(err)
	Proxy = httputil.NewSingleHostReverseProxy(url)

	go watch()
	go checkDirty()

	http.HandleFunc("/", MainHandler)
	port := c.GlobalInt("p")
	log.Printf("listening on port %v", port)
	err = http.ListenAndServe(fmt.Sprintf(":%v", port), nil)
	check(err)
}

func checkDirty() {
	var command *exec.Cmd
	for {
		if Dirty {
			log.Print("Restarting server...")
			build()
			if command != nil {
				command.Process.Kill()
			}
			command = run()
			Dirty = false
			time.Sleep(500 * time.Millisecond)
			once = sync.Once{}
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func watch() {
	watcher, err := fsnotify.NewWatcher()
	check(err)

	pwd, err := os.Getwd()
	check(err)

	err = watcher.Watch(pwd)
	check(err)

	defer watcher.Close()

	for {
		select {
		case ev := <-watcher.Event:
			if ev.IsModify() && strings.HasSuffix(ev.Name, ".go") {
				once.Do(func() {
					Dirty = true
				})
			}
		case err := <-watcher.Error:
			if err != nil {
				log.Print(err)
			}
		}
	}
}

func MainHandler(res http.ResponseWriter, req *http.Request) {
	if len(CompileErrors) > 0 {
		res.Write(CompileErrors)
	} else {
		Proxy.ServeHTTP(res, req)
	}
}

func build() {
	command := exec.Command("go", "build")

	stderr, err := command.StderrPipe()
	check(err)

	err = command.Start()
	check(err)

	CompileErrors, err = ioutil.ReadAll(stderr)
	check(err)
}

func run() *exec.Cmd {
	wd, err := os.Getwd()
	check(err)

	command := exec.Command(filepath.Join(wd, filepath.Base(wd)))
	stdout, err := command.StdoutPipe()
	check(err)

	err = command.Start()
	check(err)

	go io.Copy(os.Stdout, stdout)

	return command
}

func check(err error) {
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
}
<|endoftext|>


<commit_before>package git

import (
	"bytes"
	"regexp"
	"strings"
)

// Status is a type for reporting the status of a git repo
type Status uint8

const (
	// StatusUpToDate means the local repo matches origin
	StatusUpToDate Status = iota

	// StatusNeedToPull means the local repo needs to pull from the remote
	StatusNeedToPull

	// StatusNeedToPush means the local repo needs to be pushed to the remote
	StatusNeedToPush

	// StatusDiverged means the local repo has diverged from the remote
	StatusDiverged
)

func (s Status) String() string {
	switch s {
	case StatusUpToDate:
		return "StatusUpToDate"
	case StatusNeedToPull:
		return "StatusNeedToPull"
	case StatusNeedToPush:
		return "StatusNeedToPush"
	case StatusDiverged:
		return "StatusDiverged"
	default:
		panic("invalid status")
	}
}

// GitRemoteRegex is a regex for pulling account owner from the output of `git remote -v`
var GitRemoteRegex = regexp.MustCompile(`^([^\t\n\f\r ]+)[\t\n\v\f\r ]+(git@github\.com:|(http[s]?|git):\/\/github\.com\/)([a-zA-Z0-9]{1}[a-zA-Z0-9-]*)\/([a-zA-Z0-9_.-]+)(\.git|[^\t\n\f\r ])+.*$`)

var runner commandRunner

/*
Branch determines the git branch in the repo located at `top`.  Two attempts
are made to determine branch. First:

  git rev-parse -q --abbrev-ref HEAD

If the current working directory is not on a branch, the result will return
"HEAD". In this case, branch will be estimated by parsing the output of the
following:

  git branch -ar --contains $(git rev-parse -q HEAD)
*/
func Branch(top string) string {
	initializeRunner()
	branchBytes, err := runner.BranchCommand(top)
	if err != nil {
		return ""
	}
	branch := strings.TrimRight(string(branchBytes), "\n")
	if branch == "HEAD" {
		branchBytes, err := runner.BranchCommand2(top)
		if err != nil {
			return branch
		}
		branches := strings.Split(strings.TrimRight(string(branchBytes), "\n"), "\n")
		for _, branchStr := range branches {
			if len(branchStr) < 1 || string(branchStr[0]) == "*" {
				continue
			}
			sections := strings.Split(strings.Trim(branchStr, " \n"), "/")
			return sections[len(sections)-1]
		}
	}
	return branch
}

// Sha produces the git branch at `top` as determined by `git rev-parse -q HEAD`
func Sha(top string) string {
	initializeRunner()
	shaBytes, err := runner.ShaCommand(top)
	if err != nil {
		return ""
	}
	return strings.TrimRight(string(shaBytes), "\n")
}

// Tag produces the git tag at `top` as determined by `git describe --always --dirty --tags`
func Tag(top string) string {
	initializeRunner()
	shortBytes, err := runner.TagCommand(top)
	if err != nil {
		return ""
	}
	return strings.TrimRight(string(shortBytes), "\n")
}

// IsClean returns true `git diff --shortstat` produces no output
func IsClean(top string) bool {
	initializeRunner()
	outBytes, err := runner.CleanCommand(top)
	if err != nil || len(outBytes) > 0 {
		return false
	}
	return true
}

//UpToDate returns the status of the repo as determined by the above constants
func UpToDate(top string) Status {
	initializeRunner()
	local, err := runner.UpToDateLocal(top)
	if err != nil {
		return StatusDiverged
	}

	remote, err := runner.UpToDateRemote(top)
	if err != nil {
		return StatusDiverged
	}

	if bytes.Compare(local, remote) == 0 {
		return StatusUpToDate
	}

	base, err := runner.UpToDateBase(top)
	if err != nil {
		return StatusDiverged
	}

	if bytes.Compare(local, base) == 0 {
		return StatusNeedToPull
	} else if bytes.Compare(remote, base) == 0 {
		return StatusNeedToPush
	}
	return StatusDiverged
}

/*
RemoteAccount returns the github account as determined by the output of `git
remote -v`
*/
func RemoteAccount(top string) string {
	initializeRunner()
	remotes, err := runner.RemoteV(top)
	if err != nil {
		return ""
	}

	lines := strings.Split(string(remotes), "\n")

	var ret string

	for _, line := range lines {
		matches := GitRemoteRegex.FindStringSubmatch(line)
		if len(matches) == 7 {
			if matches[1] == "origin" {
				return matches[4]
			}
		}
	}

	return ret
}

func initializeRunner() {
	if runner == nil {
		runner = &realRunner{}
	}
}
<commit_msg>Getting rid of unused variable<commit_after>package git

import (
	"bytes"
	"regexp"
	"strings"
)

// Status is a type for reporting the status of a git repo
type Status uint8

const (
	// StatusUpToDate means the local repo matches origin
	StatusUpToDate Status = iota

	// StatusNeedToPull means the local repo needs to pull from the remote
	StatusNeedToPull

	// StatusNeedToPush means the local repo needs to be pushed to the remote
	StatusNeedToPush

	// StatusDiverged means the local repo has diverged from the remote
	StatusDiverged
)

func (s Status) String() string {
	switch s {
	case StatusUpToDate:
		return "StatusUpToDate"
	case StatusNeedToPull:
		return "StatusNeedToPull"
	case StatusNeedToPush:
		return "StatusNeedToPush"
	case StatusDiverged:
		return "StatusDiverged"
	default:
		panic("invalid status")
	}
}

// GitRemoteRegex is a regex for pulling account owner from the output of `git remote -v`
var GitRemoteRegex = regexp.MustCompile(`^([^\t\n\f\r ]+)[\t\n\v\f\r ]+(git@github\.com:|(http[s]?|git):\/\/github\.com\/)([a-zA-Z0-9]{1}[a-zA-Z0-9-]*)\/([a-zA-Z0-9_.-]+)(\.git|[^\t\n\f\r ])+.*$`)

var runner commandRunner

/*
Branch determines the git branch in the repo located at `top`.  Two attempts
are made to determine branch. First:

  git rev-parse -q --abbrev-ref HEAD

If the current working directory is not on a branch, the result will return
"HEAD". In this case, branch will be estimated by parsing the output of the
following:

  git branch -ar --contains $(git rev-parse -q HEAD)
*/
func Branch(top string) string {
	initializeRunner()
	branchBytes, err := runner.BranchCommand(top)
	if err != nil {
		return ""
	}
	branch := strings.TrimRight(string(branchBytes), "\n")
	if branch == "HEAD" {
		branchBytes, err := runner.BranchCommand2(top)
		if err != nil {
			return branch
		}
		branches := strings.Split(strings.TrimRight(string(branchBytes), "\n"), "\n")
		for _, branchStr := range branches {
			if len(branchStr) < 1 || string(branchStr[0]) == "*" {
				continue
			}
			sections := strings.Split(strings.Trim(branchStr, " \n"), "/")
			return sections[len(sections)-1]
		}
	}
	return branch
}

// Sha produces the git branch at `top` as determined by `git rev-parse -q HEAD`
func Sha(top string) string {
	initializeRunner()
	shaBytes, err := runner.ShaCommand(top)
	if err != nil {
		return ""
	}
	return strings.TrimRight(string(shaBytes), "\n")
}

// Tag produces the git tag at `top` as determined by `git describe --always --dirty --tags`
func Tag(top string) string {
	initializeRunner()
	shortBytes, err := runner.TagCommand(top)
	if err != nil {
		return ""
	}
	return strings.TrimRight(string(shortBytes), "\n")
}

// IsClean returns true `git diff --shortstat` produces no output
func IsClean(top string) bool {
	initializeRunner()
	outBytes, err := runner.CleanCommand(top)
	if err != nil || len(outBytes) > 0 {
		return false
	}
	return true
}

//UpToDate returns the status of the repo as determined by the above constants
func UpToDate(top string) Status {
	initializeRunner()
	local, err := runner.UpToDateLocal(top)
	if err != nil {
		return StatusDiverged
	}

	remote, err := runner.UpToDateRemote(top)
	if err != nil {
		return StatusDiverged
	}

	if bytes.Compare(local, remote) == 0 {
		return StatusUpToDate
	}

	base, err := runner.UpToDateBase(top)
	if err != nil {
		return StatusDiverged
	}

	if bytes.Compare(local, base) == 0 {
		return StatusNeedToPull
	} else if bytes.Compare(remote, base) == 0 {
		return StatusNeedToPush
	}
	return StatusDiverged
}

/*
RemoteAccount returns the github account as determined by the output of `git
remote -v`
*/
func RemoteAccount(top string) string {
	initializeRunner()
	remotes, err := runner.RemoteV(top)
	if err != nil {
		return ""
	}

	lines := strings.Split(string(remotes), "\n")

	for _, line := range lines {
		matches := GitRemoteRegex.FindStringSubmatch(line)
		if len(matches) == 7 {
			if matches[1] == "origin" {
				return matches[4]
			}
		}
	}

	return ""
}

func initializeRunner() {
	if runner == nil {
		runner = &realRunner{}
	}
}
<|endoftext|>


<commit_before>package acceptance_test

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os/exec"
	"path/filepath"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("The CLI", func() {
	var (
		stackName  string
		envVars    map[string]string
		workingDir string
	)

	var start = func(envVars map[string]string, args ...string) *gexec.Session {
		command := exec.Command(pathToCLI, args...)
		command.Env = []string{}
		if envVars != nil {
			for k, v := range envVars {
				command.Env = append(command.Env, fmt.Sprintf("%s=%s", k, v))
			}
		}
		command.Dir = workingDir
		session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
		Expect(err).NotTo(HaveOccurred())
		return session
	}

	BeforeEach(func() {
		stackName = fmt.Sprintf("tubes-acceptance-test-%x", rand.Int())
		var err error
		workingDir, err = ioutil.TempDir("", "tubes-acceptance-test")
		Expect(err).NotTo(HaveOccurred())
	})

	Describe("happy path", func() {
		BeforeEach(func() {
			stackName = fmt.Sprintf("tubes-acceptance-test-%x", rand.Int())
			envVars = getEnvironment()
		})

		It("should support basic environment manipulation", func() { // slow happy path
			const NormalTimeout = "10s"
			const StackChangeTimeout = "6m"

			By("booting a fresh environment", func() {
				session := start(envVars, "-n", stackName, "up")

				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Creating keypair"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Looking for latest AWS NAT box AMI"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("ami-[a-f0-9]*"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Upserting base stack"))
				Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Stack update complete"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Upserting Concourse stack"))
				Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Stack update complete"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Finished"))
				Eventually(session, NormalTimeout).Should(gexec.Exit(0))
			})

			defaultStateDir := filepath.Join(workingDir, "environments", stackName)
			By("storing the SSH key on the filesystem", func() {
				Expect(ioutil.ReadFile(filepath.Join(defaultStateDir, "ssh-key"))).To(ContainSubstring("RSA PRIVATE KEY"))
			})

			By("exposing the SSH key", func() {
				session := start(envVars, "-n", stackName, "show")

				Eventually(session, NormalTimeout).Should(gexec.Exit(0))

				pemBlock, _ := pem.Decode(session.Out.Contents())
				Expect(pemBlock).NotTo(BeNil())
				Expect(pemBlock.Type).To(Equal("RSA PRIVATE KEY"))

				_, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
				Expect(err).NotTo(HaveOccurred())
			})

			By("supporting an explicit state directory, rather than the implicit subdirectory of the working directory", func() {
				session := start(envVars, "-n", stackName, "--state-dir", defaultStateDir, "show")

				Eventually(session, NormalTimeout).Should(gexec.Exit(0))

				pemBlock, _ := pem.Decode(session.Out.Contents())
				Expect(pemBlock).NotTo(BeNil())
				Expect(pemBlock.Type).To(Equal("RSA PRIVATE KEY"))
			})

			By("storing a generated BOSH director manifest in the state directory", func() {
				directorYAMLBytes, err := ioutil.ReadFile(filepath.Join(defaultStateDir, "director.yml"))
				Expect(err).NotTo(HaveOccurred())

				Expect(directorYAMLBytes).To(ContainSubstring("resource_pools:"))

				By("ensuring we create fresh credentials for the BOSH director")
				Expect(directorYAMLBytes).NotTo(ContainSubstring(envVars["AWS_SECRET_ACCESS_KEY"]))
			})

			By("tearing down the environment", func() {
				session := start(envVars, "-n", stackName, "down")

				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting Concourse stack"))
				Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Delete complete"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting base stack"))
				Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Delete complete"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting keypair"))
				Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Finished"))
				Eventually(session, NormalTimeout).Should(gexec.Exit(0))
			})
		})
	})
})
<commit_msg>Cleanup and simplify online acceptance test<commit_after>package acceptance_test

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"os/exec"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
)

var _ = Describe("Creating and destroying real environments", func() {
	var (
		stackName  string
		envVars    map[string]string
		workingDir string
	)

	var start = func(args ...string) *gexec.Session {
		command := exec.Command(pathToCLI, args...)
		command.Env = []string{}
		if envVars != nil {
			for k, v := range envVars {
				command.Env = append(command.Env, fmt.Sprintf("%s=%s", k, v))
			}
		}
		command.Dir = workingDir
		session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
		Expect(err).NotTo(HaveOccurred())
		return session
	}

	BeforeEach(func() {
		stackName = fmt.Sprintf("tubes-acceptance-test-%x", rand.Int())
		var err error
		workingDir, err = ioutil.TempDir("", "tubes-acceptance-test")
		Expect(err).NotTo(HaveOccurred())

		envVars = getEnvironment()
	})

	It("should support basic environment manipulation", func() { // slow happy path
		const NormalTimeout = "10s"
		const StackChangeTimeout = "6m"

		By("booting a fresh environment", func() {
			session := start("-n", stackName, "up")

			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Creating keypair"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Looking for latest AWS NAT box AMI"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("ami-[a-f0-9]*"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Upserting base stack"))
			Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Stack update complete"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Upserting Concourse stack"))
			Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Stack update complete"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Finished"))
			Eventually(session, NormalTimeout).Should(gexec.Exit(0))
		})

		By("tearing down the environment", func() {
			session := start("-n", stackName, "down")

			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting Concourse stack"))
			Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Delete complete"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting base stack"))
			Eventually(session.Err, StackChangeTimeout).Should(gbytes.Say("Delete complete"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Deleting keypair"))
			Eventually(session.Err, NormalTimeout).Should(gbytes.Say("Finished"))
			Eventually(session, NormalTimeout).Should(gexec.Exit(0))
		})
	})
})
<|endoftext|>


<commit_before>package shark

import(
	tp "tritium/proto"
	"libxml/xpath"
	"rubex"
	proto "goprotobuf.googlecode.com/hg/proto"
)

type Shark struct {
	RegexpCache map[string]*rubex.Regexp
	XPathCache map[string]*xpath.Expression
}

type Ctx struct {
	Functions []*Function
	Types []string
	Exports [][]string
	Logs []string
	Env map[string]string
	LocalVar map[string]interface{}
	*Shark
	*tp.Transform
}

type Function struct {
	Name string
	*tp.Function
}

type Scope struct {
	Value interface{}
}

func NewEngine() (*Shark) {
	e := &Shark{
		RegexpCache: make(map[string]*rubex.Regexp),
		XPathCache: make(map[string]*xpath.Expression),
	}
	return e
}

func (ctx *Ctx) UsePackage(pkg *tp.Package) {
	ctx.Types = make([]string, len(pkg.Types))
	for i, t := range(pkg.Types) {
		ctx.Types[i] = proto.GetString(t.Name)
	}

	ctx.Functions = make([]*Function, len(pkg.Functions))
	for i, f := range(pkg.Functions) {
		name := proto.GetString(f.Name)
		for _, a := range(f.Args) {
			typeString := ctx.Types[int(proto.GetInt32(a.TypeId))]
			name = name + "." + typeString
		}
		fun := &Function{
			Name: name,
			Function: f,
		}
		ctx.Functions[i] = fun
	}
}

func (eng *Shark) Run(transform *tp.Transform, input string, vars map[string]string) (data string, exports [][]string, logs []string) {
	ctx := &Ctx{
		Shark: eng,
		Exports: make([][]string, 0),
		Logs: make([]string, 0),
		Env: make(map[string]string),
		Transform: transform,
		LocalVar: make(map[string]interface{}, 0),
	}
	ctx.UsePackage(transform.Pkg)
	scope := &Scope{Value:input}
	ctx.runInstruction(scope, transform.Objects[0].Root)
	data = scope.Value.(string)
	return
}

func (ctx *Ctx) runInstruction(scope *Scope, ins *tp.Instruction) (returnValue interface{}) {
	returnValue = ""
	switch *ins.Type {
	case tp.Instruction_BLOCK:
		returnValue = ctx.runChildren(scope, ins)
	case tp.Instruction_TEXT:
		returnValue = proto.GetString(ins.Value)
	case tp.Instruction_LOCAL_VAR:
		name := proto.GetString(ins.Value)
		if len(ins.Arguments) > 0 {
			ctx.LocalVar[name] = ctx.runInstruction(scope, ins.Arguments[0])
		}
		returnValue = ctx.LocalVar[name]
	case tp.Instruction_FUNCTION_CALL:
		fun := ctx.Functions[int(proto.GetInt32(ins.FunctionId))]
		args := make([]interface{}, len(ins.Arguments))
		for i, argIns := range(ins.Arguments) {
			args[i] = ctx.runInstruction(scope, argIns)
		}
		if proto.GetBool(fun.BuiltIn) {
			switch fun.Name {
			case "concat.Text.Text":
				returnValue = args[0].(string) + args[1].(string)
			case "var.Text":
				ts := &Scope{Value: ctx.Env[args[0].(string)]}
				ctx.runChildren(ts, ins)
				returnValue = ts.Value
				ctx.Env[args[0].(string)] = returnValue.(string)
			case "export.Text":
				val := make([]string, 2)
				val[0] = args[0].(string)
				ts := &Scope{Value:""}
				ctx.runChildren(ts, ins)
				val[1] = ts.Value.(string)
				ctx.Exports = append(ctx.Exports, val)
			case "set.Text":
				scope.Value = args[0]
			case "log.Text":
				ctx.Logs = append(ctx.Logs, args[0].(string))
			default:
				println("Must implement", fun.Name)
			}
		} else {
			localVar := ctx.LocalVar
			ctx.LocalVar = make(map[string]interface{}, len(args))

			for i, arg := range(fun.Args) {
				ctx.LocalVar[proto.GetString(arg.Name)] = args[i]
			}

			ctx.LocalVar = localVar
		}
	}
	return
}

func (ctx *Ctx) runChildren(scope *Scope, ins *tp.Instruction) (returnValue interface{}) {
	for _, child := range(ins.Children) {
		returnValue = ctx.runInstruction(scope, child)
	}
	return
}
<commit_msg>function arguments setup<commit_after>package shark

import(
	tp "tritium/proto"
	"libxml/xpath"
	"rubex"
	proto "goprotobuf.googlecode.com/hg/proto"
)

type Shark struct {
	RegexpCache map[string]*rubex.Regexp
	XPathCache map[string]*xpath.Expression
}

type Ctx struct {
	Functions []*Function
	Types []string
	Exports [][]string
	Logs []string
	Env map[string]string
	LocalVar map[string]interface{}
	*Shark
	*tp.Transform
}

type Function struct {
	Name string
	*tp.Function
}

type Scope struct {
	Value interface{}
}

func NewEngine() (*Shark) {
	e := &Shark{
		RegexpCache: make(map[string]*rubex.Regexp),
		XPathCache: make(map[string]*xpath.Expression),
	}
	return e
}

func (ctx *Ctx) UsePackage(pkg *tp.Package) {
	ctx.Types = make([]string, len(pkg.Types))
	for i, t := range(pkg.Types) {
		ctx.Types[i] = proto.GetString(t.Name)
	}

	ctx.Functions = make([]*Function, len(pkg.Functions))
	for i, f := range(pkg.Functions) {
		name := proto.GetString(f.Name)
		for _, a := range(f.Args) {
			typeString := ctx.Types[int(proto.GetInt32(a.TypeId))]
			name = name + "." + typeString
		}
		fun := &Function{
			Name: name,
			Function: f,
		}
		ctx.Functions[i] = fun
	}
}

func (eng *Shark) Run(transform *tp.Transform, input string, vars map[string]string) (data string, exports [][]string, logs []string) {
	ctx := &Ctx{
		Shark: eng,
		Exports: make([][]string, 0),
		Logs: make([]string, 0),
		Env: make(map[string]string),
		Transform: transform,
		LocalVar: make(map[string]interface{}, 0),
	}
	ctx.UsePackage(transform.Pkg)
	scope := &Scope{Value:input}
	ctx.runInstruction(scope, transform.Objects[0].Root)
	data = scope.Value.(string)
	return
}

func (ctx *Ctx) runInstruction(scope *Scope, ins *tp.Instruction) (returnValue interface{}) {
	returnValue = ""
	switch *ins.Type {
	case tp.Instruction_BLOCK:
		returnValue = ctx.runChildren(scope, ins)
	case tp.Instruction_TEXT:
		returnValue = proto.GetString(ins.Value)
	case tp.Instruction_LOCAL_VAR:
		name := proto.GetString(ins.Value)
		if len(ins.Arguments) > 0 {
			ctx.LocalVar[name] = ctx.runInstruction(scope, ins.Arguments[0])
		}
		returnValue = ctx.LocalVar[name]
	case tp.Instruction_FUNCTION_CALL:
		fun := ctx.Functions[int(proto.GetInt32(ins.FunctionId))]
		args := make([]interface{}, len(ins.Arguments))
		for i, argIns := range(ins.Arguments) {
			args[i] = ctx.runInstruction(scope, argIns)
		}
		if proto.GetBool(fun.BuiltIn) {
			switch fun.Name {
			case "concat.Text.Text":
				returnValue = args[0].(string) + args[1].(string)
			case "var.Text":
				ts := &Scope{Value: ctx.Env[args[0].(string)]}
				ctx.runChildren(ts, ins)
				returnValue = ts.Value
				ctx.Env[args[0].(string)] = returnValue.(string)
			case "export.Text":
				val := make([]string, 2)
				val[0] = args[0].(string)
				ts := &Scope{Value:""}
				ctx.runChildren(ts, ins)
				val[1] = ts.Value.(string)
				ctx.Exports = append(ctx.Exports, val)
			case "set.Text":
				scope.Value = args[0]
			case "log.Text":
				ctx.Logs = append(ctx.Logs, args[0].(string))
			default:
				println("Must implement", fun.Name)
			}
		} else {
			// Store the current frame
			localVar := ctx.LocalVar

			// Setup the new local var
			ctx.LocalVar = make(map[string]interface{}, len(args))
			for i, arg := range(fun.Args) {
				ctx.LocalVar[proto.GetString(arg.Name)] = args[i]
			}

			returnValue = ctx.runChildren(scope, fun.Instruction)

			// Put the local var scope back!
			ctx.LocalVar = localVar
		}
	}
	return
}

func (ctx *Ctx) runChildren(scope *Scope, ins *tp.Instruction) (returnValue interface{}) {
	for _, child := range(ins.Children) {
		returnValue = ctx.runInstruction(scope, child)
	}
	return
}
<|endoftext|>


<commit_before>package special

import (
	"testing"

	"github.com/ready-steady/probability"
	"github.com/ready-steady/probability/uniform"
	"github.com/ready-steady/support/assert"
)

func TestIncBeta(t *testing.T) {
	p, q := 2.0, 3.0
	logBeta := LogBeta(p, q)

	points := []float64{
		0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50,
		0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00,
	}

	values := []float64{
		0.000000000000000e+00,
		1.401875000000000e-02,
		5.230000000000002e-02,
		1.095187500000000e-01,
		1.807999999999999e-01,
		2.617187500000001e-01,
		3.483000000000000e-01,
		4.370187500000001e-01,
		5.248000000000003e-01,
		6.090187500000001e-01,
		6.875000000000000e-01,
		7.585187500000001e-01,
		8.208000000000000e-01,
		8.735187499999999e-01,
		9.163000000000000e-01,
		9.492187500000000e-01,
		9.728000000000000e-01,
		9.880187500000001e-01,
		9.963000000000000e-01,
		9.995187500000000e-01,
		1.000000000000000e+00,
	}

	actual := make([]float64, len(points))

	for i := range points {
		actual[i] = IncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 1e-15, t)

	p, q = 0.1, 0.2
	logBeta = LogBeta(p, q)

	values = []float64{
		0.000000000000000e+00,
		5.095391215346399e-01,
		5.482400859052436e-01,
		5.732625733722232e-01,
		5.925346573554778e-01,
		6.086596697678208e-01,
		6.228433547203172e-01,
		6.357578563479236e-01,
		6.478288604374864e-01,
		6.593557133297501e-01,
		6.705707961028990e-01,
		6.816739425887479e-01,
		6.928567823206671e-01,
		7.043251807250750e-01,
		7.163269829958610e-01,
		7.291961263917867e-01,
		7.434379555965913e-01,
		7.599272566076309e-01,
		7.804880320024465e-01,
		8.104335200313719e-01,
		1.000000000000000e+00,
	}

	for i := range points {
		actual[i] = IncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 2e-15, t)
}

func TestInvIncBeta(t *testing.T) {
	p, q := 1.0, 2.0
	logBeta := LogBeta(p, q)

	points := []float64{
		0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50,
		0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00,
	}

	values := []float64{
		0.000000000000000e+00,
		0.025320565519104e+00,
		0.051316701949486e+00,
		0.078045554270711e+00,
		0.105572809000084e+00,
		0.133974596215561e+00,
		0.163339973465924e+00,
		0.193774225170145e+00,
		0.225403330758517e+00,
		0.258380151290432e+00,
		0.292893218813452e+00,
		0.329179606750063e+00,
		0.367544467966324e+00,
		0.408392021690038e+00,
		0.452277442494834e+00,
		0.500000000000000e+00,
		0.552786404500042e+00,
		0.612701665379257e+00,
		0.683772233983162e+00,
		0.776393202250021e+00,
		1.000000000000000e+00,
	}

	actual := make([]float64, len(points))

	for i := range points {
		actual[i] = InvIncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 2e-15, t)

	p, q = 0.2, 0.3
	logBeta = LogBeta(p, q)

	values = []float64{
		0.000000000000000e+00,
		2.793072851850660e-06,
		8.937381711316164e-05,
		6.784491773826951e-04,
		2.855345858289119e-03,
		8.684107512129325e-03,
		2.144658503798324e-02,
		4.568556852983932e-02,
		8.683942933344659e-02,
		1.502095712585510e-01,
		2.391350361479824e-01,
		3.527066234122371e-01,
		4.840600731467657e-01,
		6.206841200371190e-01,
		7.474718280552188e-01,
		8.514539745840592e-01,
		9.257428898178934e-01,
		9.707021084050310e-01,
		9.923134416335146e-01,
		9.992341305241808e-01,
		1.000000000000000e+00,
	}

	for i := range points {
		actual[i] = InvIncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 1e-14, t)
}

func BenchmarkIncBeta(b *testing.B) {
	p, q := 0.5, 1.5
	logBeta := LogBeta(p, q)
	points := probability.Sample(uniform.New(0, 1), 1000)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range points {
			IncBeta(x, p, q, logBeta)
		}
	}
}

func BenchmarkInvIncBeta(b *testing.B) {
	p, q := 0.5, 1.5
	logBeta := LogBeta(p, q)
	points := probability.Sample(uniform.New(0, 1), 1000)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, α := range points {
			InvIncBeta(α, p, q, logBeta)
		}
	}
}
<commit_msg>Update the path to assert<commit_after>package special

import (
	"testing"

	"github.com/ready-steady/assert"
	"github.com/ready-steady/probability"
	"github.com/ready-steady/probability/uniform"
)

func TestIncBeta(t *testing.T) {
	p, q := 2.0, 3.0
	logBeta := LogBeta(p, q)

	points := []float64{
		0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50,
		0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00,
	}

	values := []float64{
		0.000000000000000e+00,
		1.401875000000000e-02,
		5.230000000000002e-02,
		1.095187500000000e-01,
		1.807999999999999e-01,
		2.617187500000001e-01,
		3.483000000000000e-01,
		4.370187500000001e-01,
		5.248000000000003e-01,
		6.090187500000001e-01,
		6.875000000000000e-01,
		7.585187500000001e-01,
		8.208000000000000e-01,
		8.735187499999999e-01,
		9.163000000000000e-01,
		9.492187500000000e-01,
		9.728000000000000e-01,
		9.880187500000001e-01,
		9.963000000000000e-01,
		9.995187500000000e-01,
		1.000000000000000e+00,
	}

	actual := make([]float64, len(points))

	for i := range points {
		actual[i] = IncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 1e-15, t)

	p, q = 0.1, 0.2
	logBeta = LogBeta(p, q)

	values = []float64{
		0.000000000000000e+00,
		5.095391215346399e-01,
		5.482400859052436e-01,
		5.732625733722232e-01,
		5.925346573554778e-01,
		6.086596697678208e-01,
		6.228433547203172e-01,
		6.357578563479236e-01,
		6.478288604374864e-01,
		6.593557133297501e-01,
		6.705707961028990e-01,
		6.816739425887479e-01,
		6.928567823206671e-01,
		7.043251807250750e-01,
		7.163269829958610e-01,
		7.291961263917867e-01,
		7.434379555965913e-01,
		7.599272566076309e-01,
		7.804880320024465e-01,
		8.104335200313719e-01,
		1.000000000000000e+00,
	}

	for i := range points {
		actual[i] = IncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 2e-15, t)
}

func TestInvIncBeta(t *testing.T) {
	p, q := 1.0, 2.0
	logBeta := LogBeta(p, q)

	points := []float64{
		0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50,
		0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00,
	}

	values := []float64{
		0.000000000000000e+00,
		0.025320565519104e+00,
		0.051316701949486e+00,
		0.078045554270711e+00,
		0.105572809000084e+00,
		0.133974596215561e+00,
		0.163339973465924e+00,
		0.193774225170145e+00,
		0.225403330758517e+00,
		0.258380151290432e+00,
		0.292893218813452e+00,
		0.329179606750063e+00,
		0.367544467966324e+00,
		0.408392021690038e+00,
		0.452277442494834e+00,
		0.500000000000000e+00,
		0.552786404500042e+00,
		0.612701665379257e+00,
		0.683772233983162e+00,
		0.776393202250021e+00,
		1.000000000000000e+00,
	}

	actual := make([]float64, len(points))

	for i := range points {
		actual[i] = InvIncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 2e-15, t)

	p, q = 0.2, 0.3
	logBeta = LogBeta(p, q)

	values = []float64{
		0.000000000000000e+00,
		2.793072851850660e-06,
		8.937381711316164e-05,
		6.784491773826951e-04,
		2.855345858289119e-03,
		8.684107512129325e-03,
		2.144658503798324e-02,
		4.568556852983932e-02,
		8.683942933344659e-02,
		1.502095712585510e-01,
		2.391350361479824e-01,
		3.527066234122371e-01,
		4.840600731467657e-01,
		6.206841200371190e-01,
		7.474718280552188e-01,
		8.514539745840592e-01,
		9.257428898178934e-01,
		9.707021084050310e-01,
		9.923134416335146e-01,
		9.992341305241808e-01,
		1.000000000000000e+00,
	}

	for i := range points {
		actual[i] = InvIncBeta(points[i], p, q, logBeta)
	}
	assert.EqualWithin(actual, values, 1e-14, t)
}

func BenchmarkIncBeta(b *testing.B) {
	p, q := 0.5, 1.5
	logBeta := LogBeta(p, q)
	points := probability.Sample(uniform.New(0, 1), 1000)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, x := range points {
			IncBeta(x, p, q, logBeta)
		}
	}
}

func BenchmarkInvIncBeta(b *testing.B) {
	p, q := 0.5, 1.5
	logBeta := LogBeta(p, q)
	points := probability.Sample(uniform.New(0, 1), 1000)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		for _, α := range points {
			InvIncBeta(α, p, q, logBeta)
		}
	}
}
<|endoftext|>


<commit_before>package dalga

import (
	"database/sql"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/cenkalti/dalga/dalga/Godeps/_workspace/src/github.com/cenkalti/backoff"
	"github.com/cenkalti/dalga/dalga/Godeps/_workspace/src/github.com/go-sql-driver/mysql"
)

type scheduler struct {
	table               *table
	client              http.Client
	baseURL             string
	randomizationFactor float64
	// to stop scheduler goroutine
	stop chan struct{}
	// will be closed when scheduler goroutine is stopped
	stopped chan struct{}
	// to wake up scheduler when a new job is scheduled or cancelled
	wakeUp      chan struct{}
	runningJobs map[JobKey]struct{}
	m           sync.Mutex
	wg          sync.WaitGroup
}

func newScheduler(t *table, baseURL string, clientTimeout time.Duration, randomizationFactor float64) *scheduler {
	s := &scheduler{
		table:               t,
		baseURL:             baseURL,
		randomizationFactor: randomizationFactor,
		stop:                make(chan struct{}),
		stopped:             make(chan struct{}),
		wakeUp:              make(chan struct{}, 1),
		runningJobs:         make(map[JobKey]struct{}),
	}
	s.client.Timeout = clientTimeout
	return s
}

func (s *scheduler) WakeUp(debugMessage string) {
	select {
	case s.wakeUp <- struct{}{}:
		debug("notifying scheduler:", debugMessage)
	default:
	}
}

func (s *scheduler) NotifyDone() <-chan struct{} {
	return s.stopped
}

func (s *scheduler) Stop() {
	close(s.stop)
}

func (s *scheduler) Running() int {
	s.m.Lock()
	defer s.m.Unlock()
	return len(s.runningJobs)
}

// Run runs a loop that reads the next Job from the queue and executees it in it's own goroutine.
func (s *scheduler) Run() {
	defer close(s.stopped)

	for {
		debug("---")

		var after <-chan time.Time

		job, err := s.table.Front()
		if err != nil {
			if err == sql.ErrNoRows {
				debug("no scheduled jobs in the table")
			} else if myErr, ok := err.(*mysql.MySQLError); ok && myErr.Number == 1146 {
				// Table doesn't exist
				log.Fatal(myErr)
			} else {
				log.Print(err)
				time.Sleep(time.Second)
				continue
			}
		} else {
			remaining := job.Remaining()
			after = time.After(remaining)
			debug("next job:", job, "remaining:", remaining)
		}

		// Sleep until the next job's run time or the webserver's wakes us up.
		select {
		case <-after:
			debug("job sleep time finished")
			if err = s.execute(job); err != nil {
				log.Print(err)
				time.Sleep(time.Second)
			}
		case <-s.wakeUp:
			debug("woken up from sleep by notification")
			continue
		case <-s.stop:
			debug("came quit message")
			s.wg.Wait()
			return
		}
	}
}

func randomize(d time.Duration, f float64) time.Duration {
	delta := time.Duration(f * float64(d))
	return d - delta + time.Duration(float64(2*delta)*rand.Float64())
}

// execute makes a POST request to the endpoint and updates the Job's next run time.
func (s *scheduler) execute(j *Job) error {
	debug("execute", *j)

	var add time.Duration
	if j.OneOff() {
		add = s.client.Timeout
	} else {
		add = j.Interval
		if s.randomizationFactor > 0 {
			// Add some randomization to periodic tasks.
			add = randomize(add, s.randomizationFactor)
		}
	}

	j.NextRun = time.Now().UTC().Add(add)

	if err := s.table.UpdateNextRun(j); err != nil {
		return err
	}

	s.wg.Add(1)
	go func() {
		defer s.wg.Done()

		// Do not do multiple POSTs for the same job at the same time.
		s.m.Lock()
		if _, ok := s.runningJobs[j.JobKey]; ok {
			debug("job is already running", j.JobKey)
			s.m.Unlock()
			return
		}
		s.runningJobs[j.JobKey] = struct{}{}
		s.m.Unlock()

		defer func() {
			s.m.Lock()
			delete(s.runningJobs, j.JobKey)
			s.m.Unlock()
		}()

		code := s.retryPostJob(j)
		if code == 0 {
			return
		}

		if j.OneOff() {
			debug("deleting one-off job")
			s.retryDeleteJob(j)
			s.WakeUp("deleted one-off job")
			return
		}

		if code == 204 {
			debug("deleting not found job")
			if err := s.deleteJob(j); err != nil {
				log.Print(err)
				return
			}
			s.WakeUp("deleted not found job")
			return
		}
	}()

	return nil
}

func (s *scheduler) postJob(j *Job) (code int, err error) {
	url := s.baseURL + j.Path
	debug("POSTing to ", url)
	resp, err := s.client.Post(url, "text/plain", strings.NewReader(j.Body))
	if err != nil {
		return
	}
	switch resp.StatusCode {
	case 200, 204:
		code = resp.StatusCode
	default:
		err = fmt.Errorf("endpoint error: %d", resp.StatusCode)
	}
	return
}

func (s *scheduler) retryPostJob(j *Job) interface{} {
	b := backoff.NewExponentialBackOff()
	b.MaxElapsedTime = 0 // retry forever
	if j.Interval > 0 {
		b.MaxInterval = j.Interval
	}
	f := func() (interface{}, error) { return s.postJob(j) }
	return retry(b, f, s.stop)
}

func (s *scheduler) retryDeleteJob(j *Job) {
	b := backoff.NewConstantBackOff(time.Second)
	f := func() (interface{}, error) { return nil, s.deleteJob(j) }
	retry(b, f, nil)
}

func (s *scheduler) deleteJob(j *Job) error {
	err := s.table.Delete(j.Path, j.Body)
	if err == ErrNotExist {
		return nil
	}
	return err
}

func retry(b backoff.BackOff, f func() (result interface{}, err error), stop chan struct{}) (result interface{}) {
	ticker := backoff.NewTicker(b)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			var err error
			if result, err = f(); err != nil {
				log.Print(err)
				continue
			}
			return
		case <-stop:
			return
		}
	}
}
<commit_msg>return code as int<commit_after>package dalga

import (
	"database/sql"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/cenkalti/dalga/dalga/Godeps/_workspace/src/github.com/cenkalti/backoff"
	"github.com/cenkalti/dalga/dalga/Godeps/_workspace/src/github.com/go-sql-driver/mysql"
)

type scheduler struct {
	table               *table
	client              http.Client
	baseURL             string
	randomizationFactor float64
	// to stop scheduler goroutine
	stop chan struct{}
	// will be closed when scheduler goroutine is stopped
	stopped chan struct{}
	// to wake up scheduler when a new job is scheduled or cancelled
	wakeUp      chan struct{}
	runningJobs map[JobKey]struct{}
	m           sync.Mutex
	wg          sync.WaitGroup
}

func newScheduler(t *table, baseURL string, clientTimeout time.Duration, randomizationFactor float64) *scheduler {
	s := &scheduler{
		table:               t,
		baseURL:             baseURL,
		randomizationFactor: randomizationFactor,
		stop:                make(chan struct{}),
		stopped:             make(chan struct{}),
		wakeUp:              make(chan struct{}, 1),
		runningJobs:         make(map[JobKey]struct{}),
	}
	s.client.Timeout = clientTimeout
	return s
}

func (s *scheduler) WakeUp(debugMessage string) {
	select {
	case s.wakeUp <- struct{}{}:
		debug("notifying scheduler:", debugMessage)
	default:
	}
}

func (s *scheduler) NotifyDone() <-chan struct{} {
	return s.stopped
}

func (s *scheduler) Stop() {
	close(s.stop)
}

func (s *scheduler) Running() int {
	s.m.Lock()
	defer s.m.Unlock()
	return len(s.runningJobs)
}

// Run runs a loop that reads the next Job from the queue and executees it in it's own goroutine.
func (s *scheduler) Run() {
	defer close(s.stopped)

	for {
		debug("---")

		var after <-chan time.Time

		job, err := s.table.Front()
		if err != nil {
			if err == sql.ErrNoRows {
				debug("no scheduled jobs in the table")
			} else if myErr, ok := err.(*mysql.MySQLError); ok && myErr.Number == 1146 {
				// Table doesn't exist
				log.Fatal(myErr)
			} else {
				log.Print(err)
				time.Sleep(time.Second)
				continue
			}
		} else {
			remaining := job.Remaining()
			after = time.After(remaining)
			debug("next job:", job, "remaining:", remaining)
		}

		// Sleep until the next job's run time or the webserver's wakes us up.
		select {
		case <-after:
			debug("job sleep time finished")
			if err = s.execute(job); err != nil {
				log.Print(err)
				time.Sleep(time.Second)
			}
		case <-s.wakeUp:
			debug("woken up from sleep by notification")
			continue
		case <-s.stop:
			debug("came quit message")
			s.wg.Wait()
			return
		}
	}
}

func randomize(d time.Duration, f float64) time.Duration {
	delta := time.Duration(f * float64(d))
	return d - delta + time.Duration(float64(2*delta)*rand.Float64())
}

// execute makes a POST request to the endpoint and updates the Job's next run time.
func (s *scheduler) execute(j *Job) error {
	debug("execute", *j)

	var add time.Duration
	if j.OneOff() {
		add = s.client.Timeout
	} else {
		add = j.Interval
		if s.randomizationFactor > 0 {
			// Add some randomization to periodic tasks.
			add = randomize(add, s.randomizationFactor)
		}
	}

	j.NextRun = time.Now().UTC().Add(add)

	if err := s.table.UpdateNextRun(j); err != nil {
		return err
	}

	s.wg.Add(1)
	go func() {
		defer s.wg.Done()

		// Do not do multiple POSTs for the same job at the same time.
		s.m.Lock()
		if _, ok := s.runningJobs[j.JobKey]; ok {
			debug("job is already running", j.JobKey)
			s.m.Unlock()
			return
		}
		s.runningJobs[j.JobKey] = struct{}{}
		s.m.Unlock()

		defer func() {
			s.m.Lock()
			delete(s.runningJobs, j.JobKey)
			s.m.Unlock()
		}()

		code := s.retryPostJob(j)
		if code == 0 {
			return
		}

		if j.OneOff() {
			debug("deleting one-off job")
			s.retryDeleteJob(j)
			s.WakeUp("deleted one-off job")
			return
		}

		if code == 204 {
			debug("deleting not found job")
			if err := s.deleteJob(j); err != nil {
				log.Print(err)
				return
			}
			s.WakeUp("deleted not found job")
			return
		}
	}()

	return nil
}

func (s *scheduler) postJob(j *Job) (code int, err error) {
	url := s.baseURL + j.Path
	debug("POSTing to ", url)
	resp, err := s.client.Post(url, "text/plain", strings.NewReader(j.Body))
	if err != nil {
		return
	}
	switch resp.StatusCode {
	case 200, 204:
		code = resp.StatusCode
	default:
		err = fmt.Errorf("endpoint error: %d", resp.StatusCode)
	}
	return
}

func (s *scheduler) retryPostJob(j *Job) (code int) {
	b := backoff.NewExponentialBackOff()
	b.MaxElapsedTime = 0 // retry forever
	if j.Interval > 0 {
		b.MaxInterval = j.Interval
	}
	f := func() (interface{}, error) { return s.postJob(j) }
	code, _ = retry(b, f, s.stop).(int)
	return
}

func (s *scheduler) retryDeleteJob(j *Job) {
	b := backoff.NewConstantBackOff(time.Second)
	f := func() (interface{}, error) { return nil, s.deleteJob(j) }
	retry(b, f, nil)
}

func (s *scheduler) deleteJob(j *Job) error {
	err := s.table.Delete(j.Path, j.Body)
	if err == ErrNotExist {
		return nil
	}
	return err
}

func retry(b backoff.BackOff, f func() (result interface{}, err error), stop chan struct{}) (result interface{}) {
	ticker := backoff.NewTicker(b)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			var err error
			if result, err = f(); err != nil {
				log.Print(err)
				continue
			}
			return
		case <-stop:
			return
		}
	}
}
<|endoftext|>


<commit_before>package utils

import (
	"fmt"
	"os/exec"
	"strconv"
	"strings"

	"runtime"

	"github.com/beego/bee/config"
)

const appName = "Beego"

func Notify(text, title string) {
	if !config.Conf.EnableNotification {
		return
	}
	switch runtime.GOOS {
	case "darwin":
		osxNotify(text, title)
	case "linux":
		windowsNotify(text, title)
	case "windows":
		linuxNotify(text, title)
	}
}

func osxNotify(text, title string) {
	var cmd *exec.Cmd
	if existTerminalNotifier() {
		cmd = exec.Command("terminal-notifier", "-title", appName, "-message", text, "-subtitle", title)
	} else if MacOSVersionSupport() {
		notification := fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"", text, appName, title)
		cmd = exec.Command("osascript", "-e", notification)
	} else {
		cmd = exec.Command("growlnotify", "-n", appName, "-m", title)
	}
	cmd.Run()
}

func windowsNotify(text, title string) {
	exec.Command("growlnotify", "/i:", "", "/t:", title, text).Run()
}

func linuxNotify(text, title string) {
	exec.Command("notify-send", "-i", "", title, text)
}

func existTerminalNotifier() bool {
	cmd := exec.Command("which", "terminal-notifier")
	err := cmd.Start()
	if err != nil {
		return false
	}
	err = cmd.Wait()
	return err != nil
}

func MacOSVersionSupport() bool {
	cmd := exec.Command("sw_vers", "-productVersion")
	check, _ := cmd.Output()
	version := strings.Split(string(check), ".")
	major, _ := strconv.Atoi(version[0])
	minor, _ := strconv.Atoi(version[1])
	if major < 10 || (major == 10 && minor < 9) {
		return false
	}
	return true
}
<commit_msg>Fixes desktop notificator for Windows and Linux<commit_after>// Copyright 2017 bee authors
//
// 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 utils

import (
	"fmt"
	"os/exec"
	"strconv"
	"strings"

	"runtime"

	"github.com/beego/bee/config"
)

const appName = "Beego"

func Notify(text, title string) {
	if !config.Conf.EnableNotification {
		return
	}
	switch runtime.GOOS {
	case "darwin":
		osxNotify(text, title)
	case "linux":
		linuxNotify(text, title)
	case "windows":
		windowsNotify(text, title)
	}
}

func osxNotify(text, title string) {
	var cmd *exec.Cmd
	if existTerminalNotifier() {
		cmd = exec.Command("terminal-notifier", "-title", appName, "-message", text, "-subtitle", title)
	} else if MacOSVersionSupport() {
		notification := fmt.Sprintf("display notification \"%s\" with title \"%s\" subtitle \"%s\"", text, appName, title)
		cmd = exec.Command("osascript", "-e", notification)
	} else {
		cmd = exec.Command("growlnotify", "-n", appName, "-m", title)
	}
	cmd.Run()
}

func windowsNotify(text, title string) {
	exec.Command("growlnotify", "/i:", "", "/t:", title, text).Run()
}

func linuxNotify(text, title string) {
	exec.Command("notify-send", "-i", "", title, text).Run()
}

func existTerminalNotifier() bool {
	cmd := exec.Command("which", "terminal-notifier")
	err := cmd.Start()
	if err != nil {
		return false
	}
	err = cmd.Wait()
	return err != nil
}

func MacOSVersionSupport() bool {
	cmd := exec.Command("sw_vers", "-productVersion")
	check, _ := cmd.Output()
	version := strings.Split(string(check), ".")
	major, _ := strconv.Atoi(version[0])
	minor, _ := strconv.Atoi(version[1])
	if major < 10 || (major == 10 && minor < 9) {
		return false
	}
	return true
}
<|endoftext|>


<commit_before>package main

// standard library imports
import . "fmt"

// project library imports
import . "github.com/mndrix/golog"

func main () {
    Printf("hi")
}
<commit_msg>Remove golog script which isn't used<commit_after><|endoftext|>


<commit_before>package main

import (
	"bufio"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/crypto/ssh"
)

const blacklistPath = "blacklist"

var blacklist []string

func loadBlacklistedKeys() {
	files, err := ioutil.ReadDir(blacklistPath)
	if err != nil {
		log.Fatal(err)
	}

	for _, f := range files {
		if f.IsDir() {
			log.Fatalf("Subdirectories not supported in %q directory\n", blacklistPath)
		}

		file, err := os.Open(filepath.Join(blacklistPath, f.Name()))
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			blacklist = append(blacklist, scanner.Text())
		}

		if err := scanner.Err(); err != nil {
			log.Fatal(err)
		}
	}

	return
}

func markBlacklistedKeys(keys []*publicKey) {
	for _, b := range blacklist {
		for _, k := range keys {
			if strings.TrimSpace(b) == strings.TrimSpace(string(ssh.MarshalAuthorizedKey(k.key))) {
				k.blacklisted = true
			}
		}
	}

	return
}
<commit_msg>Use a map to make blacklisting faster<commit_after>package main

import (
	"bufio"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/crypto/ssh"
)

const blacklistPath = "blacklist"

var blacklist = make(map[string]bool)

func loadBlacklistedKeys() {
	files, err := ioutil.ReadDir(blacklistPath)
	if err != nil {
		log.Fatal(err)
	}

	for _, f := range files {
		if f.IsDir() {
			log.Fatalf("Subdirectories not supported in %q directory\n", blacklistPath)
		}

		file, err := os.Open(filepath.Join(blacklistPath, f.Name()))
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			key := strings.TrimSpace(scanner.Text())
			blacklist[key] = true
		}

		if err := scanner.Err(); err != nil {
			log.Fatal(err)
		}
	}

	return
}

func markBlacklistedKeys(keys []*publicKey) {

	for _, k := range keys {
		key := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(k.key)))
		if blacklist[key] {
			k.blacklisted = true
		}
	}

	return
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"strings"
)

// Functions for displaying block pages.

// transparent1x1 is a single-pixel transparent GIF file.
const transparent1x1 = "GIF89a\x10\x00\x10\x00\x80\xff\x00\xc0\xc0\xc0\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x02\x0e\x84\x8f\xa9\xcb\xed\x0f\xa3\x9c\xb4\u068b\xb3>\x05\x00;"

func (c *config) loadBlockPage(path string) error {
	if strings.HasPrefix(path, "http") {
		c.BlockTemplate = nil
		c.BlockpageURL = path
		return nil
	}

	bt := template.New("blockpage")
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return fmt.Errorf("error loading block page template: %v", err)
	}
	_, err = bt.Parse(string(content))
	if err != nil {
		return fmt.Errorf("error parsing block page template: %v", err)
	}

	c.BlockTemplate = bt
	c.BlockpageURL = ""
	return nil
}

type blockData struct {
	URL             string
	Categories      string
	Conditions      string
	User            string
	Tally           string
	Scores          string
	RuleDescription string
	Request         *http.Request
	Response        *http.Response
}

func (c *config) aclDescription(name string) string {
	cat, ok := c.Categories[name]
	if ok {
		return cat.description
	}

	d, ok := c.ACLs.Descriptions[name]
	if ok {
		return d
	}

	return name
}

// showBlockPage shows a block page for a page that was blocked by an ACL.
func (c *config) showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule) {
	switch {
	case c.BlockTemplate != nil:
		data := blockData{
			URL:             r.URL.String(),
			Conditions:      rule.Conditions(),
			User:            user,
			Tally:           listTally(stringTally(tally)),
			Scores:          listTally(scores),
			RuleDescription: rule.Description,
			Request:         r,
			Response:        resp,
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.WriteHeader(http.StatusForbidden)

		// Convert rule conditions into category descriptions as much as possible.
		var categories []string
		for _, acl := range rule.Needed {
			categories = append(categories, c.aclDescription(acl))
		}
		for _, acl := range rule.Disallowed {
			categories = append(categories, "not "+c.aclDescription(acl))
		}
		data.Categories = strings.Join(categories, ", ")

		err := c.BlockTemplate.Execute(w, data)
		if err != nil {
			log.Println("Error filling in block page template:", err)
		}

	case c.BlockpageURL != "":
		data, err := json.Marshal(map[string]interface{}{
			"url":    r.URL.String(),
			"rule":   rule,
			"user":   user,
			"tally":  stringTally(tally),
			"scores": scores,
		})
		if err != nil {
			log.Println("Error generating JSON info for block page:", err)
			http.Error(w, "", http.StatusForbidden)
			return
		}

		blockResp, err := http.Post(c.BlockpageURL, "application/json", bytes.NewReader(data))
		if err != nil {
			log.Printf("Error fetching blockpage from %s: %v", c.BlockpageURL, err)
			http.Error(w, "", http.StatusForbidden)
			return
		}
		defer blockResp.Body.Close()

		removeHopByHopHeaders(blockResp.Header)
		if blockResp.ContentLength > 0 {
			w.Header().Set("Content-Length", strconv.FormatInt(blockResp.ContentLength, 10))
		}
		copyResponseHeader(w, blockResp)
		w.WriteHeader(http.StatusForbidden)
		_, err = io.Copy(w, blockResp.Body)
		if err != nil {
			log.Printf("Error copying blockpage: %v", err)
		}

	default:
		http.Error(w, "", http.StatusForbidden)
		return
	}
}

// showInvisibleBlock blocks the request with an invisible image.
func showInvisibleBlock(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "image/gif")
	w.WriteHeader(http.StatusForbidden)
	fmt.Fprint(w, transparent1x1)
}
<commit_msg>Send more info to blockpage generator.<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"strings"
)

// Functions for displaying block pages.

// transparent1x1 is a single-pixel transparent GIF file.
const transparent1x1 = "GIF89a\x10\x00\x10\x00\x80\xff\x00\xc0\xc0\xc0\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x02\x0e\x84\x8f\xa9\xcb\xed\x0f\xa3\x9c\xb4\u068b\xb3>\x05\x00;"

func (c *config) loadBlockPage(path string) error {
	if strings.HasPrefix(path, "http") {
		c.BlockTemplate = nil
		c.BlockpageURL = path
		return nil
	}

	bt := template.New("blockpage")
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return fmt.Errorf("error loading block page template: %v", err)
	}
	_, err = bt.Parse(string(content))
	if err != nil {
		return fmt.Errorf("error parsing block page template: %v", err)
	}

	c.BlockTemplate = bt
	c.BlockpageURL = ""
	return nil
}

type blockData struct {
	URL             string
	Categories      string
	Conditions      string
	User            string
	Tally           string
	Scores          string
	RuleDescription string
	Request         *http.Request
	Response        *http.Response
}

func (c *config) aclDescription(name string) string {
	cat, ok := c.Categories[name]
	if ok {
		return cat.description
	}

	d, ok := c.ACLs.Descriptions[name]
	if ok {
		return d
	}

	return name
}

// showBlockPage shows a block page for a page that was blocked by an ACL.
func (c *config) showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule) {
	switch {
	case c.BlockTemplate != nil:
		data := blockData{
			URL:             r.URL.String(),
			Conditions:      rule.Conditions(),
			User:            user,
			Tally:           listTally(stringTally(tally)),
			Scores:          listTally(scores),
			RuleDescription: rule.Description,
			Request:         r,
			Response:        resp,
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.WriteHeader(http.StatusForbidden)

		// Convert rule conditions into category descriptions as much as possible.
		var categories []string
		for _, acl := range rule.Needed {
			categories = append(categories, c.aclDescription(acl))
		}
		for _, acl := range rule.Disallowed {
			categories = append(categories, "not "+c.aclDescription(acl))
		}
		data.Categories = strings.Join(categories, ", ")

		err := c.BlockTemplate.Execute(w, data)
		if err != nil {
			log.Println("Error filling in block page template:", err)
		}

	case c.BlockpageURL != "":
		d := map[string]interface{}{
			"url":            r.URL.String(),
			"rule":           rule,
			"user":           user,
			"tally":          stringTally(tally),
			"scores":         scores,
			"method":         r.Method,
			"request-header": r.Header,
		}
		if resp != nil {
			d["response-header"] = resp.Header
		}
		data, err := json.Marshal(d)
		if err != nil {
			log.Println("Error generating JSON info for block page:", err)
			http.Error(w, "", http.StatusForbidden)
			return
		}

		blockResp, err := http.Post(c.BlockpageURL, "application/json", bytes.NewReader(data))
		if err != nil {
			log.Printf("Error fetching blockpage from %s: %v", c.BlockpageURL, err)
			http.Error(w, "", http.StatusForbidden)
			return
		}
		defer blockResp.Body.Close()

		removeHopByHopHeaders(blockResp.Header)
		if blockResp.ContentLength > 0 {
			w.Header().Set("Content-Length", strconv.FormatInt(blockResp.ContentLength, 10))
		}
		copyResponseHeader(w, blockResp)
		w.WriteHeader(http.StatusForbidden)
		_, err = io.Copy(w, blockResp.Body)
		if err != nil {
			log.Printf("Error copying blockpage: %v", err)
		}

	default:
		http.Error(w, "", http.StatusForbidden)
		return
	}
}

// showInvisibleBlock blocks the request with an invisible image.
func showInvisibleBlock(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "image/gif")
	w.WriteHeader(http.StatusForbidden)
	fmt.Fprint(w, transparent1x1)
}
<|endoftext|>


<commit_before>// Copyright 2018 The Ebiten Authors
//
// 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.

// +build !js

package devicescale

// TODO: Use golang.org/x/sys/windows (NewLazyDLL) instead of cgo.

// #cgo LDFLAGS: -lgdi32
//
// #include <windows.h>
//
// static char* getDPI(int* dpi) {
//   HDC dc = GetWindowDC(0);
//   *dpi = GetDeviceCaps(dc, LOGPIXELSX);
//   if (!ReleaseDC(0, dc)) {
//     return "ReleaseDC failed";
//   }
//   return "";
// }
import "C"

import (
	"fmt"
	"syscall"
)

var (
	user32 = syscall.NewLazyDLL("user32")
)

var (
	procSetProcessDPIAware = user32.NewProc("SetProcessDPIAware")
)

func setProcessDPIAware() error {
	r, _, e := syscall.Syscall(procSetProcessDPIAware.Addr(), 0, 0, 0, 0)
	if e != 0 {
		return fmt.Errorf("devicescale: SetProcessDPIAware failed: error code: %d", e)
	}
	if r == 0 {
		return fmt.Errorf("devicescale: SetProcessDPIAware failed: returned value: %d", r)
	}
	return nil
}

func impl() float64 {
	if err := setProcessDPIAware(); err != nil {
		panic(err)
	}
	dpi := C.int(0)
	if errmsg := C.GoString(C.getDPI(&dpi)); errmsg != "" {
		panic(errmsg)
	}
	return float64(dpi) / 96
}
<commit_msg>devicescale: Use NewLazyDLL on Windows<commit_after>// Copyright 2018 The Ebiten Authors
//
// 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.

// +build !js

package devicescale

import (
	"fmt"
	"syscall"
)

const logPixelSx = 88

var (
	user32 = syscall.NewLazyDLL("user32")
	gdi32  = syscall.NewLazyDLL("gdi32")
)

var (
	procSetProcessDPIAware = user32.NewProc("SetProcessDPIAware")
	procGetWindowDC        = user32.NewProc("GetWindowDC")
	procReleaseDC          = user32.NewProc("ReleaseDC")
	procGetDeviceCaps      = gdi32.NewProc("GetDeviceCaps")
)

func setProcessDPIAware() error {
	r, _, e := syscall.Syscall(procSetProcessDPIAware.Addr(), 0, 0, 0, 0)
	if e != 0 {
		return fmt.Errorf("devicescale: SetProcessDPIAware failed: error code: %d", e)
	}
	if r == 0 {
		return fmt.Errorf("devicescale: SetProcessDPIAware failed: returned value: %d", r)
	}
	return nil
}

func getWindowDC(hwnd uintptr) (uintptr, error) {
	r, _, e := syscall.Syscall(procGetWindowDC.Addr(), 1, hwnd, 0, 0)
	if e != 0 {
		return 0, fmt.Errorf("devicescale: GetWindowDC failed: error code: %d", e)
	}
	if r == 0 {
		return 0, fmt.Errorf("devicescale: GetWindowDC failed: returned value: %d", r)
	}
	return r, nil
}

func releaseDC(hwnd, hdc uintptr) error {
	r, _, e := syscall.Syscall(procReleaseDC.Addr(), 2, hwnd, hdc, 0)
	if e != 0 {
		return fmt.Errorf("devicescale: ReleaseDC failed: error code: %d", e)
	}
	if r == 0 {
		return fmt.Errorf("devicescale: ReleaseDC failed: returned value: %d", r)
	}
	return nil
}

func getDeviceCaps(hdc uintptr, nindex int) (int, error) {
	r, _, e := syscall.Syscall(procGetDeviceCaps.Addr(), 2, hdc, uintptr(nindex), 0)
	if e != 0 {
		return 0, fmt.Errorf("devicescale: GetDeviceCaps failed: error code: %d", e)
	}
	return int(r), nil
}

func impl() float64 {
	if err := setProcessDPIAware(); err != nil {
		panic(err)
	}

	dc, err := getWindowDC(0)
	if err != nil {
		panic(err)
	}
	dpi, err := getDeviceCaps(dc, logPixelSx)
	if err != nil {
		panic(err)
	}
	if err := releaseDC(0, dc); err != nil {
		panic(err)
	}

	return float64(dpi) / 96
}
<|endoftext|>


<commit_before>package model

import (
	"app/shared"
	"database/sql"
	"testing"
)

func setup() ([]int64, []int64, error) {
	var err error
	oid := make([]int64, 2, 2)
	uid := make([]int64, 2, 2)

	oid[0], err = OrgCreate("wonderland", shared.RandomKey())
	if err != nil {
		return nil, nil, err
	}
	oid[1], err = OrgCreate("glass", shared.RandomKey())
	if err != nil {
		return nil, nil, err
	}
	uid[0], err = UserCreate("alice")
	if err != nil {
		return nil, nil, err
	}
	uid[1], err = UserCreate("bob")
	if err != nil {
		return nil, nil, err
	}

	err = MemberCreate(oid[0], uid[0])
	if err != nil {
		return nil, nil, err
	}
	err = MemberCreate(oid[1], uid[1])
	if err != nil {
		return nil, nil, err
	}
	return oid, uid, nil
}

func TestMemberExists(t *testing.T) {
	oid, uid, err := setup()
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}

	err = MemberExists(oid[0], uid[0])
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[1], uid[1])
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[0], uid[1])
	if err != sql.ErrNoRows {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[1], uid[0])
	if err != sql.ErrNoRows {
		t.Fatal("Unexpected error:", err)
	}

}
<commit_msg>Clean member_test<commit_after>package model

import (
	"app/shared"
	"database/sql"
	"testing"
)

func setup() ([]int64, []int64, error) {
	var err error
	orgs := []string{
		"wonderland",
		"glass",
	}
	users := []string{
		"alice",
		"bob",
	}
	members := map[int][]int{
		0: {0},
		1: {1},
	}

	oid := make([]int64, len(orgs), len(orgs))
	for i, name := range orgs {
		oid[i], err = OrgCreate(name, shared.RandomKey())
		if err != nil {
			return nil, nil, err
		}
	}
	uid := make([]int64, len(users), len(users))
	for i, name := range users {
		uid[i], err = UserCreate(name)
		if err != nil {
			return nil, nil, err
		}
	}

	for o, mem := range members {
		for _, u := range mem {
			err = MemberCreate(oid[o], uid[u])
			if err != nil {
				return nil, nil, err
			}
		}
	}
	return oid, uid, nil
}

func TestMemberExists(t *testing.T) {
	oid, uid, err := setup()
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}

	err = MemberExists(oid[0], uid[0])
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[1], uid[1])
	if err != nil {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[0], uid[1])
	if err != sql.ErrNoRows {
		t.Fatal("Unexpected error:", err)
	}
	err = MemberExists(oid[1], uid[0])
	if err != sql.ErrNoRows {
		t.Fatal("Unexpected error:", err)
	}

}
<|endoftext|>


<commit_before>package liner

import (
	"errors"
	"syscall"
	"unsafe"
)

var (
	kernel32 = syscall.NewLazyDLL("kernel32.dll")

	procGetStdHandle               = kernel32.NewProc("GetStdHandle")
	procReadConsoleInput           = kernel32.NewProc("ReadConsoleInputW")
	procGetConsoleMode             = kernel32.NewProc("GetConsoleMode")
	procSetConsoleMode             = kernel32.NewProc("SetConsoleMode")
	procSetConsoleCursorPosition   = kernel32.NewProc("SetConsoleCursorPosition")
	procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
	procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
)

const (
	std_input_handle  = uint32(-10 & 0xFFFFFFFF)
	std_output_handle = uint32(-11 & 0xFFFFFFFF)
	std_error_handle  = uint32(-12 & 0xFFFFFFFF)
)

type State struct {
	commonState
	handle   syscall.Handle
	hOut     syscall.Handle
	origMode uint32
	key      interface{}
	repeat   uint16
}

const (
	enableEchoInput      = 0x4
	enableInsertMode     = 0x20
	enableLineInput      = 0x2
	enableMouseInput     = 0x10
	enableProcessedInput = 0x1
	enableQuickEditMode  = 0x40
	enableWindowInput    = 0x8
)

func NewLiner() *State {
	var s State
	h, _, _ := procGetStdHandle.Call(uintptr(std_input_handle))
	s.handle = syscall.Handle(h)
	h, _, _ = procGetStdHandle.Call(uintptr(std_output_handle))
	s.hOut = syscall.Handle(h)

	ok, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&s.origMode)))
	if ok != 0 {
		mode := s.origMode
		mode &^= enableEchoInput
		mode &^= enableInsertMode
		mode &^= enableLineInput
		mode &^= enableMouseInput
		mode |= enableWindowInput
		procSetConsoleMode.Call(h, uintptr(mode))
	}

	s.supported = true
	return &s
}

const (
	focus_event              = 0x0010
	key_event                = 0x0001
	menu_event               = 0x0008
	mouse_event              = 0x0002
	window_buffer_size_event = 0x0004
)

type input_record struct {
	eventType uint16
	pad       uint16
	blob      [16]byte
}

type key_event_record struct {
	KeyDown         int32
	RepeatCount     uint16
	VirtualKeyCode  uint16
	VirtualScanCode uint16
	Char            int16
	ControlKeyState uint32
}

const (
	vk_tab    = 0x09
	vk_prior  = 0x21
	vk_next   = 0x22
	vk_end    = 0x23
	vk_home   = 0x24
	vk_left   = 0x25
	vk_up     = 0x26
	vk_right  = 0x27
	vk_down   = 0x28
	vk_insert = 0x2d
	vk_delete = 0x2e
	vk_f1     = 0x70
	vk_f2     = 0x71
	vk_f3     = 0x72
	vk_f4     = 0x73
	vk_f5     = 0x74
	vk_f6     = 0x75
	vk_f7     = 0x76
	vk_f8     = 0x77
	vk_f9     = 0x78
	vk_f10    = 0x79
	vk_f11    = 0x7a
	vk_f12    = 0x7b
)

const (
	shiftPressed     = 0x0010
	leftAltPressed   = 0x0002
	leftCtrlPressed  = 0x0008
	rightAltPressed  = 0x0001
	rightCtrlPressed = 0x0004

	modKeys = shiftPressed | leftAltPressed | rightAltPressed | leftCtrlPressed | rightCtrlPressed
)

func (s *State) readNext() (interface{}, error) {
	if s.repeat > 0 {
		s.repeat--
		return s.key, nil
	}

	var input input_record
	pbuf := uintptr(unsafe.Pointer(&input))
	var rv uint32
	prv := uintptr(unsafe.Pointer(&rv))

	for {
		ok, _, err := procReadConsoleInput.Call(uintptr(s.handle), pbuf, 1, prv)

		if ok == 0 {
			return nil, err
		}

		if input.eventType != key_event {
			continue
		}
		ke := (*key_event_record)(unsafe.Pointer(&input.blob[0]))
		if ke.KeyDown == 0 {
			continue
		}

		if ke.VirtualKeyCode == vk_tab && ke.ControlKeyState&modKeys == shiftPressed {
			s.key = shiftTab
		} else if ke.Char > 0 {
			s.key = rune(ke.Char)
		} else {
			switch ke.VirtualKeyCode {
			case vk_prior:
				s.key = pageUp
			case vk_next:
				s.key = pageDown
			case vk_end:
				s.key = end
			case vk_home:
				s.key = home
			case vk_left:
				s.key = left
			case vk_right:
				s.key = right
			case vk_up:
				s.key = up
			case vk_down:
				s.key = down
			case vk_insert:
				s.key = insert
			case vk_delete:
				s.key = del
			case vk_f1:
				s.key = f1
			case vk_f2:
				s.key = f2
			case vk_f3:
				s.key = f3
			case vk_f4:
				s.key = f4
			case vk_f5:
				s.key = f5
			case vk_f6:
				s.key = f6
			case vk_f7:
				s.key = f7
			case vk_f8:
				s.key = f8
			case vk_f9:
				s.key = f9
			case vk_f10:
				s.key = f10
			case vk_f11:
				s.key = f11
			case vk_f12:
				s.key = f12
			default:
				// Eat modifier keys
				// TODO: return Action(Unknown) if the key isn't a
				// modifier.
				continue
			}
		}

		if ke.RepeatCount > 1 {
			s.repeat = ke.RepeatCount - 1
		}
		return s.key, nil
	}
	return unknown, nil
}

func (s *State) promptUnsupported(p string) (string, error) {
	return "", errors.New("Internal Error: Always supported on Windows")
}

func (s *State) Close() error {
	procSetConsoleMode.Call(uintptr(s.handle), uintptr(s.origMode))
	return nil
}
<commit_msg>fixup: eraseline<commit_after>package liner

import (
	"errors"
	"syscall"
	"unsafe"
)

var (
	kernel32 = syscall.NewLazyDLL("kernel32.dll")

	procGetStdHandle               = kernel32.NewProc("GetStdHandle")
	procReadConsoleInput           = kernel32.NewProc("ReadConsoleInputW")
	procGetConsoleMode             = kernel32.NewProc("GetConsoleMode")
	procSetConsoleMode             = kernel32.NewProc("SetConsoleMode")
	procSetConsoleCursorPosition   = kernel32.NewProc("SetConsoleCursorPosition")
	procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
	procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW")
)

const (
	std_input_handle  = uint32(-10 & 0xFFFFFFFF)
	std_output_handle = uint32(-11 & 0xFFFFFFFF)
	std_error_handle  = uint32(-12 & 0xFFFFFFFF)
)

type State struct {
	commonState
	handle   syscall.Handle
	hOut     syscall.Handle
	origMode uint32
	key      interface{}
	repeat   uint16
}

const (
	enableEchoInput      = 0x4
	enableInsertMode     = 0x20
	enableLineInput      = 0x2
	enableMouseInput     = 0x10
	enableProcessedInput = 0x1
	enableQuickEditMode  = 0x40
	enableWindowInput    = 0x8
)

func NewLiner() *State {
	var s State
	hIn, _, _ := procGetStdHandle.Call(uintptr(std_input_handle))
	s.handle = syscall.Handle(hIn)
	hOut, _, _ := procGetStdHandle.Call(uintptr(std_output_handle))
	s.hOut = syscall.Handle(hOut)

	ok, _, _ := procGetConsoleMode.Call(hIn, uintptr(unsafe.Pointer(&s.origMode)))
	if ok != 0 {
		mode := s.origMode
		mode &^= enableEchoInput
		mode &^= enableInsertMode
		mode &^= enableLineInput
		mode &^= enableMouseInput
		mode |= enableWindowInput
		procSetConsoleMode.Call(hIn, uintptr(mode))
	}

	s.supported = true
	return &s
}

const (
	focus_event              = 0x0010
	key_event                = 0x0001
	menu_event               = 0x0008
	mouse_event              = 0x0002
	window_buffer_size_event = 0x0004
)

type input_record struct {
	eventType uint16
	pad       uint16
	blob      [16]byte
}

type key_event_record struct {
	KeyDown         int32
	RepeatCount     uint16
	VirtualKeyCode  uint16
	VirtualScanCode uint16
	Char            int16
	ControlKeyState uint32
}

const (
	vk_tab    = 0x09
	vk_prior  = 0x21
	vk_next   = 0x22
	vk_end    = 0x23
	vk_home   = 0x24
	vk_left   = 0x25
	vk_up     = 0x26
	vk_right  = 0x27
	vk_down   = 0x28
	vk_insert = 0x2d
	vk_delete = 0x2e
	vk_f1     = 0x70
	vk_f2     = 0x71
	vk_f3     = 0x72
	vk_f4     = 0x73
	vk_f5     = 0x74
	vk_f6     = 0x75
	vk_f7     = 0x76
	vk_f8     = 0x77
	vk_f9     = 0x78
	vk_f10    = 0x79
	vk_f11    = 0x7a
	vk_f12    = 0x7b
)

const (
	shiftPressed     = 0x0010
	leftAltPressed   = 0x0002
	leftCtrlPressed  = 0x0008
	rightAltPressed  = 0x0001
	rightCtrlPressed = 0x0004

	modKeys = shiftPressed | leftAltPressed | rightAltPressed | leftCtrlPressed | rightCtrlPressed
)

func (s *State) readNext() (interface{}, error) {
	if s.repeat > 0 {
		s.repeat--
		return s.key, nil
	}

	var input input_record
	pbuf := uintptr(unsafe.Pointer(&input))
	var rv uint32
	prv := uintptr(unsafe.Pointer(&rv))

	for {
		ok, _, err := procReadConsoleInput.Call(uintptr(s.handle), pbuf, 1, prv)

		if ok == 0 {
			return nil, err
		}

		if input.eventType != key_event {
			continue
		}
		ke := (*key_event_record)(unsafe.Pointer(&input.blob[0]))
		if ke.KeyDown == 0 {
			continue
		}

		if ke.VirtualKeyCode == vk_tab && ke.ControlKeyState&modKeys == shiftPressed {
			s.key = shiftTab
		} else if ke.Char > 0 {
			s.key = rune(ke.Char)
		} else {
			switch ke.VirtualKeyCode {
			case vk_prior:
				s.key = pageUp
			case vk_next:
				s.key = pageDown
			case vk_end:
				s.key = end
			case vk_home:
				s.key = home
			case vk_left:
				s.key = left
			case vk_right:
				s.key = right
			case vk_up:
				s.key = up
			case vk_down:
				s.key = down
			case vk_insert:
				s.key = insert
			case vk_delete:
				s.key = del
			case vk_f1:
				s.key = f1
			case vk_f2:
				s.key = f2
			case vk_f3:
				s.key = f3
			case vk_f4:
				s.key = f4
			case vk_f5:
				s.key = f5
			case vk_f6:
				s.key = f6
			case vk_f7:
				s.key = f7
			case vk_f8:
				s.key = f8
			case vk_f9:
				s.key = f9
			case vk_f10:
				s.key = f10
			case vk_f11:
				s.key = f11
			case vk_f12:
				s.key = f12
			default:
				// Eat modifier keys
				// TODO: return Action(Unknown) if the key isn't a
				// modifier.
				continue
			}
		}

		if ke.RepeatCount > 1 {
			s.repeat = ke.RepeatCount - 1
		}
		return s.key, nil
	}
	return unknown, nil
}

func (s *State) promptUnsupported(p string) (string, error) {
	return "", errors.New("Internal Error: Always supported on Windows")
}

func (s *State) Close() error {
	procSetConsoleMode.Call(uintptr(s.handle), uintptr(s.origMode))
	return nil
}
<|endoftext|>


<commit_before>package hdf5

// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"

import (
	"errors"
	"fmt"

	"runtime"
	"unsafe"
)

type Dataspace struct {
	Location
}

type SpaceClass C.H5S_class_t

const (
	S_NO_CLASS SpaceClass = -1 // error
	S_SCALAR   SpaceClass = 0  // scalar variable
	S_SIMPLE   SpaceClass = 1  // simple data space
	S_NULL     SpaceClass = 2  // null data space
)

func newDataspace(id C.hid_t) *Dataspace {
	ds := &Dataspace{Location{id}}
	runtime.SetFinalizer(ds, (*Dataspace).finalizer)
	return ds
}

// CreateDataspace creates a new dataspace of a specified type.
func CreateDataspace(class SpaceClass) (*Dataspace, error) {
	hid := C.H5Screate(C.H5S_class_t(class))
	err := h5err(C.herr_t(int(hid)))
	if err != nil {
		return nil, err
	}
	ds := newDataspace(hid)
	return ds, nil
}

func (s *Dataspace) finalizer() {
	err := s.Close()
	if err != nil {
		panic(fmt.Sprintf("error closing dspace: %s", err))
	}
}

// Copy creates an exact copy of a dataspace.
func (s *Dataspace) Copy() (*Dataspace, error) {
	hid := C.H5Scopy(s.id)
	err := h5err(C.herr_t(int(hid)))
	if err != nil {
		return nil, err
	}
	o := newDataspace(hid)
	return o, err
}

// Close releases and terminates access to a dataspace.
func (s *Dataspace) Close() error {
	err := C.H5Sclose(s.id)
	return h5err(err)
}

func (s *Dataspace) Id() int {
	return int(s.id)
}

// CreateSimpleDataspace creates a new simple dataspace and opens it for access.
func CreateSimpleDataspace(dims, maxDims []uint) (*Dataspace, error) {
	var c_dims, c_maxdims *C.hsize_t

	rank := C.int(0)
	if dims != nil {
		rank = C.int(len(dims))
		c_dims = (*C.hsize_t)(unsafe.Pointer(&dims[0]))

	}
	if maxDims != nil {
		rank = C.int(len(maxDims))
		c_maxdims = (*C.hsize_t)(unsafe.Pointer(&maxDims[0]))

	}
	if len(dims) != len(maxDims) && (dims != nil && maxDims != nil) {
		return nil, errors.New("lengths of dims and maxDims do not match")
	}

	hid := C.H5Screate_simple(rank, c_dims, c_maxdims)
	if hid < 0 {
		return nil, fmt.Errorf("failed to create dataspace")
	}
	return newDataspace(hid), nil
}

// IsSimple returns whether a dataspace is a simple dataspace.
func (s *Dataspace) IsSimple() bool {
	return int(C.H5Sis_simple(s.id)) > 0
}

// SetOffset sets the offset of a simple dataspace.
func (s *Dataspace) SetOffset(offset []uint) error {
	rank := len(offset)
	if rank == 0 {
		err := C.H5Soffset_simple(s.id, nil)
		return h5err(err)
	}
	if rank != s.SimpleExtentNDims() {
		err := errors.New("size of offset does not match extent")
		return err
	}

	c_offset := (*C.hssize_t)(unsafe.Pointer(&offset[0]))
	err := C.H5Soffset_simple(s.id, c_offset)
	return h5err(err)
}

// SelectHyperslab creates a subset of the data space.
func (s *Dataspace) SelectHyperslab(offset, stride, count, block []uint) error {
	rank := len(offset)
	if rank == 0 {
		err := C.H5Soffset_simple(s.id, nil)
		return h5err(err)
	}
	if rank != s.SimpleExtentNDims() {
		err := errors.New("size of offset does not match extent")
		return err
	}

	c_offset := (*C.hsize_t)(unsafe.Pointer(&offset[0]))
	c_stride := (*C.hsize_t)(unsafe.Pointer(&stride[0]))
	c_count := (*C.hsize_t)(unsafe.Pointer(&count[0]))
	c_block := (*C.hsize_t)(unsafe.Pointer(&block[0]))
	err := C.H5Sselect_hyperslab(s.id, C.H5S_SELECT_SET, c_offset, c_stride, c_count, c_block)
	return h5err(err)
}

// SimpleExtentDims returns dataspace dimension size and maximum size.
func (s *Dataspace) SimpleExtentDims() (dims, maxdims []uint, err error) {
	rank := s.SimpleExtentNDims()
	dims = make([]uint, rank)
	maxdims = make([]uint, rank)

	c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
	c_maxdims := (*C.hsize_t)(unsafe.Pointer(&maxdims[0]))
	rc := C.H5Sget_simple_extent_dims(s.id, c_dims, c_maxdims)
	err = h5err(C.herr_t(rc))
	return
}

// SimpleExtentNDims returns the dimensionality of a dataspace.
func (s *Dataspace) SimpleExtentNDims() int {
	return int(C.H5Sget_simple_extent_ndims(s.id))
}

// SimpleExtentNPoints returns the number of elements in a dataspace.
func (s *Dataspace) SimpleExtentNPoints() int {
	return int(C.H5Sget_simple_extent_npoints(s.id))
}

// SimpleExtentType returns the current class of a dataspace.
func (s *Dataspace) SimpleExtentType() SpaceClass {
	return SpaceClass(C.H5Sget_simple_extent_type(s.id))
}
<commit_msg>Allow nil arguments in SelectHyperslab<commit_after>package hdf5

// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"

import (
	"errors"
	"fmt"

	"runtime"
	"unsafe"
)

type Dataspace struct {
	Location
}

type SpaceClass C.H5S_class_t

const (
	S_NO_CLASS SpaceClass = -1 // error
	S_SCALAR   SpaceClass = 0  // scalar variable
	S_SIMPLE   SpaceClass = 1  // simple data space
	S_NULL     SpaceClass = 2  // null data space
)

func newDataspace(id C.hid_t) *Dataspace {
	ds := &Dataspace{Location{id}}
	runtime.SetFinalizer(ds, (*Dataspace).finalizer)
	return ds
}

// CreateDataspace creates a new dataspace of a specified type.
func CreateDataspace(class SpaceClass) (*Dataspace, error) {
	hid := C.H5Screate(C.H5S_class_t(class))
	err := h5err(C.herr_t(int(hid)))
	if err != nil {
		return nil, err
	}
	ds := newDataspace(hid)
	return ds, nil
}

func (s *Dataspace) finalizer() {
	err := s.Close()
	if err != nil {
		panic(fmt.Sprintf("error closing dspace: %s", err))
	}
}

// Copy creates an exact copy of a dataspace.
func (s *Dataspace) Copy() (*Dataspace, error) {
	hid := C.H5Scopy(s.id)
	err := h5err(C.herr_t(int(hid)))
	if err != nil {
		return nil, err
	}
	o := newDataspace(hid)
	return o, err
}

// Close releases and terminates access to a dataspace.
func (s *Dataspace) Close() error {
	err := C.H5Sclose(s.id)
	return h5err(err)
}

func (s *Dataspace) Id() int {
	return int(s.id)
}

// CreateSimpleDataspace creates a new simple dataspace and opens it for access.
func CreateSimpleDataspace(dims, maxDims []uint) (*Dataspace, error) {
	var c_dims, c_maxdims *C.hsize_t

	rank := C.int(0)
	if dims != nil {
		rank = C.int(len(dims))
		c_dims = (*C.hsize_t)(unsafe.Pointer(&dims[0]))

	}
	if maxDims != nil {
		rank = C.int(len(maxDims))
		c_maxdims = (*C.hsize_t)(unsafe.Pointer(&maxDims[0]))

	}
	if len(dims) != len(maxDims) && (dims != nil && maxDims != nil) {
		return nil, errors.New("lengths of dims and maxDims do not match")
	}

	hid := C.H5Screate_simple(rank, c_dims, c_maxdims)
	if hid < 0 {
		return nil, fmt.Errorf("failed to create dataspace")
	}
	return newDataspace(hid), nil
}

// IsSimple returns whether a dataspace is a simple dataspace.
func (s *Dataspace) IsSimple() bool {
	return int(C.H5Sis_simple(s.id)) > 0
}

// SetOffset sets the offset of a simple dataspace.
func (s *Dataspace) SetOffset(offset []uint) error {
	rank := len(offset)
	if rank == 0 {
		err := C.H5Soffset_simple(s.id, nil)
		return h5err(err)
	}
	if rank != s.SimpleExtentNDims() {
		err := errors.New("size of offset does not match extent")
		return err
	}

	c_offset := (*C.hssize_t)(unsafe.Pointer(&offset[0]))
	err := C.H5Soffset_simple(s.id, c_offset)
	return h5err(err)
}

// SelectHyperslab creates a subset of the data space.
func (s *Dataspace) SelectHyperslab(offset, stride, count, block []uint) error {
	rank := len(offset)
	if rank == 0 {
		err := C.H5Soffset_simple(s.id, nil)
		return h5err(err)
	}
	if rank != s.SimpleExtentNDims() {
		err := errors.New("size of offset does not match extent")
		return err
	}

	var c_offset, c_stride, c_count, c_block *C.hsize_t
	if offset != nil {
		c_offset = (*C.hsize_t)(unsafe.Pointer(&offset[0]))
	}
	if stride != nil {
		c_stride = (*C.hsize_t)(unsafe.Pointer(&stride[0]))
	}
	if count != nil {
		c_count = (*C.hsize_t)(unsafe.Pointer(&count[0]))
	}
	if block != nil {
		c_block = (*C.hsize_t)(unsafe.Pointer(&block[0]))
	}
	err := C.H5Sselect_hyperslab(s.id, C.H5S_SELECT_SET, c_offset, c_stride, c_count, c_block)
	return h5err(err)
}

// SimpleExtentDims returns dataspace dimension size and maximum size.
func (s *Dataspace) SimpleExtentDims() (dims, maxdims []uint, err error) {
	rank := s.SimpleExtentNDims()
	dims = make([]uint, rank)
	maxdims = make([]uint, rank)

	c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
	c_maxdims := (*C.hsize_t)(unsafe.Pointer(&maxdims[0]))
	rc := C.H5Sget_simple_extent_dims(s.id, c_dims, c_maxdims)
	err = h5err(C.herr_t(rc))
	return
}

// SimpleExtentNDims returns the dimensionality of a dataspace.
func (s *Dataspace) SimpleExtentNDims() int {
	return int(C.H5Sget_simple_extent_ndims(s.id))
}

// SimpleExtentNPoints returns the number of elements in a dataspace.
func (s *Dataspace) SimpleExtentNPoints() int {
	return int(C.H5Sget_simple_extent_npoints(s.id))
}

// SimpleExtentType returns the current class of a dataspace.
func (s *Dataspace) SimpleExtentType() SpaceClass {
	return SpaceClass(C.H5Sget_simple_extent_type(s.id))
}
<|endoftext|>