text:
package integration

import (
	"bytes"
	"fmt"
	"math/rand"
	"os"
	"reflect"
	"testing"
	"time"

	"github.com/coreos/etcd/etcdserver/api/v3rpc"
	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
	"github.com/coreos/etcd/pkg/testutil"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

// TestV3PutOverwrite puts a key with the v3 api to a random cluster member,
// overwrites it, then checks that the change was applied.
func TestV3PutOverwrite(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	key := []byte("foo")
	reqput := &pb.PutRequest{Key: key, Value: []byte("bar")}

	respput, err := kvc.Put(context.TODO(), reqput)
	if err != nil {
		t.Fatalf("couldn't put key (%v)", err)
	}

	// overwrite
	reqput.Value = []byte("baz")
	respput2, err := kvc.Put(context.TODO(), reqput)
	if err != nil {
		t.Fatalf("couldn't put key (%v)", err)
	}
	if respput2.Header.Revision <= respput.Header.Revision {
		t.Fatalf("expected newer revision on overwrite, got %v <= %v",
			respput2.Header.Revision, respput.Header.Revision)
	}

	reqrange := &pb.RangeRequest{Key: key}
	resprange, err := kvc.Range(context.TODO(), reqrange)
	if err != nil {
		t.Fatalf("couldn't get key (%v)", err)
	}
	if len(resprange.Kvs) != 1 {
		t.Fatalf("expected 1 key, got %v", len(resprange.Kvs))
	}

	kv := resprange.Kvs[0]
	if kv.ModRevision <= kv.CreateRevision {
		t.Errorf("expected modRev > createRev, got %d <= %d",
			kv.ModRevision, kv.CreateRevision)
	}
	if !reflect.DeepEqual(reqput.Value, kv.Value) {
		t.Errorf("expected value %v, got %v", reqput.Value, kv.Value)
	}
}

// TestPutRestart checks if a put after an unrelated member restart succeeds
func TestV3PutRestart(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvIdx := rand.Intn(3)
	kvc := toGRPC(clus.Client(kvIdx)).KV

	stopIdx := kvIdx
	for stopIdx == kvIdx {
		stopIdx = rand.Intn(3)
	}

	clus.clients[stopIdx].Close()
	clus.Members[stopIdx].Stop(t)
	clus.Members[stopIdx].Restart(t)
	c, cerr := NewClientV3(clus.Members[stopIdx])
	if cerr != nil {
		t.Fatalf("cannot create client: %v", cerr)
	}
	clus.clients[stopIdx] = c

	ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
	defer cancel()
	reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
	_, err := kvc.Put(ctx, reqput)
	if err != nil && err == ctx.Err() {
		t.Fatalf("expected grpc error, got local ctx error (%v)", err)
	}
}

// TestV3CompactCurrentRev ensures keys are present when compacting on current revision.
func TestV3CompactCurrentRev(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
	for i := 0; i < 3; i++ {
		if _, err := kvc.Put(context.Background(), preq); err != nil {
			t.Fatalf("couldn't put key (%v)", err)
		}
	}
	// compact on current revision
	_, err := kvc.Compact(context.Background(), &pb.CompactionRequest{Revision: 4})
	if err != nil {
		t.Fatalf("couldn't compact kv space (%v)", err)
	}
	// key still exists?
	_, err = kvc.Range(context.Background(), &pb.RangeRequest{Key: []byte("foo")})
	if err != nil {
		t.Fatalf("couldn't get key after compaction (%v)", err)
	}
}

func TestV3TxnTooManyOps(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV

	// unique keys
	i := new(int)
	keyf := func() []byte {
		*i++
		return []byte(fmt.Sprintf("key-%d", i))
	}

	addCompareOps := func(txn *pb.TxnRequest) {
		txn.Compare = append(txn.Compare,
			&pb.Compare{
				Result: pb.Compare_GREATER,
				Target: pb.Compare_CREATE,
				Key:    keyf(),
			})
	}
	addSuccessOps := func(txn *pb.TxnRequest) {
		txn.Success = append(txn.Success,
			&pb.RequestOp{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: &pb.PutRequest{
						Key:   keyf(),
						Value: []byte("bar"),
					},
				},
			})
	}
	addFailureOps := func(txn *pb.TxnRequest) {
		txn.Failure = append(txn.Failure,
			&pb.RequestOp{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: &pb.PutRequest{
						Key:   keyf(),
						Value: []byte("bar"),
					},
				},
			})
	}

	tests := []func(txn *pb.TxnRequest){
		addCompareOps,
		addSuccessOps,
		addFailureOps,
	}

	for i, tt := range tests {
		txn := &pb.TxnRequest{}
		for j := 0; j < v3rpc.MaxOpsPerTxn+1; j++ {
			tt(txn)
		}

		_, err := kvc.Txn(context.Background(), txn)
		if !eqErrGRPC(err, rpctypes.ErrGRPCTooManyOps) {
			t.Errorf("#%d: err = %v, want %v", i, err, rpctypes.ErrGRPCTooManyOps)
		}
	}
}

func TestV3TxnDuplicateKeys(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	putreq := &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}}}
	delKeyReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
		RequestDeleteRange: &pb.DeleteRangeRequest{
			Key: []byte("abc"),
		},
	},
	}
	delInRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
		RequestDeleteRange: &pb.DeleteRangeRequest{
			Key: []byte("a"), RangeEnd: []byte("b"),
		},
	},
	}
	delOutOfRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
		RequestDeleteRange: &pb.DeleteRangeRequest{
			Key: []byte("abb"), RangeEnd: []byte("abc"),
		},
	},
	}

	kvc := toGRPC(clus.RandClient()).KV
	tests := []struct {
		txnSuccess []*pb.RequestOp

		werr error
	}{
		{
			txnSuccess: []*pb.RequestOp{putreq, putreq},

			werr: rpctypes.ErrGRPCDuplicateKey,
		},
		{
			txnSuccess: []*pb.RequestOp{putreq, delKeyReq},

			werr: rpctypes.ErrGRPCDuplicateKey,
		},
		{
			txnSuccess: []*pb.RequestOp{putreq, delInRangeReq},

			werr: rpctypes.ErrGRPCDuplicateKey,
		},
		{
			txnSuccess: []*pb.RequestOp{delKeyReq, delInRangeReq, delKeyReq, delInRangeReq},

			werr: nil,
		},
		{
			txnSuccess: []*pb.RequestOp{putreq, delOutOfRangeReq},

			werr: nil,
		},
	}
	for i, tt := range tests {
		txn := &pb.TxnRequest{Success: tt.txnSuccess}
		_, err := kvc.Txn(context.Background(), txn)
		if !eqErrGRPC(err, tt.werr) {
			t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
		}
	}
}

// Testv3TxnRevision tests that the transaction header revision is set as expected.
func TestV3TxnRevision(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	pr := &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}
	presp, err := kvc.Put(context.TODO(), pr)
	if err != nil {
		t.Fatal(err)
	}

	txnget := &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: &pb.RangeRequest{Key: []byte("abc")}}}
	txn := &pb.TxnRequest{Success: []*pb.RequestOp{txnget}}
	tresp, err := kvc.Txn(context.TODO(), txn)
	if err != nil {
		t.Fatal(err)
	}

	// did not update revision
	if presp.Header.Revision != tresp.Header.Revision {
		t.Fatalf("got rev %d, wanted rev %d", tresp.Header.Revision, presp.Header.Revision)
	}

	txndr := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{RequestDeleteRange: &pb.DeleteRangeRequest{Key: []byte("def")}}}
	txn = &pb.TxnRequest{Success: []*pb.RequestOp{txndr}}
	tresp, err = kvc.Txn(context.TODO(), txn)
	if err != nil {
		t.Fatal(err)
	}

	// did not update revision
	if presp.Header.Revision != tresp.Header.Revision {
		t.Fatalf("got rev %d, wanted rev %d", tresp.Header.Revision, presp.Header.Revision)
	}

	txnput := &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("123")}}}
	txn = &pb.TxnRequest{Success: []*pb.RequestOp{txnput}}
	tresp, err = kvc.Txn(context.TODO(), txn)
	if err != nil {
		t.Fatal(err)
	}

	// updated revision
	if tresp.Header.Revision != presp.Header.Revision+1 {
		t.Fatalf("got rev %d, wanted rev %d", tresp.Header.Revision, presp.Header.Revision+1)
	}
}

// TestV3PutIgnoreValue ensures that writes with ignore_value overwrites with previous key-value pair.
func TestV3PutIgnoreValue(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := NewClusterV3(t, &ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	key, val := []byte("foo"), []byte("bar")
	putReq := pb.PutRequest{Key: key, Value: val}

	// create lease
	lc := toGRPC(clus.RandClient()).Lease
	lresp, err := lc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 30})
	if err != nil {
		t.Fatal(err)
	}
	if lresp.Error != "" {
		t.Fatal(lresp.Error)
	}

	tests := []struct {
		putFunc  func() error
		putErr   error
		wleaseID int64
	}{
		{ // put failure for non-existent key
			func() error {
				preq := putReq
				preq.IgnoreValue = true
				_, err := kvc.Put(context.TODO(), &preq)
				return err
			},
			rpctypes.ErrGRPCKeyNotFound,
			0,
		},
		{ // txn failure for non-existent key
			func() error {
				preq := putReq
				preq.Value = nil
				preq.IgnoreValue = true
				txn := &pb.TxnRequest{}
				txn.Success = append(txn.Success, &pb.RequestOp{
					Request: &pb.RequestOp_RequestPut{RequestPut: &preq}})
				_, err := kvc.Txn(context.TODO(), txn)
				return err
			},
			rpctypes.ErrGRPCKeyNotFound,
			0,
		},
		{ // put success
			func() error {
				_, err := kvc.Put(context.TODO(), &putReq)
				return err
			},
			nil,
			0,
		},
		{ // txn success, attach lease
			func() error {
				preq := putReq
				preq.Value = nil
				preq.Lease = lresp.ID
				preq.IgnoreValue = true
				txn := &pb.TxnRequest{}
				txn.Success = append(txn.Success, &pb.RequestOp{
					Request: &pb.RequestOp_RequestPut{RequestPut: &preq}})
				_, err := kvc.Txn(context.TODO(), txn)
				return err
			},
			nil,
			lresp.ID,
		},
		{ // non-empty value with ignore_value should error
			func() error {
				preq := putReq
				preq.IgnoreValue = true
				_, err := kvc.Put(context.TODO(), &preq)
				return err
			},
			rpctypes.ErrGRPCValueProvided,
			0,
		},
		{ // overwrite with previous value, ensure no prev-kv is returned and lease is detached
			func() error {
				preq := putReq
				preq.Value = nil
				preq.IgnoreValue = true
				presp, err := kvc.Put(context.TODO(), &preq)
				if err != nil {
					return err
				}
				if presp.PrevKv != nil && len(presp.PrevKv.Key) != 0 {
					return fmt.Errorf("unexexpected previous key-value %v", presp.PrevKv)
				}
				return nil
			},
			nil,
			0,
		},
		{ // revoke lease, ensure detached key doesn't get deleted
			func() error {
				_, err := lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
				return err
			},
			nil,
			0,
		},
	}

	for i, tt := range tests {
		if err := tt.putFunc(); !eqErrGRPC(err, tt.putErr) {
			t.Fatalf("#%d: err expected %v, got %v", i, tt.putErr, err)
		}
		if tt.putErr != nil {
			continue
		}
		rr, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: key})
		if err != nil {
			t.Fatalf("#%d: %v", i, err)
		}
		if len(rr.Kvs) != 1 {
			t.Fatalf("#%d: len(rr.KVs) expected 1, got %d", i, len(rr.Kvs))
		}
		if !bytes.Equal(rr.Kvs[0].Value, val) {
			t.Fatalf("#%d: value expected %q, got %q", i, val, rr.Kvs[0].Value)
		}
		if rr.Kvs[0].Lease != tt.wleaseID {
			t.Fatalf("#%d: lease ID expected %d, got %d", i, tt.wleaseID, rr.Kvs[0].Lease)
		}
	}
}

