<commit_before>package mid_test

import (
	"bytes"
	"fmt"
	"io"
	"time"

	"github.com/gomidi/midi/mid"
	"github.com/gomidi/midi/smf"
)

func Example() {
	// This example illustrates how the same handler can be used for live and SMF MIDI messages
	// It also illustrates how live and SMF midi can be written

	// make a SMF
	mkSMF := func() io.Reader {
		var bf bytes.Buffer
		wr := mid.NewSMFWriter(&bf, 1)
		wr.Tempo(160)
		wr.SetChannel(2)
		wr.NoteOn(65, 90)
		wr.SetDelta(4000)
		wr.NoteOff(65)
		wr.EndOfTrack()
		return bytes.NewReader(bf.Bytes())
	}

	hd := mid.NewHandler(mid.NoLogger())

	// needed for the SMF timing
	var ticks smf.MetricTicks
	var bpm uint32 = 120 // default according to SMF spec

	// needed for the live timing
	var start = time.Now()

	// a helper to round the duration to seconds
	var roundSec = func(d time.Duration) time.Duration {
		return time.Second * time.Duration((d.Nanoseconds() / 1000000000))
	}

	// a helper to calculate the duration for both live and SMF messages
	var calcDuration = func(p *mid.SMFPosition) (dur time.Duration) {
		if p == nil {
			// we are in a live setting
			dur = roundSec(time.Now().Sub(start))
			return
		}

		// SMF data, calculate the time from the timeformat of the SMF file
		// we ignore the possibility that tempo information may come in a track following the one of
		// the current message as the spec does not recommend this
		return roundSec(ticks.Duration(bpm, uint32(p.AbsTime)))
	}

	hd.SMFHeader = func(head smf.Header) {
		// here we ignore that the timeformat could also be SMPTE
		ticks = head.TimeFormat.(smf.MetricTicks)
	}

	// we will override the tempo by the one given in the SMF
	hd.Message.Meta.Tempo = func(p mid.SMFPosition, valBPM uint32) {
		bpm = valBPM
	}

	// set the functions for the messages you are interested in
	hd.Message.Channel.NoteOn = func(p *mid.SMFPosition, channel, key, vel uint8) {
		fmt.Printf("[%vs] NoteOn at channel %v: key %v velocity: %v\n",
			calcDuration(p).Seconds(),
			channel, key, vel)
	}

	hd.Message.Channel.NoteOff = func(p *mid.SMFPosition, channel, key, vel uint8) {
		fmt.Printf("[%vs] NoteOff at channel %v: key %v velocity: %v\n",
			calcDuration(p).Seconds(),
			channel, key, vel)
	}

	// handle the smf
	fmt.Println("-- SMF data --")
	hd.ReadSMF(mkSMF())

	// handle the live data
	fmt.Println("-- live data --")
	lrd, lwr := io.Pipe()

	// WARNING this example does not deal with races and synchronization, it is just for illustration
	go func() {
		hd.ReadLive(lrd)
	}()

	mwr := mid.NewLiveWriter(lwr)

	// mwr := midiwriter.New(lwr)
	start = time.Now()

	mwr.SetChannel(11)

	// now write some live data
	// mwr.Write(channel.Ch11.NoteOn(120, 50))
	mwr.NoteOn(120, 50)
	time.Sleep(time.Second * 2)
	mwr.NoteOff(120)
	// mwr.Write(channel.Ch11.NoteOff(120))

	// Output: -- SMF data --
	// [0s] NoteOn at channel 2: key 65 velocity: 90
	// [1s] NoteOff at channel 2: key 65 velocity: 0
	// -- live data --
	// [0s] NoteOn at channel 11: key 120 velocity: 50
	// [2s] NoteOff at channel 11: key 120 velocity: 0
}
<commit_msg>cleanup mid example<commit_after>package mid_test

import (
	"bytes"
	"fmt"
	"io"
	"time"

	"github.com/gomidi/midi/mid"
	"github.com/gomidi/midi/smf"
)

func Example() {
	// This example illustrates how the same handler can be used for live and SMF MIDI messages
	// It also illustrates how live and SMF midi can be written

	// make a SMF
	mkSMF := func() io.Reader {
		var bf bytes.Buffer
		wr := mid.NewSMFWriter(&bf, 1)
		wr.Tempo(160)
		wr.SetChannel(2)
		wr.NoteOn(65, 90)
		wr.SetDelta(4000)
		wr.NoteOff(65)
		wr.EndOfTrack()
		return bytes.NewReader(bf.Bytes())
	}

	hd := mid.NewHandler(mid.NoLogger())

	// needed for the SMF timing
	var ticks smf.MetricTicks
	var bpm uint32 = 120 // default according to SMF spec

	// needed for the live timing
	var start = time.Now()

	// a helper to round the duration to seconds
	var roundSec = func(d time.Duration) time.Duration {
		return time.Second * time.Duration((d.Nanoseconds() / 1000000000))
	}

	// a helper to calculate the duration for both live and SMF messages
	var calcDuration = func(p *mid.SMFPosition) (dur time.Duration) {
		if p == nil {
			// we are in a live setting
			dur = roundSec(time.Now().Sub(start))
			return
		}

		// SMF data, calculate the time from the timeformat of the SMF file
		// we ignore the possibility that tempo information may come in a track following the one of
		// the current message as the spec does not recommend this
		return roundSec(ticks.Duration(bpm, uint32(p.AbsTime)))
	}

	hd.SMFHeader = func(head smf.Header) {
		// here we ignore that the timeformat could also be SMPTE
		ticks = head.TimeFormat.(smf.MetricTicks)
	}

	// we will override the tempo by the one given in the SMF
	hd.Message.Meta.Tempo = func(p mid.SMFPosition, valBPM uint32) {
		bpm = valBPM
	}

	// set the functions for the messages you are interested in
	hd.Message.Channel.NoteOn = func(p *mid.SMFPosition, channel, key, vel uint8) {
		fmt.Printf("[%vs] NoteOn at channel %v: key %v velocity: %v\n",
			calcDuration(p).Seconds(),
			channel, key, vel)
	}

	hd.Message.Channel.NoteOff = func(p *mid.SMFPosition, channel, key, vel uint8) {
		fmt.Printf("[%vs] NoteOff at channel %v: key %v velocity: %v\n",
			calcDuration(p).Seconds(),
			channel, key, vel)
	}

	// handle the smf
	fmt.Println("-- SMF data --")
	hd.ReadSMF(mkSMF())

	// handle the live data
	fmt.Println("-- live data --")
	lrd, lwr := io.Pipe()

	// WARNING this example does not deal with races and synchronization, it is just for illustration
	go func() {
		hd.ReadLive(lrd)
	}()

	mwr := mid.NewLiveWriter(lwr)

	// reset the time
	start = time.Now()

	mwr.SetChannel(11)

	// now write some live data
	mwr.NoteOn(120, 50)
	time.Sleep(time.Second * 2)
	mwr.NoteOff(120)

	// Output: -- SMF data --
	// [0s] NoteOn at channel 2: key 65 velocity: 90
	// [1s] NoteOff at channel 2: key 65 velocity: 0
	// -- live data --
	// [0s] NoteOn at channel 11: key 120 velocity: 50
	// [2s] NoteOff at channel 11: key 120 velocity: 0
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2015 The heketi 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 main

import (
	"flag"
	"fmt"
	"github.com/heketi/heketi/client/go/commands"
	"io"
	"os"
)

var (
	stdout  io.Writer = os.Stdout
	options commands.Options
)

func init() {

	flag.StringVar(&options.Url, "server", "", "server url goes here.")

	flag.Usage = func() {
		fmt.Println("USAGE: \n")
		fmt.Println("heketi cluster <n>\n")
		fmt.Println("where n can be one of the following: \n")
		fmt.Println("create <id> \n info <id> \n list \n destroy <id>")

		//TODO:  add other first level commands
	}
}

// ------ Main
func main() {
	flag.Parse()

	//ensure that we pass a server
	if options.Url == "" {
		fmt.Fprintf(stdout, "You need a server!\n")
		os.Exit(1)
	}

	//all first level commands go here (cluster, node, device, volume)
	cmds := commands.Commands{
		commands.NewClusterCommand(&options),
	}

	for _, cmd := range cmds {
		if flag.Arg(0) == cmd.Name() {

			//check for err
			err := cmd.Exec(flag.Args()[1:])
			if err != nil {
				fmt.Fprintf(stdout, "Error: %v\n", err)
				os.Exit(1)
			}
			return
		}
	}

	fmt.Println("Command not found")
}
<commit_msg>fixed newlines from go vet<commit_after>//
// Copyright (c) 2015 The heketi 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 main

import (
	"flag"
	"fmt"
	"github.com/heketi/heketi/client/go/commands"
	"io"
	"os"
)

var (
	stdout  io.Writer = os.Stdout
	options commands.Options
)

func init() {

	flag.StringVar(&options.Url, "server", "", "server url goes here.")

	flag.Usage = func() {
		fmt.Println("USAGE: ")
		fmt.Println("heketi cluster <n>")
		fmt.Println("where n can be one of the following: ")
		fmt.Println("create <id> \n info <id> \n list \n destroy <id>")

		//TODO:  add other first level commands
	}
}

// ------ Main
func main() {
	flag.Parse()

	//ensure that we pass a server
	if options.Url == "" {
		fmt.Fprintf(stdout, "You need a server!\n")
		os.Exit(1)
	}

	//all first level commands go here (cluster, node, device, volume)
	cmds := commands.Commands{
		commands.NewClusterCommand(&options),
	}

	for _, cmd := range cmds {
		if flag.Arg(0) == cmd.Name() {

			//check for err
			err := cmd.Exec(flag.Args()[1:])
			if err != nil {
				fmt.Fprintf(stdout, "Error: %v\n", err)
				os.Exit(1)
			}
			return
		}
	}

	fmt.Println("Command not found")
}
<|endoftext|>


<commit_before>package comments

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/google/go-github/github"
)

