text:
package tabletmanager

import (
	"errors"
	"flag"
	"fmt"
	"html/template"
	"reflect"
	"strings"
	"testing"
	"time"

	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/binlog/binlogplayer"
	"github.com/youtube/vitess/go/vt/health"
	"github.com/youtube/vitess/go/vt/mysqlctl"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/memorytopo"
	"github.com/youtube/vitess/go/vt/vttablet/tabletserver"
	"github.com/youtube/vitess/go/vt/vttablet/tabletservermock"

	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

func TestHealthRecordDeduplication(t *testing.T) {
	now := time.Now()
	later := now.Add(5 * time.Minute)
	cases := []struct {
		left, right *HealthRecord
		duplicate   bool
	}{
		{
			left:      &HealthRecord{Time: now},
			right:     &HealthRecord{Time: later},
			duplicate: true,
		},
		{
			left:      &HealthRecord{Time: now, Error: errors.New("foo")},
			right:     &HealthRecord{Time: now, Error: errors.New("foo")},
			duplicate: true,
		},
		{
			left:      &HealthRecord{Time: now, ReplicationDelay: defaultDegradedThreshold / 2},
			right:     &HealthRecord{Time: later, ReplicationDelay: defaultDegradedThreshold / 3},
			duplicate: true,
		},
		{
			left:      &HealthRecord{Time: now, ReplicationDelay: defaultDegradedThreshold / 2},
			right:     &HealthRecord{Time: later, ReplicationDelay: defaultDegradedThreshold * 2},
			duplicate: false,
		},
		{
			left:      &HealthRecord{Time: now, Error: errors.New("foo"), ReplicationDelay: defaultDegradedThreshold * 2},
			right:     &HealthRecord{Time: later, ReplicationDelay: defaultDegradedThreshold * 2},
			duplicate: false,
		},
	}

	for _, c := range cases {
		if got := c.left.IsDuplicate(c.right); got != c.duplicate {
			t.Errorf("IsDuplicate %v and %v: got %v, want %v", c.left, c.right, got, c.duplicate)
		}
	}
}

func TestHealthRecordClass(t *testing.T) {
	cases := []struct {
		r     *HealthRecord
		state string
	}{
		{
			r:     &HealthRecord{},
			state: "healthy",
		},
		{
			r:     &HealthRecord{Error: errors.New("foo")},
			state: "unhealthy",
		},
		{
			r:     &HealthRecord{ReplicationDelay: defaultDegradedThreshold * 2},
			state: "unhappy",
		},
		{
			r:     &HealthRecord{ReplicationDelay: defaultDegradedThreshold / 2},
			state: "healthy",
		},
	}

	for _, c := range cases {
		if got := c.r.Class(); got != c.state {
			t.Errorf("class of %v: got %v, want %v", c.r, got, c.state)
		}
	}
}

var tabletAlias = &topodatapb.TabletAlias{Cell: "cell1", Uid: 42}

// fakeHealthCheck implements health.Reporter interface
type fakeHealthCheck struct {
	reportReplicationDelay time.Duration
	reportError            error
}

func (fhc *fakeHealthCheck) Report(isSlaveType, shouldQueryServiceBeRunning bool) (replicationDelay time.Duration, err error) {
	return fhc.reportReplicationDelay, fhc.reportError
}

func (fhc *fakeHealthCheck) HTMLName() template.HTML {
	return template.HTML("fakeHealthCheck")
}

func createTestAgent(ctx context.Context, t *testing.T, preStart func(*ActionAgent)) (*ActionAgent, chan<- *binlogplayer.VtClientMock) {
	ts := memorytopo.NewServer("cell1")

	if err := ts.CreateKeyspace(ctx, "test_keyspace", &topodatapb.Keyspace{}); err != nil {
		t.Fatalf("CreateKeyspace failed: %v", err)
	}

	if err := ts.CreateShard(ctx, "test_keyspace", "0"); err != nil {
		t.Fatalf("CreateShard failed: %v", err)
	}

	port := int32(1234)
	tablet := &topodatapb.Tablet{
		Alias:    tabletAlias,
		Hostname: "host",
		PortMap: map[string]int32{
			"vt": port,
		},
		Ip:       "1.0.0.1",
		Keyspace: "test_keyspace",
		Shard:    "0",
		Type:     topodatapb.TabletType_REPLICA,
	}
	if err := ts.CreateTablet(ctx, tablet); err != nil {
		t.Fatalf("CreateTablet failed: %v", err)
	}

	mysqlDaemon := &mysqlctl.FakeMysqlDaemon{MysqlPort: 3306}
	agent := NewTestActionAgent(ctx, ts, tabletAlias, port, 0, mysqlDaemon, preStart)

	vtClientMocksChannel := make(chan *binlogplayer.VtClientMock, 1)
	agent.BinlogPlayerMap = NewBinlogPlayerMap(ts, mysqlDaemon, func() binlogplayer.VtClient {
		return <-vtClientMocksChannel
	})

	agent.HealthReporter = &fakeHealthCheck{}

	return agent, vtClientMocksChannel
}

// TestHealthCheckControlsQueryService verifies that a tablet going healthy
// starts the query service, and going unhealthy stops it.
func TestHealthCheckControlsQueryService(t *testing.T) {
	// we need an actual grace period set, so lameduck is enabled
	*gracePeriod = 10 * time.Millisecond
	defer func() {
		*gracePeriod = 0
	}()

	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, nil)

	/// Consume the first health broadcast triggered by ActionAgent.Start():
	//  (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we
	//  should be serving.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "healthcheck not run yet", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}

	// first health check, should keep us as replica and serving,
	// and update the mysql port to 3306
	before := time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 12 * time.Second
	agent.runHealthCheck()
	ti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("First health check failed to go to replica: %v", ti.Type)
	}
	if ti.PortMap["mysql"] != 3306 {
		t.Errorf("First health check failed to update mysql port: %v", ti.PortMap["mysql"])
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: %v", agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 12); err != nil {
		t.Fatal(err)
	}

	// now make the tablet unhealthy
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 13 * time.Second
	agent.HealthReporter.(*fakeHealthCheck).reportError = fmt.Errorf("tablet is unhealthy")
	before = time.Now()
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Unhappy health check failed to stay as replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should not be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_REPLICA)
	}

	// first we get the lameduck broadcast, with no error and old
	// replication delay
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "", 12); err != nil {
		t.Fatal(err)
	}

	// then query service is disabled since we are unhealthy now.
	if err := expectStateChange(agent.QueryServiceControl, false, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	// and the associated broadcast
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "tablet is unhealthy", 13); err != nil {
		t.Fatal(err)
	}

	// and nothing more.
	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestErrSlaveNotRunningIsHealthy verifies that a tablet whose
// healthcheck reports health.ErrSlaveNotRunning is still considered
// healthy with high replication lag.
func TestErrSlaveNotRunningIsHealthy(t *testing.T) {
	*unhealthyThreshold = 10 * time.Minute
	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, nil)

	/// Consume the first health broadcast triggered by ActionAgent.Start():
	//  (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we
	//  should be serving.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "healthcheck not run yet", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}

	// health check returning health.ErrSlaveNotRunning, should
	// keep us as replica and serving
	before := time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 12 * time.Second
	agent.HealthReporter.(*fakeHealthCheck).reportError = health.ErrSlaveNotRunning
	agent.runHealthCheck()
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: %v", agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 10*60); err != nil {
		t.Fatal(err)
	}

	// and nothing more.
	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestQueryServiceNotStarting verifies that if a tablet cannot start the
// query service, it should not go healthy.
func TestQueryServiceNotStarting(t *testing.T) {
	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, func(a *ActionAgent) {
		// The SetServingType that will fail is part of Start()
		// so we have to do this here.
		a.QueryServiceControl.(*tabletservermock.Controller).SetServingTypeError = fmt.Errorf("test cannot start query service")
	})

	// we should not be serving.
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should not be running")
	}

	// There is no broadcast data to consume, we're just not
	// healthy from startup

	// Now we can run another health check, it will stay unhealthy forever.
	before := time.Now()
	agent.runHealthCheck()
	ti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Happy health check which cannot start query service should stay replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should not be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	bd := <-agent.QueryServiceControl.(*tabletservermock.Controller).BroadcastData
	if bd.RealtimeStats.HealthError != "test cannot start query service" {
		t.Errorf("unexpected HealthError: %v", *bd)
	}
	if agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: %v", agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType)
	}

	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestQueryServiceStopped verifies that if a healthy tablet's query
// service is shut down, the tablet goes unhealthy
func TestQueryServiceStopped(t *testing.T) {
	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, nil)

	/// Consume the first health broadcast triggered by ActionAgent.Start():
	//  (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we
	//  should be serving.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "healthcheck not run yet", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}

	// first health check, should keep us in replica / healthy
	before := time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 14 * time.Second
	agent.runHealthCheck()
	ti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("First health check failed to stay in replica: %v", ti.Type)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	want := topodatapb.TabletType_REPLICA
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != want {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, want)
	}

	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 14); err != nil {
		t.Fatal(err)
	}

	// shut down query service and prevent it from starting again
	// (this is to simulate mysql going away, tablet server detecting it
	// and shutting itself down). Intercept the message
	agent.QueryServiceControl.SetServingType(topodatapb.TabletType_REPLICA, false, nil)
	agent.QueryServiceControl.(*tabletservermock.Controller).SetServingTypeError = fmt.Errorf("test cannot start query service")
	if err := expectStateChange(agent.QueryServiceControl, false, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	// health check should now fail
	before = time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 15 * time.Second
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Happy health check which cannot start query service should stay replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should not be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	want = topodatapb.TabletType_REPLICA
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != want {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, want)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "test cannot start query service", 15); err != nil {
		t.Fatal(err)
	}
	// NOTE: No more broadcasts or state changes since SetServingTypeError is set
	// on the mocked controller and this disables its SetServingType().

	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestTabletControl verifies the shard's TabletControl record can disable