// TestV3PutIgnoreLease ensures that writes with ignore_lease uses previous lease for the key overwrites.
func TestV3PutIgnoreLease(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := NewClusterV3(t, &ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV

	// create lease
	lc := toGRPC(clus.RandClient()).Lease
	lresp, err := lc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 30})
	if err != nil {
		t.Fatal(err)
	}
	if lresp.Error != "" {
		t.Fatal(lresp.Error)
	}

	key, val, val1 := []byte("zoo"), []byte("bar"), []byte("bar1")
	putReq := pb.PutRequest{Key: key, Value: val}

	tests := []struct {
		putFunc  func() error
		putErr   error
		wleaseID int64
		wvalue   []byte
	}{
		{ // put failure for non-existent key
			func() error {
				preq := putReq
				preq.IgnoreLease = true
				_, err := kvc.Put(context.TODO(), &preq)
				return err
			},
			rpctypes.ErrGRPCKeyNotFound,
			0,
			nil,
		},
		{ // txn failure for non-existent key
			func() error {
				preq := putReq
				preq.IgnoreLease = true
				txn := &pb.TxnRequest{}
				txn.Success = append(txn.Success, &pb.RequestOp{
					Request: &pb.RequestOp_RequestPut{RequestPut: &preq}})
				_, err := kvc.Txn(context.TODO(), txn)
				return err
			},
			rpctypes.ErrGRPCKeyNotFound,
			0,
			nil,
		},
		{ // put success
			func() error {
				preq := putReq
				preq.Lease = lresp.ID
				_, err := kvc.Put(context.TODO(), &preq)
				return err
			},
			nil,
			lresp.ID,
			val,
		},
		{ // txn success, modify value using 'ignore_lease' and ensure lease is not detached
			func() error {
				preq := putReq
				preq.Value = val1
				preq.IgnoreLease = true
				txn := &pb.TxnRequest{}
				txn.Success = append(txn.Success, &pb.RequestOp{
					Request: &pb.RequestOp_RequestPut{RequestPut: &preq}})
				_, err := kvc.Txn(context.TODO(), txn)
				return err
			},
			nil,
			lresp.ID,
			val1,
		},
		{ // non-empty lease with ignore_lease should error
			func() error {
				preq := putReq
				preq.Lease = lresp.ID
				preq.IgnoreLease = true
				_, err := kvc.Put(context.TODO(), &preq)
				return err
			},
			rpctypes.ErrGRPCLeaseProvided,
			0,
			nil,
		},
		{ // overwrite with previous value, ensure no prev-kv is returned and lease is detached
			func() error {
				presp, err := kvc.Put(context.TODO(), &putReq)
				if err != nil {
					return err
				}
				if presp.PrevKv != nil && len(presp.PrevKv.Key) != 0 {
					return fmt.Errorf("unexexpected previous key-value %v", presp.PrevKv)
				}
				return nil
			},
			nil,
			0,
			val,
		},
		{ // revoke lease, ensure detached key doesn't get deleted
			func() error {
				_, err := lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
				return err
			},
			nil,
			0,
			val,
		},
	}

	for i, tt := range tests {
		if err := tt.putFunc(); !eqErrGRPC(err, tt.putErr) {
			t.Fatalf("#%d: err expected %v, got %v", i, tt.putErr, err)
		}
		if tt.putErr != nil {
			continue
		}
		rr, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: key})
		if err != nil {
			t.Fatalf("#%d: %v", i, err)
		}
		if len(rr.Kvs) != 1 {
			t.Fatalf("#%d: len(rr.KVs) expected 1, got %d", i, len(rr.Kvs))
		}
		if !bytes.Equal(rr.Kvs[0].Value, tt.wvalue) {
			t.Fatalf("#%d: value expected %q, got %q", i, val, rr.Kvs[0].Value)
		}
		if rr.Kvs[0].Lease != tt.wleaseID {
			t.Fatalf("#%d: lease ID expected %d, got %d", i, tt.wleaseID, rr.Kvs[0].Lease)
		}
	}
}

// TestV3PutMissingLease ensures that a Put on a key with a bogus lease fails.
func TestV3PutMissingLease(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	key := []byte("foo")
	preq := &pb.PutRequest{Key: key, Lease: 123456}
	tests := []func(){
		// put case
		func() {
			if presp, err := kvc.Put(context.TODO(), preq); err == nil {
				t.Errorf("succeeded put key. req: %v. resp: %v", preq, presp)
			}
		},
		// txn success case
		func() {
			txn := &pb.TxnRequest{}
			txn.Success = append(txn.Success, &pb.RequestOp{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: preq}})
			if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
				t.Errorf("succeeded txn success. req: %v. resp: %v", txn, tresp)
			}
		},
		// txn failure case
		func() {
			txn := &pb.TxnRequest{}
			txn.Failure = append(txn.Failure, &pb.RequestOp{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: preq}})
			cmp := &pb.Compare{
				Result: pb.Compare_GREATER,
				Target: pb.Compare_CREATE,
				Key:    []byte("bar"),
			}
			txn.Compare = append(txn.Compare, cmp)
			if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
				t.Errorf("succeeded txn failure. req: %v. resp: %v", txn, tresp)
			}
		},
		// ignore bad lease in failure on success txn
		func() {
			txn := &pb.TxnRequest{}
			rreq := &pb.RangeRequest{Key: []byte("bar")}
			txn.Success = append(txn.Success, &pb.RequestOp{
				Request: &pb.RequestOp_RequestRange{
					RequestRange: rreq}})
			txn.Failure = append(txn.Failure, &pb.RequestOp{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: preq}})
			if tresp, err := kvc.Txn(context.TODO(), txn); err != nil {
				t.Errorf("failed good txn. req: %v. resp: %v", txn, tresp)
			}
		},
	}

	for i, f := range tests {
		f()
		// key shouldn't have been stored
		rreq := &pb.RangeRequest{Key: key}
		rresp, err := kvc.Range(context.TODO(), rreq)
		if err != nil {
			t.Errorf("#%d. could not rangereq (%v)", i, err)
		} else if len(rresp.Kvs) != 0 {
			t.Errorf("#%d. expected no keys, got %v", i, rresp)
		}
	}
}

// TestV3DeleteRange tests various edge cases in the DeleteRange API.
func TestV3DeleteRange(t *testing.T) {
	defer testutil.AfterTest(t)
	tests := []struct {
		keySet []string
		begin  string
		end    string
		prevKV bool

		wantSet [][]byte
		deleted int64
	}{
		// delete middle
		{
			[]string{"foo", "foo/abc", "fop"},
			"foo/", "fop", false,
			[][]byte{[]byte("foo"), []byte("fop")}, 1,
		},
		// no delete
		{
			[]string{"foo", "foo/abc", "fop"},
			"foo/", "foo/", false,
			[][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")}, 0,
		},
		// delete first
		{
			[]string{"foo", "foo/abc", "fop"},
			"fo", "fop", false,
			[][]byte{[]byte("fop")}, 2,
		},
		// delete tail
		{
			[]string{"foo", "foo/abc", "fop"},
			"foo/", "fos", false,
			[][]byte{[]byte("foo")}, 2,
		},
		// delete exact
		{
			[]string{"foo", "foo/abc", "fop"},
			"foo/abc", "", false,
			[][]byte{[]byte("foo"), []byte("fop")}, 1,
		},
		// delete none, [x,x)
		{
			[]string{"foo"},
			"foo", "foo", false,
			[][]byte{[]byte("foo")}, 0,
		},
		// delete middle with preserveKVs set
		{
			[]string{"foo", "foo/abc", "fop"},
			"foo/", "fop", true,
			[][]byte{[]byte("foo"), []byte("fop")}, 1,
		},
	}

	for i, tt := range tests {
		clus := NewClusterV3(t, &ClusterConfig{Size: 3})
		kvc := toGRPC(clus.RandClient()).KV

		ks := tt.keySet
		for j := range ks {
			reqput := &pb.PutRequest{Key: []byte(ks[j]), Value: []byte{}}
			_, err := kvc.Put(context.TODO(), reqput)
			if err != nil {
				t.Fatalf("couldn't put key (%v)", err)
			}
		}

		dreq := &pb.DeleteRangeRequest{
			Key:      []byte(tt.begin),
			RangeEnd: []byte(tt.end),
			PrevKv:   tt.prevKV,
		}
		dresp, err := kvc.DeleteRange(context.TODO(), dreq)
		if err != nil {
			t.Fatalf("couldn't delete range on test %d (%v)", i, err)
		}
		if tt.deleted != dresp.Deleted {
			t.Errorf("expected %d on test %v, got %d", tt.deleted, i, dresp.Deleted)
		}
		if tt.prevKV {
			if len(dresp.PrevKvs) != int(dresp.Deleted) {
				t.Errorf("preserve %d keys, want %d", len(dresp.PrevKvs), dresp.Deleted)
			}
		}

		rreq := &pb.RangeRequest{Key: []byte{0x0}, RangeEnd: []byte{0xff}}
		rresp, err := kvc.Range(context.TODO(), rreq)
		if err != nil {
			t.Errorf("couldn't get range on test %v (%v)", i, err)
		}
		if dresp.Header.Revision != rresp.Header.Revision {
			t.Errorf("expected revision %v, got %v",
				dresp.Header.Revision, rresp.Header.Revision)
		}

		keys := [][]byte{}
		for j := range rresp.Kvs {
			keys = append(keys, rresp.Kvs[j].Key)
		}
		if !reflect.DeepEqual(tt.wantSet, keys) {
			t.Errorf("expected %v on test %v, got %v", tt.wantSet, i, keys)
		}
		// can't defer because tcp ports will be in use
		clus.Terminate(t)
	}
}

// TestV3TxnInvalidRange tests that invalid ranges are rejected in txns.
func TestV3TxnInvalidRange(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV
	preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}

	for i := 0; i < 3; i++ {
		_, err := kvc.Put(context.Background(), preq)
		if err != nil {
			t.Fatalf("couldn't put key (%v)", err)
		}
	}

	_, err := kvc.Compact(context.Background(), &pb.CompactionRequest{Revision: 2})
	if err != nil {
		t.Fatalf("couldn't compact kv space (%v)", err)
	}

	// future rev
	txn := &pb.TxnRequest{}
	txn.Success = append(txn.Success, &pb.RequestOp{
		Request: &pb.RequestOp_RequestPut{
			RequestPut: preq}})

	rreq := &pb.RangeRequest{Key: []byte("foo"), Revision: 100}
	txn.Success = append(txn.Success, &pb.RequestOp{
		Request: &pb.RequestOp_RequestRange{
			RequestRange: rreq}})

	if _, err := kvc.Txn(context.TODO(), txn); !eqErrGRPC(err, rpctypes.ErrGRPCFutureRev) {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCFutureRev)
	}

	// compacted rev
	tv, _ := txn.Success[1].Request.(*pb.RequestOp_RequestRange)
	tv.RequestRange.Revision = 1
	if _, err := kvc.Txn(context.TODO(), txn); !eqErrGRPC(err, rpctypes.ErrGRPCCompacted) {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCCompacted)
	}
}