type CommentHandler func(client *github.Client, comment github.IssueCommentEvent) error

type CommentsHandler struct {
	client               *github.Client
	issueCommentHandlers []CommentHandler
	pullCommentHandlers  []CommentHandler
}

// NewHandler returns an HTTP handler which deprecates repositories
// by closing new issues with a comment directing attention elsewhere.
func NewHandler(client *github.Client, issuesHandlers []CommentHandler, pullRequestsHandlers []CommentHandler) *CommentsHandler {
	return &CommentsHandler{
		client:               client,
		issueCommentHandlers: issuesHandlers,
		pullCommentHandlers:  pullRequestsHandlers,
	}
}

func (h *CommentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if eventType := r.Header.Get("X-GitHub-Event"); eventType != "issue_comment" {
		log.Printf("received invalid event of type X-GitHub-Event: %s", eventType)
		http.Error(w, "not an issue_comment event.", 200)
		return
	}

	var event github.IssueCommentEvent
	err := json.NewDecoder(r.Body).Decode(&event)
	if err != nil {
		log.Println("error unmarshalling issue comment stuffs:", err)
		http.Error(w, "bad json", 400)
		return
	}

	var handlers []CommentHandler
	if isPullRequest(event) {
		handlers = h.pullCommentHandlers
	} else {
		handlers = h.issueCommentHandlers
	}

	for _, handler := range handlers {
		go handler(h.client, event)
	}

	fmt.Fprintf(w, "fired %d handlers", len(handlers))
}

func isPullRequest(event github.IssueCommentEvent) bool {
	return event.Issue.PullRequestLinks != nil
}
<commit_msg>Allow pull_request event type for comment handlers<commit_after>package comments

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/google/go-github/github"
)

type CommentHandler func(client *github.Client, comment github.IssueCommentEvent) error

type CommentsHandler struct {
	client               *github.Client
	issueCommentHandlers []CommentHandler
	pullCommentHandlers  []CommentHandler
}

// NewHandler returns an HTTP handler which deprecates repositories
// by closing new issues with a comment directing attention elsewhere.
func NewHandler(client *github.Client, issuesHandlers []CommentHandler, pullRequestsHandlers []CommentHandler) *CommentsHandler {
	return &CommentsHandler{
		client:               client,
		issueCommentHandlers: issuesHandlers,
		pullCommentHandlers:  pullRequestsHandlers,
	}
}

func (h *CommentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if eventType := r.Header.Get("X-GitHub-Event"); !isComment(eventType) {
		log.Printf("received invalid event of type X-GitHub-Event: %s", eventType)
		http.Error(w, "not an issue_comment event.", 200)
		return
	}

	var event github.IssueCommentEvent
	err := json.NewDecoder(r.Body).Decode(&event)
	if err != nil {
		log.Println("error unmarshalling issue comment stuffs:", err)
		http.Error(w, "bad json", 400)
		return
	}

	var handlers []CommentHandler
	if isPullRequest(event) {
		handlers = h.pullCommentHandlers
	} else {
		handlers = h.issueCommentHandlers
	}

	for _, handler := range handlers {
		go handler(h.client, event)
	}

	fmt.Fprintf(w, "fired %d handlers", len(handlers))
}

func isPullRequest(event github.IssueCommentEvent) bool {
	return event.Issue.PullRequestLinks != nil
}

func isComment(eventType string) bool {
	return eventType == "issue_comment" || eventType == "pull_request"
}
<|endoftext|>


<commit_before>package clients

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/boltdb/bolt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"github.com/docker/go-connections/nat"
)

// Docker struct to manage all CryutoDev action with Docker
type Docker struct {
	Client *client.Client
}

var images = map[string]string{
	"bitcoin":  "heraware/bitcoin:latest",
	"litecoin": "heraware/litecoin:latest",
}

// NewDockerClient Return a Docker instance with Docker client
// configured from OS ENV
func NewDockerClient() *Docker {
	client, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}
	docker := Docker{Client: client}
	return &docker
}

func (d *Docker) getContainerInfo(containerName string) ([]byte, error) {
	var result []byte
	if err := DB.View(func(tx *bolt.Tx) error {
		txBucket := tx.Bucket([]byte("containers"))
		if txBucket == nil {
			return fmt.Errorf("Bucket doesn't exists")
		}
		result = txBucket.Get([]byte(containerName))
		return nil
	}); err != nil {
		return nil, err
	}
	return result, nil
}

func (d *Docker) deleteContainerInfo(containerName string) error {
	return DB.Update(func(tx *bolt.Tx) error {
		txBucket := tx.Bucket([]byte("containers"))
		if txBucket == nil {
			return fmt.Errorf("Bucket doesn't exists")
		}
		return txBucket.Delete([]byte(containerName))
	})
}

func (d *Docker) saveContainerInfo(containerName string, containerID string) error {
	if err := DB.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte("containers"))
		if err != nil {
			return err
		}
		if err := b.Put([]byte(containerName), []byte(containerID)); err != nil {
			return err
		}
		return nil
	}); err != nil {
		return err
	}
	return nil
}

func (d *Docker) containerExists(containerName string) bool {
	value, err := d.getContainerInfo(containerName)
	if err != nil {
		return false
	}
	if len(value) == 0 {
		return false
	}
	return true
}

func (d *Docker) runContainer(containerID string) error {
	return d.Client.ContainerStart(context.Background(), containerID, types.ContainerStartOptions{})
}

func (d *Docker) stopContainer(containerID string) error {
	timeout := 10 * time.Second
	return d.Client.ContainerStop(context.Background(), containerID, &timeout)
}

func (d *Docker) createAndRunContainer(name string, image string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	if d.containerExists(containerName) {
		log.Fatalf("Container: %s already exists", containerName)
	}
	containerConfig := container.Config{
		Image: images[name],
	}
	portBindings := map[nat.Port][]nat.PortBinding{
		"20001/tcp": []nat.PortBinding{nat.PortBinding{HostIP: "0.0.0.0", HostPort: "20001"}}}
	hostConfig := container.HostConfig{
		PortBindings: portBindings,
		Privileged:   false,
	}
	containerBody, err := d.Client.ContainerCreate(context.Background(), &containerConfig, &hostConfig, nil, containerName)
	if err != nil {
		panic(err)
	}
	d.saveContainerInfo(containerName, containerBody.ID)
	if err := d.runContainer(containerBody.ID); err != nil {
		panic(err)
	}
	fmt.Println(fmt.Sprintf("Node: %s is created and running - Container ID: %s", containerName, containerBody.ID))
}

// CreateNode create a container with the cryptocurrency client
func (d *Docker) CreateNode(name string) {
	d.createAndRunContainer(name, images[name])
}

func (d *Docker) RunNode(name string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	containerID, err := d.getContainerInfo(containerName)
	if err != nil {
		panic(err)
	}
	containerIDString := string(containerID)
	err = d.runContainer(containerIDString)
	if err != nil {
		fmt.Println(d.deleteContainerInfo(containerName))
		log.Fatalf("Container: %s doesn't exists, try to run `cryptodev create %s`", containerName, name)
	}
	fmt.Println(fmt.Sprintf("Node: %s is running - Container ID: %s", containerName, containerIDString))
}

func (d *Docker) StopNode(name string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	containerID, err := d.getContainerInfo(containerName)
	if err != nil {
		panic(err)
	}
	containerIDString := string(containerID)
	err = d.stopContainer(containerIDString)
	if err != nil {
		log.Fatalf("Container: %s doesn't exists, try to run `cryptodev create %s`", containerName, name)
	}
	fmt.Println(fmt.Sprintf("Node: %s was stopped", containerName))
}
<commit_msg>Create map of string and PortMap for each node ports.<commit_after>package clients

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/boltdb/bolt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
	"github.com/docker/go-connections/nat"
)

// Docker struct to manage all CryutoDev action with Docker
type Docker struct {
	Client *client.Client
}

var images = map[string]string{
	"bitcoin":  "heraware/bitcoin:latest",
	"litecoin": "heraware/litecoin:latest",
}

var ports = map[string]nat.PortMap{
	"bitcoin": map[nat.Port][]nat.PortBinding{
		"20001/tcp": []nat.PortBinding{
			nat.PortBinding{HostIP: "0.0.0.0", HostPort: "20001"},
		},
		"20000/tcp": []nat.PortBinding{
			nat.PortBinding{HostIP: "0.0.0.0", HostPort: "20000"},
		},
	},
	"litecoin": map[nat.Port][]nat.PortBinding{
		"21001/tcp": []nat.PortBinding{
			nat.PortBinding{HostIP: "0.0.0.0", HostPort: "21001"},
		},
		"21000/tcp": []nat.PortBinding{
			nat.PortBinding{HostIP: "0.0.0.0", HostPort: "21000"},
		},
	},
}

// NewDockerClient Return a Docker instance with Docker client
// configured from OS ENV
func NewDockerClient() *Docker {
	client, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}
	docker := Docker{Client: client}
	return &docker
}

func (d *Docker) getContainerInfo(containerName string) ([]byte, error) {
	var result []byte
	if err := DB.View(func(tx *bolt.Tx) error {
		txBucket := tx.Bucket([]byte("containers"))
		if txBucket == nil {
			return fmt.Errorf("Bucket doesn't exists")
		}
		result = txBucket.Get([]byte(containerName))
		return nil
	}); err != nil {
		return nil, err
	}
	return result, nil
}

func (d *Docker) deleteContainerInfo(containerName string) error {
	return DB.Update(func(tx *bolt.Tx) error {
		txBucket := tx.Bucket([]byte("containers"))
		if txBucket == nil {
			return fmt.Errorf("Bucket doesn't exists")
		}
		return txBucket.Delete([]byte(containerName))
	})
}