// query service in a tablet.
func TestTabletControl(t *testing.T) {
	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, nil)

	/// Consume the first health broadcast triggered by ActionAgent.Start():
	//  (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we
	//  should be serving.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "healthcheck not run yet", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	// first health check, should keep us in replica, just broadcast
	before := time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 16 * time.Second
	agent.runHealthCheck()
	ti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("First health check failed to go to replica: %v", ti.Type)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_REPLICA)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 16); err != nil {
		t.Fatal(err)
	}

	// now update the shard
	_, err = agent.TopoServer.UpdateShardFields(ctx, "test_keyspace", "0", func(si *topo.ShardInfo) error {
		si.TabletControls = []*topodatapb.Shard_TabletControl{
			{
				TabletType:          topodatapb.TabletType_REPLICA,
				DisableQueryService: true,
			},
		}
		return nil
	})
	if err != nil {
		t.Fatalf("UpdateShardFields failed: %v", err)
	}

	// now refresh the tablet state, as the resharding process would do
	agent.RefreshState(ctx)

	// check we shutdown query service
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}

	// check UpdateStream is still running
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}

	// Consume the health broadcast which was triggered due to the QueryService
	// state change from SERVING to NOT_SERVING.
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "", 16); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, false, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	// check running a health check will not start it again
	before = time.Now()
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 17 * time.Second
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Health check failed to go to replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_REPLICA)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "", 17); err != nil {
		t.Fatal(err)
	}
	// NOTE: No state change here since nothing has changed.

	// go unhealthy, check we go to error state and QS is not running
	agent.HealthReporter.(*fakeHealthCheck).reportError = fmt.Errorf("tablet is unhealthy")
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 18 * time.Second
	before = time.Now()
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Unhealthy health check should stay replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should not be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "tablet is unhealthy", 18); err != nil {
		t.Fatal(err)
	}
	// NOTE: No state change here since QueryService is already NOT_SERVING.
	want := topodatapb.TabletType_REPLICA
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != want {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, want)
	}

	// go back healthy, check QS is still not running
	agent.HealthReporter.(*fakeHealthCheck).reportError = nil
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 19 * time.Second
	before = time.Now()
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_REPLICA {
		t.Errorf("Healthy health check should go to replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if !agent.UpdateStream.IsEnabled() {
		t.Errorf("UpdateStream should be running")
	}
	if agent._healthyTime.Sub(before) < 0 {
		t.Errorf("runHealthCheck did not update agent._healthyTime")
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, false, "", 19); err != nil {
		t.Fatal(err)
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_REPLICA)
	}

	// now clear TabletControl, run health check, make sure we go
	// back healthy and serving.
	_, err = agent.TopoServer.UpdateShardFields(ctx, "test_keyspace", "0", func(si *topo.ShardInfo) error {
		si.TabletControls = nil
		return nil
	})
	if err != nil {
		t.Fatalf("UpdateShardFields failed: %v", err)
	}

	// now refresh the tablet state, as the resharding process would do
	agent.RefreshState(ctx)

	// QueryService changed back from SERVING to NOT_SERVING since refreshTablet()
	// re-read the topology and saw that REPLICA is still not allowed to serve.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 19); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestQueryServiceChangeImmediateHealthcheckResponse verifies that a change
// of the QueryService state or the tablet type will result into a broadcast
// of a StreamHealthResponse message.
func TestStateChangeImmediateHealthBroadcast(t *testing.T) {
	// BinlogPlayer will fail in the second retry because we don't fully mock
	// it. Retry faster to make it fail faster.
	flag.Set("binlog_player_retry_delay", "100ms")

	ctx := context.Background()
	agent, vtClientMocksChannel := createTestAgent(ctx, t, nil)

	/// Consume the first health broadcast triggered by ActionAgent.Start():
	//  (REPLICA, NOT_SERVING) goes to (REPLICA, SERVING). And we
	//  should be serving.
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "healthcheck not run yet", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_REPLICA); err != nil {
		t.Fatal(err)
	}

	// Run health check to turn into a healthy replica
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 12 * time.Second
	agent.runHealthCheck()
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_REPLICA {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_REPLICA)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 12); err != nil {
		t.Fatal(err)
	}

	// Run TER to turn us into a proper master, wait for it to finish.
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 19 * time.Second
	if err := agent.TabletExternallyReparented(ctx, "unused_id"); err != nil {
		t.Fatal(err)
	}
	select {
	case <-agent.finalizeReparentCtx.Done():
	}
	ti, err := agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_MASTER {
		t.Errorf("TER failed to go to master: %v", ti.Type)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_MASTER {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_MASTER)
	}

	// Consume the health broadcast (no replication delay as we are master)
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 0); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_MASTER); err != nil {
		t.Fatal(err)
	}

	// Run health check to make sure we stay good
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 20 * time.Second
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_MASTER {
		t.Errorf("First health check failed to go to master: %v", ti.Type)
	}
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should be running")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_MASTER {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_MASTER)
	}
	if _, err := expectBroadcastData(agent.QueryServiceControl, true, "", 20); err != nil {
		t.Fatal(err)
	}

	// Simulate a vertical split resharding where we set
	// SourceShards in the topo and enable filtered replication.
	_, err = agent.TopoServer.UpdateShardFields(ctx, "test_keyspace", "0", func(si *topo.ShardInfo) error {
		si.SourceShards = []*topodatapb.Shard_SourceShard{
			{
				Uid:      1,
				Keyspace: "source_keyspace",
				Shard:    "0",
				Tables: []string{
					"table1",
				},
			},
		}
		return nil
	})
	if err != nil {
		t.Fatalf("UpdateShardFields failed: %v", err)
	}

	// Mock out the BinlogPlayer client. Tell the BinlogPlayer not to start.
	vtClientMock := binlogplayer.NewVtClientMock()
	vtClientMock.AddResult(&sqltypes.Result{
		Fields:       nil,
		RowsAffected: 1,
		InsertID:     0,
		Rows: [][]sqltypes.Value{
			{
				sqltypes.MakeString([]byte("MariaDB/0-1-1234")),
				sqltypes.MakeString([]byte("DontStart")),
			},
		},
	})
	vtClientMocksChannel <- vtClientMock

	// Refresh the tablet state, as vtworker would do.
	// Since we change the QueryService state, we'll also trigger a health broadcast.
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 21 * time.Second
	agent.RefreshState(ctx)

	// (Destination) MASTER with enabled filtered replication mustn't serve anymore.
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	// Consume health broadcast sent out due to QueryService state change from
	// (MASTER, SERVING) to (MASTER, NOT_SERVING).
	// Since we didn't run healthcheck again yet, the broadcast data contains the
	// cached replication lag of 20 instead of 21.
	if bd, err := expectBroadcastData(agent.QueryServiceControl, false, "", 20); err == nil {
		if bd.RealtimeStats.BinlogPlayersCount != 1 {
			t.Fatalf("filtered replication must be enabled: %v", bd)
		}
	} else {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, false, topodatapb.TabletType_MASTER); err != nil {
		t.Fatal(err)
	}

	// Running a healthcheck won't put the QueryService back to SERVING.
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 22 * time.Second
	agent.runHealthCheck()
	ti, err = agent.TopoServer.GetTablet(ctx, tabletAlias)
	if err != nil {
		t.Fatalf("GetTablet failed: %v", err)
	}
	if ti.Type != topodatapb.TabletType_MASTER {
		t.Errorf("Health check failed to go to replica: %v", ti.Type)
	}
	if agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	if got := agent.QueryServiceControl.(*tabletservermock.Controller).CurrentTarget.TabletType; got != topodatapb.TabletType_MASTER {
		t.Errorf("invalid tabletserver target: got = %v, want = %v", got, topodatapb.TabletType_MASTER)
	}
	if bd, err := expectBroadcastData(agent.QueryServiceControl, false, "", 22); err == nil {
		if bd.RealtimeStats.BinlogPlayersCount != 1 {
			t.Fatalf("filtered replication must be still running: %v", bd)
		}
	} else {
		t.Fatal(err)
	}
	// NOTE: No state change here since nothing has changed.

	// Simulate migration to destination master i.e. remove SourceShards.
	_, err = agent.TopoServer.UpdateShardFields(ctx, "test_keyspace", "0", func(si *topo.ShardInfo) error {
		si.SourceShards = nil
		return nil
	})
	if err != nil {
		t.Fatalf("UpdateShardFields failed: %v", err)
	}

	// Refresh the tablet state, as vtctl MigrateServedFrom would do.
	// This should also trigger a health broadcast since the QueryService state
	// changes from NOT_SERVING to SERVING.
	agent.HealthReporter.(*fakeHealthCheck).reportReplicationDelay = 23 * time.Second
	agent.RefreshState(ctx)

	// QueryService changed from NOT_SERVING to SERVING.
	if !agent.QueryServiceControl.IsServing() {
		t.Errorf("Query service should not be running")
	}
	// Since we didn't run healthcheck again yet, the broadcast data contains the
	// cached replication lag of 22 instead of 23.
	if bd, err := expectBroadcastData(agent.QueryServiceControl, true, "", 22); err == nil {
		if bd.RealtimeStats.BinlogPlayersCount != 0 {
			t.Fatalf("filtered replication must be disabled now: %v", bd)
		}
	} else {
		t.Fatal(err)
	}
	if err := expectStateChange(agent.QueryServiceControl, true, topodatapb.TabletType_MASTER); err != nil {
		t.Fatal(err)
	}

	if err := expectBroadcastDataEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
	if err := expectStateChangesEmpty(agent.QueryServiceControl); err != nil {
		t.Fatal(err)
	}
}

// TestOldHealthCheck verifies that a healthcheck that is too old will
// return an error
func TestOldHealthCheck(t *testing.T) {
	ctx := context.Background()
	agent, _ := createTestAgent(ctx, t, nil)
	*healthCheckInterval = 20 * time.Second
	agent._healthy = nil

	// last health check time is now, we're good
	agent._healthyTime = time.Now()
	if _, healthy := agent.Healthy(); healthy != nil {
		t.Errorf("Healthy returned unexpected error: %v", healthy)
	}

	// last health check time is 2x interval ago, we're good
	agent._healthyTime = time.Now().Add(-2 * *healthCheckInterval)
	if _, healthy := agent.Healthy(); healthy != nil {
		t.Errorf("Healthy returned unexpected error: %v", healthy)
	}

	// last health check time is 4x interval ago, we're not good
	agent._healthyTime = time.Now().Add(-4 * *healthCheckInterval)
	if _, healthy := agent.Healthy(); healthy == nil || !strings.Contains(healthy.Error(), "last health check is too old") {
		t.Errorf("Healthy returned wrong error: %v", healthy)
	}
}

// expectBroadcastData checks that runHealthCheck() broadcasted the expected
// stats (going the value for secondsBehindMaster).
func expectBroadcastData(qsc tabletserver.Controller, serving bool, healthError string, secondsBehindMaster uint32) (*tabletservermock.BroadcastData, error) {
	bd := <-qsc.(*tabletservermock.Controller).BroadcastData
	if got := bd.Serving; got != serving {
		return nil, fmt.Errorf("unexpected BroadcastData.Serving, got: %v want: %v with bd: %+v", got, serving, bd)
	}
	if got := bd.RealtimeStats.HealthError; got != healthError {
		return nil, fmt.Errorf("unexpected BroadcastData.HealthError, got: %v want: %v with bd: %+v", got, healthError, bd)
	}
	if got := bd.RealtimeStats.SecondsBehindMaster; got != secondsBehindMaster {
		return nil, fmt.Errorf("unexpected BroadcastData.SecondsBehindMaster, got: %v want: %v with bd: %+v", got, secondsBehindMaster, bd)
	}
	return bd, nil
}