func TestV3TooLargeRequest(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kvc := toGRPC(clus.RandClient()).KV

	// 2MB request value
	largeV := make([]byte, 2*1024*1024)
	preq := &pb.PutRequest{Key: []byte("foo"), Value: largeV}

	_, err := kvc.Put(context.Background(), preq)
	if !eqErrGRPC(err, rpctypes.ErrGRPCRequestTooLarge) {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCRequestTooLarge)
	}
}

// TestV3Hash tests hash.
func TestV3Hash(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	cli := clus.RandClient()
	kvc := toGRPC(cli).KV
	m := toGRPC(cli).Maintenance

	preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}

	for i := 0; i < 3; i++ {
		_, err := kvc.Put(context.Background(), preq)
		if err != nil {
			t.Fatalf("couldn't put key (%v)", err)
		}
	}

	resp, err := m.Hash(context.Background(), &pb.HashRequest{})
	if err != nil || resp.Hash == 0 {
		t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
	}
}

// TestV3HashRestart ensures that hash stays the same after restart.
func TestV3HashRestart(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := NewClusterV3(t, &ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	cli := clus.RandClient()
	resp, err := toGRPC(cli).Maintenance.Hash(context.Background(), &pb.HashRequest{})
	if err != nil || resp.Hash == 0 {
		t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
	}
	hash1 := resp.Hash

	clus.Members[0].Stop(t)
	clus.Members[0].Restart(t)
	clus.waitLeader(t, clus.Members)
	kvc := toGRPC(clus.Client(0)).KV
	waitForRestart(t, kvc)

	cli = clus.RandClient()
	resp, err = toGRPC(cli).Maintenance.Hash(context.Background(), &pb.HashRequest{})
	if err != nil || resp.Hash == 0 {
		t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
	}
	hash2 := resp.Hash

	if hash1 != hash2 {
		t.Fatalf("hash expected %d, got %d", hash1, hash2)
	}
}

// TestV3StorageQuotaAPI tests the V3 server respects quotas at the API layer
func TestV3StorageQuotaAPI(t *testing.T) {
	defer testutil.AfterTest(t)
	quotasize := int64(16 * os.Getpagesize())

	clus := NewClusterV3(t, &ClusterConfig{Size: 3})

	// Set a quota on one node
	clus.Members[0].QuotaBackendBytes = quotasize
	clus.Members[0].Stop(t)
	clus.Members[0].Restart(t)

	defer clus.Terminate(t)
	kvc := toGRPC(clus.Client(0)).KV
	waitForRestart(t, kvc)

	key := []byte("abc")

	// test small put that fits in quota
	smallbuf := make([]byte, 512)
	if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err != nil {
		t.Fatal(err)
	}

	// test big put
	bigbuf := make([]byte, quotasize)
	_, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: bigbuf})
	if !eqErrGRPC(err, rpctypes.ErrGRPCNoSpace) {
		t.Fatalf("big put got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
	}

	// test big txn
	puttxn := &pb.RequestOp{
		Request: &pb.RequestOp_RequestPut{
			RequestPut: &pb.PutRequest{
				Key:   key,
				Value: bigbuf,
			},
		},
	}
	txnreq := &pb.TxnRequest{}
	txnreq.Success = append(txnreq.Success, puttxn)
	_, txnerr := kvc.Txn(context.TODO(), txnreq)
	if !eqErrGRPC(txnerr, rpctypes.ErrGRPCNoSpace) {
		t.Fatalf("big txn got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
	}
}

// TestV3StorageQuotaApply tests the V3 server respects quotas during apply
func TestV3StorageQuotaApply(t *testing.T) {
	testutil.AfterTest(t)
	quotasize := int64(16 * os.Getpagesize())

	clus := NewClusterV3(t, &ClusterConfig{Size: 2})
	defer clus.Terminate(t)
	kvc0 := toGRPC(clus.Client(0)).KV
	kvc1 := toGRPC(clus.Client(1)).KV

	// Set a quota on one node
	clus.Members[0].QuotaBackendBytes = quotasize
	clus.Members[0].Stop(t)
	clus.Members[0].Restart(t)
	clus.waitLeader(t, clus.Members)
	waitForRestart(t, kvc0)

	key := []byte("abc")

	// test small put still works
	smallbuf := make([]byte, 1024)
	_, serr := kvc0.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf})
	if serr != nil {
		t.Fatal(serr)
	}

	// test big put
	bigbuf := make([]byte, quotasize)
	_, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: bigbuf})
	if err != nil {
		t.Fatal(err)
	}

	// quorum get should work regardless of whether alarm is raised
	_, err = kvc0.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
	if err != nil {
		t.Fatal(err)
	}

	// wait until alarm is raised for sure-- poll the alarms
	stopc := time.After(5 * time.Second)
	for {
		req := &pb.AlarmRequest{Action: pb.AlarmRequest_GET}
		resp, aerr := clus.Members[0].s.Alarm(context.TODO(), req)
		if aerr != nil {
			t.Fatal(aerr)
		}
		if len(resp.Alarms) != 0 {
			break
		}
		select {
		case <-stopc:
			t.Fatalf("timed out waiting for alarm")
		case <-time.After(10 * time.Millisecond):
		}
	}

	// small quota machine should reject put
	if _, err := kvc0.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
		t.Fatalf("past-quota instance should reject put")
	}

	// large quota machine should reject put
	if _, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
		t.Fatalf("past-quota instance should reject put")
	}

	// reset large quota node to ensure alarm persisted
	clus.Members[1].Stop(t)
	clus.Members[1].Restart(t)
	clus.waitLeader(t, clus.Members)

	if _, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
		t.Fatalf("alarmed instance should reject put after reset")
	}
}

// TestV3AlarmDeactivate ensures that space alarms can be deactivated so puts go through.
func TestV3AlarmDeactivate(t *testing.T) {
	clus := NewClusterV3(t, &ClusterConfig{Size: 3})
	defer clus.Terminate(t)
	kvc := toGRPC(clus.RandClient()).KV
	mt := toGRPC(clus.RandClient()).Maintenance

	alarmReq := &pb.AlarmRequest{
		MemberID: 123,
		Action:   pb.AlarmRequest_ACTIVATE,
		Alarm:    pb.AlarmType_NOSPACE,
	}
	if _, err := mt.Alarm(context.TODO(), alarmReq); err != nil {
		t.Fatal(err)
	}

	key := []byte("abc")
	smallbuf := make([]byte, 512)
	_, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf})
	if err == nil && !eqErrGRPC(err, rpctypes.ErrGRPCNoSpace) {
		t.Fatalf("put got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
	}

	alarmReq.Action = pb.AlarmRequest_DEACTIVATE
	if _, err = mt.Alarm(context.TODO(), alarmReq); err != nil {
		t.Fatal(err)
	}

	if _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err != nil {
		t.Fatal(err)
	}
}