func (d *Docker) saveContainerInfo(containerName string, containerID string) error {
	if err := DB.Update(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte("containers"))
		if err != nil {
			return err
		}
		if err := b.Put([]byte(containerName), []byte(containerID)); err != nil {
			return err
		}
		return nil
	}); err != nil {
		return err
	}
	return nil
}

func (d *Docker) containerExists(containerName string) bool {
	value, err := d.getContainerInfo(containerName)
	if err != nil {
		return false
	}
	if len(value) == 0 {
		return false
	}
	return true
}

func (d *Docker) runContainer(containerID string) error {
	return d.Client.ContainerStart(context.Background(), containerID, types.ContainerStartOptions{})
}

func (d *Docker) stopContainer(containerID string) error {
	timeout := 10 * time.Second
	return d.Client.ContainerStop(context.Background(), containerID, &timeout)
}

func (d *Docker) createAndRunContainer(name string, image string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	if d.containerExists(containerName) {
		log.Fatalf("Container: %s already exists", containerName)
	}
	containerConfig := container.Config{
		Image: images[name],
	}
	hostConfig := container.HostConfig{
		PortBindings: ports[name],
		Privileged:   false,
	}
	containerBody, err := d.Client.ContainerCreate(context.Background(), &containerConfig, &hostConfig, nil, containerName)
	if err != nil {
		panic(err)
	}
	d.saveContainerInfo(containerName, containerBody.ID)
	if err := d.runContainer(containerBody.ID); err != nil {
		panic(err)
	}
	fmt.Println(fmt.Sprintf("Node: %s is created and running - Container ID: %s", containerName, containerBody.ID))
}

// CreateNode create a container with the cryptocurrency client
func (d *Docker) CreateNode(name string) {
	d.createAndRunContainer(name, images[name])
}

func (d *Docker) RunNode(name string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	containerID, err := d.getContainerInfo(containerName)
	if err != nil {
		panic(err)
	}
	containerIDString := string(containerID)
	err = d.runContainer(containerIDString)
	if err != nil {
		fmt.Println(d.deleteContainerInfo(containerName))
		log.Fatalf("Container: %s doesn't exists, try to run `cryptodev create %s`", containerName, name)
	}
	fmt.Println(fmt.Sprintf("Node: %s is running - Container ID: %s", containerName, containerIDString))
}

func (d *Docker) StopNode(name string) {
	containerName := fmt.Sprintf("cryptodev-%s", name)
	containerID, err := d.getContainerInfo(containerName)
	if err != nil {
		panic(err)
	}
	containerIDString := string(containerID)
	err = d.stopContainer(containerIDString)
	if err != nil {
		log.Fatalf("Container: %s doesn't exists, try to run `cryptodev create %s`", containerName, name)
	}
	fmt.Println(fmt.Sprintf("Node: %s was stopped", containerName))
}
<|endoftext|>


<commit_before>package base

import (
	"github.com/qiniu/api.v7/kodo"
	"qiniupkg.com/api.v7/conf"
)

var (
	Domain    string
	Bucket    string
	AccessKey string
	SecretKey string
)
var QiNiuExpire uint32 = 3600

// QiNiuUploadToken return token for upload pics
func QiNiuUploadToken(key string) string {
	conf.ACCESS_KEY = AccessKey
	conf.SECRET_KEY = SecretKey
	c := kodo.New(0, nil)
	policy := &kodo.PutPolicy{
		Scope:   Bucket + ":" + key,
		Expires: QiNiuExpire,
	}
	return c.MakeUptoken(policy)

}

// QiNiuDownloadUrl return download url for file key
func QiNiuDownloadUrl(key string) string {
	baseUrl := kodo.MakeBaseUrl(Domain, key)
	policy := kodo.GetPolicy{}
	c := kodo.New(0, nil)
	return c.MakePrivateUrl(baseUrl, &policy)
}
<commit_msg>upload qiniu token<commit_after>package base

import (
	"github.com/qiniu/api.v7/kodo"
	"qiniupkg.com/api.v7/conf"
)

var (
	Domain    string
	Bucket    string
	AccessKey string
	SecretKey string
)
var QiNiuExpire uint32 = 3600

// QiNiuUploadToken return token for upload pics
func QiNiuUploadToken(key string) string {
	conf.ACCESS_KEY = AccessKey
	conf.SECRET_KEY = SecretKey
	c := kodo.New(0, nil)
	var scope = Bucket
	if key != "" {
		scope = Bucket + ":" + key
	}
	policy := &kodo.PutPolicy{
		Scope:   scope,
		Expires: QiNiuExpire,
	}
	return c.MakeUptoken(policy)

}

// QiNiuDownloadUrl return download url for file key
func QiNiuDownloadUrl(key string) string {
	baseUrl := kodo.MakeBaseUrl(Domain, key)
	policy := kodo.GetPolicy{}
	c := kodo.New(0, nil)
	return c.MakePrivateUrl(baseUrl, &policy)
}
<|endoftext|>


<commit_before>package common

import (
	"os"
	"testing"

	"errors"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func init() {
	s := MockShell{}
	s.On("GetName").Return("script-shell")
	s.On("GenerateScript", mock.Anything, mock.Anything).Return("script", nil)
	RegisterShell(&s)
}

func TestBuildRun(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor only once
	p.On("Create").Return(&e).Once()

	// We run everything once
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
	e.On("Finish", nil).Return().Once()
	e.On("Cleanup").Return().Once()

	// Run script successfully
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(nil)

	RegisterExecutor("build-run-test", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-test",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.NoError(t, err)
}

func TestRetryPrepare(t *testing.T) {
	PreparationRetryInterval = 0

	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(3)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(errors.New("prepare failed")).Twice()
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(nil).Once()
	e.On("Cleanup").Return().Times(3)

	// Succeed a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(nil)
	e.On("Finish", nil).Return().Once()

	RegisterExecutor("build-run-retry-prepare", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-retry-prepare",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.NoError(t, err)
}

func TestPrepareFailure(t *testing.T) {
	PreparationRetryInterval = 0

	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(3)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(errors.New("prepare failed")).Times(3)
	e.On("Cleanup").Return().Times(3)

	RegisterExecutor("build-run-prepare-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-prepare-failure",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "prepare failed")
}

func TestPrepareFailureOnBuildError(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(1)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(&BuildError{}).Times(1)
	e.On("Cleanup").Return().Times(1)

	RegisterExecutor("build-run-prepare-failure-on-build-error", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-prepare-failure-on-build-error",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.IsType(t, err, &BuildError{})
}

func TestRunFailure(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Once()

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil)
	e.On("Cleanup").Return().Once()

	// Fail a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(errors.New("build fail")).Times(3)
	e.On("Finish", errors.New("build fail")).Return().Once()

	RegisterExecutor("build-run-run-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-run-failure",
			},
		},
	}

	build.Variables = append(build.Variables, BuildVariable{Key: "PRE_BUILD_ATTEMPTS", Value: "3"})
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "build fail")
}

func TestRunWrongAttempts(t *testing.T) {
	e := MockExecutor{}

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil)
	e.On("Cleanup").Return()

	// Fail a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(errors.New("Number of attempts specified in PRE_BUILD_ATTEMPTS out of the range [1, 10]"))
	e.On("Finish", errors.New("Number of attempts specified in PRE_BUILD_ATTEMPTS out of the range [1, 10]")).Return()

	RegisterExecutor("build-run-attempt-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-attempt-failure",
			},
		},
	}

	build.Variables = append(build.Variables, BuildVariable{Key: "PRE_BUILD_ATTEMPTS", Value: "0"})
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "Number of attempts specified in PRE_BUILD_ATTEMPTS out of the range [1, 10]")
}
<commit_msg>added new test and fixed changelog<commit_after>package common

import (
	"os"
	"testing"

	"errors"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func init() {
	s := MockShell{}
	s.On("GetName").Return("script-shell")
	s.On("GenerateScript", mock.Anything, mock.Anything).Return("script", nil)
	RegisterShell(&s)
}

func TestBuildRun(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor only once
	p.On("Create").Return(&e).Once()

	// We run everything once
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
	e.On("Finish", nil).Return().Once()
	e.On("Cleanup").Return().Once()

	// Run script successfully
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(nil)

	RegisterExecutor("build-run-test", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-test",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.NoError(t, err)
}

func TestRetryPrepare(t *testing.T) {
	PreparationRetryInterval = 0

	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(3)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(errors.New("prepare failed")).Twice()
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(nil).Once()
	e.On("Cleanup").Return().Times(3)

	// Succeed a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(nil)
	e.On("Finish", nil).Return().Once()

	RegisterExecutor("build-run-retry-prepare", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-retry-prepare",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.NoError(t, err)
}

func TestPrepareFailure(t *testing.T) {
	PreparationRetryInterval = 0

	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(3)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(errors.New("prepare failed")).Times(3)
	e.On("Cleanup").Return().Times(3)

	RegisterExecutor("build-run-prepare-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-prepare-failure",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "prepare failed")
}

func TestPrepareFailureOnBuildError(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Times(1)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).
		Return(&BuildError{}).Times(1)
	e.On("Cleanup").Return().Times(1)

	RegisterExecutor("build-run-prepare-failure-on-build-error", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-prepare-failure-on-build-error",
			},
		},
	}
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.IsType(t, err, &BuildError{})
}

func TestRunFailure(t *testing.T) {
	e := MockExecutor{}
	defer e.AssertExpectations(t)

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e).Once()

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil)
	e.On("Cleanup").Return().Once()

	// Fail a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(errors.New("build fail")).Times(3)
	e.On("Finish", errors.New("build fail")).Return().Once()

	RegisterExecutor("build-run-run-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-run-failure",
			},
		},
	}

	build.Variables = append(build.Variables, BuildVariable{Key: "PRE_BUILD_ATTEMPTS", Value: "3"})
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "build fail")
}

