text:
package integration

import (
	"fmt"
	"math/rand"
	"reflect"
	"sort"
	"testing"
	"time"

	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/etcdserver/api/v3rpc"
	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	"github.com/coreos/etcd/integration"
	mvccpb "github.com/coreos/etcd/mvcc/mvccpb"
	"github.com/coreos/etcd/pkg/testutil"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

type watcherTest func(*testing.T, *watchctx)

type watchctx struct {
	clus          *integration.ClusterV3
	w             clientv3.Watcher
	wclient       *clientv3.Client
	kv            clientv3.KV
	wclientMember int
	kvMember      int
	ch            clientv3.WatchChan
}

func runWatchTest(t *testing.T, f watcherTest) {
	defer testutil.AfterTest(t)

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

	wclientMember := rand.Intn(3)
	wclient := clus.Client(wclientMember)
	w := clientv3.NewWatcher(wclient)
	defer w.Close()
	// select a different client from wclient so puts succeed if
	// a test knocks out the watcher client
	kvMember := rand.Intn(3)
	for kvMember == wclientMember {
		kvMember = rand.Intn(3)
	}
	kvclient := clus.Client(kvMember)
	kv := clientv3.NewKV(kvclient)

	wctx := &watchctx{clus, w, wclient, kv, wclientMember, kvMember, nil}
	f(t, wctx)
}

// TestWatchMultiWatcher modifies multiple keys and observes the changes.
func TestWatchMultiWatcher(t *testing.T) {
	runWatchTest(t, testWatchMultiWatcher)
}

func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
	numKeyUpdates := 4
	keys := []string{"foo", "bar", "baz"}

	donec := make(chan struct{})
	readyc := make(chan struct{})
	for _, k := range keys {
		// key watcher
		go func(key string) {
			ch := wctx.w.Watch(context.TODO(), key)
			if ch == nil {
				t.Fatalf("expected watcher channel, got nil")
			}
			readyc <- struct{}{}
			for i := 0; i < numKeyUpdates; i++ {
				resp, ok := <-ch
				if !ok {
					t.Fatalf("watcher unexpectedly closed")
				}
				v := fmt.Sprintf("%s-%d", key, i)
				gotv := string(resp.Events[0].Kv.Value)
				if gotv != v {
					t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
				}
			}
			donec <- struct{}{}
		}(k)
	}
	// prefix watcher on "b" (bar and baz)
	go func() {
		prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
		if prefixc == nil {
			t.Fatalf("expected watcher channel, got nil")
		}
		readyc <- struct{}{}
		evs := []*clientv3.Event{}
		for i := 0; i < numKeyUpdates*2; i++ {
			resp, ok := <-prefixc
			if !ok {
				t.Fatalf("watcher unexpectedly closed")
			}
			evs = append(evs, resp.Events...)
		}

		// check response
		expected := []string{}
		bkeys := []string{"bar", "baz"}
		for _, k := range bkeys {
			for i := 0; i < numKeyUpdates; i++ {
				expected = append(expected, fmt.Sprintf("%s-%d", k, i))
			}
		}
		got := []string{}
		for _, ev := range evs {
			got = append(got, string(ev.Kv.Value))
		}
		sort.Strings(got)
		if !reflect.DeepEqual(expected, got) {
			t.Errorf("got %v, expected %v", got, expected)
		}

		// ensure no extra data
		select {
		case resp, ok := <-prefixc:
			if !ok {
				t.Fatalf("watcher unexpectedly closed")
			}
			t.Fatalf("unexpected event %+v", resp)
		case <-time.After(time.Second):
		}
		donec <- struct{}{}
	}()

	// wait for watcher bring up
	for i := 0; i < len(keys)+1; i++ {
		<-readyc
	}
	// generate events
	ctx := context.TODO()
	for i := 0; i < numKeyUpdates; i++ {
		for _, k := range keys {
			v := fmt.Sprintf("%s-%d", k, i)
			if _, err := wctx.kv.Put(ctx, k, v); err != nil {
				t.Fatal(err)
			}
		}
	}
	// wait for watcher shutdown
	for i := 0; i < len(keys)+1; i++ {
		<-donec
	}
}

// TestWatchRange tests watcher creates ranges
func TestWatchRange(t *testing.T) {
	runWatchTest(t, testWatchRange)
}

func testWatchRange(t *testing.T, wctx *watchctx) {
	if wctx.ch = wctx.w.Watch(context.TODO(), "a", clientv3.WithRange("c")); wctx.ch == nil {
		t.Fatalf("expected non-nil channel")
	}
	putAndWatch(t, wctx, "a", "a")
	putAndWatch(t, wctx, "b", "b")
	putAndWatch(t, wctx, "bar", "bar")
}

// TestWatchReconnRequest tests the send failure path when requesting a watcher.
func TestWatchReconnRequest(t *testing.T) {
	runWatchTest(t, testWatchReconnRequest)
}

func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
	donec, stopc := make(chan struct{}), make(chan struct{}, 1)
	go func() {
		timer := time.After(2 * time.Second)
		defer close(donec)
		// take down watcher connection
		for {
			wctx.clus.Members[wctx.wclientMember].DropConnections()
			select {
			case <-timer:
				// spinning on close may live lock reconnection
				return
			case <-stopc:
				return
			default:
			}
		}
	}()
	// should reconnect when requesting watch
	if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
		t.Fatalf("expected non-nil channel")
	}

	// wait for disconnections to stop
	stopc <- struct{}{}
	<-donec

	// spinning on dropping connections may trigger a leader election
	// due to resource starvation; l-read to ensure the cluster is stable
	ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
	if _, err := wctx.kv.Get(ctx, "_"); err != nil {
		t.Fatal(err)
	}
	cancel()

	// ensure watcher works
	putAndWatch(t, wctx, "a", "a")
}

// TestWatchReconnInit tests watcher resumes correctly if connection lost
// before any data was sent.
func TestWatchReconnInit(t *testing.T) {
	runWatchTest(t, testWatchReconnInit)
}

func testWatchReconnInit(t *testing.T, wctx *watchctx) {
	if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
		t.Fatalf("expected non-nil channel")
	}
	wctx.clus.Members[wctx.wclientMember].DropConnections()
	// watcher should recover
	putAndWatch(t, wctx, "a", "a")
}

// TestWatchReconnRunning tests watcher resumes correctly if connection lost
// after data was sent.
func TestWatchReconnRunning(t *testing.T) {
	runWatchTest(t, testWatchReconnRunning)
}

func testWatchReconnRunning(t *testing.T, wctx *watchctx) {
	if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
		t.Fatalf("expected non-nil channel")
	}
	putAndWatch(t, wctx, "a", "a")
	// take down watcher connection
	wctx.clus.Members[wctx.wclientMember].DropConnections()
	// watcher should recover
	putAndWatch(t, wctx, "a", "b")
}

// TestWatchCancelImmediate ensures a closed channel is returned
// if the context is cancelled.
func TestWatchCancelImmediate(t *testing.T) {
	runWatchTest(t, testWatchCancelImmediate)
}

func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	wch := wctx.w.Watch(ctx, "a")
	select {
	case wresp, ok := <-wch:
		if ok {
			t.Fatalf("read wch got %v; expected closed channel", wresp)
		}
	default:
		t.Fatalf("closed watcher channel should not block")
	}
}

// TestWatchCancelInit tests watcher closes correctly after no events.
func TestWatchCancelInit(t *testing.T) {
	runWatchTest(t, testWatchCancelInit)
}

func testWatchCancelInit(t *testing.T, wctx *watchctx) {
	ctx, cancel := context.WithCancel(context.Background())
	if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
		t.Fatalf("expected non-nil watcher channel")
	}
	cancel()
	select {
	case <-time.After(time.Second):
		t.Fatalf("took too long to cancel")
	case _, ok := <-wctx.ch:
		if ok {
			t.Fatalf("expected watcher channel to close")
		}
	}
}

// TestWatchCancelRunning tests watcher closes correctly after events.
func TestWatchCancelRunning(t *testing.T) {
	runWatchTest(t, testWatchCancelRunning)
}

func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
	ctx, cancel := context.WithCancel(context.Background())
	if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
		t.Fatalf("expected non-nil watcher channel")
	}
	if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
		t.Fatal(err)
	}
	cancel()
	select {
	case <-time.After(time.Second):
		t.Fatalf("took too long to cancel")
	case v, ok := <-wctx.ch:
		if !ok {
			// closed before getting put; OK
			break
		}
		// got the PUT; should close next
		select {
		case <-time.After(time.Second):
			t.Fatalf("took too long to close")
		case v, ok = <-wctx.ch:
			if ok {
				t.Fatalf("expected watcher channel to close, got %v", v)
			}
		}
	}
}

func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
	if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
		t.Fatal(err)
	}
	select {
	case <-time.After(5 * time.Second):
		t.Fatalf("watch timed out")
	case v, ok := <-wctx.ch:
		if !ok {
			t.Fatalf("unexpected watch close")
		}
		if string(v.Events[0].Kv.Value) != val {
			t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
		}
	}
}