// expectBroadcastDataEmpty closes the health broadcast channel and verifies
// that all broadcasted messages were consumed by expectBroadcastData().
func expectBroadcastDataEmpty(qsc tabletserver.Controller) error {
	c := qsc.(*tabletservermock.Controller).BroadcastData
	close(c)
	bd, ok := <-c
	if ok {
		return fmt.Errorf("BroadcastData channel should have been consumed, but was not: %v", bd)
	}
	return nil
}

// expectStateChange verifies that the test changed the QueryService state
// to the expected state (serving or not, specific tablet type).
func expectStateChange(qsc tabletserver.Controller, serving bool, tabletType topodatapb.TabletType) error {
	want := &tabletservermock.StateChange{
		Serving:    serving,
		TabletType: tabletType,
	}
	got := <-qsc.(*tabletservermock.Controller).StateChanges
	if !reflect.DeepEqual(got, want) {
		return fmt.Errorf("unexpected state change. got: %v want: %v got", got, want)
	}
	return nil
}

// expectStateChangesEmpty closes the StateChange channel and verifies
// that all sent state changes were consumed by expectStateChange().
func expectStateChangesEmpty(qsc tabletserver.Controller) error {
	c := qsc.(*tabletservermock.Controller).StateChanges
	close(c)
	sc, ok := <-c
	if ok {
		return fmt.Errorf("StateChanges channel should have been consumed, but was not: %v", sc)
	}
	return nil
}


text:
{% extends "base.html" %}
{% load staticfiles %}

{% load i18n %}
{% load url from future %}

{% block head_title %}pinax-project-zero{% endblock %}

{% block body_class %}home{% endblock %}

{% block body_base %}

		<form class="answer-question-form" method="POST" action="/edit_answer_question/{{ question_id }}">
			{% csrf_token %}
			<input name="question-id" type="hidden" value="{{ question_id  }}">

					Question
					<input type="text" class="form-control" name="question" placeholder="Question..." value="{{ question }}">

					Choose type question
					<select class="form-control" name="categories">
						<option value="">--- Select category ---</option>
						{% for c in categories %}
							<option {% if category == c.id %}selected{% endif %} value="{{ c.id }}">{{ c.value.name }}</option>
						{% endfor %}
					</select>

					Type answer

Radio

Check

Seek

					<input name="type-answers" type="hidden" value="{{ type }}">

					Answers
					{% if type != "03" %}

							{% if answers %}
								{% for answer in answers %}

										The answer: {{ answer.value.content }}

										{% if forloop.counter > 0 %}

										{% endif %}

								{% endfor %}
							{% endif %}

						<input name="answer" type="text" class="form-control answer-detail" placeholder="Input answer here...">
						<input name="answer" type="text" class="form-control answer-detail" placeholder="Input answer here...">
					{% endif %}

					<button id="edit_question" class="btn btn-primary pull-right"> Update</button>
					<button id="delete_question" style="margin-right: 5px" type="button" class="btn btn-danger pull-right"> Delete</button>

					 Back to list
					 Create question

		</form>

{% endblock %}

{% block extra_script %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include <omp.h>

#include "approximators/bfp2d.h"

#include "lib/structures.h"

#include "solvers/chan_2d.h"
#include "solvers/graham_scan_2d.h"
#include "solvers/jarvis_scan_2d.h"
#include "solvers/jarvis_scan_3d.h"
#include "solvers/monotone_chain_2d.h"
#include "solvers/quickhull_2d.h"

/**
 * Header only interfaces for solvers, used in library form of ditribution.
 */

namespace ch
{

/**
 * Uses Quickhull algorithm to find convex hull of given 2D point set
 *
 * @param input Input set of points
 * @param output Reference to set of points containing convex hull
 *
 * @return Same as output param, reference to result
 */
Points2D& findHull(const Points2D& input, Points2D& output);

/** Enumerates types of 2d solvers */
enum SolverType {JARVIS, GRAHAM, ANDREW, QUICKHULL, CHAN};

/**
 * Uses chosen algorithm to find convex hull of given point set
 *
 * @param input Input set of points
 * @param output Reference to set of points containing convex hull
 * @param type SolverType of chosen algorithm
 *
 * @return Same as output param, reference to result
 */
Points2D& findHull(const Points2D& input, Points2D& output, SolverType type);

/** Parallel version of findHull, allows to choose number of threads */
Points2D& findHullParallel(const Points2D& input, Points2D& output, int thr);

/**
 * Parallel version of findHull with algorithm selection,
 * allows to choose number of threads
 */
Points2D& findHullParallel(const Points2D& input, Points2D& output,
        SolverType type, int thr);

/**
 * Approximates convex hull of given set of points using BFP approximation
 *
 * @param input Input set of points
 * @param output Approximation of convex hull
 *
 * @return Same as output
 */
Points2D& approximateHull(const Points2D& input, Points2D& output);

/**
 * Uses Jarvis algorithm to find convex hull of given set of 3D points
 *
 * @param input Input set of points
 * @param output Convex hull of input, represented by list of facets
 *
 * @return same as output
 */
Polyhedron& findHull3D(const Points3D input, Polyhedron& output);

}


text:
<?php

namespace Office365\Runtime\Auth;
use Office365\Runtime\Http\RequestException;
use Office365\Runtime\Http\Requests;

/**
 * Provider to acquire the access token from a Microsoft Azure Access Control Service (ACS)
 */
class ACSTokenProvider extends BaseTokenProvider
{

    /**
     * @var string
     */
    private static $SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";

    /**
     * @var string
     */
    private $url;

    /**
     * ACSTokenProvider constructor.
     * @param string $url
     */
    public function __construct($url)
    {
        $this->url = $url;
    }

    /**
     * Acquires the access token from a Microsoft ACS
     * @param array $parameters
     * @return mixed
     * @throws RequestException
     */
    public function acquireToken($parameters)
    {
        $realm = $this->getRealmFromTargetUrl();
        $urlInfo = parse_url($this->url);
        return $this->getAppOnlyAccessToken(
            $parameters["clientId"],
            $parameters["clientSecret"],
            $urlInfo["host"],
            $realm);
    }

    /**
     * @return string
     * @throws RequestException
     */
    private function getRealmFromTargetUrl()
    {
        $headers = array();
        $headers['Authorization'] = 'Bearer';
        $response = Requests::head($this->url, $headers);
        return $this->processRealmResponse($response->getContent());
    }

    /**
     * @param string $payload
     * @return string
     */
    private function processRealmResponse($payload){
        $headerKey = "WWW-Authenticate";
        $result = array_filter(
            explode("\r\n", $payload),
            function ($line) use ($headerKey) {
                return stripos($line,$headerKey) === 0;
            }
        );

        if(count($result) > 0){
            $authHeader = explode(",", reset($result));
            $bearerHeader = explode(':', $authHeader[0]);
            $realm = explode('=', $bearerHeader[1]);
            return str_replace('"', '', $realm[1]);
        }
        return null;
    }

    /**
     * Obtain access token from Azure ACS
     * @param string $clientId
     * @param string $clientSecret
     * @param string $targetHost
     * @param string $targetRealm
     * @return mixed
     * @throws RequestException
     */
    private function getAppOnlyAccessToken($clientId, $clientSecret, $targetHost,$targetRealm)
    {
        $resource = $this->getFormattedPrincipal(self::$SharePointPrincipal,$targetHost,$targetRealm);
        $principalId = $this->getFormattedPrincipal($clientId,null, $targetRealm);
        $stsUrl = $this->getSecurityTokenServiceUrl($targetRealm);
        $oauth2Request = $this->createAccessTokenRequestWithClientCredentials($principalId,$clientSecret,$resource);

        $headers = array();
        $headers[] = 'content-Type: application/x-www-form-urlencoded';
        $response = Requests::post($stsUrl, $headers, $oauth2Request);
        return json_decode($response->getContent(),true);
    }

    private function getFormattedPrincipal($principalName, $hostName, $realm)
    {
        if ($hostName) {
            return "$principalName/$hostName@$realm";
        }
        return "$principalName@$realm";
    }

    private function getSecurityTokenServiceUrl($realm){
        return "https://accounts.accesscontrol.windows.net/$realm/tokens/OAuth/2";
    }

    private function createAccessTokenRequestWithClientCredentials($clientId, $clientSecret, $scope)
    {
        $data = array(
            'grant_type' => 'client_credentials',
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'scope' => $scope,
            'resource' => $scope
        );
        return http_build_query($data);
    }
}


text:
package org.springframework.boot.autoconfigure.security.oauth2.client;

import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Condition that checks for {@link EnableOAuth2Sso} on a
 * {@link WebSecurityConfigurerAdapter}.
 *
 * @author Dave Syer
 */
class EnableOAuth2SsoCondition extends SpringBootCondition {

	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context,
			AnnotatedTypeMetadata metadata) {
		String[] enablers = context.getBeanFactory()
				.getBeanNamesForAnnotation(EnableOAuth2Sso.class);
		ConditionMessage.Builder message = ConditionMessage
				.forCondition("@EnableOAuth2Sso Condition");
		for (String name : enablers) {
			if (context.getBeanFactory().isTypeMatch(name,
					WebSecurityConfigurerAdapter.class)) {
				return ConditionOutcome.match(message
						.found("@EnableOAuth2Sso annotation on WebSecurityConfigurerAdapter")
						.items(name));
			}
		}
		return ConditionOutcome.noMatch(message.didNotFind(
				"@EnableOAuth2Sso annotation " + "on any WebSecurityConfigurerAdapter")
				.atAll());
	}

}


text:
package com.sinyuk.yuk.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ViewAnimator;

/**
 * Custom View Animator which is more easier to be uesd
 */
public class BetterViewAnimator extends ViewAnimator {
  public BetterViewAnimator(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public void setDisplayedChildId(int id) {
    if (getDisplayedChildId() == id) {
      return;
    }
    for (int i = 0, count = getChildCount(); i < count; i++) {
      if (getChildAt(i).getId() == id) {
        setDisplayedChild(i);
        return;
      }
    }
    String name = getResources().getResourceEntryName(id);
    throw new IllegalArgumentException("No view with ID " + name);
  }

  public int getDisplayedChildId() {
    return getChildAt(getDisplayedChild()).getId();
  }
}


text:
package xal.app.scope;

import xal.tools.ArrayMath;

/**
 * ChannelTraceEvent is an event which wraps the capture of a trace from a channel model.
 *
 * @author  tap
 */
public class ChannelTraceEvent implements TraceEvent {
	final protected ChannelModel _source;
	final protected double scale;
	final protected double offset;
	protected double[] _defaultTrace;
	final protected double[] _rawTrace;
	final protected double[] _elementTimes;