func TestRunWrongAttempts(t *testing.T) {
	e := MockExecutor{}

	p := MockExecutorProvider{}
	defer p.AssertExpectations(t)

	// Create executor
	p.On("Create").Return(&e)

	// Prepare plan
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil)
	e.On("Cleanup").Return()

	// Fail a build script
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})
	e.On("Run", mock.Anything).Return(errors.New("Number of attempts out of the range [1, 10]"))
	e.On("Finish", errors.New("Number of attempts out of the range [1, 10]")).Return()

	RegisterExecutor("build-run-attempt-failure", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-attempt-failure",
			},
		},
	}

	build.Variables = append(build.Variables, BuildVariable{Key: "PRE_BUILD_ATTEMPTS", Value: "0"})
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.EqualError(t, err, "Number of attempts out of the range [1, 10]")
}

func TestRunSuccessOnSecondAttempt(t *testing.T) {
	e := MockExecutor{}
	p := MockExecutorProvider{}

	// Create executor only once
	p.On("Create").Return(&e).Once()

	// We run everything once
	e.On("Prepare", mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
	e.On("Finish", mock.Anything).Return().Twice()
	e.On("Cleanup").Return().Twice()

	// Run script successfully
	e.On("Shell").Return(&ShellScriptInfo{Shell: "script-shell"})

	e.On("Run", mock.Anything).Return(errors.New("build fail")).Once()
	e.On("Run", mock.Anything).Return(nil)

	RegisterExecutor("build-run-success-second-attempt", &p)

	successfulBuild, err := GetSuccessfulBuild()
	assert.NoError(t, err)
	build := &Build{
		GetBuildResponse: successfulBuild,
		Runner: &RunnerConfig{
			RunnerSettings: RunnerSettings{
				Executor: "build-run-success-second-attempt",
			},
		},
	}

	build.Variables = append(build.Variables, BuildVariable{Key: "PRE_BUILD_ATTEMPTS", Value: "3"})
	err = build.Run(&Config{}, &Trace{Writer: os.Stdout})
	assert.NoError(t, err)
}
<|endoftext|>


<commit_before>package comparer

import (
	"fmt"
	"io/ioutil"
	"os"
	"reflect"
	"sort"
)

// Compare looks to two different directories,
// and creates a file named "missingFolders.txt" and/or "missingFiles.txt" and/or "<fileName>MissingTags.txt"
// with the missing files, folders and tags on each line of the file
func Compare(original, translation string) error {
	missFiles, missFolders, err := diff(original, translation)
	if err != nil {
		return err
	}
	if missFolders != nil {
		if err := createOutuputFile(translation, "", "missingFolders.txt", missFolders); err != nil {
			return err
		}
	}
	if missFiles != nil {
		if err := createOutuputFile(translation, "", "missingFiles.txt", missFiles); err != nil {
			return err
		}
	}
	if err := readFiles(original, translation); err != nil {
		return err
	}
	return nil
}

func diff(original, translation string) (missingFiles, missingFolders []string, err error) {
	dirOri, filesOri, err := directoriesAndFiles(original)
	if err != nil {
		return nil, nil, err
	}
	dirTrans, filesTrans, err := directoriesAndFiles(translation)
	if err != nil {
		return nil, nil, err
	}
	missingFolders = findMissing(dirOri, dirTrans)
	missingFiles = findMissing(filesOri, filesTrans)
	return missingFiles, missingFolders, nil
}

func isItFileOrFolder(filesInfo []os.FileInfo) ([]string, []string) {
	var folders, files []string
	for _, v := range filesInfo {
		if v.IsDir() {
			folders = append(folders, v.Name())
		} else {
			files = append(files, v.Name())
		}
	}
	return folders, files
}

// More info: https://gist.github.com/ArxdSilva/7392013cbba7a7090cbcd120b7f5ca31
func findMissing(fileFolderA, fileFolderB []string) []string {
	sort.Strings(fileFolderA)
	sort.Strings(fileFolderB)
	if reflect.DeepEqual(fileFolderA, fileFolderB) {
		return nil
	}
	for i := len(fileFolderA) - 1; i >= 0; i-- {
		for _, vD := range fileFolderB {
			if fileFolderA[i] == vD {
				fileFolderA = append(fileFolderA[:i], fileFolderA[i+1:]...)
				break
			}
		}
	}
	return fileFolderA
}

func createOutuputFile(path, prefix, name string, missing []string) error {
	file, err := os.Create(fmt.Sprintf("%s/%s%s", path, prefix, name))
	defer file.Close()
	if err != nil {
		return err
	}
	for _, v := range missing {
		d := []byte(fmt.Sprintf("%s\n", v))
		file.Write(d)
	}
	return nil
}

func directoriesAndFiles(language string) ([]string, []string, error) {
	filesInfo, err := ioutil.ReadDir(language)
	if err != nil {
		return nil, nil, err
	}
	dir, files := isItFileOrFolder(filesInfo)
	return dir, files, nil
}
<commit_msg>comparer: prevent new line in cmd<commit_after>package comparer

import (
	"fmt"
	"io/ioutil"
	"os"
	"reflect"
	"sort"
)

// Compare looks to two different directories,
// and creates a file named "missingFolders.txt" and/or "missingFiles.txt" and/or "<fileName>MissingTags.txt"
// with the missing files, folders and tags on each line of the file
func Compare(original, translation string) error {
	missFiles, missFolders, err := diff(original, translation)
	if err != nil {
		return err
	}
	if missFolders != nil {
		if err := createOutuputFile(translation, "", "missingFolders.txt", missFolders); err != nil {
			return err
		}
	}
	if missFiles != nil {
		if err := createOutuputFile(translation, "", "missingFiles.txt", missFiles); err != nil {
			return err
		}
	}
	if err := readFiles(original, translation); err != nil {
		return err
	}
	return nil
}

func diff(original, translation string) (missingFiles, missingFolders []string, err error) {
	dirOri, filesOri, err := directoriesAndFiles(original)
	if err != nil {
		return nil, nil, err
	}
	dirTrans, filesTrans, err := directoriesAndFiles(translation)
	if err != nil {
		return nil, nil, err
	}
	missingFolders = findMissing(dirOri, dirTrans)
	missingFiles = findMissing(filesOri, filesTrans)
	return missingFiles, missingFolders, nil
}

func isItFileOrFolder(filesInfo []os.FileInfo) ([]string, []string) {
	var folders, files []string
	for _, v := range filesInfo {
		if v.IsDir() {
			folders = append(folders, v.Name())
		} else {
			files = append(files, v.Name())
		}
	}
	return folders, files
}

// More info: https://gist.github.com/ArxdSilva/7392013cbba7a7090cbcd120b7f5ca31
func findMissing(fileFolderA, fileFolderB []string) []string {
	sort.Strings(fileFolderA)
	sort.Strings(fileFolderB)
	if reflect.DeepEqual(fileFolderA, fileFolderB) {
		return nil
	}
	for i := len(fileFolderA) - 1; i >= 0; i-- {
		for _, vD := range fileFolderB {
			fmt.Print(".")
			if fileFolderA[i] == vD {
				fileFolderA = append(fileFolderA[:i], fileFolderA[i+1:]...)
				break
			}
		}
	}
	return fileFolderA
}

func createOutuputFile(path, prefix, name string, missing []string) error {
	file, err := os.Create(fmt.Sprintf("%s/%s%s", path, prefix, name))
	defer file.Close()
	if err != nil {
		return err
	}
	for _, v := range missing {
		d := []byte(fmt.Sprintf("%s\n", v))
		file.Write(d)
	}
	return nil
}

func directoriesAndFiles(language string) ([]string, []string, error) {
	filesInfo, err := ioutil.ReadDir(language)
	if err != nil {
		return nil, nil, err
	}
	dir, files := isItFileOrFolder(filesInfo)
	return dir, files, nil
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource"
)

func TestAccDataSourceAwsSsoPermissionSet_basic(t *testing.T) {
	datasourceName := "data.aws_sso_permission_set.test"
	rName := acctest.RandomWithPrefix("tf-sso-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t); testAccPreCheckAWSSSOInstance(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataSourceAwsSsoPermissionSetConfigBasic(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(datasourceName, "managed_policy_arns.#", "1"),
					tfawsresource.TestCheckTypeSetElemAttr(datasourceName, "managed_policy_arns.*", "arn:aws:iam::aws:policy/ReadOnlyAccess"),
					resource.TestCheckResourceAttr(datasourceName, "name", fmt.Sprintf("%s", rName)),
					resource.TestCheckResourceAttr(datasourceName, "description", "testing"),
					resource.TestCheckResourceAttr(datasourceName, "session_duration", "PT1H"),
					resource.TestCheckResourceAttr(datasourceName, "relay_state", "https://console.aws.amazon.com/console/home"),
					resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"),
				),
			},
		},
	})
}

func TestAccDataSourceAwsSsoPermissionSet_byTags(t *testing.T) {
	datasourceName := "data.aws_sso_permission_set.test"
	rName := acctest.RandomWithPrefix("tf-sso-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t); testAccPreCheckAWSSSOInstance(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataSourceAwsSsoPermissionSetConfigByTags(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(datasourceName, "managed_policy_arns.#", "1"),
					tfawsresource.TestCheckTypeSetElemAttr(datasourceName, "managed_policy_arns.*", "arn:aws:iam::aws:policy/ReadOnlyAccess"),
					resource.TestCheckResourceAttr(datasourceName, "name", fmt.Sprintf("%s", rName)),
					resource.TestCheckResourceAttr(datasourceName, "description", "testing"),
					resource.TestCheckResourceAttr(datasourceName, "session_duration", "PT1H"),
					resource.TestCheckResourceAttr(datasourceName, "relay_state", "https://console.aws.amazon.com/console/home"),
					resource.TestCheckResourceAttr(datasourceName, "tags.%", "3"),
				),
			},
		},
	})
}