func TestV3RangeRequest(t *testing.T) {
	defer testutil.AfterTest(t)
	tests := []struct {
		putKeys []string
		reqs    []pb.RangeRequest

		wresps [][]string
		wmores []bool
	}{
		// single key
		{
			[]string{"foo", "bar"},
			[]pb.RangeRequest{
				// exists
				{Key: []byte("foo")},
				// doesn't exist
				{Key: []byte("baz")},
			},

			[][]string{
				{"foo"},
				{},
			},
			[]bool{false, false},
		},
		// multi-key
		{
			[]string{"a", "b", "c", "d", "e"},
			[]pb.RangeRequest{
				// all in range
				{Key: []byte("a"), RangeEnd: []byte("z")},
				// [b, d)
				{Key: []byte("b"), RangeEnd: []byte("d")},
				// out of range
				{Key: []byte("f"), RangeEnd: []byte("z")},
				// [c,c) = empty
				{Key: []byte("c"), RangeEnd: []byte("c")},
				// [d, b) = empty
				{Key: []byte("d"), RangeEnd: []byte("b")},
				// ["\0", "\0") => all in range
				{Key: []byte{0}, RangeEnd: []byte{0}},
			},

			[][]string{
				{"a", "b", "c", "d", "e"},
				{"b", "c"},
				{},
				{},
				{},
				{"a", "b", "c", "d", "e"},
			},
			[]bool{false, false, false, false, false, false},
		},
		// revision
		{
			[]string{"a", "b", "c", "d", "e"},
			[]pb.RangeRequest{
				{Key: []byte("a"), RangeEnd: []byte("z"), Revision: 0},
				{Key: []byte("a"), RangeEnd: []byte("z"), Revision: 1},
				{Key: []byte("a"), RangeEnd: []byte("z"), Revision: 2},
				{Key: []byte("a"), RangeEnd: []byte("z"), Revision: 3},
			},

			[][]string{
				{"a", "b", "c", "d", "e"},
				{},
				{"a"},
				{"a", "b"},
			},
			[]bool{false, false, false, false},
		},
		// limit
		{
			[]string{"foo", "bar"},
			[]pb.RangeRequest{
				// more
				{Key: []byte("a"), RangeEnd: []byte("z"), Limit: 1},
				// no more
				{Key: []byte("a"), RangeEnd: []byte("z"), Limit: 2},
			},

			[][]string{
				{"bar"},
				{"bar", "foo"},
			},
			[]bool{true, false},
		},
		// sort
		{
			[]string{"b", "a", "c", "d", "c"},
			[]pb.RangeRequest{
				{
					Key: []byte("a"), RangeEnd: []byte("z"),
					Limit:      1,
					SortOrder:  pb.RangeRequest_ASCEND,
					SortTarget: pb.RangeRequest_KEY,
				},
				{
					Key: []byte("a"), RangeEnd: []byte("z"),
					Limit:      1,
					SortOrder:  pb.RangeRequest_DESCEND,
					SortTarget: pb.RangeRequest_KEY,
				},
				{
					Key: []byte("a"), RangeEnd: []byte("z"),
					Limit:      1,
					SortOrder:  pb.RangeRequest_ASCEND,
					SortTarget: pb.RangeRequest_CREATE,
				},
				{
					Key: []byte("a"), RangeEnd: []byte("z"),
					Limit:      1,
					SortOrder:  pb.RangeRequest_DESCEND,
					SortTarget: pb.RangeRequest_MOD,
				},
				{
					Key: []byte("z"), RangeEnd: []byte("z"),
					Limit:      1,
					SortOrder:  pb.RangeRequest_DESCEND,
					SortTarget: pb.RangeRequest_CREATE,
				},
				{ // sort ASCEND by default
					Key: []byte("a"), RangeEnd: []byte("z"),
					Limit:      10,
					SortOrder:  pb.RangeRequest_NONE,
					SortTarget: pb.RangeRequest_CREATE,
				},
			},

			[][]string{
				{"a"},
				{"d"},
				{"b"},
				{"c"},
				{},
				{"b", "a", "c", "d"},
			},
			[]bool{true, true, true, true, false, false},
		},
		// min/max mod rev
		{
			[]string{"rev2", "rev3", "rev4", "rev5", "rev6"},
			[]pb.RangeRequest{
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MinModRevision: 3,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MaxModRevision: 3,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MinModRevision: 3,
					MaxModRevision: 5,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MaxModRevision: 10,
				},
			},

			[][]string{
				{"rev3", "rev4", "rev5", "rev6"},
				{"rev2", "rev3"},
				{"rev3", "rev4", "rev5"},
				{"rev2", "rev3", "rev4", "rev5", "rev6"},
			},
			[]bool{false, false, false, false},
		},
		// min/max create rev
		{
			[]string{"rev2", "rev3", "rev2", "rev2", "rev6", "rev3"},
			[]pb.RangeRequest{
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MinCreateRevision: 3,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MaxCreateRevision: 3,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MinCreateRevision: 3,
					MaxCreateRevision: 5,
				},
				{
					Key: []byte{0}, RangeEnd: []byte{0},
					MaxCreateRevision: 10,
				},
			},

			[][]string{
				{"rev3", "rev6"},
				{"rev2", "rev3"},
				{"rev3"},
				{"rev2", "rev3", "rev6"},
			},
			[]bool{false, false, false, false},
		},
	}

	for i, tt := range tests {
		clus := NewClusterV3(t, &ClusterConfig{Size: 3})
		for _, k := range tt.putKeys {
			kvc := toGRPC(clus.RandClient()).KV
			req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
			if _, err := kvc.Put(context.TODO(), req); err != nil {
				t.Fatalf("#%d: couldn't put key (%v)", i, err)
			}
		}

		for j, req := range tt.reqs {
			kvc := toGRPC(clus.RandClient()).KV
			resp, err := kvc.Range(context.TODO(), &req)
			if err != nil {
				t.Errorf("#%d.%d: Range error: %v", i, j, err)
				continue
			}
			if len(resp.Kvs) != len(tt.wresps[j]) {
				t.Errorf("#%d.%d: bad len(resp.Kvs). got = %d, want = %d, ", i, j, len(resp.Kvs), len(tt.wresps[j]))
				continue
			}
			for k, wKey := range tt.wresps[j] {
				respKey := string(resp.Kvs[k].Key)
				if respKey != wKey {
					t.Errorf("#%d.%d: key[%d]. got = %v, want = %v, ", i, j, k, respKey, wKey)
				}
			}
			if resp.More != tt.wmores[j] {
				t.Errorf("#%d.%d: bad more. got = %v, want = %v, ", i, j, resp.More, tt.wmores[j])
			}
			wrev := int64(len(tt.putKeys) + 1)
			if resp.Header.Revision != wrev {
				t.Errorf("#%d.%d: bad header revision. got = %d. want = %d", i, j, resp.Header.Revision, wrev)
			}
		}
		clus.Terminate(t)
	}
}

func newClusterV3NoClients(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
	cfg.UseGRPC = true
	clus := &ClusterV3{cluster: NewClusterByConfig(t, cfg)}
	clus.Launch(t)
	return clus
}

// TestTLSGRPCRejectInsecureClient checks that connection is rejected if server is TLS but not client.
func TestTLSGRPCRejectInsecureClient(t *testing.T) {
	defer testutil.AfterTest(t)

	cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
	clus := newClusterV3NoClients(t, &cfg)
	defer clus.Terminate(t)

	// nil out TLS field so client will use an insecure connection
	clus.Members[0].ClientTLSInfo = nil
	client, err := NewClientV3(clus.Members[0])
	if err != nil && err != grpc.ErrClientConnTimeout {
		t.Fatalf("unexpected error (%v)", err)
	} else if client == nil {
		// Ideally, no client would be returned. However, grpc will
		// return a connection without trying to handshake first so
		// the connection appears OK.
		return
	}
	defer client.Close()

	donec := make(chan error, 1)
	go func() {
		ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
		reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
		_, perr := toGRPC(client).KV.Put(ctx, reqput)
		cancel()
		donec <- perr
	}()

	if perr := <-donec; perr == nil {
		t.Fatalf("expected client error on put")
	}
}

// TestTLSGRPCRejectSecureClient checks that connection is rejected if client is TLS but not server.
func TestTLSGRPCRejectSecureClient(t *testing.T) {
	defer testutil.AfterTest(t)

	cfg := ClusterConfig{Size: 3}
	clus := newClusterV3NoClients(t, &cfg)
	defer clus.Terminate(t)

	clus.Members[0].ClientTLSInfo = &testTLSInfo
	client, err := NewClientV3(clus.Members[0])
	if client != nil || err == nil {
		t.Fatalf("expected no client")
	} else if err != grpc.ErrClientConnTimeout {
		t.Fatalf("unexpected error (%v)", err)
	}
}

// TestTLSGRPCAcceptSecureAll checks that connection is accepted if both client and server are TLS
func TestTLSGRPCAcceptSecureAll(t *testing.T) {
	defer testutil.AfterTest(t)

	cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
	clus := newClusterV3NoClients(t, &cfg)
	defer clus.Terminate(t)

	client, err := NewClientV3(clus.Members[0])
	if err != nil {
		t.Fatalf("expected tls client (%v)", err)
	}
	defer client.Close()

	reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
	if _, err := toGRPC(client).KV.Put(context.TODO(), reqput); err != nil {
		t.Fatalf("unexpected error on put over tls (%v)", err)
	}
}

func TestGRPCRequireLeader(t *testing.T) {
	defer testutil.AfterTest(t)

	cfg := ClusterConfig{Size: 3}
	clus := newClusterV3NoClients(t, &cfg)
	defer clus.Terminate(t)

	clus.Members[1].Stop(t)
	clus.Members[2].Stop(t)

	client, err := NewClientV3(clus.Members[0])
	if err != nil {
		t.Fatalf("cannot create client: %v", err)
	}
	defer client.Close()

	// wait for election timeout, then member[0] will not have a leader.
	time.Sleep(time.Duration(3*electionTicks) * tickDuration)

	md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
	ctx := metadata.NewContext(context.Background(), md)
	reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
	if _, err := toGRPC(client).KV.Put(ctx, reqput); grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
	}
}

func TestGRPCStreamRequireLeader(t *testing.T) {
	defer testutil.AfterTest(t)

	cfg := ClusterConfig{Size: 3}
	clus := newClusterV3NoClients(t, &cfg)
	defer clus.Terminate(t)

	client, err := NewClientV3(clus.Members[0])
	if err != nil {
		t.Fatalf("failed to create client (%v)", err)
	}
	defer client.Close()

	wAPI := toGRPC(client).Watch
	md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
	ctx := metadata.NewContext(context.Background(), md)
	wStream, err := wAPI.Watch(ctx)
	if err != nil {
		t.Fatalf("wAPI.Watch error: %v", err)
	}

	clus.Members[1].Stop(t)
	clus.Members[2].Stop(t)

	// existing stream should be rejected
	_, err = wStream.Recv()
	if grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
	}

	// new stream should also be rejected
	wStream, err = wAPI.Watch(ctx)
	if err != nil {
		t.Fatalf("wAPI.Watch error: %v", err)
	}
	_, err = wStream.Recv()
	if grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
		t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
	}

	clus.Members[1].Restart(t)
	clus.Members[2].Restart(t)

	clus.waitLeader(t, clus.Members)
	time.Sleep(time.Duration(2*electionTicks) * tickDuration)

	// new stream should also be OK now after we restarted the other members
	wStream, err = wAPI.Watch(ctx)
	if err != nil {
		t.Fatalf("wAPI.Watch error: %v", err)
	}
	wreq := &pb.WatchRequest{
		RequestUnion: &pb.WatchRequest_CreateRequest{
			CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")},
		},
	}
	err = wStream.Send(wreq)
	if err != nil {
		t.Errorf("err = %v, want nil", err)
	}
}

func eqErrGRPC(err1 error, err2 error) bool {
	return !(err1 == nil && err2 != nil) || err1.Error() == err2.Error()
}