	/**
	 * Constructor of a ChannelTraceEvent
	 */
	public ChannelTraceEvent(ChannelModel source, double[] trace, double[] elementTimes) {
		_source = source;
		scale = source.getSignalScale();
		offset = source.getSignalOffset();
		_rawTrace = trace;
		_elementTimes = elementTimes;
	}

	/**
	 * Get the source of the trace event.
	 * @return the source of the trace event.
	 */
	public TraceSource getSource() {
		return _source;
	}

	/**
	 * Get the raw trace.
	 * @return the raw trace.
	 */
	public double[] getRawTrace() {
		return _rawTrace;
	}

	/**
	 * Get the default trace with appropriate scale and offsets set by the user.
	 * @return Teh default trace.
	 */
	public double[] getDefaultTrace() {
		if ( _defaultTrace == null && _rawTrace != null ) {
			_defaultTrace = ArrayMath.transform(_rawTrace, scale, offset);
		}
		return _defaultTrace;
	}

	/**
	 * Get the element times.
	 * @return the element times which specify the time of each waveform element.
	 */
	public double[] getElementTimes() {
		return _elementTimes;
	}
}


text:
package sos.base.util.namayangar.tools;

import java.util.ArrayList;

import sos.base.util.namayangar.view.ViewLayer;

public class SOSSelectedObj {

	ArrayList<ViewLayer> layers=new ArrayList<ViewLayer>();
	private final Object object;
	public SOSSelectedObj(Object object) {
		this.object = object;
	}
	public void addLayer(ViewLayer layer) {
		layers.add(layer);
	}
	public Object getObject() {
		return object;
	}
	public ArrayList<ViewLayer> getLayers() {
		return layers;
	}
}


text:
package org.broadleafcommerce.core.order.domain;

import org.broadleafcommerce.common.money.Money;

import java.io.Serializable;

public interface BundleOrderItemFeePrice extends Serializable {

    public abstract Long getId();

    public abstract void setId(Long id);

    public abstract BundleOrderItem getBundleOrderItem();

    public abstract void setBundleOrderItem(BundleOrderItem bundleOrderItem);

    public abstract Money getAmount();

    public abstract void setAmount(Money amount);

    public abstract String getName();

    public abstract void setName(String name);

    public abstract Boolean isTaxable();

    public abstract void setTaxable(Boolean isTaxable);

    public abstract String getReportingCode();

    public abstract void setReportingCode(String reportingCode);

    public BundleOrderItemFeePrice clone();

}


text:
# Original code taken from mcuboot project at:
# https://github.com/mcu-tools/mcuboot
# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f
#
# SPDX-License-Identifier: Apache-2.0
#
# 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.
"""General key class."""

import sys

AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"

class KeyClass(object):
    def _emit(self, header, trailer, encoded_bytes, indent, file=sys.stdout, len_format=None):
        print(AUTOGEN_MESSAGE, file=file)
        print(header, end='', file=file)
        for count, b in enumerate(encoded_bytes):
            if count % 8 == 0:
                print("\n" + indent, end='', file=file)
            else:
                print(" ", end='', file=file)
            print("0x{:02x},".format(b), end='', file=file)
        print("\n" + trailer, file=file)
        if len_format is not None:
            print(len_format.format(len(encoded_bytes)), file=file)

    def emit_c_public(self, file=sys.stdout):
        self._emit(
                header="const unsigned char {}_pub_key[] = {{".format(self.shortname()),
                trailer="};",
                encoded_bytes=self.get_public_bytes(),
                indent="    ",
                len_format="const unsigned int {}_pub_key_len = {{}};".format(self.shortname()),
                file=file)

    def emit_rust_public(self, file=sys.stdout):
        self._emit(
                header="static {}_PUB_KEY: &[u8] = &[".format(self.shortname().upper()),
                trailer="];",
                encoded_bytes=self.get_public_bytes(),
                indent="    ",
                file=file)

    def emit_private(self, minimal, file=sys.stdout):
        self._emit(
                header="const unsigned char enc_priv_key[] = {",
                trailer="};",
                encoded_bytes=self.get_private_bytes(minimal),
                indent="    ",
                len_format="const unsigned int enc_priv_key_len = {};",
                file=file)


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Beachbum Berry — How to make a Mai Tai</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

    <link rel="stylesheet" href="css/normalize.min.css">
    <link rel="stylesheet" href="css/page.css">

    <link rel="stylesheet" href="https://use.typekit.net/wfg5int.css">

                    MENU

About

Barware

Books & App

Restaurant

Syrups & Rums

Recipes

About

Barware

Books & App

Restaurant

Syrups & Rums

Recipes

How to Make a Mai Tai

The Bum has a confession to make. Actually, he has quite a few, but since we are on his website and not the local constabulary's, he will limit himself to this one: on those happy occasions when he has begged, borrowed, or (heaven forbid) earned enough change to buy a drink, he never orders a Mai Tai.

Why? A Mai Tai should not be red. A Mai Tai should not be blue. The Bum has been served Mai Tais in every color of the rainbow, and the time has come to put his foot down (a gesture that would have more impact were he not now lying on a bar-room floor, but never mind that).

Don The Beachcomber invented a drink he called the Mai Tai Swizzle in 1933, but it seems to have disappeared from his menu sometime before 1937. Strong evidence suggests that Trader Vic developed his own Mai Tai, without any knowledge of Donn's, in 1944. Equally strong evidence suggests that Vic was aware of Donn's; for the whole tangled history, check out pages 64 through 72 of our book Beachbum Berry Remixed.

                           In any event, Trader Vic's Mai Tai is the one that became the iconic Tiki Drink -- and rightly so, as it's the better recipe.

                               Vic created his Mai Tai to showcase a 17-year-old rum imported by J. Wray & Nephew. "The flavor of this great rum wasn't meant to be overpowered with heavy additions of fruit juices and flavorings," warned the Trader, a warning that has since fallen on deaf ears – specifically, the ears of bar owners and tenders who have transformed Vic's signature drink into crayon-colored liquid candy.

                                   A proper Mai Tai has a deep amber hue, because it's the liquor that should dominate the drink, not the sweeteners. Unfortunately, 17-year-old J. Wray & Nephew rum is a thing of the past. But by replacing it with an aged Martinique rum mixed with a premium Jamaican rum, we can approximate Vic's original goal of "creating a drink that would be the finest drink we could make, using the finest ingredients we could find."

                                   Recipe: In your shaker pour 1 ounce each fresh lime juice, Rhum Clément VSOP Martinique rum, and Appleton Estate Extra or Coruba Dark Jamaican rum; 1/2 ounce orange Curacao; 1/2 ounce Latitude 29 Formula Orgeat; and 1/4 ounce sugar syrup. Add at least 2 cups of crushed ice, then shake well for around 10 seconds. Pour unstrained into a double old-fashioned glass. Sink your spent lime shell in the drink, and garnish with a mint sprig. (Drink pictured above.)

                                       Okole maluna!

Learn more about the orgeat here:

Latitude 29 Formula Orgeat

© 2015-2022 Jeff Berry

 | Contact | Press


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Contr. Dudley Herb. 4:317. 1955

#### Original name
null

### Remarks
null


text:
#include "barrage.h"
#include "../../servers/physics_2d_server.h"
#include "character.h"

//=========================Bullet================

void Bullet::_process(float delta_time) {
    total_time += delta_time;
    // rotation = start_rotation + total_time * rotation_accel;
    // if (rotation_accel == 0) {
    //     float cosr = cos(start_rotation);
    //     float sinr = sin(start_rotation);
    //     position.x = start_position.x + accel * cosr * total_time * total_time / 2 + speed * cosr * total_time;
    //     position.y = start_position.y + accel * sinr * total_time * total_time / 2 + speed * sinr * total_time;
    // }else {
    //     float s = accel * total_time + speed;
    //     float cx = -speed/rotation_accel*sin(start_rotation) - accel/rotation_accel/rotation_accel*cos(start_rotation);
    //     float cy = speed/rotation_accel*cos(start_rotation) - accel/rotation_accel/rotation_accel*sin(start_rotation);
    //     float cosr = cos(rotation);
    //     float sinr = sin(rotation);
    //     position.x = start_position.x + s/rotation_accel*sinr + accel/rotation_accel/rotation_accel * cosr + cx;
    //     position.y = start_position.y - s/rotation_accel*cosr + accel/rotation_accel/rotation_accel * sinr + cy;
    // }

    speed += accel * delta_time;
    float move = speed * delta_time;
    if (!target_set) {
        rotation += rotation_accel * delta_time;
        position.x += cos(rotation) * move;
        position.y += sin(rotation) * move;
    }else {
        Vector2 vec2(target_position - position);
        if (vec2.length() < move) {
            move = vec2.length();
        }
        position += vec2.normalized() * move;
    }
}

void Bullet::_bind_methods() {
    ClassDB::bind_method(D_METHOD("set_frame", "frame"), &Bullet::set_frame);
    ClassDB::bind_method(D_METHOD("get_frame"), &Bullet::get_frame);

    ClassDB::bind_method(D_METHOD("set_speed", "speed"), &Bullet::set_speed);
    ClassDB::bind_method(D_METHOD("get_speed"), &Bullet::get_speed);

    ClassDB::bind_method(D_METHOD("set_rotation", "rotation"), &Bullet::set_rotation);
    ClassDB::bind_method(D_METHOD("get_rotation"), &Bullet::get_rotation);

    ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Bullet::set_scale);
    ClassDB::bind_method(D_METHOD("get_scale"), &Bullet::get_scale);

    ClassDB::bind_method(D_METHOD("set_position", "position"), &Bullet::set_position);
    ClassDB::bind_method(D_METHOD("get_position"), &Bullet::get_position);

    ClassDB::bind_method(D_METHOD("set_data", "data:Variant"), &Bullet::set_data);
    ClassDB::bind_method(D_METHOD("get_data"), &Bullet::get_data);

    ClassDB::bind_method(D_METHOD("set_body_size", "body_size"), &Bullet::set_body_size);
    ClassDB::bind_method(D_METHOD("get_body_size"), &Bullet::get_body_size);

    ClassDB::bind_method(D_METHOD("_body_inout"),&Bullet::_body_inout);
    ClassDB::bind_method(D_METHOD("_area_inout"),&Bullet::_area_inout);