func testAccDataSourceAwsSsoPermissionSetConfigBasic(rName string) string {
	return fmt.Sprintf(`
data "aws_sso_instance" "selected" {}

resource "aws_sso_permission_set" "test" {
  name                = "%s"
  description         = "testing"
  instance_arn        = data.aws_sso_instance.selected.arn
  session_duration    = "PT1H"
  relay_state         = "https://console.aws.amazon.com/console/home"
  managed_policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"]
}

data "aws_sso_permission_set" "test" {
  instance_arn = data.aws_sso_instance.selected.arn
  name         = aws_sso_permission_set.test.name
}
`, rName)
}

func testAccDataSourceAwsSsoPermissionSetConfigByTags(rName string) string {
	return fmt.Sprintf(`
data "aws_sso_instance" "selected" {}

resource "aws_sso_permission_set" "test" {
  name                = "%s"
  description         = "testing"
  instance_arn        = data.aws_sso_instance.selected.arn
  session_duration    = "PT1H"
  relay_state         = "https://console.aws.amazon.com/console/home"
  managed_policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"]

  tags = {
    Key1 = "Value1"
    Key2 = "Value2"
    Key3 = "Value3"
  }
}

data "aws_sso_permission_set" "test" {
  instance_arn = data.aws_sso_instance.selected.arn
  name         = aws_sso_permission_set.test.name

  tags = {
    Key1 = "Value1"
    Key2 = "Value2"
    Key3 = "Value3"
  }
}
`, rName)
}
<commit_msg>lint fixes<commit_after>package aws

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource"
)

func TestAccDataSourceAwsSsoPermissionSet_basic(t *testing.T) {
	datasourceName := "data.aws_sso_permission_set.test"
	rName := acctest.RandomWithPrefix("tf-sso-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t); testAccPreCheckAWSSSOInstance(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataSourceAwsSsoPermissionSetConfigBasic(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(datasourceName, "managed_policy_arns.#", "1"),
					tfawsresource.TestCheckTypeSetElemAttr(datasourceName, "managed_policy_arns.*", "arn:aws:iam::aws:policy/ReadOnlyAccess"),
					resource.TestCheckResourceAttr(datasourceName, "name", rName),
					resource.TestCheckResourceAttr(datasourceName, "description", "testing"),
					resource.TestCheckResourceAttr(datasourceName, "session_duration", "PT1H"),
					resource.TestCheckResourceAttr(datasourceName, "relay_state", "https://console.aws.amazon.com/console/home"),
					resource.TestCheckResourceAttr(datasourceName, "tags.%", "0"),
				),
			},
		},
	})
}

func TestAccDataSourceAwsSsoPermissionSet_byTags(t *testing.T) {
	datasourceName := "data.aws_sso_permission_set.test"
	rName := acctest.RandomWithPrefix("tf-sso-test")

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t); testAccPreCheckAWSSSOInstance(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataSourceAwsSsoPermissionSetConfigByTags(rName),
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttr(datasourceName, "managed_policy_arns.#", "1"),
					tfawsresource.TestCheckTypeSetElemAttr(datasourceName, "managed_policy_arns.*", "arn:aws:iam::aws:policy/ReadOnlyAccess"),
					resource.TestCheckResourceAttr(datasourceName, "name", fmt.Sprintf("%s", rName)),
					resource.TestCheckResourceAttr(datasourceName, "description", "testing"),
					resource.TestCheckResourceAttr(datasourceName, "session_duration", "PT1H"),
					resource.TestCheckResourceAttr(datasourceName, "relay_state", "https://console.aws.amazon.com/console/home"),
					resource.TestCheckResourceAttr(datasourceName, "tags.%", "3"),
				),
			},
		},
	})
}

func testAccDataSourceAwsSsoPermissionSetConfigBasic(rName string) string {
	return fmt.Sprintf(`
data "aws_sso_instance" "selected" {}

resource "aws_sso_permission_set" "test" {
  name                = "%s"
  description         = "testing"
  instance_arn        = data.aws_sso_instance.selected.arn
  session_duration    = "PT1H"
  relay_state         = "https://console.aws.amazon.com/console/home"
  managed_policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"]
}

data "aws_sso_permission_set" "test" {
  instance_arn = data.aws_sso_instance.selected.arn
  name         = aws_sso_permission_set.test.name
}
`, rName)
}

func testAccDataSourceAwsSsoPermissionSetConfigByTags(rName string) string {
	return fmt.Sprintf(`
data "aws_sso_instance" "selected" {}

resource "aws_sso_permission_set" "test" {
  name                = "%s"
  description         = "testing"
  instance_arn        = data.aws_sso_instance.selected.arn
  session_duration    = "PT1H"
  relay_state         = "https://console.aws.amazon.com/console/home"
  managed_policy_arns = ["arn:aws:iam::aws:policy/ReadOnlyAccess"]

  tags = {
    Key1 = "Value1"
    Key2 = "Value2"
    Key3 = "Value3"
  }
}

data "aws_sso_permission_set" "test" {
  instance_arn = data.aws_sso_instance.selected.arn
  name         = aws_sso_permission_set.test.name

  tags = {
    Key1 = "Value1"
    Key2 = "Value2"
    Key3 = "Value3"
  }
}
`, rName)
}
<|endoftext|>


<commit_before>package azurerm

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAzureRMCosmosDBAccountName_validation(t *testing.T) {
	str := acctest.RandString(50)
	cases := []struct {
		Value    string
		ErrCount int
	}{
		{
			Value:    "ab",
			ErrCount: 1,
		},
		{
			Value:    "abc",
			ErrCount: 0,
		},
		{
			Value:    str,
			ErrCount: 0,
		},
		{
			Value:    str + "a",
			ErrCount: 1,
		},
	}

	for _, tc := range cases {
		_, errors := validateAzureRmCosmosDBAccountName(tc.Value, "azurerm_cosmosdb_account")

		if len(errors) != tc.ErrCount {
			t.Fatalf("Expected the AzureRM CosmosDB Name to trigger a validation error for '%s'", tc.Value)
		}
	}
}