// waitForRestart tries a range request until the client's server responds.
// This is mainly a stop-gap function until grpcproxy's KVClient adapter
// (and by extension, clientv3) supports grpc.CallOption pass-through so
// FailFast=false works with Put.
func waitForRestart(t *testing.T, kvc pb.KVClient) {
	req := &pb.RangeRequest{Key: []byte("_"), Serializable: true}
	if _, err := kvc.Range(context.TODO(), req, grpc.FailFast(false)); err != nil {
		t.Fatal(err)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Playnite
{
    public static class GlobalTaskHandler
    {
        private static CancellationTokenSource cancelToken = new CancellationTokenSource();
        public static CancellationTokenSource CancelToken
        {
            get => cancelToken;
            set
            {
                cancelToken?.Dispose();
                cancelToken = value;
            }
        }

        public static Task ProgressTask;

        public static bool IsActive
        {
            get => ProgressTask?.Status == TaskStatus.Running || ProgressTask?.Status == TaskStatus.WaitingForActivation;
        }

        public static void CancelAndWait()
        {
            if (IsActive)
            {
                CancelToken?.Cancel();
                ProgressTask?.Wait();
            }
        }

        public static bool? CancelAndWait(int millisecondsTimeout)
        {
            if (IsActive)
            {
                CancelToken?.Cancel();
                return ProgressTask?.Wait(millisecondsTimeout);
            }

            return null;
        }

        public async static Task CancelAndWaitAsync()
        {
            if (IsActive)
            {
                CancelToken?.Cancel();
                await ProgressTask;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package psidev.psi.mi.jami.xml.io.writer.elements.impl.xml30;

import junit.framework.Assert;
import org.junit.Test;
import psidev.psi.mi.jami.exception.IllegalRangeException;
import psidev.psi.mi.jami.model.Allostery;
import psidev.psi.mi.jami.model.CooperativityEvidence;
import psidev.psi.mi.jami.model.ModelledInteraction;
import psidev.psi.mi.jami.model.impl.*;
import psidev.psi.mi.jami.utils.CvTermUtils;
import psidev.psi.mi.jami.utils.InteractorUtils;
import psidev.psi.mi.jami.xml.cache.InMemoryIdentityObjectCache;
import psidev.psi.mi.jami.xml.cache.PsiXmlObjectCache;
import psidev.psi.mi.jami.xml.io.writer.elements.impl.AbstractXmlWriterTest;

import javax.xml.stream.XMLStreamException;
import java.io.IOException;

/**
 * Unit tester for XmlAllosteryWriter
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
21/11/13

 */

public class XmlAllosteryWriterTest extends AbstractXmlWriterTest {
    private PsiXmlObjectCache elementCache = new InMemoryIdentityObjectCache();

    private String allostery = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>1</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n" +
            "  <allostericMoleculeRef>2</allostericMoleculeRef>\n" +
            "  <allostericEffectorRef>3</allostericEffectorRef>\n" +
            "</allostery>";
    private String allostery_response = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>1</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n"+
            "  <cooperativeEffectResponse>\n" +
            "    <names>\n" +
            "      <shortLabel>binding site hiding</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1173\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectResponse>\n"+
            "  <allostericMoleculeRef>2</allostericMoleculeRef>\n" +
            "  <allostericEffectorRef>3</allostericEffectorRef>\n" +
            "</allostery>";
    private String allostery_attributes = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>1</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n"+
            "  <attributeList>\n" +
            "    <attribute name=\"test3\"/>\n"+
            "  </attributeList>\n"+
            "  <allostericMoleculeRef>2</allostericMoleculeRef>\n" +
            "  <allostericEffectorRef>3</allostericEffectorRef>\n" +
            "</allostery>";
    private String allostery_already_registered = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>2</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n"+
            "  <allostericMoleculeRef>3</allostericMoleculeRef>\n" +
            "  <allostericEffectorRef>4</allostericEffectorRef>\n" +
            "</allostery>";
    private String allostery_feature_effector = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>1</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n" +
            "  <allostericMoleculeRef>2</allostericMoleculeRef>\n" +
            "  <allostericModificationRef>3</allostericModificationRef>\n" +
            "</allostery>";
    private String allostery_type_mechanism = "<allostery>\n" +
            "  <cooperativityEvidenceList>\n" +
            "    <cooperativityEvidenceDescription>\n" +
            "      <bibref>\n" +
            "        <xref>\n" +
            "          <primaryRef db=\"pubmed\" dbAc=\"MI:0446\" id=\"xxxxxx\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "        </xref>\n"+
            "        <attributeList>\n" +
            "          <attribute name=\"publication title\" nameAc=\"MI:1091\">test title</attribute>\n"+
            "        </attributeList>\n"+
            "      </bibref>\n"+
            "    </cooperativityEvidenceDescription>\n"+
            "  </cooperativityEvidenceList>\n" +
            "  <affectedInteractionList>\n" +
            "    <affectedInteractionRef>1</affectedInteractionRef>\n" +
            "  </affectedInteractionList>\n"+
            "  <cooperativeEffectOutcome>\n" +
            "    <names>\n" +
            "      <shortLabel>positive cooperative effect</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1154\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </cooperativeEffectOutcome>\n" +
            "  <allostericMoleculeRef>2</allostericMoleculeRef>\n" +
            "  <allostericEffectorRef>3</allostericEffectorRef>\n" +
            "  <allostericMechanism>\n" +
            "    <names>\n" +
            "      <shortLabel>allosteric change in dynamics</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1166\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </allostericMechanism>\n" +
            "  <allosteryType>\n" +
            "    <names>\n" +
            "      <shortLabel>heterotropic allostery</shortLabel>\n"+
            "    </names>\n"+
            "    <xref>\n" +
            "      <primaryRef db=\"psi-mi\" dbAc=\"MI:0488\" id=\"MI:1168\" refType=\"identity\" refTypeAc=\"MI:0356\"/>\n"+
            "    </xref>\n"+
            "  </allosteryType>\n" +
            "</allostery>";

    @Test
    public void test_write_allostery() throws XMLStreamException, IOException, IllegalRangeException {
        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor())));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(new DefaultModelledInteraction());

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(this.allostery, output.toString());
    }

    @Test
    public void test_write_allostery_response() throws XMLStreamException, IOException, IllegalRangeException {
        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor())));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(new DefaultModelledInteraction());
        effect.setResponse(CvTermUtils.createMICvTerm("binding site hiding","MI:1173"));

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(allostery_response, output.toString());
    }

    @Test
    public void test_write_allostery_attributes() throws XMLStreamException, IOException, IllegalRangeException {
        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor())));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(new DefaultModelledInteraction());
        effect.getAnnotations().add(new DefaultAnnotation(new DefaultCvTerm("test3")));

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(allostery_attributes, output.toString());
    }

    @Test
    public void test_write_modelled_interaction_already_registered() throws XMLStreamException {
        ModelledInteraction interaction = new DefaultModelledInteraction();
        this.elementCache.clear();
        this.elementCache.extractIdForInteraction(new DefaultModelledInteraction());
        this.elementCache.extractIdForInteraction(interaction);

        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor())));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(interaction);

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(this.allostery_already_registered, output.toString());
    }

    @Test
    public void test_write_allostery_feature_effector() throws XMLStreamException, IOException, IllegalRangeException {
        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultFeatureModificationEffector(new DefaultModelledFeature()));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(new DefaultModelledInteraction());

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(this.allostery_feature_effector, output.toString());
    }

    @Test
    public void test_write_allostery_type_mechanism() throws XMLStreamException, IOException, IllegalRangeException {
        Allostery effect = new DefaultAllostery(CvTermUtils.createMICvTerm("positive cooperative effect","MI:1154"),
                new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()),
                new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor())));
        CooperativityEvidence ev = new DefaultCooperativityEvidence(new DefaultPublication("xxxxxx"));
        ev.getPublication().setTitle("test title");
        effect.getCooperativityEvidences().add(ev);
        effect.getAffectedInteractions().add(new DefaultModelledInteraction());
        effect.setAllosteryType(CvTermUtils.createMICvTerm("heterotropic allostery","MI:1168"));
        effect.setAllostericMechanism(CvTermUtils.createMICvTerm("allosteric change in dynamics","MI:1166"));

        XmlAllosteryWriter writer = new XmlAllosteryWriter(createStreamWriter(), elementCache);
        writer.write(effect);
        streamWriter.flush();

        Assert.assertEquals(this.allostery_type_mechanism, output.toString());
    }
}


text:
import { observer } from '@ember/object';
import Helper from '@ember/component/helper';

export default Helper.extend({

	changed: observer('array.[]', function() {
		this.recompute();
	}),

	compute([array]) {
		this.set('array', array);
		return this.get('array.length') === 0;
	},

});


text:
class EvtId;

class EvtBToPlnuBKFF : public EvtSemiLeptonicFF {

public:
  EvtBToPlnuBKFF(double alpha, double beta);

  void getscalarff(EvtId parent,EvtId daught,
		   double t, double mass, double *fp, double *f0);

  void getvectorff(EvtId, EvtId, double, double, double*,
		   double*, double*, double*);

  void gettensorff(EvtId, EvtId, double, double, double*,
		   double*, double*, double*);

  void getbaryonff(EvtId, EvtId, double, double, double*,
		   double*, double*, double*);

  void getdiracff(EvtId, EvtId, double, double, double*, double*,
                  double*, double*, double*, double*);

  void getraritaff(EvtId, EvtId, double, double, double*, double*,
		   double*, double*, double*, double*, double*, double*);

private:
  double _alpha;
  double _beta;
};

#endif


text:
using System.Web.Http.ExceptionHandling;

namespace Api.Web.Extensions
{
    public class AppExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {

            context.Result = new CustomMessageResult("Oops! Sorry! Something went wrong. Please try later !");

        }

    }
}


text:
<?php
/**
 * Created by JiangJiaCai.
 * User: Administrator
 * Date: 2017/8/28 0028
 * Time: 14:53
 */

namespace com_jjcbs\cases\test;

use com_jjcbs\lib\AnnotationBodyParser;
use com_jjcbs\service\AnnotationServiceImpl;
use PHPUnit\Framework\TestCase;

define('COM_JJCBS_ROOT_PATH', dirname(dirname(dirname(dirname(dirname(__FILE__))))));

class AnnotationBodyParserTest extends TestCase
{
    const FILE_PATH = COM_JJCBS_ROOT_PATH . '/src/com_jjcbs/service/AnnotationServiceImpl.php';

    public function testGetInput()
    {
        $input = [
            'class' => new \ReflectionClass(AnnotationServiceImpl::class),
            'input' => file_get_contents(self::FILE_PATH)
        ];
        $this->assertNotEmpty($input);
        return $input;
    }

    /**
     * @depends testGetInput
     */
    public function testMethod(array $input)
    {
        $str = AnnotationBodyParser::parseMethod($input['class']->getMethod('exec'), file(self::FILE_PATH));
        $this->assertNotEmpty($str);
    }

    /**
     * @depends testGetInput
     * @param string $input
     */
    public function testClassInfo(array $input)
    {
        $str = AnnotationBodyParser::parseClass($input['class'], file(self::FILE_PATH));
        $this->assertNotEmpty($str);
    }

}