    ClassDB::bind_method(D_METHOD("set_target_set", "target_set"), &Bullet::set_target_set);
    ClassDB::bind_method(D_METHOD("get_target_set"), &Bullet::get_target_set);

    ClassDB::bind_method(D_METHOD("set_target_position", "target_position"), &Bullet::set_target_position);
    ClassDB::bind_method(D_METHOD("get_target_position"), &Bullet::set_target_position);

    ClassDB::bind_method(D_METHOD("set_accel", "accel"), &Bullet::set_accel);
    ClassDB::bind_method(D_METHOD("get_accel"), &Bullet::get_accel);

    ClassDB::bind_method(D_METHOD("set_rotation_accel", "accel"), &Bullet::set_rotation_accel);
    ClassDB::bind_method(D_METHOD("get_rotation_accel"), &Bullet::get_rotation_accel);
}

void Bullet::_body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape) {
    if (!live) return;
    bool body_in = p_status==Physics2DServer::AREA_BODY_ADDED;
    if (body_in) {
        ObjectID objid=p_instance;

        Object *obj = ObjectDB::get_instance(objid);
        Node *node = obj ? Object::cast_to<Node>(obj) : NULL;
        owner->hit(this, id, node);
    }
}
void Bullet::_area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape) {
    if (!live) return;
    bool area_in = p_status==Physics2DServer::AREA_BODY_ADDED;
    if (area_in) {
        ObjectID objid=p_instance;

        Object *obj = ObjectDB::get_instance(objid);
        HitArea *area = obj ? Object::cast_to<HitArea>(obj) : NULL;
        if (area) {
            owner->hit(this, id, area);
        }else {
            GrazeArea *grz_area = obj ? Object::cast_to<GrazeArea>(obj) : NULL;
            if (grz_area) {
                owner->graze(this, grz_area);
            }
        }
    }
}

#define DEFAULT_SIZE 8.0

bool Barrage::shape_created = false;
RID Barrage::shape;

Bullet *Barrage::create_bullet(const Point2 &p_position) {
    if (!shape_created)
        return NULL;
    int index = bullets.size();

    Bullet *bullet;
    if (dead_cache.size() > 0) {
        int idx = dead_cache.size()-1;
        bullet = *bullets[dead_cache[idx]];
        dead_cache.remove(idx);
    }else {
        bullets.push_back(memnew(Bullet));
        bullet = *bullets[index];
        bullet->id = index;
        bullet->checker = Physics2DServer::get_singleton()->area_create();
        Physics2DServer::get_singleton()->area_set_space(bullet->checker, get_world_2d()->get_space());
        Physics2DServer::get_singleton()->area_add_shape(bullet->checker, shape);
    }
    bullet->index = max_index++;
    Transform2D xform = get_global_transform();
    bullet->start_position = xform.xform(p_position);
    bullet->position = xform.xform(p_position);
    bullet->owner = this;
    bullet->live = true;
    bullet->total_time = 0;
    Physics2DServer::get_singleton()->area_set_transform(bullet->checker, Transform2D(0, bullet->position));
    Physics2DServer::get_singleton()->area_set_monitor_callback(bullet->checker, bullet, "_body_inout");
    Physics2DServer::get_singleton()->area_set_area_monitor_callback(bullet->checker, bullet, "_area_inout");
    Physics2DServer::get_singleton()->area_set_collision_layer(bullet->checker, _layer_mask);
    Physics2DServer::get_singleton()->area_set_collision_mask(bullet->checker, _collision_mask);
    Physics2DServer::get_singleton()->area_set_monitorable(bullet->checker, true);
    return bullet;
}

void Barrage::graze(const Ref<Bullet> &bullet, GrazeArea* area) {
    area->graze(bullet->checker);
}

void Barrage::hit(const Ref<Bullet> &bullet, int index, Node* target) {
    if (is_inside_tree()) {
        Character *cha = get_character();
        if (!hit_status.is_null() && target) {
            Character *cha_tar = Object::cast_to<Character>(target);
            if (cha_tar) {
                if (cha_tar->attack_by(hit_status->duplicate(), cha)) {
                    if (!explosion_scene.is_null()) {
                        Node *node = explosion_scene->instance();
                        Node2D *node2d = Object::cast_to<Node2D>(node);
                        if (node2d) {
                            cha->get_parent()->add_child(node2d);
                            node2d->set_global_position(bullet->position);
                        }
                    }
                    kill(bullet, index);
                }
                return;
            }
        }
        if (!explosion_scene.is_null()) {
            Node *node = explosion_scene->instance();
            Node2D *node2d = Object::cast_to<Node2D>(node);
            if (node2d) {
                cha->get_parent()->add_child(node2d);
                node2d->set_global_position(bullet->position);
            }
        }
        kill(bullet,index);
    }
}

void Barrage::hit(const Ref<Bullet> &bullet, int index, HitArea *target) {
    if (is_inside_tree()) {
        Character *cha = get_character();
        if (!hit_status.is_null()) {
            Ref<HitStatus> hs = hit_status->duplicate(true);
            Vector2 force = hs->get_force();
            float cx = cos(bullet->rotation);
            if (cx > 0)
                force.x =  Math::abs(force.x);
            else if (cx < 0)
                force.x = -Math::abs(force.x);
            hs->set_force(force);
            hs->set_velocity(force);
            hs->set_stun_velocity(Vector2(force.x, 0));
            if (target->attack_by(hs, cha)) {
                if (!explosion_scene.is_null()) {
                    Node *node = explosion_scene->instance();
                    Node2D *node2d = Object::cast_to<Node2D>(node);
                    if (node2d) {
                        cha->get_parent()->add_child(node2d);
                        node2d->set_global_position(bullet->position);
                    }
                }
                kill(bullet, index);
            }
            return;
        }
        if (!explosion_scene.is_null() && cha) {
            Node *node = explosion_scene->instance();
            Node2D *node2d = Object::cast_to<Node2D>(node);
            if (node2d) {
                cha->get_parent()->add_child(node2d);
                node2d->set_global_position(bullet->position);
            }
        }
        kill(bullet,index);
    }
}

void Barrage::kill(const Ref<Bullet> &bullet, int index) {
    if (bullet->live) {
        const_cast<Bullet*>(*bullet)->live = false;
        dead_cache.push_back(index);
        Physics2DServer::get_singleton()->area_set_collision_layer(bullet->checker, 0);
        Physics2DServer::get_singleton()->area_set_collision_mask(bullet->checker, 0);
    }
}

void Barrage::clear() {
    for (int i = 0, t = bullets.size(); i < t; ++i) {
        kill(bullets[i], i);
    }
}

void Barrage::_fixed_process_bullets(float delta_time) {
    ScriptInstance *instance = get_script_instance();

    Transform2D mx = get_viewport_transform();
    Rect2 vis = get_viewport_rect();
    vis.position = -Point2(mx[2][0]/mx[0][0], mx[2][1]/mx[1][1]);
    vis = vis.grow(kill_range);

    for (int i = 0, t = bullets.size(); i < t; ++i) {
        Bullet *bullet = *bullets[i];
        if (bullet->live) {
            _process_bullet(bullet, delta_time);
            if (instance) {
                Variant v1(bullet);
                Variant v2(delta_time);
                const Variant* ptr[2]={&v1, &v2};
                instance->call_multilevel(StringName("_process_bullet"),ptr,2);
            }
            bullet->_process(delta_time);
            if (vis.has_point(bullet->position))   {
                Transform2D matrix = Transform2D(0, bullet->position);
                float scale = bullet->body_size/DEFAULT_SIZE;
                matrix.scale_basis(Size2(scale, scale));
                Physics2DServer::get_singleton()->area_set_transform(bullet->checker, matrix);
            }else{
                kill(bullet, i);
            }
        }
    }
}

void Barrage::_process_draw_bullets() {
    Size2 size = texture->get_size();
    size = Size2(size.x / h_frames, size.y / v_frames);
    Transform2D m = get_global_transform().affine_inverse();
    if (!texture.is_null()) {
        RID ci=get_canvas_item();
        for (int i = 0, t = bullets.size(); i < t; ++i) {
            Bullet *bullet = *bullets[i];
            if (bullet->live) {
                Transform2D xform(-bullet->rotation, bullet->position);
                xform = m * xform;
                xform.scale_basis(Size2(bullet->scale,bullet->scale));
                VisualServer::get_singleton()->canvas_item_add_set_transform(ci,xform);
                texture->draw_rect_region(ci, Rect2(-size/2.0,size), Rect2(Point2(size.x * (bullet->frame % h_frames), size.y * (bullet->frame / h_frames)), size), Color(1,1,1,1));
            }
        }
    }
}

void Barrage::_update_character() {
    if (is_inside_tree()) {
        if (character_path != NodePath() && has_node(character_path)) {
            Node *node = get_node(character_path);
            Character *character = Object::cast_to<Character>(node);
            if (character) {
                character_id = character->get_instance_id();
            }else {
                character_id = 0;
            }
        }else {
            character_id = 0;
        }
    }else {
        character_id = 0;
    }
}

void Barrage::_notification(int p_notification) {
    switch (p_notification) {
        case NOTIFICATION_ENTER_TREE: {
            if (!shape_created) {
                shape = Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CIRCLE);
                Physics2DServer::get_singleton()->shape_set_data(shape, DEFAULT_SIZE);
                shape_created = true;
            }
            _update_character();
        } break;
        case NOTIFICATION_PROCESS: {
            _fixed_process_bullets(get_process_delta_time());
            update();
        } break;
        case NOTIFICATION_DRAW: {
            _process_draw_bullets();
        } break;
    }
}

Barrage::Barrage() {
    h_frames = 1;
    v_frames = 1;
    _layer_mask = 0;
    _collision_mask = 0;
    max_index=0;
    kill_range = 600;
    kill_out_screen = true;
    set_process(true);
}

Barrage::~Barrage() {
    for (int i = 0, t = bullets.size(); i < t; ++i) {
        Physics2DServer::get_singleton()->free(bullets[i]->checker);
    }
}