func TestAccAzureRMCosmosDBAccount_boundedStaleness(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_boundedStaleness(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_boundedStalenessComplete(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_boundedStalenessComplete(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_eventualConsistency(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_eventualConsistency(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_session(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_session(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_strong(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_strong(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_geoReplicated(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_geoReplicated(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func testCheckAzureRMCosmosDBAccountDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*ArmClient).documentDBClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "azurerm_cosmos_db" {
			continue
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup := rs.Primary.Attributes["resource_group_name"]

		resp, err := conn.Get(resourceGroup, name)

		if err != nil {
			return nil
		}

		if resp.StatusCode != http.StatusNotFound {
			return fmt.Errorf("CosmosDB Account still exists:\n%#v", resp)
		}
	}

	return nil
}

func testCheckAzureRMCosmosDBAccountExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		// Ensure we have enough information in state to look up in API
		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
		if !hasResourceGroup {
			return fmt.Errorf("Bad: no resource group found in state for CosmosDB Account: '%s'", name)
		}

		conn := testAccProvider.Meta().(*ArmClient).documentDBClient

		resp, err := conn.Get(resourceGroup, name)
		if err != nil {
			return fmt.Errorf("Bad: Get on documentDBClient: %s", err)
		}

		if resp.StatusCode == http.StatusNotFound {
			return fmt.Errorf("Bad: CosmosDB Account '%s' (resource group: '%s') does not exist", name, resourceGroup)
		}

		return nil
	}
}

func testAccAzureRMCosmosDBAccount_boundedStaleness(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "BoundedStaleness"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_boundedStalenessComplete(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level       = "BoundedStaleness"
    max_interval_in_seconds = 10
    max_staleness_prefix    = 200
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_eventualConsistency(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Eventual"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_session(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Session"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_strong(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Strong"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_geoReplicated(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level       = "Eventual"
    max_interval_in_seconds = 10
    max_staleness           = 200
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }

  failover_policy {
    location = "West Europe"
    priority = 1
  }
}
`, rInt, rInt)
}
<commit_msg>Fixing the geoReplication tests<commit_after>package azurerm

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAzureRMCosmosDBAccountName_validation(t *testing.T) {
	str := acctest.RandString(50)
	cases := []struct {
		Value    string
		ErrCount int
	}{
		{
			Value:    "ab",
			ErrCount: 1,
		},
		{
			Value:    "abc",
			ErrCount: 0,
		},
		{
			Value:    str,
			ErrCount: 0,
		},
		{
			Value:    str + "a",
			ErrCount: 1,
		},
	}

	for _, tc := range cases {
		_, errors := validateAzureRmCosmosDBAccountName(tc.Value, "azurerm_cosmosdb_account")

		if len(errors) != tc.ErrCount {
			t.Fatalf("Expected the AzureRM CosmosDB Name to trigger a validation error for '%s'", tc.Value)
		}
	}
}

func TestAccAzureRMCosmosDBAccount_boundedStaleness(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_boundedStaleness(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_boundedStalenessComplete(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_boundedStalenessComplete(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_eventualConsistency(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_eventualConsistency(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_session(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_session(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_strong(t *testing.T) {
	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_strong(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func TestAccAzureRMCosmosDBAccount_geoReplicated(t *testing.T) {

	ri := acctest.RandInt()
	config := testAccAzureRMCosmosDBAccount_geoReplicated(ri)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy,
		Steps: []resource.TestStep{
			{
				Config: config,
				Check: resource.ComposeTestCheckFunc(
					testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"),
				),
			},
		},
	})
}

func testCheckAzureRMCosmosDBAccountDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*ArmClient).documentDBClient

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "azurerm_cosmos_db" {
			continue
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup := rs.Primary.Attributes["resource_group_name"]

		resp, err := conn.Get(resourceGroup, name)

		if err != nil {
			return nil
		}

		if resp.StatusCode != http.StatusNotFound {
			return fmt.Errorf("CosmosDB Account still exists:\n%#v", resp)
		}
	}

	return nil
}

func testCheckAzureRMCosmosDBAccountExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		// Ensure we have enough information in state to look up in API
		rs, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		name := rs.Primary.Attributes["name"]
		resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
		if !hasResourceGroup {
			return fmt.Errorf("Bad: no resource group found in state for CosmosDB Account: '%s'", name)
		}

		conn := testAccProvider.Meta().(*ArmClient).documentDBClient

		resp, err := conn.Get(resourceGroup, name)
		if err != nil {
			return fmt.Errorf("Bad: Get on documentDBClient: %s", err)
		}

		if resp.StatusCode == http.StatusNotFound {
			return fmt.Errorf("Bad: CosmosDB Account '%s' (resource group: '%s') does not exist", name, resourceGroup)
		}

		return nil
	}
}

func testAccAzureRMCosmosDBAccount_boundedStaleness(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "BoundedStaleness"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_boundedStalenessComplete(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level       = "BoundedStaleness"
    max_interval_in_seconds = 10
    max_staleness_prefix    = 200
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_eventualConsistency(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Eventual"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_session(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Session"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_strong(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level = "Strong"
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }
}
`, rInt, rInt)
}

func testAccAzureRMCosmosDBAccount_geoReplicated(rInt int) string {
	return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
    name = "acctestRG-%d"
    location = "West US"
}
resource "azurerm_cosmosdb_account" "test" {
  name                = "acctest-%d"
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
  offer_type          = "Standard"

  consistency_policy {
    consistency_level       = "BoundedStaleness"
    max_interval_in_seconds = 10
    max_staleness_prefix    = 200
  }

  failover_policy {
    location = "${azurerm_resource_group.test.location}"
    priority = 0
  }

  failover_policy {
    location = "West Europe"
    priority = 1
  }
}
`, rInt, rInt)
}
<|endoftext|>


<commit_before>package testdata

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"testing"
	"time"

	"v.io/core/veyron/lib/modules"
	"v.io/core/veyron/lib/testutil/integration"

	_ "v.io/core/veyron/profiles/static"
)

func TestHelperProcess(t *testing.T) {
	modules.DispatchInTest()
}

func TestDebugGlob(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	inv := binary.Start("glob", env.RootMT()+"/__debug/*")

	var want string
	for _, entry := range []string{"logs", "pprof", "stats", "vtrace"} {
		want += env.RootMT() + "/__debug/" + entry + "\n"
	}
	if got := inv.Output(); got != want {
		t.Fatalf("unexpected output, want %s, got %s", want, got)
	}
}

func TestDebugGlobLogs(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	fileName := filepath.Base(env.TempFile().Name())
	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	output := binary.Start("glob", env.RootMT()+"/__debug/logs/*").Output()

	// The output should contain the filename.
	want := "/logs/" + fileName
	if !strings.Contains(output, want) {
		t.Fatalf("output should contain %s but did not\n%s", want, output)
	}
}

func TestReadHostname(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	path := env.RootMT() + "/__debug/stats/system/hostname"
	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	got := binary.Start("stats", "read", path).Output()
	hostname, err := os.Hostname()
	if err != nil {
		t.Fatalf("Hostname() failed: %v", err)
	}
	if want := path + ": " + hostname + "\n"; got != want {
		t.Fatalf("unexpected output, want %s, got %s", want, got)
	}
}

func createTestLogFile(t *testing.T, env integration.TestEnvironment, content string) *os.File {
	file := env.TempFile()
	_, err := file.Write([]byte(content))
	if err != nil {
		t.Fatalf("Write failed: %v", err)
	}
	return file
}

func TestLogSize(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	testLogData := "This is a test log file"
	file := createTestLogFile(t, env, testLogData)

	// Check to ensure the file size is accurate
	str := strings.TrimSpace(binary.Start("logs", "size", env.RootMT()+"/__debug/logs/"+filepath.Base(file.Name())).Output())
	got, err := strconv.Atoi(str)
	if err != nil {
		t.Fatalf("Atoi(\"%q\") failed", str)
	}
	want := len(testLogData)
	if got != want {
		t.Fatalf("unexpected output, want %d, got %d", got, want)
	}
}

func TestStatsRead(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	testLogData := "This is a test log file\n"
	file := createTestLogFile(t, env, testLogData)
	logName := filepath.Base(file.Name())
	runCount := 12
	for i := 0; i < runCount; i++ {
		binary.Start("logs", "read", env.RootMT()+"/__debug/logs/"+logName).Wait(nil, nil)
	}
	got := binary.Start("stats", "read", env.RootMT()+"/__debug/stats/ipc/server/routing-id/*/methods/ReadLog/latency-ms").Output()
	want := fmt.Sprintf("Count: %d", runCount)
	if !strings.Contains(got, want) {
		t.Fatalf("expected output to contain %s, but did not\n", want, got)
	}
}

func TestStatsWatch(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/veyron/veyron/tools/debug")
	testLogData := "This is a test log file\n"
	file := createTestLogFile(t, env, testLogData)
	logName := filepath.Base(file.Name())
	binary.Start("logs", "read", env.RootMT()+"/__debug/logs/"+logName).Wait(nil, nil)

	inv := binary.Start("stats", "watch", "-raw", env.RootMT()+"/__debug/stats/ipc/server/routing-id/*/methods/ReadLog/latency-ms")

	lines := make(chan string)
	// Go off and read the invocation's stdout.
	go func() {
		line, err := bufio.NewReader(inv.Stdout()).ReadString('\n')
		if err != nil {
			t.Fatalf("Could not read line from invocation")
		}
		lines <- line
	}()

	// Wait up to 10 seconds for some stats output. Either some output
	// occurs or the timeout expires without any output.
	select {
	case <-time.After(10 * time.Second):
		t.Errorf("Timed out waiting for output")
	case got := <-lines:
		// Expect one ReadLog call to have occurred.
		want := "latency-ms: {Count:1"
		if !strings.Contains(got, want) {
			t.Errorf("wanted but could not find %q in output\n%s", want, got)
		}
	}

	// TODO(sjr): make env cleanup take care of invocations that are still
	// running at the end of the test.
	inv.Kill(15 /* SIGHUP */)
}

func performTracedRead(debugBinary integration.TestBinary, path string) string {
	return debugBinary.Start("--veyron.vtrace.sample_rate=1", "logs", "read", path).Output()
}

func TestVTrace(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	logContent := "Hello, world!\n"
	logPath := env.RootMT() + "/__debug/logs/" + filepath.Base(createTestLogFile(t, env, logContent).Name())
	// Create a log file with tracing, read it and check that the resulting trace exists.
	got := performTracedRead(binary, logPath)
	if logContent != got {
		t.Fatalf("unexpected output: want %s, got %s", logContent, got)
	}

	// Grab the ID of the first and only trace.
	want, traceContent := 1, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace").Output()
	if count := strings.Count(traceContent, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, traceContent)
	}
	fields := strings.Split(traceContent, " ")
	if len(fields) < 3 {
		t.Fatalf("expected at least 3 space-delimited fields, got %d\n", len(fields), traceContent)
	}
	traceId := fields[2]

	// Do a sanity check on the trace ID: it should be a 32-character hex ID.
	if match, _ := regexp.MatchString("[0-9a-f]{32}", traceId); !match {
		t.Fatalf("wanted a 32-character hex ID, got %s", traceId)
	}

	// Do another traced read, this will generate a new trace entry.
	performTracedRead(binary, logPath)

	// Read vtrace, we should have 2 traces now.
	want, output := 2, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace").Output()
	if count := strings.Count(output, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, output)
	}

	// Now ask for a particular trace. The output should contain exactly
	// one trace whose ID is equal to the one we asked for.
	want, got = 1, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace", traceId).Output()
	if count := strings.Count(got, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, got)
	}
	fields = strings.Split(got, " ")
	if len(fields) < 3 {
		t.Fatalf("expected at least 3 space-delimited fields, got %d\n", len(fields), got)
	}
	got = fields[2]
	if traceId != got {
		t.Fatalf("unexpected traceId, want %s, got %s", traceId, got)
	}
}
<commit_msg>veyron/tools/debug/testdata: add debug pprof test<commit_after>package testdata

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"testing"
	"time"

	"v.io/core/veyron/lib/modules"
	"v.io/core/veyron/lib/testutil/integration"

	_ "v.io/core/veyron/profiles/static"
)

func TestHelperProcess(t *testing.T) {
	modules.DispatchInTest()
}

func TestDebugGlob(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	inv := binary.Start("glob", env.RootMT()+"/__debug/*")

	var want string
	for _, entry := range []string{"logs", "pprof", "stats", "vtrace"} {
		want += env.RootMT() + "/__debug/" + entry + "\n"
	}
	if got := inv.Output(); got != want {
		t.Fatalf("unexpected output, want %s, got %s", want, got)
	}
}

func TestDebugGlobLogs(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	fileName := filepath.Base(env.TempFile().Name())
	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	output := binary.Start("glob", env.RootMT()+"/__debug/logs/*").Output()

	// The output should contain the filename.
	want := "/logs/" + fileName
	if !strings.Contains(output, want) {
		t.Fatalf("output should contain %s but did not\n%s", want, output)
	}
}

func TestReadHostname(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	path := env.RootMT() + "/__debug/stats/system/hostname"
	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	got := binary.Start("stats", "read", path).Output()
	hostname, err := os.Hostname()
	if err != nil {
		t.Fatalf("Hostname() failed: %v", err)
	}
	if want := path + ": " + hostname + "\n"; got != want {
		t.Fatalf("unexpected output, want %s, got %s", want, got)
	}
}

func createTestLogFile(t *testing.T, env integration.TestEnvironment, content string) *os.File {
	file := env.TempFile()
	_, err := file.Write([]byte(content))
	if err != nil {
		t.Fatalf("Write failed: %v", err)
	}
	return file
}

func TestLogSize(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	testLogData := "This is a test log file"
	file := createTestLogFile(t, env, testLogData)

	// Check to ensure the file size is accurate
	str := strings.TrimSpace(binary.Start("logs", "size", env.RootMT()+"/__debug/logs/"+filepath.Base(file.Name())).Output())
	got, err := strconv.Atoi(str)
	if err != nil {
		t.Fatalf("Atoi(\"%q\") failed", str)
	}
	want := len(testLogData)
	if got != want {
		t.Fatalf("unexpected output, want %d, got %d", got, want)
	}
}

func TestStatsRead(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	testLogData := "This is a test log file\n"
	file := createTestLogFile(t, env, testLogData)
	logName := filepath.Base(file.Name())
	runCount := 12
	for i := 0; i < runCount; i++ {
		binary.Start("logs", "read", env.RootMT()+"/__debug/logs/"+logName).Wait(nil, nil)
	}
	got := binary.Start("stats", "read", env.RootMT()+"/__debug/stats/ipc/server/routing-id/*/methods/ReadLog/latency-ms").Output()
	want := fmt.Sprintf("Count: %d", runCount)
	if !strings.Contains(got, want) {
		t.Fatalf("expected output to contain %s, but did not\n", want, got)
	}
}

func TestStatsWatch(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	testLogData := "This is a test log file\n"
	file := createTestLogFile(t, env, testLogData)
	logName := filepath.Base(file.Name())
	binary.Start("logs", "read", env.RootMT()+"/__debug/logs/"+logName).Wait(nil, nil)

	inv := binary.Start("stats", "watch", "-raw", env.RootMT()+"/__debug/stats/ipc/server/routing-id/*/methods/ReadLog/latency-ms")

	lines := make(chan string)
	// Go off and read the invocation's stdout.
	go func() {
		line, err := bufio.NewReader(inv.Stdout()).ReadString('\n')
		if err != nil {
			t.Fatalf("Could not read line from invocation")
		}
		lines <- line
	}()

	// Wait up to 10 seconds for some stats output. Either some output
	// occurs or the timeout expires without any output.
	select {
	case <-time.After(10 * time.Second):
		t.Errorf("Timed out waiting for output")
	case got := <-lines:
		// Expect one ReadLog call to have occurred.
		want := "latency-ms: {Count:1"
		if !strings.Contains(got, want) {
			t.Errorf("wanted but could not find %q in output\n%s", want, got)
		}
	}

	// TODO(sjr): make env cleanup take care of invocations that are still
	// running at the end of the test.
	inv.Kill(15 /* SIGHUP */)
}

func performTracedRead(debugBinary integration.TestBinary, path string) string {
	return debugBinary.Start("--veyron.vtrace.sample_rate=1", "logs", "read", path).Output()
}

func TestVTrace(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	logContent := "Hello, world!\n"
	logPath := env.RootMT() + "/__debug/logs/" + filepath.Base(createTestLogFile(t, env, logContent).Name())
	// Create a log file with tracing, read it and check that the resulting trace exists.
	got := performTracedRead(binary, logPath)
	if logContent != got {
		t.Fatalf("unexpected output: want %s, got %s", logContent, got)
	}

	// Grab the ID of the first and only trace.
	want, traceContent := 1, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace").Output()
	if count := strings.Count(traceContent, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, traceContent)
	}
	fields := strings.Split(traceContent, " ")
	if len(fields) < 3 {
		t.Fatalf("expected at least 3 space-delimited fields, got %d\n", len(fields), traceContent)
	}
	traceId := fields[2]

	// Do a sanity check on the trace ID: it should be a 32-character hex ID.
	if match, _ := regexp.MatchString("[0-9a-f]{32}", traceId); !match {
		t.Fatalf("wanted a 32-character hex ID, got %s", traceId)
	}

	// Do another traced read, this will generate a new trace entry.
	performTracedRead(binary, logPath)

	// Read vtrace, we should have 2 traces now.
	want, output := 2, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace").Output()
	if count := strings.Count(output, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, output)
	}

	// Now ask for a particular trace. The output should contain exactly
	// one trace whose ID is equal to the one we asked for.
	want, got = 1, binary.Start("vtrace", env.RootMT()+"/__debug/vtrace", traceId).Output()
	if count := strings.Count(got, "Trace -"); count != want {
		t.Fatalf("unexpected trace count, want %d, got %d\n%s", want, count, got)
	}
	fields = strings.Split(got, " ")
	if len(fields) < 3 {
		t.Fatalf("expected at least 3 space-delimited fields, got %d\n", len(fields), got)
	}
	got = fields[2]
	if traceId != got {
		t.Fatalf("unexpected traceId, want %s, got %s", traceId, got)
	}
}

func TestPprof(t *testing.T) {
	env := integration.NewTestEnvironment(t)
	defer env.Cleanup()

	binary := env.BuildGoPkg("v.io/core/veyron/tools/debug")
	inv := binary.Start("pprof", "run", env.RootMT()+"/__debug/pprof", "heap", "--text")

	// Assert that a profile was written out.
	want, got := "(.*) of (.*) total", inv.Output()
	var groups []string
	if groups = regexp.MustCompile(want).FindStringSubmatch(got); groups == nil || len(groups) < 3 {
		t.Logf("groups = %v", groups)
		t.Fatalf("could not find regexp %q in output\n%s", want, got)
	}

	t.Logf("got a heap profile showing a heap size of %s", groups[2])
}
<|endoftext|>


<commit_before>// +build  gromacs

/*
 * untitled.go
 *
 * Copyright 2012 Raul Mera Adasme <rmera_changeforat_chem-dot-helsinki-dot-fi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License  as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */
  /*
 *
 * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry,
 * University of Helsinki, Finland.
 *
 *
 */
/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/

package chem

// #cgo CFLAGS:  -I.
// #cgo LDFLAGS:  -L.  -lnsl -lm   -lxdrfile
//#include <xtc.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <xdrfile_xtc.h>
//#include <xdrfile_trr.h>
//#include <xdrfile.h>
import "C"
import "fmt"
import "github.com/skelterjohn/go.matrix"

/*ReadXtcFrames opens the Gromacs trajectory xtc file with name filename
and reads the coordinates for frames starting from ini to end (or the
last frame in the trajectory) and skipping skip frame between each
read. The frames are returned as a slice of matrix.Densematrix.
 It returns also the number of frames read, and
 error/nil in failure/success. Note that if there are less frames than
 end, the function wont return error, just the read frames and
 the number of them.*/
func ReadXtcFrames(ini, end, skip int, filename string)([]*matrix.DenseMatrix,int, error) {
	Coords:=make([]*matrix.DenseMatrix,0,1) // I might attempt to give the capacity later
	natoms,err:=XtcCountAtoms(filename)
	if err!=nil{
		return nil, 0, err
		}
	fp,_:=XtcOpen(filename) //We already tested that the name is ok, no need to catch this error
	defer XtcClose(fp)
	ccoords:=make([]C.float,natoms*3)
	i:=0
	for ;;i++{
		if i>end {
			break
			}
		if i<ini || (i-(1+ini))%skip!=0{
			err:=xtcGetFrameEfficientDrop(fp,ccoords,natoms)
			if err!=nil{
				if err.Error()=="No more frames"{
					break //No more frames is not really an error
					}else{
					return Coords, i, err
					}
				}
			}else{
			coords,err:=xtcGetFrameEfficient(fp,ccoords,natoms)
			if err!=nil{
				if err.Error()=="No more frames"{
					break //No more frames is not really an error
					}else{
					return Coords, i, err
					}
				}
			Coords=append(Coords,matrix.MakeDenseMatrix(coords,natoms,3))
			}
		}
	return Coords, i, nil
	}

//XtcCountAtoms takes the name of a Gromacs xtc trajectory file and returns the
//number of atoms per frame in the trajectory.
func XtcCountAtoms(name string)(int, error){
	Cfilename:=C.CString(name)
	Cnatoms:=C.read_natoms(Cfilename)
	natoms:=int(Cnatoms)
	return natoms, nil
	}

/*XtcOpen Opens the Gromacs xtc trajectory file with the name name and
 * returns a C pointer to it, which can passed to other functions of
 * the package to  */
func  XtcOpen(name string)(*C.XDRFILE, error){
	Cfilename:=C.CString(name)
	fp:=C.openfile(Cfilename)
	if fp==nil{
		return nil, fmt.Errorf("Unable to open xtc file")
		}
	return fp, nil
	}

/*XtcGetFrame takes a C pointer to an open Gromacs xtc file and the
 * number of atoms per frame in the file. It reads the coordinates
 * for the next frame of the file and returns  them as a slice of
 * float64 */
func XtcGetFrame(fp *C.XDRFILE,natoms int)(*matrix.DenseMatrix,error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	Ccoords:= make([]C.float,totalcoords)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return nil, fmt.Errorf("No more frames") //This is not really an error and should be catched in the calling function
		}
	if worked!=0{
		return nil, fmt.Errorf("Error reading frame")
			}
	goCoords:=make([]float64,totalcoords)
	for j:=0;j<totalcoords;j++{
		goCoords[j]=10*(float64(Ccoords[j]))  //nm to Angstroms
		}
	return matrix.MakeDenseMatrix(goCoords,natoms,3), nil
	}

/*XtcGetFrameEfficient takes a C pointer to an open Gromacs xtc file,
 * a slice of C float with enough size to contain all the coordinates
 * to be read, and number of atoms per frame in the file.
 * It reads the coordinates for the next frame of the file and returns
 * them as a slice of float64. The fact that it takes the intermediate
 * buffer as an argument means that one can save many memory allocations.
 * It returns nill on success, a "No more frames" error if no more
 * frames, and other error in other case.*/
func xtcGetFrameEfficient(fp *C.XDRFILE, Ccoords []C.float, natoms int)([]float64,error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		goCoords:=make([]float64,1)
		return goCoords, fmt.Errorf("No more frames")
		}
	if worked!=0{
		goCoords:=make([]float64,1)
		return goCoords, fmt.Errorf("Error reading frame")
			}
	goCoords:=make([]float64,totalcoords)
	for j:=0;j<totalcoords;j++{
		goCoords[j]=10*float64(Ccoords[j])  //nm to angstroms
		}
	return goCoords, nil
	}

/*XtcGetFrameDrop takes a C pointer to an open Gromacs xtc file and the
 * number of atoms per frame in the file. It reads the coordinates
 * for the next frame of the file and discards them, returning only
 * error/nil in case of failure/success. The special case of no more
 * frames to read causes it to return a "No more frames" error.*/
func XtcGetFrameDrop(fp *C.XDRFILE,natoms int)(error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	Ccoords:= make([]C.float,totalcoords)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return fmt.Errorf("No more frames")
		}
	if worked!=0{
		return fmt.Errorf("Error reading frame")
			}
	return nil
	}

/*XtcGetFrameEfficientDrop takes a C pointer to an open Gromacs xtc file,
 * a slice of C float with enough size to contain all the coordinates
 * to be read, and number of atoms per frame in the file.
 * It reads the coordinates for the next frame of the file and discart
 * them, returning error/nil in case of failure/success.
 * The fact that it takes the intermediate
 * buffer as an argument means that one can save many memory allocations. */
func xtcGetFrameEfficientDrop(fp *C.XDRFILE, Ccoords []C.float, natoms int)(error){
	cnatoms:=C.int(natoms)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return fmt.Errorf("No more frames")
		}
	if worked!=0{
		return fmt.Errorf("Error reading frame")
			}
	return nil
	}

/*XtcClose takes a pointer to an open Gromacs xtc trajectory file
 * and closes the file pointed by the pointer.*/
func XtcClose(fp *C.XDRFILE){
	C.xtc_close(fp)
	}
<commit_msg>small fixes for xtc<commit_after>// +build  gromacs

/*
 * xtc.go, part of gochem
 *
 * Copyright 2012 Raul Mera Adasme <rmera_changeforat_chem-dot-helsinki-dot-fi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License  as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */
  /*
 *
 * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry,
 * University of Helsinki, Finland.
 *
 *
 */
/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/

package chem

// #cgo CFLAGS:  -I.
// #cgo LDFLAGS:  -L.  -lnsl -lm   -lxdrfile
//#include <xtc.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <xdrfile_xtc.h>
//#include <xdrfile_trr.h>
//#include <xdrfile.h>
import "C"
import "fmt"
import "github.com/skelterjohn/go.matrix"

/*ReadXtcFrames opens the Gromacs trajectory xtc file with name filename
and reads the coordinates for frames starting from ini to end (or the
last frame in the trajectory) and skipping skip frame between each
read. The frames are returned as a slice of matrix.Densematrix.
 It returns also the number of frames read, and
 error/nil in failure/success. Note that if there are less frames than
 end, the function wont return error, just the read frames and
 the number of them.*/
func ReadXtcFrames(ini, end, skip int, filename string)([]*matrix.DenseMatrix,int, error) {
	Coords:=make([]*matrix.DenseMatrix,0,1) // I might attempt to give the capacity later
	natoms,err:=XtcCountAtoms(filename)
	if err!=nil{
		return nil, 0, err
		}
	fp,_:=XtcOpen(filename) //We already tested that the name is ok, no need to catch this error
	defer XtcClose(fp)
	ccoords:=make([]C.float,natoms*3)
	i:=0
	for ;;i++{
		if i>end {
			break
			}
		if i<ini || (i-(1+ini))%skip!=0{
			err:=xtcGetFrameEfficientDrop(fp,ccoords,natoms)
			if err!=nil{
				if err.Error()=="No more frames"{
					break //No more frames is not really an error
					}else{
					return Coords, i, err
					}
				}
			}else{
			coords,err:=xtcGetFrameEfficient(fp,ccoords,natoms)
			if err!=nil{
				if err.Error()=="No more frames"{
					break //No more frames is not really an error
					}else{
					return Coords, i, err
					}
				}
			Coords=append(Coords,matrix.MakeDenseMatrix(coords,natoms,3))
			}
		}
	return Coords, i, nil
	}

//XtcCountAtoms takes the name of a Gromacs xtc trajectory file and returns the
//number of atoms per frame in the trajectory.
func XtcCountAtoms(name string)(int, error){
	Cfilename:=C.CString(name)
	Cnatoms:=C.read_natoms(Cfilename)
	natoms:=int(Cnatoms)
	return natoms, nil
	}

/*XtcOpen Opens the Gromacs xtc trajectory file with the name name and
 * returns a C pointer to it, which can passed to other functions of
 * the package to  */
func  XtcOpen(name string)(*C.XDRFILE, error){
	Cfilename:=C.CString(name)
	fp:=C.openfile(Cfilename)
	if fp==nil{
		return nil, fmt.Errorf("Unable to open xtc file")
		}
	return fp, nil
	}

/*XtcGetFrame takes a C pointer to an open Gromacs xtc file and the
 * number of atoms per frame in the file. It reads the coordinates
 * for the next frame of the file and returns  them as a slice of
 * float64 */
func XtcGetFrame(fp *C.XDRFILE,natoms int)(*matrix.DenseMatrix,error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	Ccoords:= make([]C.float,totalcoords)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return nil, fmt.Errorf("No more frames") //This is not really an error and should be catched in the calling function
		}
	if worked!=0{
		return nil, fmt.Errorf("Error reading frame")
			}
	goCoords:=make([]float64,totalcoords)
	for j:=0;j<totalcoords;j++{
		goCoords[j]=10*(float64(Ccoords[j]))  //nm to Angstroms
		}
	return matrix.MakeDenseMatrix(goCoords,natoms,3), nil
	}

/*XtcGetFrameEfficient takes a C pointer to an open Gromacs xtc file,
 * a slice of C float with enough size to contain all the coordinates
 * to be read, and number of atoms per frame in the file.
 * It reads the coordinates for the next frame of the file and returns
 * them as a slice of float64. The fact that it takes the intermediate
 * buffer as an argument means that one can save many memory allocations.
 * It returns nill on success, a "No more frames" error if no more
 * frames, and other error in other case.*/
func xtcGetFrameEfficient(fp *C.XDRFILE, Ccoords []C.float, natoms int)([]float64,error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		goCoords:=make([]float64,1)
		return goCoords, fmt.Errorf("No more frames")
		}
	if worked!=0{
		goCoords:=make([]float64,1)
		return goCoords, fmt.Errorf("Error reading frame")
			}
	goCoords:=make([]float64,totalcoords)
	for j:=0;j<totalcoords;j++{
		goCoords[j]=10*float64(Ccoords[j])  //nm to angstroms
		}
	return goCoords, nil
	}

/*XtcGetFrameDrop takes a C pointer to an open Gromacs xtc file and the
 * number of atoms per frame in the file. It reads the coordinates
 * for the next frame of the file and discards them, returning only
 * error/nil in case of failure/success. The special case of no more
 * frames to read causes it to return a "No more frames" error.*/
func XtcGetFrameDrop(fp *C.XDRFILE,natoms int)(error){
	totalcoords:=natoms*3
	cnatoms:=C.int(natoms)
	Ccoords:= make([]C.float,totalcoords)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return fmt.Errorf("No more frames")
		}
	if worked!=0{
		return fmt.Errorf("Error reading frame")
			}
	return nil
	}

/*XtcGetFrameEfficientDrop takes a C pointer to an open Gromacs xtc file,
 * a slice of C float with enough size to contain all the coordinates
 * to be read, and number of atoms per frame in the file.
 * It reads the coordinates for the next frame of the file and discart
 * them, returning error/nil in case of failure/success.
 * The fact that it takes the intermediate
 * buffer as an argument means that one can save many memory allocations. */
func xtcGetFrameEfficientDrop(fp *C.XDRFILE, Ccoords []C.float, natoms int)(error){
	cnatoms:=C.int(natoms)
	worked:=C.get_coords(fp,&Ccoords[0],cnatoms)
	if worked==11{
		return fmt.Errorf("No more frames")
		}
	if worked!=0{
		return fmt.Errorf("Error reading frame")
			}
	return nil
	}

/*XtcClose takes a pointer to an open Gromacs xtc trajectory file
 * and closes the file pointed by the pointer.*/
func XtcClose(fp *C.XDRFILE){
	C.xtc_close(fp)
	}
<|endoftext|>


<commit_before>// Package wkbhex implements Well Known Binary encoding and decoding of
// strings.
package wkbhex

import (
	"encoding/binary"
	"encoding/hex"

	"github.com/twpayne/go-geom"
	"github.com/twpayne/go-geom/encoding/wkb"
)

// Encode encodes an arbitrary geometry to a string.
func Encode(g geom.T, byteOrder binary.ByteOrder) (string, error) {
	wkb, err := wkb.Marshal(g, byteOrder)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(wkb), nil
}

// Decode decodes an arbitrary geometry from a string.
func Decode(s string) (geom.T, error) {
	data, err := hex.DecodeString(s)
	if err != nil {
		return nil, err
	}
	return wkb.Unmarshal(data)
}
<commit_msg>Export NDR and XDR from wkbhex<commit_after>// Package wkbhex implements Well Known Binary encoding and decoding of
// strings.
package wkbhex

import (
	"encoding/binary"
	"encoding/hex"

	"github.com/twpayne/go-geom"
	"github.com/twpayne/go-geom/encoding/wkb"
)

var (
	// XDR is big endian.
	XDR = wkb.XDR
	// NDR is little endian.
	NDR = wkb.NDR
)

// Encode encodes an arbitrary geometry to a string.
func Encode(g geom.T, byteOrder binary.ByteOrder) (string, error) {
	wkb, err := wkb.Marshal(g, byteOrder)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(wkb), nil
}

// Decode decodes an arbitrary geometry from a string.
func Decode(s string) (geom.T, error) {
	data, err := hex.DecodeString(s)
	if err != nil {
		return nil, err
	}
	return wkb.Unmarshal(data)
}
<|endoftext|>