text:
// @flow
/* eslint-env jest */

import { polyfillWindow, polyunfillWindow } from './spec-helpers'
import { Client, Server } from '../ipc'

beforeEach(polyfillWindow)

afterEach(polyunfillWindow)

describe('Client', () => {
  it('takes a request, sets up a channel to the parent window, and promises a response from the parent', async () => {
    expect.assertions(5)
    const parent = window
    // window.open is not yet implemented in jsdom.  for the purposes of testing, this does just fine.
    const child = parent
    const origin = window.location.origin
    const client = new Client(parent, origin)
    parent.addEventListener('message', function testServer(event) {
      const { data, origin } = event
      const isRequest =
        data &&
        typeof data === 'object' &&
        data['solid-auth-client'].method &&
        data['solid-auth-client'].args
      if (isRequest) {
        expect(origin).toBe(parent.location.origin)
        const request = data['solid-auth-client']
        const { id, method, args } = request
        expect(id).toBeTruthy()
        expect(method).toBe('foo')
        expect(args).toEqual(['bar', 'baz'])
        child.postMessage(
          {
            'solid-auth-client': {
              id,
              ret: 'the return value!',
            },
          },
          child.location.origin
        )
        parent.removeEventListener('message', testServer)
      }
    })
    const response = await client.request('foo', 'bar', 'baz')
    expect(response).toBe('the return value!')
  })

  it('ignores responses to other requests', async () => {
    expect.assertions(5)
    const parent = window
    // window.open is not yet implemented in jsdom.  for the purposes of testing, this does just fine.
    const child = parent
    const origin = window.location.origin
    const client = new Client(parent, origin)
    parent.addEventListener('message', function testServer(event) {
      const { data, origin } = event
      const isRequest =
        data &&
        typeof data === 'object' &&
        data['solid-auth-client'].method &&
        data['solid-auth-client'].args
      if (isRequest) {
        expect(origin).toBe(parent.location.origin)
        const request = data['solid-auth-client']
        const { id, method, args } = request
        expect(id).toBeTruthy()
        expect(method).toBe('foo')
        expect(args).toEqual(['bar', 'baz'])
        child.postMessage(
          {
            'solid-auth-client': {
              id: 'other-id',
              ret: 'other return value',
            },
          },
          child.location.origin
        )
        child.postMessage(
          {
            'solid-auth-client': {
              id,
              ret: 'the return value!',
            },
          },
          child.location.origin
        )
        parent.removeEventListener('message', testServer)
      }
    })
    const response = await client.request('foo', 'bar', 'baz')
    expect(response).toBe('the return value!')
  })
})

describe('Server', () => {
  // eslint-disable-next-line jest/no-test-callback
  it('only responds to valid requests', (done) => {
    expect.assertions(1)
    const parent = window
    const child = parent
    const handler = jest.fn()
    const server = new Server(child, child.location.origin, handler)
    server.start()
    parent.addEventListener('message', function listener() {
      try {
        expect(handler.mock.calls).toHaveLength(0)
        parent.removeEventListener('message', listener)
        done()
      } catch (e) {
        done.fail(e)
      } finally {
        server.stop()
      }
    })
    parent.postMessage('not-a-well-formed-message', parent.location.origin)
  })

  // eslint-disable-next-line jest/no-test-callback
  it('delegates to a handler to compute responses', (done) => {
    expect.assertions(3)
    const testHandler = jest.fn(async () => 'testHandler return value')
    const parent = window
    const child = parent
    const server = new Server(child, child.location.origin, testHandler)
    server.start()
    child.addEventListener('message', function listener(event) {
      try {
        const request = event.data['solid-auth-client']
        const { id, ret } = request
        if (!(id && ret)) {
          return
        }
        expect(testHandler.mock.calls[0]).toEqual(['foo', 'a', 'b', 'c'])
        expect(id).toBe('12345')
        expect(ret).toBe('testHandler return value')
        child.removeEventListener('message', listener)
        done()
      } catch (e) {
        done.fail(e)
      } finally {
        server.stop()
      }
    })
    parent.postMessage(
      {
        'solid-auth-client': {
          id: '12345',
          method: 'foo',
          args: ['a', 'b', 'c'],
        },
      },
      parent.location.origin
    )
  })
})


text:
package android.content.pm;

import android.util.ArraySet;

/**
 * Refer from VirtualAPK
 *
 * @author CaMnter
 */

public class PackageUserState {

    public boolean stopped;
    public boolean notLaunched;
    public boolean installed;
    public boolean hidden; // Is the app restricted by owner / admin
    public int enabled;
    public boolean blockUninstall;

    public String lastDisableAppCaller;

    public ArraySet<String> disabledComponents;
    public ArraySet<String> enabledComponents;

    public int domainVerificationStatus;
    public int appLinkGeneration;

    public PackageUserState() {
        throw new RuntimeException("Stub!");
    }

    public PackageUserState(final PackageUserState o) {
        throw new RuntimeException("Stub!");
    }

}


text:
using System;
using NUnit.Framework;

namespace Tennis
{
    class TennisGame1 : TennisGame
    {
        private int player1Score = 0;
        private int player2Score = 0;
        private string player1Name;
        private string player2Name;

        public TennisGame1(string player1Name, string player2Name)
        {
            this.player1Name = player1Name;
            this.player2Name = player2Name;
        }

        public void WonPoint(string playerName)
        {
            if (playerName == player1Name)
                player1Score += 1;
            else if (playerName == player2Name)
                player2Score += 1;
        }

        public string GetScore()
        {
            String score = "";
            if (player1Score == player2Score)
            {
                switch (player1Score)
                {
                    case 0:
                        return "Love-All";
                    case 1:
                        return "Fifteen-All";
                    case 2:
                        return "Thirty-All";
                    default:
                        return "Deuce";
                }
            }
            else if (player1Score >= 4 || player2Score >= 4)
            {
                int scoreDifference = player1Score - player2Score;
                if (scoreDifference == 1)
                    return "Advantage player1";
                else if (scoreDifference == -1)
                    return "Advantage player2";
                else if (scoreDifference >= 2)
                    return "Win for player1";
                else
                    return "Win for player2";
            }
            else
            {
                switch (player1Score)
                {
                    case 0:
                        score += "Love";
                        break;
                    case 1:
                        score += "Fifteen";
                        break;
                    case 2:
                        score += "Thirty";
                        break;
                    case 3:
                        score += "Forty";
                        break;
                }

                score += " - ";

                switch (player2Score)
                {
                    case 0:
                        score += "Love";
                        break;
                    case 1:
                        score += "Fifteen";
                        break;
                    case 2:
                        score += "Thirty";
                        break;
                    case 3:
                        score += "Forty";
                        break;
                }
            }
            return score;
        }
    }

}


text:
<!DOCTYPE HTML>

	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name='viewport' content='width=device-width, initial-scale=1.0'>

	<title>QUnit Test for GridLayout</title>
	<link rel="shortcut icon" type="image/x-icon" href="../../images/controls/sap.ui.layout.form.GridLayout.gif">
	<link rel="stylesheet" href="../../../../../../resources/sap/ui/thirdparty/qunit-2.css" type="text/css" media="screen">


text:
<?php
namespace basic\classes;
defined("_uniq_token_") or die('');

/**
* Classe qui permet de minifier des fichiers JS ou CSS via une API en ligne
*/
class Minifier {
	private static $URL = array("js" => "http://javascript-minifier.com/raw", "css" => "http://cssminifier.com/raw");
	private static $baseDirectory = "";
	private static $sourcesDirectories = array("js", "css");

	/**
	* Demande la compression de tous les fichiers CSS/JS contenu dans le dossier où à lieu l'appel
	* @param 	String 		$addToBasePath 		Chemin vers le dossier de statiques
	* @param 	boolean 	$combine 			Demande de combiner tous les JS en un seul gros JS. Non implémenté car inutile sur ce projet.
	* @return 	void
	*/
	public static function minifyAllFiles($addToBasePath = "/static", $combine = false){
		self::$baseDirectory = DOCUMENT_ROOT.$addToBasePath;

		foreach(self::$sourcesDirectories as $dir){
			self::includeDir($dir, $files);

			foreach($files as $file){
				$content = file_get_contents($file);
				$minified = self::minify(self::$URL[$dir], $content);

				if($minified === null)
					continue;

				if(PROD)
					file_put_contents($file, $minified); //on remplace le fichier si on est en prod !
				else { //sinon on génère des fichiers .min. pour les tests
					$name = str_replace(".".$dir, "", $file).".min.".$dir; //path/to/file/css/myFile.min.css   => uniquement pour tester ces fichiers !
					file_put_contents($name, $minified);
				}
			}
		}
	}

	/**
	* Minify avec un appel distant sur une API via POST
	* @return  		La version minifié en String
	*/
	public static function minify($url, $datas){
		$result = null;

		$data = array('input' => $datas);
		$options = array(
			'http' => array(
			    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
			    'method'  => 'POST',
			    'content' => http_build_query($data),
			)
		);
		$context  = stream_context_create($options);
		$result = file_get_contents($url, false, $context);

		if($result === false)
			$result = null;

		return $result;
	}

	/**
	* Fonction récursive d'inclusion
	* @return 	Ajoute à &$result les path de chaque fichier (path complet)
	*/
	public static function includeDir($folder, &$result){
		try {
			$d = opendir(self::$baseDirectory."/".$folder);
			while($entry = @readdir($d)) {
				if(!is_dir($folder.$entry) AND $entry != "." AND $entry != "..")
					$result[] = self::$baseDirectory."/".$folder.$entry;
				else if($entry != "." AND $entry != "..")
					self::includeDir($folder.$entry."/", $result);
			}
		}
		catch (Exception $e){
			Handler::exception($this, $e);
		}
	}
}


text:
package me.ccampo.example.service;

import org.springframework.stereotype.Service;

/**
 * Notice here we're using Spring's {@link Service} annotation
 * to register this class as a bean.
 */
@Service
public class ExampleServiceB {

    public String getMessage() {
        return "B";
    }
}


text:
@implementation DateUnixTime
+ (double)convertUnixTimeFromDate:(NSDate *)date
{
    double unixtime = [date timeIntervalSince1970];
    return unixtime;
}

+ (double)convertUnixTimeFromString:(NSString *)string
                        inputFormat:(NSString *)format

{
    NSDateFormatter *formatter = [self setformatterWithFormat:format];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSDate *date = [formatter dateFromString:string];

    double unixTime = [self convertUnixTimeFromDate:date];
    return unixTime;
}

+ (NSDate *)convertDateFromUnixTime:(double)unixtime
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixtime];

    return date;
}