void Barrage::_bind_methods() {
    ClassDB::bind_method(D_METHOD("create_bullet:Bullet", "position"), &Barrage::create_bullet);

    ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &Barrage::set_texture);
    ClassDB::bind_method(D_METHOD("get_texture"), &Barrage::get_texture);

    ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &Barrage::set_layer_mask);
    ClassDB::bind_method(D_METHOD("get_layer_mask"), &Barrage::get_layer_mask);

    ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &Barrage::set_collision_mask);
    ClassDB::bind_method(D_METHOD("get_collision_mask"), &Barrage::get_collision_mask);

    ClassDB::bind_method(D_METHOD("set_character_path", "character_path"), &Barrage::set_character_path);
    ClassDB::bind_method(D_METHOD("get_character_path"), &Barrage::get_character_path);
    ClassDB::bind_method(D_METHOD("get_character"), &Barrage::get_character);

    ClassDB::bind_method(D_METHOD("set_hit_status", "hit_status"), &Barrage::set_hit_status);
    ClassDB::bind_method(D_METHOD("get_hit_status"), &Barrage::get_hit_status);

    ClassDB::bind_method(D_METHOD("set_explosion_scene", "explosion_scene"), &Barrage::set_explosion_scene);
    ClassDB::bind_method(D_METHOD("get_explosion_scene"), &Barrage::get_explosion_scene);

    ClassDB::bind_method(D_METHOD("set_kill_out_screen", "kill_out_screen"), &Barrage::set_kill_out_screen);
    ClassDB::bind_method(D_METHOD("get_kill_out_screen"), &Barrage::get_kill_out_screen);

    ClassDB::bind_method(D_METHOD("set_kill_range", "kill_range"), &Barrage::set_kill_range);
    ClassDB::bind_method(D_METHOD("get_kill_range"), &Barrage::get_kill_range);

    ClassDB::bind_method(D_METHOD("clear"), &Barrage::clear);

    ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");

    ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "character_path"), "set_character_path", "get_character_path");
    ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "hit_status", PROPERTY_HINT_RESOURCE_TYPE, "HitStatus"), "set_hit_status", "get_hit_status");
    ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "explosion_scene", PROPERTY_HINT_RESOURCE_TYPE, "PackedScene"), "set_explosion_scene", "get_explosion_scene");

    ADD_PROPERTY(PropertyInfo(Variant::BOOL, "kill_out_screen"), "set_kill_out_screen", "get_kill_out_screen");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "kill_range"), "set_kill_range", "get_kill_range");

    ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_FLAGS), "set_layer_mask", "get_layer_mask");
    ADD_PROPERTY(PropertyInfo(Variant::INT, "masks", PROPERTY_HINT_FLAGS), "set_collision_mask", "get_collision_mask");

    BIND_VMETHOD(MethodInfo("_process_bullet", PropertyInfo(Variant::OBJECT, "bullet", PROPERTY_HINT_RESOURCE_TYPE, "Bullet"), PropertyInfo(Variant::REAL, "delta")));
}
//==================ShootBarrage==========================

void ShootBarrage::_notification(int p_notification) {

    switch (p_notification) {

        case NOTIFICATION_PROCESS: {
            if (shoot_count > 0) {
                if (frame_count <= 0) {
                    shoot_count -= 1;
                    frame_count += frame_interval;
                    _shoot();
                    ScriptInstance *instance = get_script_instance();
                    if (instance) {
                        static const StringName shoot = StringName("_shoot");
                        instance->call_multilevel(shoot);
                    }
                }
                frame_count-=get_process_delta_time();
            }
        }
    }
}

void ShootBarrage::_bind_methods() {

    ClassDB::bind_method(D_METHOD("set_speed", "speed"), &ShootBarrage::set_speed);
    ClassDB::bind_method(D_METHOD("get_speed"), &ShootBarrage::get_speed);

    ClassDB::bind_method(D_METHOD("set_radius", "radius"), &ShootBarrage::set_radius);
    ClassDB::bind_method(D_METHOD("get_radius"), &ShootBarrage::get_radius);

    ClassDB::bind_method(D_METHOD("set_accel", "accel"), &ShootBarrage::set_accel);
    ClassDB::bind_method(D_METHOD("get_accel"), &ShootBarrage::get_accel);

    ClassDB::bind_method(D_METHOD("set_rotation_accel", "accel"), &ShootBarrage::set_rotation_accel);
    ClassDB::bind_method(D_METHOD("get_rotation_accel"), &ShootBarrage::get_rotation_accel);

    ClassDB::bind_method(D_METHOD("set_body_size", "body_size"), &ShootBarrage::set_body_size);
    ClassDB::bind_method(D_METHOD("get_body_size"), &ShootBarrage::get_body_size);

    ClassDB::bind_method(D_METHOD("set_bullet_scale", "bullet_scale"), &ShootBarrage::set_bullet_scale);
    ClassDB::bind_method(D_METHOD("get_bullet_scale"), &ShootBarrage::get_bullet_scale);

    ClassDB::bind_method(D_METHOD("set_shoot_time", "shoot_time"), &ShootBarrage::set_shoot_time);
    ClassDB::bind_method(D_METHOD("get_shoot_time"), &ShootBarrage::get_shoot_time);

    ClassDB::bind_method(D_METHOD("set_frame_interval", "frame_interval"), &ShootBarrage::set_frame_interval);
    ClassDB::bind_method(D_METHOD("get_frame_interval"), &ShootBarrage::get_frame_interval);

    ClassDB::bind_method(D_METHOD("start_shoot"), &ShootBarrage::start_shoot);

    ADD_PROPERTY(PropertyInfo(Variant::REAL, "speed"), "set_speed", "get_speed");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius"), "set_radius", "get_radius");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "accel"), "set_accel", "get_accel");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "rotation_accel"), "set_rotation_accel", "get_rotation_accel");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "body_size"), "set_body_size", "get_body_size");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "bullet_scale"), "set_bullet_scale", "get_bullet_scale");
    ADD_PROPERTY(PropertyInfo(Variant::INT, "shoot_time"), "set_shoot_time", "get_shoot_time");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "frame_interval"), "set_frame_interval", "get_frame_interval");

    BIND_VMETHOD(MethodInfo("_shoot"));
}

//==================ScatterBarrage==========================

void ScatterBarrage::_shoot(){

    Vector2 v2 = target - get_global_position();
    float in = Math::deg2rad(angle_interval);
    float angle = Math::atan2(v2.y, v2.x);
    float start = angle - in*((bullet_count-1)/2.0);
    if (distance_interval != 0) {
        Vector2 step(Math::cos(angle+Math_PI/2)*distance_interval, Math::sin(angle+Math_PI/2)*distance_interval);
        Vector2 start_pos = -step*((bullet_count-1)/2.0);

        for (int i = 0; i < bullet_count; ++i) {
            float alpha = start + in*i;
            Vector2 vn(Math::cos(alpha), Math::sin(alpha));
            Bullet *bullet = create_bullet(vn*radius + (start_pos+i*step));
            bullet->set_rotation(alpha);
            bullet->set_speed(speed);
            bullet->set_frame(sprite_frame);
            bullet->set_body_size(body_size);
            bullet->set_scale(bullet_scale);
            bullet->set_accel(accel);
            bullet->set_rotation_accel(rotation_accel/180*Math_PI);
        }
    }else {
        for (int i = 0; i < bullet_count; ++i) {
            float alpha = start + in*i;
            Vector2 vn(Math::cos(alpha), Math::sin(alpha));
            Bullet *bullet = create_bullet(vn*radius);
            bullet->set_rotation(alpha);
            bullet->set_speed(speed);
            bullet->set_frame(sprite_frame);
            bullet->set_body_size(body_size);
            bullet->set_scale(bullet_scale);
            bullet->set_accel(accel);
            bullet->set_rotation_accel(rotation_accel/180*Math_PI);
        }
    }
}

void ScatterBarrage::shoot(int frame) {
    sprite_frame = frame;
    start_shoot();
}

void ScatterBarrage::_bind_methods() {
    ClassDB::bind_method(D_METHOD("set_interval", "interval"), &ScatterBarrage::set_interval);
    ClassDB::bind_method(D_METHOD("get_interval"), &ScatterBarrage::get_interval);

    ClassDB::bind_method(D_METHOD("set_distance_interval", "interval"), &ScatterBarrage::set_distance_interval);
    ClassDB::bind_method(D_METHOD("get_distance_interval"), &ScatterBarrage::get_distance_interval);

    ClassDB::bind_method(D_METHOD("set_target", "target"), &ScatterBarrage::set_target);
    ClassDB::bind_method(D_METHOD("get_target"), &ScatterBarrage::get_target);

    ClassDB::bind_method(D_METHOD("set_bullet_count", "bullet_count"), &ScatterBarrage::set_bullet_count);
    ClassDB::bind_method(D_METHOD("get_bullet_count"), &ScatterBarrage::get_bullet_count);

    ClassDB::bind_method(D_METHOD("shoot", "frame"), &ScatterBarrage::shoot);

    ADD_PROPERTY(PropertyInfo(Variant::REAL, "interval"), "set_interval", "get_interval");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "distance_interval"), "set_distance_interval", "get_distance_interval");
    ADD_PROPERTY(PropertyInfo(Variant::INT, "bullet_count"), "set_bullet_count", "get_bullet_count");
}

//==================RandomBarrage==========================

void RandomBarrage::_shoot() {
    for (int i = 0; i < bullet_once_count; ++i) {
        make_bullet();
    }
}

float RandomBarrage::randf() {
    return Math::randf()*2-1;
}

Bullet *RandomBarrage::make_bullet() {

    float angle = Math::deg2rad(shoot_angle+angle_range*randf());
    Bullet *bullet = create_bullet(Vector2(pos_range.x*randf(), pos_range.y*randf()));
    bullet->set_rotation(angle);
    bullet->set_speed(speed+speed_range*randf());
    bullet->set_frame(sprite_frame);
    bullet->set_body_size(body_size);
    bullet->set_scale(bullet_scale);
    return bullet;
}

void RandomBarrage::shoot(float angle, int frame) {
    shoot_angle = angle;
    sprite_frame = frame;
    start_shoot();
}

void RandomBarrage::_bind_methods() {
    ClassDB::bind_method(D_METHOD("set_pos_range", "pos_range"), &RandomBarrage::set_pos_range);
    ClassDB::bind_method(D_METHOD("get_pos_range"), &RandomBarrage::get_pos_range);

    ClassDB::bind_method(D_METHOD("set_angle_range", "angle_range"), &RandomBarrage::set_angle_range);
    ClassDB::bind_method(D_METHOD("get_angle_range"), &RandomBarrage::get_angle_range);

    ClassDB::bind_method(D_METHOD("set_speed_range", "speed_range"), &RandomBarrage::set_speed_range);
    ClassDB::bind_method(D_METHOD("get_speed_range"), &RandomBarrage::get_speed_range);

    ClassDB::bind_method(D_METHOD("set_bullet_once_count", "bullet_count"), &RandomBarrage::set_bullet_once_count);
    ClassDB::bind_method(D_METHOD("get_bullet_once_count"), &RandomBarrage::get_bullet_once_count);

    ClassDB::bind_method(D_METHOD("shoot", "angle", "frame"), &RandomBarrage::shoot);

    ADD_PROPERTY(PropertyInfo(Variant::INT, "bullet_count"), "set_bullet_once_count", "get_bullet_once_count");
    ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "pos_range"), "set_pos_range", "get_pos_range");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "angle_range"), "set_angle_range", "get_angle_range");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "speed_range"), "set_speed_range", "get_speed_range");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "shoot_time"), "set_shoot_time", "get_shoot_time");
    ADD_PROPERTY(PropertyInfo(Variant::REAL, "frame_interval"), "set_frame_interval", "get_frame_interval");
}