// TestWatchResumeComapcted checks that the watcher gracefully closes in case
// that it tries to resume to a revision that's been compacted out of the store.
func TestWatchResumeCompacted(t *testing.T) {
	defer testutil.AfterTest(t)

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

	// create a waiting watcher at rev 1
	w := clientv3.NewWatcher(clus.Client(0))
	defer w.Close()
	wch := w.Watch(context.Background(), "foo", clientv3.WithRev(1))
	select {
	case w := <-wch:
		t.Errorf("unexpected message from wch %v", w)
	default:
	}
	clus.Members[0].Stop(t)

	ticker := time.After(time.Second * 10)
	for clus.WaitLeader(t) <= 0 {
		select {
		case <-ticker:
			t.Fatalf("failed to wait for new leader")
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}

	// put some data and compact away
	kv := clientv3.NewKV(clus.Client(1))
	for i := 0; i < 5; i++ {
		if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
			t.Fatal(err)
		}
	}
	if _, err := kv.Compact(context.TODO(), 3); err != nil {
		t.Fatal(err)
	}

	clus.Members[0].Restart(t)

	// get compacted error message
	wresp, ok := <-wch
	if !ok {
		t.Fatalf("expected wresp, but got closed channel")
	}
	if wresp.Err() != rpctypes.ErrCompacted {
		t.Fatalf("wresp.Err() expected %v, but got %v", rpctypes.ErrCompacted, wresp.Err())
	}
	// ensure the channel is closed
	if wresp, ok = <-wch; ok {
		t.Fatalf("expected closed channel, but got %v", wresp)
	}
}

// TestWatchCompactRevision ensures the CompactRevision error is given on a
// compaction event ahead of a watcher.
func TestWatchCompactRevision(t *testing.T) {
	defer testutil.AfterTest(t)

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

	// set some keys
	kv := clientv3.NewKV(clus.RandClient())
	for i := 0; i < 5; i++ {
		if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
			t.Fatal(err)
		}
	}

	w := clientv3.NewWatcher(clus.RandClient())
	defer w.Close()

	if _, err := kv.Compact(context.TODO(), 4); err != nil {
		t.Fatal(err)
	}
	wch := w.Watch(context.Background(), "foo", clientv3.WithRev(2))

	// get compacted error message
	wresp, ok := <-wch
	if !ok {
		t.Fatalf("expected wresp, but got closed channel")
	}
	if wresp.Err() != rpctypes.ErrCompacted {
		t.Fatalf("wresp.Err() expected %v, but got %v", rpctypes.ErrCompacted, wresp.Err())
	}

	// ensure the channel is closed
	if wresp, ok = <-wch; ok {
		t.Fatalf("expected closed channel, but got %v", wresp)
	}
}

func TestWatchWithProgressNotify(t *testing.T)        { testWatchWithProgressNotify(t, true) }
func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }

func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
	defer testutil.AfterTest(t)

	// accelerate report interval so test terminates quickly
	oldpi := v3rpc.GetProgressReportInterval()
	// using atomics to avoid race warnings
	v3rpc.SetProgressReportInterval(3 * time.Second)
	pi := 3 * time.Second
	defer func() { v3rpc.SetProgressReportInterval(oldpi) }()

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

	wc := clientv3.NewWatcher(clus.RandClient())
	defer wc.Close()

	opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
	if watchOnPut {
		opts = append(opts, clientv3.WithPrefix())
	}
	rch := wc.Watch(context.Background(), "foo", opts...)

	select {
	case resp := <-rch: // wait for notification
		if len(resp.Events) != 0 {
			t.Fatalf("resp.Events expected none, got %+v", resp.Events)
		}
	case <-time.After(2 * pi):
		t.Fatalf("watch response expected in %v, but timed out", pi)
	}

	kvc := clientv3.NewKV(clus.RandClient())
	if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
		t.Fatal(err)
	}

	select {
	case resp := <-rch:
		if resp.Header.Revision != 2 {
			t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
		}
		if watchOnPut { // wait for put if watch on the put key
			ev := []*clientv3.Event{{Type: clientv3.EventTypePut,
				Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
			if !reflect.DeepEqual(ev, resp.Events) {
				t.Fatalf("expected %+v, got %+v", ev, resp.Events)
			}
		} else if len(resp.Events) != 0 { // wait for notification otherwise
			t.Fatalf("expected no events, but got %+v", resp.Events)
		}
	case <-time.After(time.Duration(1.5 * float64(pi))):
		t.Fatalf("watch response expected in %v, but timed out", pi)
	}
}

func TestWatchEventType(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)

	client := cluster.RandClient()
	ctx := context.Background()
	watchChan := client.Watch(ctx, "/", clientv3.WithPrefix())

	if _, err := client.Put(ctx, "/toDelete", "foo"); err != nil {
		t.Fatalf("Put failed: %v", err)
	}
	if _, err := client.Put(ctx, "/toDelete", "bar"); err != nil {
		t.Fatalf("Put failed: %v", err)
	}
	if _, err := client.Delete(ctx, "/toDelete"); err != nil {
		t.Fatalf("Delete failed: %v", err)
	}
	lcr, err := client.Lease.Grant(ctx, 1)
	if err != nil {
		t.Fatalf("lease create failed: %v", err)
	}
	if _, err := client.Put(ctx, "/toExpire", "foo", clientv3.WithLease(lcr.ID)); err != nil {
		t.Fatalf("Put failed: %v", err)
	}

	tests := []struct {
		et       mvccpb.Event_EventType
		isCreate bool
		isModify bool
	}{{
		et:       clientv3.EventTypePut,
		isCreate: true,
	}, {
		et:       clientv3.EventTypePut,
		isModify: true,
	}, {
		et: clientv3.EventTypeDelete,
	}, {
		et:       clientv3.EventTypePut,
		isCreate: true,
	}, {
		et: clientv3.EventTypeDelete,
	}}

	var res []*clientv3.Event

	for {
		select {
		case wres := <-watchChan:
			res = append(res, wres.Events...)
		case <-time.After(10 * time.Second):
			t.Fatalf("Should receive %d events and then break out loop", len(tests))
		}
		if len(res) == len(tests) {
			break
		}
	}

	for i, tt := range tests {
		ev := res[i]
		if tt.et != ev.Type {
			t.Errorf("#%d: event type want=%s, get=%s", i, tt.et, ev.Type)
		}
		if tt.isCreate && !ev.IsCreate() {
			t.Errorf("#%d: event should be CreateEvent", i)
		}
		if tt.isModify && !ev.IsModify() {
			t.Errorf("#%d: event should be ModifyEvent", i)
		}
	}
}

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

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

	cli := clus.Client(0)
	wc := clientv3.NewWatcher(cli)

	donec := make(chan struct{})
	go func() {
		defer close(donec)
		wc.Watch(context.TODO(), "foo")
		if err := wc.Close(); err != nil && err != grpc.ErrClientConnClosing {
			t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
		}
	}()

	if err := cli.Close(); err != nil {
		t.Fatal(err)
	}
	clus.TakeClient(0)

	select {
	case <-time.After(3 * time.Second):
		t.Fatal("wc.Watch took too long")
	case <-donec:
	}
}

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

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

	cli := clus.Client(0)
	clus.TakeClient(0)
	if err := cli.Close(); err != nil {
		t.Fatal(err)
	}

	donec := make(chan struct{})
	go func() {
		wc := clientv3.NewWatcher(cli)
		wc.Watch(context.TODO(), "foo")
		if err := wc.Close(); err != nil && err != grpc.ErrClientConnClosing {
			t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
		}
		close(donec)
	}()
	select {
	case <-time.After(3 * time.Second):
		t.Fatal("wc.Watch took too long")
	case <-donec:
	}
}

// TestWatchWithRequireLeader checks the watch channel closes when no leader.
func TestWatchWithRequireLeader(t *testing.T) {
	defer testutil.AfterTest(t)

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

	// something for the non-require leader watch to read as an event
	if _, err := clus.Client(1).Put(context.TODO(), "foo", "bar"); err != nil {
		t.Fatal(err)
	}

	clus.Members[1].Stop(t)
	clus.Members[2].Stop(t)
	clus.Client(1).Close()
	clus.Client(2).Close()
	clus.TakeClient(1)
	clus.TakeClient(2)

	// wait for election timeout, then member[0] will not have a leader.
	tickDuration := 10 * time.Millisecond
	time.Sleep(time.Duration(3*clus.Members[0].ElectionTicks) * tickDuration)

	chLeader := clus.Client(0).Watch(clientv3.WithRequireLeader(context.TODO()), "foo", clientv3.WithRev(1))
	chNoLeader := clus.Client(0).Watch(context.TODO(), "foo", clientv3.WithRev(1))

	select {
	case resp, ok := <-chLeader:
		if !ok {
			t.Fatalf("expected %v watch channel, got closed channel", rpctypes.ErrNoLeader)
		}
		if resp.Err() != rpctypes.ErrNoLeader {
			t.Fatalf("expected %v watch response error, got %+v", rpctypes.ErrNoLeader, resp)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("watch without leader took too long to close")
	}

	select {
	case resp, ok := <-chLeader:
		if ok {
			t.Fatalf("expected closed channel, got response %v", resp)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("waited too long for channel to close")
	}

	if _, ok := <-chNoLeader; !ok {
		t.Fatalf("expected response, got closed channel")
	}
}

// TestWatchWithFilter checks that watch filtering works.
func TestWatchWithFilter(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)

	client := cluster.RandClient()
	ctx := context.Background()

	wcNoPut := client.Watch(ctx, "a", clientv3.WithFilterPut())
	wcNoDel := client.Watch(ctx, "a", clientv3.WithFilterDelete())

	if _, err := client.Put(ctx, "a", "abc"); err != nil {
		t.Fatal(err)
	}
	if _, err := client.Delete(ctx, "a"); err != nil {
		t.Fatal(err)
	}

	npResp := <-wcNoPut
	if len(npResp.Events) != 1 || npResp.Events[0].Type != clientv3.EventTypeDelete {
		t.Fatalf("expected delete event, got %+v", npResp.Events)
	}
	ndResp := <-wcNoDel
	if len(ndResp.Events) != 1 || ndResp.Events[0].Type != clientv3.EventTypePut {
		t.Fatalf("expected put event, got %+v", ndResp.Events)
	}

	select {
	case resp := <-wcNoPut:
		t.Fatalf("unexpected event on filtered put (%+v)", resp)
	case resp := <-wcNoDel:
		t.Fatalf("unexpected event on filtered delete (%+v)", resp)
	case <-time.After(100 * time.Millisecond):
	}
}

// TestWatchWithCreatedNotification checks that createdNotification works.
func TestWatchWithCreatedNotification(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)

	client := cluster.RandClient()

	ctx := context.Background()

	createC := client.Watch(ctx, "a", clientv3.WithCreatedNotify())

	resp := <-createC

	if !resp.Created {
		t.Fatalf("expected created event, got %v", resp)
	}
}