+ (NSString *)convertStringFromUnixTime:(double)unixTime
                           outputFormat:(NSString *)format

{
    NSDate *unixTimeDate = [self convertDateFromUnixTime:unixTime];

    NSDateFormatter *formatter = [self setformatterWithFormat:format];
    NSString *dateString = [formatter stringFromDate:unixTimeDate];
    return dateString;
}

+ (NSString *)convertStringFromDate:(NSDate *)date
                       outputFormat:(NSString *)format
{
    double unixTime = [self convertUnixTimeFromDate:date];
    NSString *dateString = [self convertStringFromUnixTime:unixTime
                                              outputFormat:format];
    return dateString;
}

+ (NSDate *)convertDateFromString:(NSString *)string
                       inputFormat:(NSString *)format
{
    double unixTime = [self convertUnixTimeFromString:string
                                          inputFormat:format];

    NSDate *unixTimeDate = [self convertDateFromUnixTime:unixTime];

    return unixTimeDate;
}

+ (NSDateFormatter *)setformatterWithFormat:(NSString *)format
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:format];
    [formatter setLocale:[NSLocale currentLocale]];
    return formatter;
}
@end


text:
import json
import os

from cauldron import cli
from cauldron import environ
from cauldron import runner
from cauldron.cli import sync
from cauldron.cli.commands.open import opener as local_opener
from cauldron.environ.response import Response

def sync_open(
        context: cli.CommandContext,
        path: str,
        forget: bool = False
) -> Response:
    """..."""
    source_directory = environ.paths.clean(path)
    environ.remote_connection.local_project_directory = source_directory
    source_path = os.path.join(source_directory, 'cauldron.json')

    with open(source_path, 'r') as f:
        definition = json.load(f)

    response = sync.comm.send_request(
        endpoint='/sync-open',
        method='POST',
        remote_connection=context.remote_connection,
        data=dict(
            definition=definition,
            source_directory=source_directory,
        )
    ).response
    response.log_notifications()

    if not forget:  # pragma: no cover
        local_opener.update_recent_paths(response, source_directory)

    runner.add_library_path(source_directory)

    return response


text:
"""
Copyright 2010-2019 University Of Southern California

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.

Multisegment tool for merging multiple BBP runs into a combined simulation
"""
from __future__ import division, print_function

# Import Python modules
import os
import sys
import glob
import shutil
import argparse

# Import Broadband modules
import seqnum
import bband_utils
from install_cfg import InstallCfg
from station_list import StationList

# Import BBP workflow modules
import plot_srf
import plot_rotd50
from plot_seis import PlotSeis
from rotd100 import RotD100

class MergeScenario(object):
    """
    Implements merging a number of individual simulations into a combined
    BBP run. Useful for combining simulation results from individualy computed
    fault segments into a multi-segment fault
    """

    def __init__(self):
        """
        Initialize class structures
        """
        self.install = InstallCfg.getInstance()
        self.output_sim_id = None
        self.a_indir = None
        self.a_outdir = None
        self.a_logdir = None
        self.a_tmpdir = None
        self.station_list = None
        self.input_sims = []
        self.src_files = []
        self.srf_files = []
        self.scenario = None

    def parse_arguments(self):
        """
        This function takes care of parsing the command-line arguments and
        asking the user for any missing parameters that we need
        """
        parser = argparse.ArgumentParser(description="Processes a numer of "
                                         "single segment BBP runs and combines "
                                         "them into a merged run.")
        parser.add_argument("--sim-id", dest="sim_id", type=int,
                            help="sim_id for merged simulation")
        parser.add_argument("--scenario", dest="scenario",
                            help="scenario name")
        parser.add_argument('input_sims', nargs='*')
        args = parser.parse_args()

        # Input simulations
        if len(args.input_sims) < 2:
            print("[ERROR]: Please provide at least two simulations to merge!")
            sys.exit(-1)

        self.input_sims = args.input_sims

        # Output simulation id
        if args.sim_id is None:
            self.output_sim_id = int(seqnum.get_seq_num())
        else:
            self.output_sim_id = args.sim_id

        # Scenario name
        if args.scenario is None:
            print("[ERROR]: Please provide a scenario name!")
            sys.exit(-1)

        self.scenario = args.scenario

    def create_merged_dirs(self):
        """
        Creates the directory struction for the merged simulation
        """
        install = self.install

        self.a_indir = os.path.join(install.A_IN_DATA_DIR,
                                    str(self.output_sim_id))
        self.a_tmpdir = os.path.join(install.A_TMP_DATA_DIR,
                                     str(self.output_sim_id))
        self.a_outdir = os.path.join(install.A_OUT_DATA_DIR,
                                     str(self.output_sim_id))
        self.a_logdir = os.path.join(install.A_OUT_LOG_DIR,
                                     str(self.output_sim_id))

        # Make sure directories exist
        bband_utils.mkdirs([self.a_tmpdir, self.a_indir,
                            self.a_outdir, self.a_logdir],
                           print_cmd=False)

    def copy_indata_files(self):
        """
        Copies all needed indata files to the new indata directory
        """
        for sim_id in self.input_sims:
            input_dir = os.path.join(self.install.A_IN_DATA_DIR,
                                     str(sim_id))
            # SRC files
            src_file = glob.glob("%s/*.src" % (input_dir))
            if len(src_file) != 1:
                print("[ERROR]: Can't find single SRC file in %s" % (input_dir))
                sys.exit(1)
            src_file = src_file[0]
            self.src_files.append(src_file)
            # SRF files
            in_srf_file = "%s.srf" % (os.path.splitext(src_file)[0])
            tmp_srf_file = os.path.join(self.a_tmpdir,
                                        os.path.basename(in_srf_file))
            self.srf_files.append(tmp_srf_file)
            # Copy files
            shutil.copy2(src_file, self.a_indir)
            shutil.copy2(in_srf_file, self.a_tmpdir)
            shutil.copy2(in_srf_file, self.a_indir)

        # Now copy station list
        input_dir = os.path.join(self.install.A_IN_DATA_DIR,
                                 str(self.input_sims[0]))
        station_file = glob.glob("%s/*.stl" % (input_dir))
        if len(station_file) != 1:
            print("[ERROR]: Can't find station list file in %s" % (input_dir))
            sys.exit(1)
        station_file = station_file[0]
        self.station_list = station_file
        shutil.copy2(station_file, self.a_indir)

        # Copy corrections file if needed
        correction_file = glob.glob("%s/*corrections.txt" % (input_dir))
        if len(correction_file) == 1:
            correction_file = correction_file[0]
            shutil.copy2(correction_file, self.a_indir)

    def add_bbp_seismograms(self, input_files, output_file):
        """
        Add all input files and write output_file with the combined data
        """
        # Start empty
        headers = []
        times = []
        ns_comp = []
        ew_comp = []
        ud_comp = []

        # Read first file
        input_file = input_files[0]
        input_files = input_files[1:]
        i_file = open(input_file, 'r')
        for line in i_file:
            line = line.strip()
            # Empty lines
            if not line:
                continue
            if line.startswith('#') or line.startswith('%'):
                headers.append(line)
                continue
            pieces = line.split()
            pieces = [float(piece) for piece in pieces]
            times.append(pieces[0])
            ns_comp.append(pieces[1])
            ew_comp.append(pieces[2])
            ud_comp.append(pieces[3])
        i_file.close()

        # Now add other files
        for input_file in input_files:
            index = 0
            i_file = open(input_file, 'r')
            for line in i_file:
                line = line.strip()
                # Empty lines
                if not line:
                    continue
                if line.startswith('#') or line.startswith('%'):
                    continue
                pieces = line.split()
                pieces = [float(piece) for piece in pieces]
                if index > len(times):
                    print("[ERROR]: File size mismatch!")
                    sys.exit(1)
                ns_comp[index] = ns_comp[index] + pieces[1]
                ew_comp[index] = ew_comp[index] + pieces[2]
                ud_comp[index] = ud_comp[index] + pieces[3]
                index = index + 1
            i_file.close()

        # Finally write output file
        o_file = open(output_file, 'w')
        for header_line in headers:
            o_file.write("%s\n" % (header_line))
        for time, ns_val, ew_val, ud_val in zip(times, ns_comp,
                                                ew_comp, ud_comp):
            o_file.write("%5.7f   %5.9e   %5.9e    %5.9e\n" %
                         (time, ns_val, ew_val, ud_val))
        o_file.close()

    def merge_seismograms(self):
        """
        Adds seismograms from multiple simulations, creating a set
        of merged seismograms
        """
        # Load station list
        slo = StationList(self.station_list)
        site_list = slo.getStationList()

        # Merge each station
        for station in site_list:
            print("==> Merging station: %s" % (station.scode))
            # Merge both velocity and acceleration
            for file_type in ['vel', 'acc']:
                input_files = []
                for sim_id in self.input_sims:
                    input_dir = os.path.join(self.install.A_OUT_DATA_DIR,
                                             str(sim_id))
                    input_file = os.path.join(input_dir,
                                              "%s.%s.%s.bbp" %
                                              (str(sim_id),
                                               station.scode,
                                               file_type))
                    input_files.append(input_file)
                output_file = os.path.join(self.a_outdir,
                                           "%s.%s.%s.bbp" %
                                           (str(self.output_sim_id),
                                            station.scode,
                                            file_type))
                self.add_bbp_seismograms(input_files, output_file)

    def plot_srf(self):
        """
        Creates the multi-segment SRF plot
        """
        # Save current directory
        old_cwd = os.getcwd()
        os.chdir(self.a_tmpdir)

        for srf_file in self.srf_files:
            srf_file = os.path.basename(srf_file)
            # Write slip file
            srfbase = srf_file[0:srf_file.find(".srf")]
            slipfile = "%s.slip" % (srfbase)
            cmd = ("%s calc_xy=0 type=slip nseg=-1 < %s > %s" %
                   (os.path.join(self.install.A_GP_BIN_DIR, "srf2xyz"),
                    os.path.join(self.a_indir, srf_file),
                    slipfile))
            bband_utils.runprog(cmd)

            # Write tinit file
            tinitfile = "%s.tinit" % (srfbase)
            cmd = ("%s calc_xy=0 type=tinit nseg=-1 < %s > %s" %
                   (os.path.join(self.install.A_GP_BIN_DIR, "srf2xyz"),
                    os.path.join(self.a_indir, srf_file),
                    tinitfile))
            bband_utils.runprog(cmd)

        plottitle = 'Rupture Model for %s' % (self.scenario)
        plot_srf.plot_multi_srf_files(plottitle,
                                      self.srf_files,
                                      self.a_outdir)

        # Restore directory
        os.chdir(old_cwd)

    def post_process(self):
        """
        Run the standard BBP post-processing tasks
        """
        # Plot seismograms
        plotter = PlotSeis(os.path.basename(self.station_list),
                           os.path.basename(self.src_files[0]),
                           True, True, self.output_sim_id)
        plotter.run()
        # RotD50
        process = RotD100(os.path.basename(self.station_list),
                          sim_id=self.output_sim_id)
        process.run()
        # Plot RotD50

        # Load station list
        slo = StationList(self.station_list)
        site_list = slo.getStationList()

        for site in site_list:
            stat = site.scode
            rd50_file = "%d.%s.rd50" % (self.output_sim_id, stat)
            rd50_filename1 = os.path.join(self.a_outdir, rd50_file)
            outfile = os.path.join(self.a_outdir, "%s_%d_%s_rotd50.png" %
                                   (self.scenario, self.output_sim_id, stat))
            plot_rotd50.plot_rd50(stat, rd50_filename1, "-",
                                  self.scenario, "-", outfile,
                                  site.low_freq_corner,
                                  site.high_freq_corner,
                                  quiet=True)

    def merge_multisegment_scenario(self):
        """
        Merges multiple BBP runs for separate fault segments
        into a single simulation
        """
        # Start parsing command-line
        self.parse_arguments()
        print(" BBP Multi-segment Merging Tool ".center(80, '-'))
        # Create new directories
        self.create_merged_dirs()
        # Copy indata files
        self.copy_indata_files()
        # Merge seismograms
        self.merge_seismograms()
        # Plot combined SRF plot
        self.plot_srf()
        # Post-processing steps
        self.post_process()
        print(" BBP Multi-segment Merging Tool Completed ".center(80, '-'))