text:
define({
  "styleText": "Typ nástroje překrývání",
  "vertical": "Svislý pruh",
  "horizontal": "Vodorovný pruh",
  "scope": "Lupa",
  "placement": "Směr",
  "showLeftSide": "Zobrazit překryté vrstvy vlevo",
  "showRigthSide": "Zobrazit překryté vrstvy vpravo",
  "showUpSide": "Zobrazit překryté vrstvy nahoře",
  "showDownSide": "Zobrazit překryté vrstvy dole",
  "barColor": "Barva pruhu",
  "swipeMode": "Režim překrývání",
  "singleLayer": "Jedna vrstva",
  "MultipleLayers": "Několik vrstev",
  "allowToSwipe": "Povolit překrývání",
  "layer": "Vrstva",
  "swipeByDefault": "Překrývání jako výchozí nastavení",
  "defaultLayerMustBeVisible": "výchozí vrstva musí být viditelná",
  "noDefaultLayer": "Nastavte prosím výchozí vrstvy pro překrývání",
  "defaultLayerHolder": "Kliknutím vyberte",
  "selectLayers": "Vybrat vrstvy",
  "layerText": "Výchozí vrstvy překryvu",
  "spyglassText": "Vyberte výchozí vrstvu lupy.",
  "layerHint": "Poznámka: Pokud je vrstva zakrytá svrchnějšími vrstvami, překrývání se nijak neprojeví.",
  "isZoom": "Přiblížit na vrstvu překryvu",
  "isZooms": "Přiblížit na vrstvu překryvu",
  "layersAvailable": "Rolovatelné vrstvy",
  "hidePanel": "Skrýt panel pro výběr vrstvy při otevření widgetu"
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Polish Botanical Journal 49(1): 3 (2004)

#### Original name
Corticium subcretaceum Litsch., 1939

### Remarks
null


text:
package net.kleinhaneveld.cli.instantiator;

import net.kleinhaneveld.cli.collection.ServiceLoaderStreamer;

public class ServiceLoaderInstantiator implements Instantiator {
    @Override
    public <T> T instantiate(Class<T> aClass) {
        return ServiceLoaderStreamer.loadUniqueInstance(aClass);
    }
}


text:
/*
 * HostDeviceVector.h
 *
 *  Created on: 11 янв. 2016 г.
 *      Author: aleksandr
 */

#ifndef HOSTDEVICEVECTOR_H_
#define HOSTDEVICEVECTOR_H_

#include <thrust/device_vector.h>
#include <thrust/host_vector.h>

/*
 * Основной контейнер для данных. Позволяет синхронизировать данные
 * между GPU b CPU. Позволяет получать прямые указатели на данные.
 */

class HostDeviceVector {
public:
	HostDeviceVector();
	HostDeviceVector(std::size_t size, float placeHolder);
	~HostDeviceVector();

	// Синхронизирует данные с GPU на CPU
	void GPUtoCPU();
	// Синхронизирует данные с CPU на GPU
	void CPUtoGPU();
	// Изменяет размер вектора на GPU и на GPU и заполняет его placeholder
	void resize(std::size_t size, float placeHolder);
	// Заполняет и GPU и CPu вектор placeholder-ом
	void fill(float placeHolder);
	// Преобразует в тип указателя на вектор GPU
	thrust::device_ptr<float> getDevicePtr();
	// Преобразует в тип указвтеля на вектор CPU
	float* getHostPtr();
	// Возвращает размер вектора на CPU
	std::size_t getSize() const;
	// Перегрузка [ ] для доступа к CPU вектору
	float& operator[] (std::size_t index);

private:
	thrust::device_vector<float> deviceVector;
	thrust::host_vector<float> hostVector;
};

#endif /* HOSTDEVICEVECTOR_H_ */


text:
<?php
    include("includes/nav.php");
    include("includes/classSystemRoles.php");

    $systemFunction=new systemFunctions();

    //check if post variable has stuff(form is filled)
    if(isset($_POST['route_name'])        &&
       isset($_POST['route_distance'])           &&
       isset($_POST['cargo_price'])      &&
       isset($_POST['passenger_price'])
      ){

        //form inputs
        $routename=$_POST['route_name'];
        $routedistance=$_POST['route_distance'];
        $cargoprice=$_POST['cargo_price'];
        $passengerprice=$_POST['passenger_price'];

        //add details to clients table
        $result=$systemFunction->newRoute($routename, $routedistance, $cargoprice, $passengerprice);
        if($result == "success"){
            $msgClass="alert-success";
            $msg="Route ".$routename ." added successfully!";
        }

        else{
            $msgClass="alert-danger";
            $msg="Could not register client now!";

        }

       }

?>

                    <form accept-charset="UTF-8" action="#" class="form-signin" style="max-width: 330px; display: block; margin: auto;" enctype="multipart/form-data" id="new_task" method="post">

                        <?php
                                //display the error/success message
                                if(isset($msgClass) && isset($msg)){
                                        echo '

                                        &times
                                       '.$msg.'

';
                                }

                        ?>

<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="X/ebtXac2ncy15haszff6iLyXjp7jDqWR+Rp51TgC0s=" />

New Route

                        <input class="form-control" id="route_name" name="route_name" placeholder="route name e.g NAI-KSM" required="required" type="text" />

                        <input class="form-control" id="route_distance" name="route_distance" placeholder="route distance" required="required" type="text" />

                        <input class="form-control" id="cargo_price" name="cargo_price" placeholder="cargo price" required="required" type="text" />

                        <input class="form-control" id="passenger_price" name="passenger_price" placeholder="passenger price" required="required" type="text" />

                        <input class="btn btn-lg btn-primary btn-block" name="commit" type="submit" value="Save Route" />
                    </form>

<?php
    include("includes/footer.php");
?>


text:
import heapq
import os
import time

import operator
from caching.base import cached
from django.shortcuts import render

from django.conf import settings
from math import log10

is_cached = False

def get_obj():
    time.sleep(2)
    return 'hello'

def data_dir():
    # return os.path.join(settings.BASE_DIR, '../data/')
    # TODO: use relative path
    return r'D:\andersc\github\spellchecker\data'

## Helpers
def product(nums):
    return reduce(operator.mul, nums, 1)

def missing_func(k, n):
    return 1. / n

def avoid_long_words(key, N):
    """Estimate the probability of an unknown word."""
    return 10. / (N * 10 ** len(key))

class Pdist(dict):
    """A probability distribution estimated from counts in datafile."""
    def __init__(self, data=[], N=None, missingfn=missing_func):
        for key, count in data:
            self[key] = self.get(key, 0) + int(count)
        self.N = float(N or sum(self.itervalues()))
        self.missingfn = missingfn or (lambda k, N: 1. / N)

    def __call__(self, key):
        if key in self:
            return self[key] / self.N
        else:
            return self.missingfn(key, self.N)

def datafile(name, sep='\t'):
    """Read key, vlaue pairs from file."""
    for line in file(os.path.join(data_dir(), name)):
        yield line.split(sep)

def get_primary_dict():
    return Pdist(datafile('ngrams/primary_dict.txt'), None, avoid_long_words)

def get_bigram_dict():
    return Pdist(datafile('../data/ngrams/bigram_dict_less.txt'), None)

def get_valid_prefixes():
    return set(w[:i] for w in Pw for i in xrange(len(w)+1))

def get_p1edit():
    """the prob of single edits"""
    # TODO: use a better missingfn
    return Pdist(datafile('norvig/count_1edit.txt'))

Pw = cached(get_primary_dict, 'primary_dict', 600)
P2w = cached(get_bigram_dict, 'bigram_dict', 600)
PREFIXES = cached(get_valid_prefixes, 'prefixes', 600)
P1edit = cached(get_p1edit, 'p1edit', 600)

def cPw(word, prev):
    """
    The conditional probability P(word | previous word)
    """
    try:
        return P2w[prev + ' ' + word] / float(Pw[prev])
    except KeyError:
        return Pw(word)

def sPw(w, prev, next):
    print(' '.join([prev, w, next, str(log10(cPw(w, prev)) + log10(cPw(next, w)))]))
    return log10(cPw(w, prev)) + log10(cPw(next, w))

# common error rate
p_spell_error = 1./20

def Pedit(edit):
    # prob of 'right is right'
    if edit == '':
        return 1. - p_spell_error

    return p_spell_error * product(P1edit(e) for e in edit.split('+'))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits(word, d=2):
    results = {}

    def editsR(hd, tl, d, edits):
        def ed(L, R):
            return edits + [R + '|' + L]
        C = hd+tl
        # if C is in the dict
        if C in Pw:
            e = '+'.join(edits)
            if C not in results:
                results[C] = e
            else:
                results[C] = max(results[C], e, key=Pedit)

        if d <= 0:
            return

        extensions = [hd+c for c in alphabet if hd+c in PREFIXES]
        # previous char
        p = (hd[-1] if hd else '<')

        # insertion
        for h in extensions:
            editsR(h, tl, d-1, ed(p+h[-1], p))
        if not tl:
            return

        # deletion
        editsR(hd, tl[1:], d-1, ed(p, p+tl[0]))

        # replacement
        for h in extensions:
            # match
            if h[-1] == tl[0]:
                editsR(h, tl[1:], d, edits)
            else:
                editsR(h, tl[1:], d-1, ed(h[-1], tl[0]))

        # transpose
        if len(tl) >= 2 and tl[0] != tl[1] and hd+tl[1] in PREFIXES:
            editsR(hd+tl[1], tl[0]+tl[2:], d-1, ed(tl[1]+tl[0], tl[0:2]))

    # body of edits
    editsR('', word, d, [])
    return results

def correct(w, n=1):

    candicates = edits(w).items()
    most_likely = heapq.nlargest(n, candicates, key=lambda (c, e): Pedit(e) * Pw(c))
    # c, edit = max(candicates, key=lambda (c, e): Pedit(e) * Pw(c))
    return [c for c, edit in most_likely]

def correct_bigram(words, n=1):

    print(words)
    print(len(words))
    print()

    idx = -1
    for i, elem in enumerate(words):
        if elem not in Pw:
            idx = i
            break
    print('idx: ' + str(idx))
    if idx < 0:
        return [' '.join(words)]

    candicates = edits(words[idx]).items()
    prev = words[idx-1] if idx > 0 else '<S>'
    next = words[idx+1] if idx < (len(words) - 1) else '</S>'
    most_likely = heapq.nlargest(n, candicates, key=lambda (c, e): log10(Pedit(e)) + sPw(c, prev, next))
    return [' '.join(words[0:idx] + [c] + words[idx+1:]) for c, edit in most_likely]

# view functions ###

def index(request):

    word = request.GET.get('word', '')
    if not word:
        return render(request, 'checker/index.html', {'page_name': 'checker.index'})

    n = request.GET.get('n', '5')
    grams = request.GET.get('grams', 1)

    in_dict = 'real word' if word in Pw else 'non-word'
    c = correct(word, int(n))
    return render(request, 'checker/index.html', {'page_name': 'checker.index',
                                                  'word': word,
                                                  'in_dict': in_dict,
                                                  'corrections': c})

def check_bigram(request):

    word = request.GET.get('word', '')
    if not word:
        return render(request, 'checker/bigram.html', {'page_name': 'checker.bigram'})

    n = request.GET.get('n', '5')
    c = correct_bigram(word.split(' '), int(n))
    return render(request, 'checker/bigram.html', {'page_name': 'checker.bigram',
                                                  'word': word,
                                                  'corrections': c})

def stats(request):
    return render(request, 'checker/stats.html', {'page_name': 'checker.stats'})


text:
class ChangeThingsInComments < ActiveRecord::Migration
  def change
    add_column :comments, :user_id, :integer
    remove_column :comments, :username
    remove_column :comments, :email
  end
end


text:
package org.openkilda.wfm.topology.network.storm.bolt.sw.command;

import org.openkilda.messaging.model.SwitchAvailabilityData;
import org.openkilda.model.SwitchId;

public abstract class SwitchAvailabilityCommandBase extends SwitchCommand {
    protected final SwitchAvailabilityData availabilityData;

    SwitchAvailabilityCommandBase(SwitchId switchId, SwitchAvailabilityData availabilityData) {
        super(switchId);
        this.availabilityData = availabilityData;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="Start" href="index.html">
<link rel="previous" href="StdLabels.html">
<link rel="next" href="String.html">
<link rel="Up" href="index.html">
<link title="Index of types" rel=Appendix href="index_types.html">
<link title="Index of exceptions" rel=Appendix href="index_exceptions.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Index of module types" rel=Appendix href="index_module_types.html">
<link title="Barray" rel="Chapter" href="Barray.html">
<link title="Barray_slice" rel="Chapter" href="Barray_slice.html">
<link title="Barraylabels" rel="Chapter" href="Barraylabels.html">
<link title="Bbool" rel="Chapter" href="Bbool.html">
<link title="Bchar" rel="Chapter" href="Bchar.html">
<link title="Bfloat" rel="Chapter" href="Bfloat.html">
<link title="Bformat" rel="Chapter" href="Bformat.html">
<link title="Bfun" rel="Chapter" href="Bfun.html">
<link title="Bhash" rel="Chapter" href="Bhash.html">
<link title="Bhashtbl" rel="Chapter" href="Bhashtbl.html">
<link title="Bheap" rel="Chapter" href="Bheap.html">
<link title="Bint" rel="Chapter" href="Bint.html">
<link title="Bint64" rel="Chapter" href="Bint64.html">
<link title="Blist" rel="Chapter" href="Blist.html">
<link title="Blistlabels" rel="Chapter" href="Blistlabels.html">
<link title="Bmap" rel="Chapter" href="Bmap.html">
<link title="Bopt" rel="Chapter" href="Bopt.html">
<link title="Bord" rel="Chapter" href="Bord.html">
<link title="Bpair" rel="Chapter" href="Bpair.html">
<link title="Bparse" rel="Chapter" href="Bparse.html">
<link title="Brandom" rel="Chapter" href="Brandom.html">
<link title="Bref" rel="Chapter" href="Bref.html">
<link title="Bresult" rel="Chapter" href="Bresult.html">
<link title="Bset" rel="Chapter" href="Bset.html">
<link title="Bstring" rel="Chapter" href="Bstring.html">
<link title="Bvector" rel="Chapter" href="Bvector.html">
<link title="Sequence" rel="Chapter" href="Sequence.html">
<link title="Arg" rel="Chapter" href="Arg.html">
<link title="Array" rel="Chapter" href="Array.html">
<link title="ArrayLabels" rel="Chapter" href="ArrayLabels.html">
<link title="Bigarray" rel="Chapter" href="Bigarray.html">
<link title="Buffer" rel="Chapter" href="Buffer.html">
<link title="Bytes" rel="Chapter" href="Bytes.html">
<link title="BytesLabels" rel="Chapter" href="BytesLabels.html">
<link title="Callback" rel="Chapter" href="Callback.html">
<link title="CamlinternalFormat" rel="Chapter" href="CamlinternalFormat.html">
<link title="CamlinternalFormatBasics" rel="Chapter" href="CamlinternalFormatBasics.html">
<link title="CamlinternalLazy" rel="Chapter" href="CamlinternalLazy.html">
<link title="CamlinternalMod" rel="Chapter" href="CamlinternalMod.html">
<link title="CamlinternalOO" rel="Chapter" href="CamlinternalOO.html">
<link title="Char" rel="Chapter" href="Char.html">
<link title="Complex" rel="Chapter" href="Complex.html">
<link title="Digest" rel="Chapter" href="Digest.html">
<link title="Filename" rel="Chapter" href="Filename.html">
<link title="Format" rel="Chapter" href="Format.html">
<link title="Gc" rel="Chapter" href="Gc.html">
<link title="Genlex" rel="Chapter" href="Genlex.html">
<link title="Hashtbl" rel="Chapter" href="Hashtbl.html">
<link title="Int32" rel="Chapter" href="Int32.html">
<link title="Int64" rel="Chapter" href="Int64.html">
<link title="Lazy" rel="Chapter" href="Lazy.html">
<link title="Lexing" rel="Chapter" href="Lexing.html">
<link title="List" rel="Chapter" href="List.html">
<link title="ListLabels" rel="Chapter" href="ListLabels.html">
<link title="Map" rel="Chapter" href="Map.html">
<link title="Marshal" rel="Chapter" href="Marshal.html">
<link title="MoreLabels" rel="Chapter" href="MoreLabels.html">
<link title="Nativeint" rel="Chapter" href="Nativeint.html">
<link title="Obj" rel="Chapter" href="Obj.html">
<link title="Oo" rel="Chapter" href="Oo.html">
<link title="Parsing" rel="Chapter" href="Parsing.html">
<link title="Pervasives" rel="Chapter" href="Pervasives.html">
<link title="Printexc" rel="Chapter" href="Printexc.html">
<link title="Printf" rel="Chapter" href="Printf.html">
<link title="Queue" rel="Chapter" href="Queue.html">
<link title="Random" rel="Chapter" href="Random.html">
<link title="Scanf" rel="Chapter" href="Scanf.html">
<link title="Set" rel="Chapter" href="Set.html">
<link title="Sort" rel="Chapter" href="Sort.html">
<link title="Stack" rel="Chapter" href="Stack.html">
<link title="StdLabels" rel="Chapter" href="StdLabels.html">
<link title="Stream" rel="Chapter" href="Stream.html">
<link title="String" rel="Chapter" href="String.html">
<link title="StringLabels" rel="Chapter" href="StringLabels.html">
<link title="Sys" rel="Chapter" href="Sys.html">
<link title="Unix" rel="Chapter" href="Unix.html">
<link title="UnixLabels" rel="Chapter" href="UnixLabels.html">
<link title="Weak" rel="Chapter" href="Weak.html"><title>Stream</title>

Previous
 Up
 Next

Module Stream

module Stream: sig .. end

Streams and parsers.

type 'a t

The type of streams holding values of type 'a.

exception Failure

Raised by parsers when none of the first components of the stream
   patterns is accepted.

exception Error of string

Raised by parsers when the first component of a stream pattern is
   accepted, but one of the following components is rejected.

val from : (int -> 'a option) -> 'a t

Stream.from f returns a stream built from the function f.
   To create a new stream element, the function f is called with
   the current stream count. The user function f must return either
   Some <value> for a value or None to specify the end of the
   stream.

   Do note that the indices passed to f may not start at 0 in the
   general case. For example, [< '0; '1; Stream.from f >] would call
   f the first time with count 2.

val of_list : 'a list -> 'a t

Return the stream holding the elements of the list in the same
   order.

val of_string : string -> char t

Return the stream of the characters of the string parameter.

val of_bytes : bytes -> char t

Return the stream of the characters of the bytes parameter.

Since 4.02.0

val of_channel : Pervasives.in_channel -> char t

Return the stream of the characters read from the input channel.

val iter : ('a -> unit) -> 'a t -> unit

Stream.iter f s scans the whole stream s, applying function f
   in turn to each stream element encountered.

val next : 'a t -> 'a

Return the first element of the stream and remove it from the
   stream. Raise Stream.Failure if the stream is empty.

val empty : 'a t -> unit

Return () if the stream is empty, else raise Stream.Failure.

val peek : 'a t -> 'a option

Return Some of "the first element" of the stream, or None if
   the stream is empty.

val junk : 'a t -> unit

Remove the first element of the stream, possibly unfreezing
   it before.

val count : 'a t -> int

Return the current count of the stream elements, i.e. the number
   of the stream elements discarded.

val npeek : int -> 'a t -> 'a list

npeek n returns the list of the n first elements of
   the stream, or all its remaining elements if less than n
   elements are available.

val iapp : 'a t -> 'a t -> 'a t

val icons : 'a -> 'a t -> 'a t

val ising : 'a -> 'a t

val lapp : (unit -> 'a t) -> 'a t -> 'a t

val lcons : (unit -> 'a) -> 'a t -> 'a t

val lsing : (unit -> 'a) -> 'a t

val sempty : 'a t

val slazy : (unit -> 'a t) -> 'a t

val dump : ('a -> unit) -> 'a t -> unit


text:
from django.db.models import ForeignKey, ManyToManyField

class CategoryM2MField(ManyToManyField):
    def __init__(self, **kwargs):
        from .models import Category
        if 'to' in kwargs:
            kwargs.pop('to')
        super(CategoryM2MField, self).__init__(to=Category, **kwargs)

class CategoryFKField(ForeignKey):
    def __init__(self, **kwargs):
        from .models import Category
        if 'to' in kwargs:
            kwargs.pop('to')
        super(CategoryFKField, self).__init__(to=Category, **kwargs)

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^categories\.fields\.CategoryFKField"])
    add_introspection_rules([], ["^categories\.fields\.CategoryM2MField"])
except ImportError:
    pass