// TestWatchCancelOnServer ensures client watcher cancels propagate back to the server.
func TestWatchCancelOnServer(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)

	client := cluster.RandClient()

	for i := 0; i < 10; i++ {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		client.Watch(ctx, "a", clientv3.WithCreatedNotify())
		cancel()
	}
	// wait for cancels to propagate
	time.Sleep(time.Second)

	watchers, err := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
	if err != nil {
		t.Fatal(err)
	}
	if watchers != "0" {
		t.Fatalf("expected 0 watchers, got %q", watchers)
	}
}

// TestWatchOverlapContextCancel stresses the watcher stream teardown path by
// creating/canceling watchers to ensure that new watchers are not taken down
// by a torn down watch stream. The sort of race that's being detected:
//     1. create w1 using a cancelable ctx with %v as "ctx"
//     2. cancel ctx
//     3. watcher client begins tearing down watcher grpc stream since no more watchers
//     3. start creating watcher w2 using a new "ctx" (not canceled), attaches to old grpc stream
//     4. watcher client finishes tearing down stream on "ctx"
//     5. w2 comes back canceled
func TestWatchOverlapContextCancel(t *testing.T) {
	f := func(clus *integration.ClusterV3) {}
	testWatchOverlapContextCancel(t, f)
}

func TestWatchOverlapDropConnContextCancel(t *testing.T) {
	f := func(clus *integration.ClusterV3) {
		clus.Members[0].DropConnections()
	}
	testWatchOverlapContextCancel(t, f)
}

func testWatchOverlapContextCancel(t *testing.T, f func(*integration.ClusterV3)) {
	defer testutil.AfterTest(t)
	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	// each unique context "%v" has a unique grpc stream
	n := 100
	ctxs, ctxc := make([]context.Context, 5), make([]chan struct{}, 5)
	for i := range ctxs {
		// make "%v" unique
		ctxs[i] = context.WithValue(context.TODO(), "key", i)
		// limits the maximum number of outstanding watchers per stream
		ctxc[i] = make(chan struct{}, 2)
	}

	// issue concurrent watches on "abc" with cancel
	cli := clus.RandClient()
	if _, err := cli.Put(context.TODO(), "abc", "def"); err != nil {
		t.Fatal(err)
	}
	ch := make(chan struct{}, n)
	for i := 0; i < n; i++ {
		go func() {
			defer func() { ch <- struct{}{} }()
			idx := rand.Intn(len(ctxs))
			ctx, cancel := context.WithCancel(ctxs[idx])
			ctxc[idx] <- struct{}{}
			wch := cli.Watch(ctx, "abc", clientv3.WithRev(1))
			f(clus)
			select {
			case _, ok := <-wch:
				if !ok {
					t.Fatalf("unexpected closed channel %p", wch)
				}
			// may take a second or two to reestablish a watcher because of
			// grpc backoff policies for disconnects
			case <-time.After(5 * time.Second):
				t.Errorf("timed out waiting for watch on %p", wch)
			}
			// randomize how cancel overlaps with watch creation
			if rand.Intn(2) == 0 {
				<-ctxc[idx]
				cancel()
			} else {
				cancel()
				<-ctxc[idx]
			}
		}()
	}
	// join on watches
	for i := 0; i < n; i++ {
		select {
		case <-ch:
		case <-time.After(5 * time.Second):
			t.Fatalf("timed out waiting for completed watch")
		}
	}
}

// TestWatchCanelAndCloseClient ensures that canceling a watcher then immediately
// closing the client does not return a client closing error.
func TestWatchCancelAndCloseClient(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)
	cli := clus.Client(0)
	ctx, cancel := context.WithCancel(context.Background())
	wch := cli.Watch(ctx, "abc")
	donec := make(chan struct{})
	go func() {
		defer close(donec)
		select {
		case wr, ok := <-wch:
			if ok {
				t.Fatalf("expected closed watch after cancel(), got resp=%+v err=%v", wr, wr.Err())
			}
		case <-time.After(5 * time.Second):
			t.Fatal("timed out waiting for closed channel")
		}
	}()
	cancel()
	if err := cli.Close(); err != nil {
		t.Fatal(err)
	}
	<-donec
	clus.TakeClient(0)
}


text:
{% extends "_layouts/default.html" %}

{% block content %}

        {% for section in protocols %}