if __name__ == "__main__":
    ME = MergeScenario()
    ME.merge_multisegment_scenario()
    sys.exit(0)


text:
var express = require('express');
var util = require('util');

// Elasticsearch REST API client module
var elasticsearch = require('es');
var config =
			{
				_index:'dmp',
				server:{ host:'localhost', port:19821 }
			};

var es = elasticsearch(config);

// --------------------------------------------------------------------------------
// DATABASE ACCESS LAYER
// (should be moved to separate service? To move, or not to move, that's question... yet.)
//

// mock database
var data = {"mailboxes":[]};

// Simple test / checking if index exists
exports.testDB = function() {
	es.indices.exists({ _index : 'dmp' }, function (err, data) {

		if(err === null)
		{
			console.log('Test result: ' + (data.exists ? '"dmp" index exists in db' : '"dmp" index does not exists in db'));
			console.log('Code: ' + data.statusCode);
		}
		else
		{
			console.error('EROR: ' + util.inspect(err));
		}
	});

	es.count(function(err, data){
		console.log( 'DATA:'+util.inspect(data));
		console.log( 'ERROR:'+util.inspect(err));
	});
};

// Returns all mailboxes
exports.GetMailboxes = function(sCallback) {
	// mock
	if(sCallback !== null)
	   sCallback(data.mailboxes);
};

// Add new mailbox to DB
exports.AddMailbox = function(email, departament, mailboxsize, sCallback, eCallback) {

	try
	{
		data.mailboxes[data.mailboxes.length] =
								{
									"email": email,
									"departament": departament,
									"mailboxsize": mailboxsize
								};
	}
	catch(ex)
	{
		if(eCallback !== null)
		   eCallback(ex);
	}

	if(sCallback !== null)
	   sCallback( { message: 'Mailbox added successfully'} );
};

// Add numbers of maiboxes with rundom deparaments names supplied in departamentsNamesArray
exports.CreateRundomMailboxes = function(count, departamentsNamesArray, sCallback, eCallback) {
	if(count > 0 && departamentsNamesArray !== null && departamentsNamesArray.length > 0) {

		var maxDepIndex = departamentsNamesArray.length;
		var maxMailboxSize = 1000;
		for(var i = 0; i < count; i++)
		{
			exports.AddMailbox('mailbox'+i+'@domain.com',
				departamentsNamesArray[Math.floor(Math.random() * maxDepIndex)],
				Math.floor(Math.random() * maxMailboxSize), null, eCallback);
		}

		if(sCallback !== null)
		   sCallback( {message: count + " mailboxes added successfully"} );
	}
};

// Just pring error message to console for dubugging purposes
function PrintError(err) {
	var u = require('util');
	console.error(u.log('ERROR: ' + u.inspect(err)));
}

// --------------------------------------------------------------------------------
// simple tests

exports.CreateRundomMailboxes(1000000, ['Dep1', 'Dep2', 'Dep3'], function(data){ console.log(data.message); }, PrintError);
exports.AddMailbox('my.name@domain.com', 'my departament', 250, function(data){ console.log(data.message); }, PrintError);
exports.GetMailboxes(function(mailboxes) {
	console.log('I have got a ' + mailboxes.length + ' mailboxes');

});

exports.testDB();


text:
class MethodCallSummarizer
{
public:
    MethodCallSummarizer(WCHAR* name);
    void AddCall(const char* name);
    void SaveTextFile();

private:
    char**        names;
    unsigned int* counts;
    int           numNames;
    WCHAR*        dataFileName;
};

#endif


text:
import type {Element} from './types';
import * as React from 'react';
import {useContext, useMemo} from 'react';
import {TreeStateContext} from './TreeContext';
import {SettingsContext} from '../Settings/SettingsContext';
import TreeFocusedContext from './TreeFocusedContext';
import {StoreContext} from '../context';
import {useSubscription} from '../hooks';

import styles from './SelectedTreeHighlight.css';

type Data = {
  startIndex: number,
  stopIndex: number,
};

export default function SelectedTreeHighlight(_: {}): React.Node {
  const {lineHeight} = useContext(SettingsContext);
  const store = useContext(StoreContext);
  const treeFocused = useContext(TreeFocusedContext);
  const {ownerID, selectedElementID} = useContext(TreeStateContext);

  const subscription = useMemo(
    () => ({
      getCurrentValue: () => {
        if (
          selectedElementID === null ||
          store.isInsideCollapsedSubTree(selectedElementID)
        ) {
          return null;
        }

        const element = store.getElementByID(selectedElementID);
        if (
          element === null ||
          element.isCollapsed ||
          element.children.length === 0
        ) {
          return null;
        }

        const startIndex = store.getIndexOfElementID(element.children[0]);
        if (startIndex === null) {
          return null;
        }

        let stopIndex = null;
        let current: null | Element = element;
        while (current !== null) {
          if (current.isCollapsed || current.children.length === 0) {
            // We've found the last/deepest descendant.
            stopIndex = store.getIndexOfElementID(current.id);
            current = null;
          } else {
            const lastChildID = current.children[current.children.length - 1];
            current = store.getElementByID(lastChildID);
          }
        }

        if (stopIndex === null) {
          return null;
        }

        return {
          startIndex,
          stopIndex,
        };
      },
      subscribe: (callback: Function) => {
        store.addListener('mutated', callback);
        return () => {
          store.removeListener('mutated', callback);
        };
      },
    }),
    [selectedElementID, store],
  );
  const data = useSubscription<Data | null>(subscription);

  if (ownerID !== null) {
    return null;
  }

  if (data === null) {
    return null;
  }

  const {startIndex, stopIndex} = data;

  return (
    <div
      className={treeFocused ? styles.Active : styles.Inactive}
      style={{
        position: 'absolute',
        top: `${startIndex * lineHeight}px`,
        height: `${(stopIndex + 1 - startIndex) * lineHeight}px`,
      }}
    />
  );
}


text:
<?php

declare(strict_types=1);

namespace Talesweaver\Application\Command\Location\AddToScene;

use Talesweaver\Application\Bus\CommandHandlerInterface;

final class CommandHandler implements CommandHandlerInterface
{
    public function __invoke(Command $command): void
    {
        $scene = $command->getScene();
        $location = $command->getLocation();

        $scene->addLocation($location);
        $location->addScene($scene);
    }
}


text:
namespace blink {
class WebFrame;
}

namespace extensions {

// A struct containing information about a script run.
struct ScriptsRunInfo {
  // Map of extensions IDs to the executing script paths.
  typedef std::map<std::string, std::set<std::string> > ExecutingScriptsMap;

  ScriptsRunInfo();
  ~ScriptsRunInfo();

  // The number of CSS scripts injected.
  size_t num_css;
  // The number of JS scripts injected.
  size_t num_js;
  // A map of extension ids to executing script paths.
  ExecutingScriptsMap executing_scripts;
  // The elapsed time since the ScriptsRunInfo was constructed.
  base::ElapsedTimer timer;

  // Log information about a given script run.
  void LogRun(blink::WebFrame* web_frame, UserScript::RunLocation location);

 private:
  DISALLOW_COPY_AND_ASSIGN(ScriptsRunInfo);
};

}  // namespace extensions

#endif  // EXTENSIONS_RENDERER_SCRIPTS_RUN_INFO_H_


text:
<?php

namespace Http\Message\Formatter;

use Http\Message\Formatter;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Normalize a request or a response into a string or an array.
 *
 * @author Joel Wurtz <joel.wurtz@gmail.com>
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class SimpleFormatter implements Formatter
{
    /**
     * {@inheritdoc}
     */
    public function formatRequest(RequestInterface $request)
    {
        return sprintf(
            '%s %s %s',
            $request->getMethod(),
            $request->getUri()->__toString(),
            $request->getProtocolVersion()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function formatResponse(ResponseInterface $response)
    {
        return sprintf(
            '%s %s %s',
            $response->getStatusCode(),
            $response->getReasonPhrase(),
            $response->getProtocolVersion()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function formatResponseForRequest(ResponseInterface $response, RequestInterface $request)
    {
        return $this->formatResponse($response);
    }
}


text:
using Topshelf.Builders;
using Topshelf.HostConfigurators;
using Topshelf.Runtime;

namespace Topshelf.StartParameters
{
    public class SpWindowsHostEnvironmentBuilder :
        EnvironmentBuilder
    {
        private readonly HostConfigurator _hostConfigurator;

        public SpWindowsHostEnvironmentBuilder(HostConfigurator configurator)
        {
            _hostConfigurator = configurator;
        }

        public HostEnvironment Build()
        {
            return new SpWindowsHostEnvironment(_hostConfigurator);
        }
    }
}


text:
<component name="ArtifactManager">
  <artifact type="exploded-ear" name="REST_TEST:ear exploded">
    <output-path>$PROJECT_DIR$/out/artifacts/REST_TEST_ear_exploded</output-path>
    <root id="root">
      <element id="javaee-facet-resources" facet="NUNTIUS/javaeeApplication/javaEEApplication" />
    </root>
  </artifact>
</component>