{{ section }}

            {% for protocol in protocols[section] %}

                        {{ protocol.name|safe }}

                {% endfor %}
                {% if section == 'Maintenance' %}
                    For common methods of C. elegans maintenance, see the WormBook chapter here.
                {% endif %}

            {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sling.jcr.resource.internal.helper.jcr;

import static org.apache.jackrabbit.JcrConstants.JCR_CONTENT;
import static org.apache.jackrabbit.JcrConstants.JCR_DATA;
import static org.apache.jackrabbit.JcrConstants.NT_FILE;
import static org.apache.jackrabbit.JcrConstants.NT_LINKEDFILE;

import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Iterator;
import java.util.Map;

import javax.jcr.Item;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;

import org.apache.sling.adapter.annotations.Adaptable;
import org.apache.sling.adapter.annotations.Adapter;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
import org.apache.sling.jcr.resource.internal.HelperData;
import org.apache.sling.jcr.resource.internal.JcrModifiableValueMap;
import org.apache.sling.jcr.resource.internal.JcrValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** A Resource that wraps a JCR Node */
@Adaptable(adaptableClass=Resource.class, adapters={
        @Adapter({Node.class, Map.class, Item.class, ValueMap.class}),
        @Adapter(value=InputStream.class, condition="If the resource is a JcrNodeResource and has a jcr:data property or is an nt:file node.")
})
class JcrNodeResource extends JcrItemResource<Node> { // this should be package private, see SLING-1414

    /** marker value for the resourceSupertType before trying to evaluate */
    private static final String UNSET_RESOURCE_SUPER_TYPE = "<unset>";

    /** default log */
    private static final Logger LOGGER = LoggerFactory.getLogger(JcrNodeResource.class);

    private String resourceType;

    private String resourceSuperType;

    private final HelperData helper;

    /**
     * Constructor
     * @param resourceResolver
     * @param path The path of the resource (lazily initialized if null)
     * @param node The Node underlying this resource
     * @param dynamicClassLoader Dynamic class loader for loading serialized objects.
     * @throws RepositoryException
     */
    public JcrNodeResource(final ResourceResolver resourceResolver,
                           final String path,
                           final String version,
                           final Node node,
                           final HelperData helper) {
        super(resourceResolver, path, version, node, new JcrNodeResourceMetadata(node));
        this.helper = helper;
        this.resourceSuperType = UNSET_RESOURCE_SUPER_TYPE;
    }

    /**
     * @see org.apache.sling.api.resource.Resource#getResourceType()
     */
    @Override
    public String getResourceType() {
        if ( this.resourceType == null ) {
            try {
                this.resourceType = getResourceTypeForNode(getNode());
            } catch (final RepositoryException e) {
                LOGGER.error("Unable to get resource type for node " + getNode(), e);
                this.resourceType = "<unknown resource type>";
            }
        }
        return resourceType;
    }

    /**
     * @see org.apache.sling.api.resource.Resource#getResourceSuperType()
     */
    @Override
    public String getResourceSuperType() {
        // Yes, this isn't how you're supposed to compare Strings, but this is intentional.
        if ( resourceSuperType == UNSET_RESOURCE_SUPER_TYPE ) {
            try {
                if (getNode().hasProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY)) {
                    resourceSuperType = getNode().getProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY).getValue().getString();
                }
            } catch (RepositoryException re) {
                // we ignore this
            }
            if ( resourceSuperType == UNSET_RESOURCE_SUPER_TYPE ) {
                resourceSuperType = null;
            }
        }
        return resourceSuperType;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <Type> Type adaptTo(Class<Type> type) {
        if (type == Node.class || type == Item.class) {
            return (Type) getNode(); // unchecked cast
        } else if (type == InputStream.class) {
            return (Type) getInputStream(); // unchecked cast
        } else if (type == Map.class || type == ValueMap.class) {
            return (Type) new JcrValueMap(getNode(), this.helper); // unchecked cast
        } else if (type == ModifiableValueMap.class ) {
            // check write
            try {
                getNode().getSession().checkPermission(getPath(),
                    "set_property");
                return (Type) new JcrModifiableValueMap(getNode(), this.helper);
            } catch (AccessControlException ace) {
                // the user has no write permission, cannot adapt
                LOGGER.debug(
                    "adaptTo(ModifiableValueMap): Cannot set properties on {}",
                    this);
            } catch (RepositoryException e) {
                // some other problem, cannot adapt
                LOGGER.debug(
                    "adaptTo(ModifiableValueMap): Unexpected problem for {}",
                    this);
            }
        }

        // fall back to default implementation
        return super.adaptTo(type);
    }

    @Override
    public String toString() {
        return getClass().getSimpleName()
        	+ ", type=" + getResourceType()
        	+ ", superType=" + getResourceSuperType()
            + ", path=" + getPath();
    }

    // ---------- internal -----------------------------------------------------

    private Node getNode() {
        return getItem();
    }

    /**
     * Returns a stream to the jcr:data property if the
     * {@link #getNode() node} is an nt:file or nt:resource
     * node. Otherwise returns null.
     */
    private InputStream getInputStream() {
        // implement this for nt:file only
        final Node node = getNode();
        if (node != null) {
            try {
                // find the content node: for nt:file it is jcr:content
                // otherwise it is the node of this resource
                Node content = node.isNodeType(NT_FILE)
                        ? node.getNode(JCR_CONTENT)
                        : node.isNodeType(NT_LINKEDFILE) ? node.getProperty(JCR_CONTENT).getNode() : node;

                Property data;

                // if the node has a jcr:data property, use that property
                if (content.hasProperty(JCR_DATA)) {
                    data = content.getProperty(JCR_DATA);
                } else {
                    // otherwise try to follow default item trail
                    try {
                        Item item = content.getPrimaryItem();
                        while (item.isNode()) {
                            item = ((Node) item).getPrimaryItem();
                        }
                        data = (Property) item;

                    } catch (ItemNotFoundException infe) {
                        // we don't actually care, but log for completeness
                        LOGGER.debug("getInputStream: No primary items for {}", toString(), infe);
                        data = null;
                    }
                }

                if (data != null) {
                    return data.getBinary().getStream();
                }

            } catch (RepositoryException re) {
                LOGGER.error("getInputStream: Cannot get InputStream for " + this,
                    re);
            }
        }

        // fallback to non-streamable resource
        return null;
    }

    // ---------- Descendable interface ----------------------------------------

    @Override
    Iterator<Resource> listJcrChildren() {
        try {
            if (getNode().hasNodes()) {
                return new JcrNodeResourceIterator(getResourceResolver(), path, version,
                    getNode().getNodes(), this.helper, null);
            }
        } catch (final RepositoryException re) {
            LOGGER.error("listChildren: Cannot get children of " + this, re);
        }

        return null;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.eventhubs.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.eventhubs.fluent.models.PrivateLinkResourcesListResultInner;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in PrivateLinkResourcesClient. */
public interface PrivateLinkResourcesClient {
    /**
     * Gets lists of resources that supports Privatelinks.
     *
     * @param resourceGroupName Name of the resource group within the azure subscription.
     * @param namespaceName The Namespace name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return lists of resources that supports Privatelinks.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Mono<Response<PrivateLinkResourcesListResultInner>> getWithResponseAsync(
        String resourceGroupName, String namespaceName);

    /**
     * Gets lists of resources that supports Privatelinks.
     *
     * @param resourceGroupName Name of the resource group within the azure subscription.
     * @param namespaceName The Namespace name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return lists of resources that supports Privatelinks.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Mono<PrivateLinkResourcesListResultInner> getAsync(String resourceGroupName, String namespaceName);

    /**
     * Gets lists of resources that supports Privatelinks.
     *
     * @param resourceGroupName Name of the resource group within the azure subscription.
     * @param namespaceName The Namespace name.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return lists of resources that supports Privatelinks.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    PrivateLinkResourcesListResultInner get(String resourceGroupName, String namespaceName);

    /**
     * Gets lists of resources that supports Privatelinks.
     *
     * @param resourceGroupName Name of the resource group within the azure subscription.
     * @param namespaceName The Namespace name.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return lists of resources that supports Privatelinks.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<PrivateLinkResourcesListResultInner> getWithResponse(
        String resourceGroupName, String namespaceName, Context context);
}


text:
create view "Order Details Extended" AS
SELECT "Order Details".OrderID, "Order Details".ProductID, Products.ProductName,
	"Order Details".UnitPrice, "Order Details".Quantity, "Order Details".Discount,
	(CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS ExtendedPrice
FROM Products INNER JOIN "Order Details" ON Products.ProductID = "Order Details".ProductID
--ORDER BY "Order Details".OrderID


text:
import subprocess
import datetime

from ipf.error import StepError

from . import computing_activity
from . import computing_manager
from . import computing_service
from . import computing_share
from . import execution_environment
from . import accelerator_environment
from . import computing_manager_accel_info
from . import computing_share_accel_info

#######################################################################################################################

class ComputingServiceStep(computing_service.ComputingServiceStep):

    def __init__(self):
        computing_service.ComputingServiceStep.__init__(self)

    def _run(self):
        service = computing_service.ComputingService()
        service.Name = "Condor"
        service.Capability = ["executionmanagement.jobexecution",
                              "executionmanagement.jobdescription",
                              "executionmanagement.jobmanager",
                              "executionmanagement.executionandplanning",
                              "executionmanagement.reservation",
                              ]
        service.Type = "org.teragrid.Condor"
        service.QualityLevel = "production"

        return service

#######################################################################################################################

class ComputingManagerStep(computing_manager.ComputingManagerStep):

    def __init__(self):
        computing_manager.ComputingManagerStep.__init__(self)

    def _run(self):
        manager = computing_manager.ComputingManager()
        manager.ProductName = "Condor"
        manager.Name = "Condor"
        manager.Reservation = True
        #self.BulkSubmission = True

        return manager

#######################################################################################################################

class ComputingActivitiesStep(computing_activity.ComputingActivitiesStep):
    def __init__(self):
        computing_activity.ComputingActivitiesStep.__init__(self)

        self._acceptParameter(
            "condor_q", "the path to the Condor condor_q program (default 'condor_q')", False)

    def _run(self):
        condor_q = self.params.get("condor_q", "condor_q")

        cmd = condor_q + " -long"
        logger.debug("running "+cmd)
        status, output = subprocess.getstatusoutput(cmd)
        if status != 0:
            raise StepError("condor_q failed: "+output+"\n")

        jobStrings = output.split("\n\n")

        jobs = []
        for jobString in jobStrings:
            job = self._getJob(jobString)
            if job != None and includeQueue(self.config, job.Queue, True):
                jobs.append(job)

        for job in jobs:
            job.id = job.LocalIDFromManager+"."+self._getSystemName()

        return jobs

    def _getJob(self, jobString):
        job = computing_activity.ComputingActivity()

        # put multi-lines on one line?

        clusterId = None
        procId = None
        usedWallTime = None
        usedCpuTime = None
        lines = jobString.split("\n")
        for line in lines:
            if line.startswith("ClusterId = "):
                clusterId = line.split()[2]
            if line.startswith("ProcId = "):
                procId = line.split()[2]
            # don't think there are any job.Name...
            if line.startswith("Owner = "):
                owner = line.split()[2]
                job.LocalOwner = owner[1:len(owner)-1]
            if line.startswith("TGProject = "):
                project = line.split()[2]
                job.Extension["LocalAccount"] = project[1:len(project)-1]
            # job.Queue doesn't apply
            if line.startswith("JobStatus = "):
                status = line.split()[2]
                if status == "0":
                    job.State = [computing_activity.ComputingActivity.STATE_PENDING,
                                 "htcondor:Unexpanded"]
                elif status == "1":
                    job.State = [computing_activity.ComputingActivity.STATE_PENDING,
                                 "htcondor:Idle"]
                elif status == "2":
                    job.State = [computing_activity.ComputingActivity.STATE_RUNNING,
                                 "htcondor:Running"]
                elif status == "3":
                    job.State = [computing_activity.ComputingActivity.STATE_TERMINATED,
                                 "htcondor:Removed"]
                elif status == "4":
                    job.State = [computing_activity.ComputingActivity.STATE_FINISHED,
                                 "htcondor:Completed"]
                elif status == "5":
                    job.State = [computing_activity.ComputingActivity.STATE_HELD,
                                 "htcondor:Held"]
                elif status == "6":
                    job.State = [computing_activity.ComputingActivity.FAILED,
                                 "htcondor:Submission_err"]
                elif status == "7":
                    job.State = [computing_activity.ComputingActivity.SUSPENDED,
                                 "htcondor:Suspended"]
                else:
                    self.warning(
                        "found unknown Condor job status '" + status + "'")
                    job.State = [
                        computing_activity.ComputingActivity.STATE_UNKNOWN]

            # not sure if this is right - don't see any mpi jobs for comparison
            if line.startswith("MinHosts = "):
                job.RequestedSlots = int(line.split()[2])
                if usedWallTime != None:
                    job.UsedTotalWallTime = usedWallTime * job.RequestedSlots
                if usedCpuTime != None:
                    job.UsedTotalCpuTime = usedCpuTime * job.RequestedSlots

            # job.RequestedTotalWallTime doesn't apply

            if line.startswith("RemoteWallClockTime = "):
                if float(line.split()[2]) > 0:
                    usedWallTime = float(line.split()[2])
                    if job.RequestedSlots != None:
                        job.UsedTotalWallTime = usedWallTime * job.RequestedSlots
            if line.startswith("RemoteUserCpu = "):
                if float(line.split()[2]) > 0:
                    usedCpuTime = float(line.split()[2])
                    if job.RequestedSlots != None:
                        job.UsedTotalCpuTime = usedCpuTime * job.RequestedSlots

            if line.startswith("QDate = "):
                job.SubmissionTime = self._getDateTime(line.split()[2])
                job.ComputingManagerSubmissionTime = job.SubmissionTime
            if line.startswith("JobStartDate = "):
                job.StartTime = self._getDateTime(line.split()[2])
            if line.startswith("CompletionDate = "):
                date = line.split()[2]
                if date != "0":
                    job.ComputingManagerEndTime = self._getDateTime(date)

        if clusterId == None or procId == None:
            self.error("didn't find cluster or process ID in " + jobString)
            return None

        job.LocalIDFromManager = clusterId+"."+procId

        return job

    monthDict = {"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6,
                 "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12}

    def _getDateTime(self, aStr):
        # string containing the epoch time
        return datetime.datetime.fromtimestamp(float(aStr), localtzoffset())

#######################################################################################################################

class ComputingSharesStep(computing_share.ComputingSharesStep):

    def __init__(self):
        computing_share.ComputingSharesStep.__init__(self)

        self._acceptParameter(
            "qstat", "the path to the PBS qstat program (default 'qstat')", False)

    def _run(self):
        return []

#######################################################################################################################

class ExecutionEnvironmentsStep(execution_environment.ExecutionEnvironmentsStep):

    def __init__(self):
        execution_environment.ExecutionEnvironmentsStep.__init__(self)

        self._acceptParameter("condor_status",
                              "the path to the Condor condor_status program (default 'condor_status')",
                              False)

    def _run(self):
        condor_status = self.params.get("condor_status", "condor_status")

        cmd = condor_status + " -long"
        info.debug("running "+cmd)
        status, output = subprocess.getstatusoutput(cmd)
        if status != 0:
            raise StepError("condor_status failed: "+output+"\n")

        node_strings = output.split("\n\n")

        hosts = []
        for node_string in node_strings:
            host = self._getHost(node_string)
            if self._goodHost(host):
                hosts.append(host)

        return self._groupHosts(hosts)

    def _getHost(self, node_str):
        host = execution_environment.ExecutionEnvironment()

        load = None
        lines = node_str.split("\n")
        # ID set by ExecutionEnvironment
        for line in lines:
            if line.startswith("Name = "):
                host.Name = line.split()[2]
                host.Name = host.Name[1:len(host.Name)-1]
            if line.startswith("State = "):
                state = line.split()[2]
                state = state[1:len(state)-1]
                if state == "Owner":
                    host.UsedInstances = 0
                    host.UnavailableInstances = 1
                elif state == "Unclaimed":
                    host.UsedInstances = 0
                    host.UnavailableInstances = 0
                elif state == "Matched":
                    host.UsedInstances = 1
                    host.UnavailableInstances = 0
                elif state == "Claimed":
                    host.UsedInstances = 1
                    host.UnavailableInstances = 0
                elif state == "Preempting":
                    host.UsedInstances = 1
                    host.UnavailableInstances = 0
                else:
                    logger.warn("unknown state: "+state)
                    host.UsedInstances = 0
                    host.UnavailableInstances = 1
                host.TotalInstances = 1
                if load != None:
                    if host.UsedInstances > 0:
                        host.Extension["UsedAverageLoad"] = load
                    elif host.UnavailableInstances == 0:
                        host.Extension["AvailableAverageLoad"] = load
            if line.startswith("LoadAvg = "):
                load = float(line.split()[2])
                if host.TotalInstances != None:
                    if host.UsedInstances > 0:
                        host.Extension["UsedAverageLoad"] = load
                    elif host.UnavailableInstances == 0:
                        host.Extension["AvailableAverageLoad"] = load
            if line.startswith("Cpus = "):
                host.PhysicalCPUs = int(line.split()[2])
                host.LogicalCPUs = host.PhysicalCPUs
            if line.startswith("Memory = "):
                host.MainMemorySize = int(line.split()[2])  # assuming MB
            if line.startswith("VirtualMemory = "):
                memSize = line.split()[2]
                if memSize != "0":
                    host.VirtualMemorySize = int(memSize)  # assuming MB
            if line.startswith("OpSys = "):
                host.OSFamily = line.split()[2].lower()
                host.OSFamily = host.OSFamily[1:len(host.OSFamily)-1]
            if line.startswith("Arch = "):
                host.Platform = line.split()[2].lower()
                host.Platform = host.Platform[1:len(host.Platform)-1]
            if line.startswith("CheckpointPlatform = "):
                host.OSVersion = line.split()[4]

        return host

#######################################################################################################################

class AcceleratorEnvironmentsStep(accelerator_environment.AcceleratorEnvironmentsStep):
    def __init__(self):
        accelerator_environment.AcceleratorEnvironmentsStep.__init__(self)

        self._acceptParameter(
            "scontrol", "the path to the SLURM scontrol program (default 'scontrol')", False)

    def _run(self):
        # get info on the nodes
        return

#######################################################################################################################

class ComputingManagerAcceleratorInfoStep(computing_manager_accel_info.ComputingManagerAcceleratorInfoStep):

    def __init__(self):
        computing_manager_accel_info.ComputingManagerAcceleratorInfoStep.__init__(
            self)

    def _run(self):
        manager_accel_info = computing_manager_accel_info.ComputingManagerAcceleratorInfo()

        return manager_accel_info

#######################################################################################################################

class ComputingShareAcceleratorInfoStep(computing_share_accel_info.ComputingShareAcceleratorInfoStep):

    def __init__(self):
        computing_share_accel_info.ComputingShareAcceleratorInfoStep.__init__(
            self)

    def _run(self):
        share_accel_info = computing_share_accel_info.ComputingShareAcceleratorInfo()
        return share_accel_info

#######################################################################################################################


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

package cmd

import (
	"io/ioutil"

	"github.com/Sirupsen/logrus"
)

// consoleLogger - default logger if not other logging is enabled.
type consoleLogger struct {
	Enable bool   `json:"enable"`
	Level  string `json:"level"`
}

// enable console logger.
func enableConsoleLogger() {
	clogger := serverConfig.GetConsoleLogger()
	if !clogger.Enable {
		// Disable console logger if asked for.
		log.Out = ioutil.Discard
		return
	}

	// log.Out and log.Formatter use the default versions.
	// Only set specific log level.
	lvl, err := logrus.ParseLevel(clogger.Level)
	fatalIf(err, "Unknown log level found in the config file.")

	log.Level = lvl
}


text:
  <md-content>

      <acme-navbar creation-date="main.creationDate"></acme-navbar>

'Allo, 'Allo!

        Always a pleasure scaffolding your apps.

      <md-button class="md-raised animated infinite" ng-class="main.classAnimation" ng-click="main.showToastr()">Splendid Toastr</md-button>

        With ♥ thanks to the contributions of<acme-malarkey extra-values="['Yeoman', 'Gulp', 'Angular']"></acme-malarkey>

      <md-card ng-repeat="awesomeThing in main.awesomeThings | orderBy:'rank'">
        <md-card-content>

{{ awesomeThing.title }}

{{ awesomeThing.description }}

        </md-card-content>

          <md-button ng-href="{{ awesomeThing.url }}">Website</md-button>

      </md-card>

  </md-content>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour
{
    public GameObject enemy;

    public float width = 10;
    public float height = 5;

    public float xmax;
    public float xmin;
    public float ymin;
    public float ymax;

    public float spawnDelay = 0.5f;

    public float speed = 1f;
    public float padding = 10;

    public PlayerController player;

    public bool TrackingPlayer;
    public bool MovingRight;

	void Start()
    {

        player = FindObjectOfType<PlayerController>();

        var distance = transform.position.z - Camera.main.transform.position.z;
        var leftMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
        var rightMost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance));
        var topMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, distance));
        var bottomMost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance));
        xmin = leftMost.x + padding;
        xmax = rightMost.x - padding;
        ymin = bottomMost.y;
        ymax = topMost.y;

        SpawnUntilFull();

	}
    void SpawnEnemies()
    {
        foreach (Transform child in transform)
        {
            var prefab = Instantiate(enemy, child.position, Quaternion.identity);
            prefab.transform.parent = child;
        }
    }

    void SpawnUntilFull()
    {
        var next = NextFreePosition();
        if (!next)
        {
            return;
        }

        var prefab = Instantiate(enemy, next.position, Quaternion.identity);
        prefab.transform.parent = next;
        if (NextFreePosition())
        {
            Invoke("SpawnUntilFull", spawnDelay);
        }
    }
    private void OnDrawGizmos()
    {
        Gizmos.DrawWireCube(transform.position, new Vector3(width, height, 0));
        //
    }

    void Update()
    {
        if(transform.position.x > xmax )
        {
            MovingRight = false;
        }
        else if(transform.position.x < xmin)
        {
            MovingRight = true;
        }

        if (TrackingPlayer)
        {
            var playerPos = player.transform.position;

            transform.position += new Vector3(playerPos.x * speed * Time.deltaTime, 0, 0);

            var clamped = new Vector3(Mathf.Clamp(transform.position.x, xmin, xmax), Mathf.Clamp(transform.position.y, ymin, ymax), 0f);
            transform.position = clamped;
        }
        else if (MovingRight)
        {
            transform.position += Vector3.right * speed * Time.deltaTime;
        }
        else
        {
            transform.position += Vector3.left * speed * Time.deltaTime;
        }

        if (AllMembersDead())
        {
            print("All members dead");
            SpawnUntilFull();
        }
    }
    Transform NextFreePosition()
    {
        foreach(Transform child in transform)
        {
            if(child.childCount == 0)
            {
                return child;
            }
        }
        return null;
    }
    bool AllMembersDead()
    {
        foreach(Transform child in transform)
        {
            if(child.childCount > 0)
            {
                return false;
            }
        }
        return true;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>

      <title>raycoarana.com</title>

   <link>http://raycoarana.com/</link>
   <description>My coding adventures and other random stuff</description>
   <language>en-uk</language>
   <managingEditor> Rayco Araña</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />

	<item>
	  <title>RoboRouter, mi primera librería OpenSource</title>
	  <link>//blog/2014/11/roborouter/</link>
	  <author>Rayco Araña</author>
	  <pubDate>2014-11-03T23:17:07+01:00</pubDate>
	  <guid>//blog/2014/11/roborouter/</guid>
	  <description><![CDATA[

Hace tiempo que no escribo nada en el Blog, pero hoy tengo el orgullo de presentar mi primera librería OpenSource: RoboRouter. Es para Android y disponible a través de Maven/Gradle.

¿Qué es RoboRouter?

RoboRouter es un pequeña librería -de apenas dos clases- que permite mediante la activación/desactivación de componentes manejar el punto de arranque de nuestra aplicación cuando esta tiene una pantalla de inicio de sesión y/o un asistente de bienvenida o tutorial inicial. Cosas que es muestran escasamente una vez en la vida de la aplicación en el móvil de un usuario y que no debería ensuciar el código de la actividad principal con la que arrancamos la aplicación normalmente. RoboRouter permite gestionar este tipo de escenarios de una forma muy fácil y sin apenas escribir código.

Pasaos por GitHub y mirad como funciona, descargad el proyecto de ejemplo y jugad con él. Cualquier sugerencia será bienvenida.

raycoarana/roborouter

??

 — Read More

Latest commit to the master branch on
Download as zip

	  ]]></description>
	</item>

	<item>
	  <title>Parcelables con Android AutoParcel</title>
	  <link>//blog/2014/06/parcelables-con-android-autoparcel/</link>
	  <author>Rayco Araña</author>
	  <pubDate>2014-06-09T22:29:34+02:00</pubDate>
	  <guid>//blog/2014/06/parcelables-con-android-autoparcel/</guid>
	  <description><![CDATA[

Cuando vamos a crear una app en Android y tenemos que pasar datos entre Activities y/o Fragments, el sistema operativo nos brinda la posibilidad de usar un Bundle, ya sea a través del Intent (y el Bundle de extras) o a través del método setArguments() de los Fragments. Esta es la manera idónea de pasar datos entre componentes, ya que no crea acoplamientos poco deseables, además estos se gestionan de manera automática por el sistema, por lo que no debemos preocuparnos de qué pasa con ellos si el sistema ha tenido que recrear el Activity o Fragment debido al ciclo de vida de la aplicación.

El problema viene con los tipos de datos que nos permite almacenar un Bundle, estos son tipos básicos u objetos que implementen la interfaz Serializable o Parcelable. A la hora de implementar una u otra interfaz, la primera es sencilla, con solo hacer que nuestra clase implemente la interfaz Serializable el sistema por medio de reflexión es capaz de serializar el objeto a una representación binaria que se puede persistir. En el caso de Parcelable, sin embargo, debemos implementar dos métodos para serializar -writeToParcel()- y deserializar -constructor- el objeto. Además debemos escribirlo con sumo cuidado y en perfecto orden inverso o no funcionará, algo muy tedioso y difícil de mantener.

¿Porqué usar Parcelable sobre Serializable?

La principal razón para implementar Parcelable sobre Serializable es su velocidad de ejecución, se habla de hasta 10x más rápido trabajar con objetos Parcelable. Si estamos en un entorno móvil, esto se traduce no solo en mayor rapidez, sino también en menor consumo de batería, algo que nunca debemos obviar a la hora de desarrollar apps.
Como decimos esta gran ventaja en cuanto a velocidad viene con un precio y es que la implementación y sobre todo el mantenimiento de este tipo de objetos es muy tediosa, siendo una tarea muy repetitiva y donde es muy fácil cometer errores.

Android AutoParcel al rescate

Para solucionar esto, existe una librería muy interesante, o más que librería deberíamos hablar de plug-in para Gradle, que en tiempo de compilación, es capaz de generar el código de serialización y deserialización de nuestros objetos. Al ser en tiempo de compilación, no penaliza en absoluto la ejecución y nos beneficiamos de no tener que lidiar con los tediosos métodos de la interfaz Parcelable. Esta se llama Android AutoParcel y es un port de la librería Google AutoValue.

Vamos a ver cómo podemos integrar fácilmente este plug-in en nuestros proyectos y cómo usarlo. Lo primero será modificar el fichero raíz build.gradle, donde agregaremos en las dependencias la siguiente línea:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.11.+'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:+'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

Ahora nos vamos al fichero build.gradle de la aplicación, lo primero será aplicar el plug-in android-apt y luego agregamos en la sección de dependencias del proyecto tanto el procesador que generará el código en tiempo de compilación como la librería con las anotaciones de AutoParcel.

apply plugin: 'android'
apply plugin: 'android-apt'

android {
    ...
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.github.frankiesardo:android-auto-value:+'
    apt 'com.github.frankiesardo:android-auto-value-processor:+'
}

Ahora refrescamos el proyecto y vamos a escribir nuestro primer objeto con AutoParcel. Nuestras clases tendrán que ser abstractas y por cada propiedad que queramos que tenga, debemos generar un método abstracto para obtener su valor.

import android.auto.value.AutoValue;
import android.os.Parcelable;

@AutoValue
public abstract class Foo implements Parcelable {

   public abstract String fooString();
   public abstract int fooInteger();

}

Solo nos falta una forma para poder construir objetos de tipo Foo, para ello agregamos un método estático con todos los valores e internamente y llamaremos en su interior al constructor del objeto que AutoParcel genera. El orden de los parámetros será el mismo con el que hemos escrito nuestra clase abstracta. Al momento de escribir este código muy probablemente la clase AutoValue_Foo aún no exista, debemos compilar para que el generador se ejecute y cree la clase.

import android.auto.value.AutoValue;
import android.os.Parcelable;

@AutoValue
public abstract class Foo implements Parcelable {

   public abstract String fooString();
   public abstract int fooInteger();

   public static final Foo create(String fooString, int fooInteger) {
      return new AutoValue_Foo(fooString, fooInteger);
   }

}

Y con esto ya está todo, de esta forma tan simple podemos ahora generar objetos que utilizar como argumentos o extras para los Fragments y Activities que usemos en nuestras aplicaciones, reduciendo la cantidad de código que tenemos que escribir considerablemente y sin caer en malas prácticas acoplando los componentes de nuestra aplicación.

Más info

Puedes obtener más info y acceder al código en su página en GitHub.

frankiesardo/auto-parcel

??

 — Read More

Latest commit to the master branch on
Download as zip

	  ]]></description>
	</item>

</channel>
</rss>


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.nio.charset.spi.CharsetProvider
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_DECL
#define J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_DECL

namespace j2cpp { namespace java { namespace nio { namespace charset { class Charset; } } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace util { class Iterator; } } }

#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/nio/charset/Charset.hpp>
#include <java/util/Iterator.hpp>

namespace j2cpp {

namespace java { namespace nio { namespace charset { namespace spi {

	class CharsetProvider;
	class CharsetProvider
		: public object<CharsetProvider>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)

		explicit CharsetProvider(jobject jobj)
		: object<CharsetProvider>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;

		local_ref< java::util::Iterator > charsets();
		local_ref< java::nio::charset::Charset > charsetForName(local_ref< java::lang::String >  const&);
	}; //class CharsetProvider

} //namespace spi
} //namespace charset
} //namespace nio
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_IMPL
#define J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_IMPL

namespace j2cpp {

java::nio::charset::spi::CharsetProvider::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

local_ref< java::util::Iterator > java::nio::charset::spi::CharsetProvider::charsets()
{
	return call_method<
		java::nio::charset::spi::CharsetProvider::J2CPP_CLASS_NAME,
		java::nio::charset::spi::CharsetProvider::J2CPP_METHOD_NAME(1),
		java::nio::charset::spi::CharsetProvider::J2CPP_METHOD_SIGNATURE(1),
		local_ref< java::util::Iterator >
	>(get_jobject());
}

local_ref< java::nio::charset::Charset > java::nio::charset::spi::CharsetProvider::charsetForName(local_ref< java::lang::String > const &a0)
{
	return call_method<
		java::nio::charset::spi::CharsetProvider::J2CPP_CLASS_NAME,
		java::nio::charset::spi::CharsetProvider::J2CPP_METHOD_NAME(2),
		java::nio::charset::spi::CharsetProvider::J2CPP_METHOD_SIGNATURE(2),
		local_ref< java::nio::charset::Charset >
	>(get_jobject(), a0);
}

J2CPP_DEFINE_CLASS(java::nio::charset::spi::CharsetProvider,"java/nio/charset/spi/CharsetProvider")
J2CPP_DEFINE_METHOD(java::nio::charset::spi::CharsetProvider,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::nio::charset::spi::CharsetProvider,1,"charsets","()Ljava/util/Iterator;")
J2CPP_DEFINE_METHOD(java::nio::charset::spi::CharsetProvider,2,"charsetForName","(Ljava/lang/String;)Ljava/nio/charset/Charset;")

} //namespace j2cpp

#endif //J2CPP_JAVA_NIO_CHARSET_SPI_CHARSETPROVIDER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
#include <aws/servicediscovery/model/GetInstancesHealthStatusRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ServiceDiscovery::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetInstancesHealthStatusRequest::GetInstancesHealthStatusRequest() :
    m_serviceIdHasBeenSet(false),
    m_instancesHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String GetInstancesHealthStatusRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_serviceIdHasBeenSet)
  {
   payload.WithString("ServiceId", m_serviceId);

  }

  if(m_instancesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> instancesJsonList(m_instances.size());
   for(unsigned instancesIndex = 0; instancesIndex < instancesJsonList.GetLength(); ++instancesIndex)
   {
     instancesJsonList[instancesIndex].AsString(m_instances[instancesIndex]);
   }
   payload.WithArray("Instances", std::move(instancesJsonList));

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetInstancesHealthStatusRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53AutoNaming_v20170314.GetInstancesHealthStatus"));
  return headers;

}


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>IoT Controller</title>
    <link rel="stylesheet" type="text/css" href="./controller.css">

IoT Controller

LED controll

      <button class="btn" onclick="led('on')" disabled/>Turn On</button>
      <button class="btn" onclick="led('off')" disabled/>Turn Off</button>

Button Reciver

    Press the button on your hardware


text:
从早期使用Fortran开始,通过程序和子程序构成一个系统,到现在为止,program包含的特性只有Function这一项留到了现在,下面是摘自FitNesse工具的一段代码,这个函数不仅很长而且还有重复的code、奇怪的字符串,很多奇怪的数据类型和APIs。尝试着读读看,看你能理解多少。

    public static SeSetup) throws Exception {
        WikiPage wikiPage = pageData.getWikiPage();
        StringBuffer buffer = new StringBuffer();
        if (pageData.hasAttribute("Test")) {
            if (includeSuiteSetup) {
                WikiPage suiteSetup = PageCrawlerImpl.getInheritedPage(SuiteResponder.SUITE_SETUP_NAME, wikiPage);
                if (suiteSetup! = null) {
                    WikiPagePath pagePath = suiteSetup.getPageCrawler().getFullPath(suiteSetup);
                    String pagePathName = PathParser.render(pagePath);
                    buffer.append("!include -setup.").
                        .append(pagePathName)
                        .append("\n");
                }
            }

            WikiPage setup = PageCrawlerImpl.getInteritedPage("Setup", wikiPage);
            if (setup != null) {
                WikiPagePath setupPath = wikiPage.getPageCrawler().getFullPath(setup);
                String setupPathName = PathParser.render(setupPath);
                buffer.append("!include -setup.")
                    .append(setupPathName)
                    .append("\n");
            }
        }

        buffer.append(pageData.getContent);

        if (pageData.hasAttribute("Test")) {
            WikiPage teardown = PageCrawlerImpl.getInheritedPage("TearDown", wikiPage);
            if (teardown != null) {
                WikiPagePath tearDownPath = wikiPage.getPageCrawler().getFullPath(teardown);
                String tearDownPathName = PathPaser.rander(tearDownPath);
                buffer.append("!include -teardown.")
                    .append(tearDownPathName)
                    .append("\n");
            }

            if (includeSuiteSetup) {
                WikiPage pagePath = PageCrawlerImpl.getInheritedPage(SuiteResponder.SUITE_TEARDOWN_NAME, wikiPage);
                if (suiteTearDown != null) {
                    WikiPagePath pagePath = suiteTearDown.getPageCrawler().getFullPath(suiteTeardown);
                String pagePathName = PathPaser.rander(pagePath);
                buffer.append("!include -teardown.")
                    .append(pagePathName)
                    .append("\n");

                }
            }
        }
        pageData.setContent(buffer.toString());
        return pageData.getHtml();
    }

如果给你三分钟阅读时间,你能够弄明白这个函数吗?很有可能是不行的,这个代码显然不那么平缓,而且还有很多级抽象,以及大量字符串和调用,然而我们也有办法,通过一些命名和重构来解决这个问题。看下面的代码:

    public static String renderPageWithSetupsAndTeardowns (PageData pageData, boolean isSuite) throws Exception {
        boolean isTestPage = pageData.getAttribute.hasAttribute("Test");
        if (isTestPage) {
            WikiPage testPage = pageData.getWIkiPage();
            StringBuffer new PageConent = new StringBuffer();
            includeSetupPages(testPage, newPageContent, isSuite);
            newPageContent.append(pageData.getContent());
            includeTeardownPages(testPage, newPageContent, isSuite);
            pageData.setContent(newPageContent.toString());
        }

        return pageData.getHtml();
    }

除非你是学习FitNesse代码的学生,否则你不能直接看出代码的很多细节,不过现在理解这个代码的行为对你来说是比较容易的。如果你熟悉JUnit的话就很容易看出这是属于某个测试框架的代码。


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Enters a given Gift Certificate into the check balance field an subints it</description>
  <parameter name="giftcode"/>
  <command name="type" target="id=dwfrm_giftcert_balance_giftCertID" value="@{giftcode}"/>
  <command name="clickAndWait" target="id=CheckBalanceButton"/>
</scriptmodule>


text:
using System;
using ToolKit.Data;

namespace SuggestionBox.Data.Entities
{
    /// <summary>
    /// Comment Entity
    /// </summary>
    public class Comment : Entity
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Comment"/> class.
        /// </summary>
        // ReSharper disable DoNotCallOverridableMethodsInConstructor
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
            "CA2214:DoNotCallOverridableMethodsInConstructors",
            Justification = "Entities Always Have Virtual Members")]
        public Comment()
        {
            Blocked = false;
            Liked = 0;
            WhenPosted = DateTime.Now;
        }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="Comment"/> is blocked.
        /// </summary>
        /// <value><c>true</c> if blocked; otherwise, <c>false</c>.</value>
        public virtual bool Blocked { get; set; }

        /// <summary>
        /// Gets or sets the number of people who like this comment.
        /// </summary>
        /// <value>The liked.</value>
        public virtual int Liked { get; set; }

        /// <summary>
        /// Gets or sets the parent question of this comment
        /// </summary>
        /// <value>The parent question of this comment</value>
        public virtual Question ParentQuestion { get; set; }

        /// <summary>
        /// Gets or sets the text of the comment.
        /// </summary>
        /// <value>The text of the comment.</value>
        public virtual string Text { get; set; }

        /// <summary>
        /// Gets or sets when this comment was posted.
        /// </summary>
        /// <value>The date and time when this comment was posted.</value>
        public virtual DateTime WhenPosted { get; set; }
    }
}


text:
package main

import (
	// "errors"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	// "strings"
	"syscall"
)

// EnvironmentKeyValue ...
type EnvironmentKeyValue struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

// CommandModel ...
type CommandModel struct {
	Command          string                `json:"command"`
	WorkingDirectory string                `json:"working_directory"`
	LogFilePath      string                `json:"log_file_path"`
	Environments     []EnvironmentKeyValue `json:"environments"`
}

// RunCommandInDirWithArgsEnvsAndWriters ...
func RunCommandInDirWithArgsEnvsAndWriters(dirPath string, command string, cmdArgs []string, cmdEnvs []string, stdOutWriter, stdErrWriter io.Writer) (int, error) {
	c := exec.Command(command, cmdArgs...)
	c.Env = append(os.Environ(), cmdEnvs...)
	// c.Env = cmdEnvs // only the supported envs, no inherited ones
	c.Stdout = stdOutWriter
	c.Stderr = stdErrWriter
	if dirPath != "" {
		c.Dir = dirPath
	}

	cmdExitCode := 0
	if err := c.Run(); err != nil {
		// Did the command fail because of an unsuccessful exit code
		if exitError, ok := err.(*exec.ExitError); ok {
			waitStatus, ok := exitError.Sys().(syscall.WaitStatus)
			if !ok {
				return 1, errors.New("Failed to cast exit status")
			}
			cmdExitCode = waitStatus.ExitStatus()
		}
		return cmdExitCode, err
	}
	return 0, nil
}

// func RunCommandInDirWithArgs(dirPath string, command string, cmdArgs []string) error {
// 	return RunCommandInDirWithArgsAndWriters(dirPath, command, cmdArgs, os.Stdout, os.Stderr)
// }

// func ExecuteUnlockKeychain(keychainName, keychainPsw string) error {
// 	cmdArgs := []string{
// 		"-v", "unlock-keychain", "-p", keychainPsw, keychainName,
// 	}
// 	err := RunCommandInDirWithArgsAndWriters("", "security", cmdArgs, CommandLogWriter, CommandLogWriter)
// 	return err
// }

// ExecuteCommand ...
func ExecuteCommand(cmdToRun CommandModel) (int, error) {
	if ConfigIsVerboseLogMode {
		if err := WriteLineToCommandLog("[[command-start]]"); err != nil {
			return 0, err
		}
	}

	// // unlock keychain
	// if err := ExecuteUnlockKeychain(commandParams.KeychainName, commandParams.KeychainPassword); err != nil {
	// 	return err
	// }

	if ConfigIsVerboseLogMode {
		if err := WriteLineToCommandLog(fmt.Sprintf("Command to run: $ %s", cmdToRun.Command)); err != nil {
			log.Println(" [!] Failed to write 'command to run' into Command Log")
		}
	}

	cmdExec := "/bin/bash"
	cmdArgs := []string{
		"--login",
		"-c",
		cmdToRun.Command,
	}
	cmdEnvs := []string{}
	envLength := len(cmdToRun.Environments)
	if envLength > 0 {
		cmdEnvs = make([]string, envLength, envLength)
		for idx, aEnvPair := range cmdToRun.Environments {
			cmdEnvs[idx] = aEnvPair.Key + "=" + aEnvPair.Value
		}
	}

	//
	cmdExitCode, commandErr := RunCommandInDirWithArgsEnvsAndWriters(cmdToRun.WorkingDirectory, cmdExec, cmdArgs, cmdEnvs, CommandLogWriter, CommandLogWriter)

	if commandErr != nil {
		if err := WriteLineToCommandLog(fmt.Sprintf("Command failed: %s", commandErr)); err != nil {
			log.Println(" [!] Failed to write 'Command failed' into Command Log")
		}
	}

	if ConfigIsVerboseLogMode {
		if err := WriteLineToCommandLog("[[command-finished]]"); err != nil {
			log.Println(" [!] Failed to write '[[command-finished]]' into Command Log")
		}
	}
	return cmdExitCode, commandErr
}


text: type a = ??string;


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Archive for posts tagged with 'webdesign' | Lee Kelleher - Umbraco Consultant</title>
	<meta name="description" content="The personal website of Lee Kelleher; Umbraco Consultant">
	<meta name="keywords" content="leekelleher,kelleher,umbraco,asp.net,c#,csharp,xslt,mvc,mvp">
	<meta name="generator" content="Wyam">
	<meta name="twitter:card" content="summary">
	<meta name="twitter:site" content="@leekelleher">
	<meta name="twitter:url" property="og:url" content="https://leekelleher.com/tag/webdesign/">
	<meta name="twitter:title" property="og:title" content="Archive for posts tagged with 'webdesign'">
	<meta name="twitter:description" property="og:description" content="The personal website of Lee Kelleher; Umbraco Consultant">
	<meta name="twitter:image" property="og:image" content="https://leekelleher.com/assets/img/nxnw_300x300.jpg">
	<link rel="alternate" href="https://leekelleher.com/feed/" type="application/rss+xml">
	<link rel="canonical" href="https://leekelleher.com/tag/webdesign/">
	<link rel="pingback" href="https://webmention.io/leekelleher.com/xmlrpc">
	<link rel="webmention" href="https://webmention.io/leekelleher.com/webmention">
	<link rel="stylesheet" href="/assets/css/style.css">

Lee Kelleher

About

Now

Contact

Archive for posts tagged with 'webdesign'

Web Design Survey

				Posted on <time datetime="2007-04-25T19:36+01:00">25/04/2007</time>.
				Estimated read time:  under a minute (28 words)

Just took the A List Apart's Web Design Survey… they want to know more about people who make websites.

Tags: webdesign

Dodgy PNG Colour Rendering

				Posted on <time datetime="2007-04-20T16:17+01:00">20/04/2007</time>.
				Estimated read time:  under a minute (32 words)

I thought I was going mad, but it seems that browsers (specifically IE6/7 & FF) still render PNGs differently! (It's related to the Gamma Correction and Colour Correction)

Tags: browser, firefox, webdesign, webdev

For any feedback, comments or questions, feel free to ask me via my contact page, on Twitter, or on GitHub.

Be notified of new posts, subscribe to my RSS feed.

All content by Lee Kelleher (© 2006-2021) and licensed under Creative Commons. All code snippets are licensed under the MIT license.

This website is statically generated using Wyam. All code and content for this blog is available as open source on GitHub.


text:
require 'eh/myob/data/organisation_mapper'
require 'eh/myob/data/location_mapper'
require 'eh/myob/data/address_mapper'
require 'eh/myob/data/member_mapper'
require 'eh/myob/data/leave_category_mapper'
require 'eh/myob/data/leave_balance_mapper'
require 'eh/myob/data/work_type_mapper'
require 'eh/myob/data/employing_entity_mapper'
require 'eh/myob/data/pay_category_mapper'
require 'eh/myob/data/superannuation_fund_mapper'
require 'eh/myob/data/bank_account_mapper'
require 'eh/myob/data/payslip_mapper'
require 'eh/myob/data/tax_declaration_mapper'
require 'eh/myob/data/leave_request_mapper'
require 'eh/myob/data/util'


text: {{data.name}}


text: Cropping of Images via canvas using pure JavaScript.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ftt.elastic.match.core;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author nimeshagarwal
 */
public final class MatcherFactory {

    private static final Map<String, Matcher> matchers = new HashMap();

    public static void register() {
        Matcher matcher = new MagicalMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new EqualsMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new GreaterThanMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new GreaterThanEqualsMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new LessThanMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new LessThanEqualsMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new SimilarMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new SimilarCaseInsensitiveMatcher();
        matchers.put(matcher.getComparaorName(), matcher);

        matcher = new NotSimilarMatcher();
        matchers.put(matcher.getComparaorName(), matcher);
    }

    public static Matcher getInstance(String comparatorName) {

        if (matchers.isEmpty()) {
            register();
        }

        return matchers.get(comparatorName);
    }
}


text:
// *************************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
//   Support: support@scichart.com
//   Sales:   sales@scichart.com
//
// LogarithmicAxisView.xaml.cs is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
// *************************************************************************************

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using SciChart.Charting.Model.DataSeries;
using SciChart.Examples.ExternalDependencies.Data;
using SciChart.Charting.Model.Filters;
using SciChart.Charting.Visuals.PointMarkers;
using SciChart.Charting.Visuals.RenderableSeries;
using SciChart.Charting.Visuals.RenderableSeries.Animations;

namespace SciChart.Examples.Examples.FiltersAPI
{
    /// <summary>
    /// Interaction logic for FiltersAPIExample.xaml
    /// </summary>
    public partial class FiltersAPIExample : UserControl
    {
        private readonly XyDataSeries<TimeSpan, double> _originalData = new XyDataSeries<TimeSpan, double>();

        public FiltersAPIExample()
        {
            InitializeComponent();

            OnUpdatedData(1.0d, 0.01d);

            var filteredDataLinearTrendline = _originalData.ToLinearTrendline();
            var filteredDataPolynomialTrendline = _originalData.ToPolynomialTrend(3);
            var filteredDataScale = _originalData.Scale(0.5);
            var filteredDataOffset = _originalData.Offset(-50.0);
            var filteredDataSpline = _originalData.ToSpline(5);
            var filteredDataCustom = new CustomFilter(_originalData);

            var sweepAnimation1 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation2 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation3 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation4 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation5 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation6 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };
            var sweepAnimation7 = new SweepAnimation() { AnimationDelay = TimeSpan.FromSeconds(1), Duration = TimeSpan.FromSeconds(3) };

            _originalData.SeriesName = "Original Data";
            filteredDataLinearTrendline.SeriesName = "Linear Trendline";
            filteredDataPolynomialTrendline.SeriesName = "Polynomial (3rd Order)";
            filteredDataScale.SeriesName = "Scaled * 0.5";
            filteredDataOffset.SeriesName = "Offset -50";
            filteredDataSpline.SeriesName = "Spline, Tension=5";
            filteredDataCustom.FilteredDataSeries.SeriesName = "Custom Filter";

            sciChart.RenderableSeries.Add(new XyScatterRenderableSeries() { DataSeries = _originalData, Stroke = Colors.Red, PointMarker = new EllipsePointMarker() { Fill = Colors.Red, Stroke = Colors.Red }, SeriesAnimation = sweepAnimation1 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataLinearTrendline, StrokeThickness = 2, Stroke = Colors.GreenYellow, SeriesAnimation = sweepAnimation2 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataPolynomialTrendline, StrokeThickness = 2, Stroke = Colors.Yellow, SeriesAnimation = sweepAnimation3 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataScale, StrokeThickness = 2, Stroke = Colors.DeepSkyBlue, SeriesAnimation = sweepAnimation4 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataSpline, StrokeThickness = 1, Stroke = Colors.DeepSkyBlue, Opacity = 0.5, SeriesAnimation = sweepAnimation5 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataOffset, StrokeThickness = 2, Stroke = Color.FromArgb(0x77, 0xFF, 0x33, 0x33), SeriesAnimation = sweepAnimation6 });
            sciChart.RenderableSeries.Add(new FastLineRenderableSeries() { DataSeries = filteredDataCustom.FilteredDataSeries, StrokeThickness = 2, Stroke = Colors.MediumPurple, SeriesAnimation = sweepAnimation7 });

            sweepAnimation1.StartAnimation();
            sweepAnimation2.StartAnimation();
            sweepAnimation3.StartAnimation();
            sweepAnimation4.StartAnimation();
            sweepAnimation5.StartAnimation();
            sweepAnimation6.StartAnimation();
            sweepAnimation7.StartAnimation();
        }

        private void FiltersAPIExample_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void OnUpdatedData(double randomness, double curviness)
        {
            var someDummyData = CreateSomeScatterData(randomness, curviness);
            _originalData.Clear();
            _originalData.Append(someDummyData.XData.Select(x => TimeSpan.FromSeconds(x)), someDummyData.YData);
        }

        private DoubleSeries CreateSomeScatterData(double randomness, double curviness)
        {
            var doubleSeries = new DoubleSeries();
            Random r = new Random(0);
            const double c = 0;
            const double m = 0.02;

            // Create some data which looks like a scatter chart with points randomly spaced around a
            // slightly curved / linear trendline dataset
            //
            // this will be used to apply filters such as Trendline, Polynomial, Scale, Offset etc...
            for (int x = 0; x < 200; x++)
            {
                double y = (m * x + c + (r.NextDouble() * randomness)) * x * (1 + curviness);
                doubleSeries.Add(new XYPoint { X = x, Y = y });
            }

            return doubleSeries;
        }

        private void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (randomSlider == null || slopeSlider == null) return;
            OnUpdatedData(randomSlider.Value, slopeSlider.Value);
        }
    }
}