text:
package pod

import (
	"strings"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
	"github.com/tektoncd/pipeline/test/diff"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"knative.dev/pkg/apis"
	duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1"
	"knative.dev/pkg/logging"
)

var ignoreVolatileTime = cmp.Comparer(func(_, _ apis.VolatileTime) bool { return true })

func TestSetTaskRunStatusBasedOnStepStatus(t *testing.T) {
	for _, c := range []struct {
		desc              string
		ContainerStatuses []corev1.ContainerStatus
	}{{
		desc: "test result with large pipeline result",
		ContainerStatuses: []corev1.ContainerStatus{{
			Name: "step-bar-0",
			State: corev1.ContainerState{
				Terminated: &corev1.ContainerStateTerminated{
					Message: `[{"key":"resultName","value":"resultValue", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
				},
			},
		},
			{
				Name: "step-bar1",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"resultValue", "type":1}, {"key":"digest","value":"sha256:1234` + strings.Repeat("a", 3072) + `","resourceName":"source-image"}]`,
					},
				},
			},
			{
				Name: "step-bar2",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"resultValue", "type":1}, {"key":"digest","value":"sha256:1234` + strings.Repeat("a", 3072) + `","resourceName":"source-image"}]`,
					},
				},
			}},
	}} {
		t.Run(c.desc, func(t *testing.T) {
			startTime := time.Date(2010, 1, 1, 1, 1, 1, 1, time.UTC)
			tr := v1beta1.TaskRun{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "task-run",
					Namespace: "foo",
				},
				Status: v1beta1.TaskRunStatus{
					TaskRunStatusFields: v1beta1.TaskRunStatusFields{
						StartTime: &metav1.Time{Time: startTime},
					},
				},
			}

			logger, _ := logging.NewLogger("", "status")
			merr := setTaskRunStatusBasedOnStepStatus(logger, c.ContainerStatuses, &tr)
			if merr != nil {
				t.Errorf("setTaskRunStatusBasedOnStepStatus: %s", merr)
			}

		})
	}
}

func TestMakeTaskRunStatus(t *testing.T) {
	for _, c := range []struct {
		desc      string
		podStatus corev1.PodStatus
		pod       corev1.Pod
		want      v1beta1.TaskRunStatus
	}{{
		desc:      "empty",
		podStatus: corev1.PodStatus{},

		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "ignore-creds-init",
		podStatus: corev1.PodStatus{
			InitContainerStatuses: []corev1.ContainerStatus{{
				// creds-init; ignored
				ImageID: "ignored",
			}},
			ContainerStatuses: []corev1.ContainerStatus{{
				Name:    "step-state-name",
				ImageID: "",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 123,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 123,
						}},
					Name:          "state-name",
					ContainerName: "step-state-name",
				}},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "ignore-init-containers",
		podStatus: corev1.PodStatus{
			InitContainerStatuses: []corev1.ContainerStatus{{
				// creds-init; ignored.
				ImageID: "ignoreme",
			}, {
				// git-init; ignored.
				ImageID: "ignoreme",
			}},
			ContainerStatuses: []corev1.ContainerStatus{{
				Name:    "step-state-name",
				ImageID: "image-id",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 123,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 123,
						}},
					Name:          "state-name",
					ContainerName: "step-state-name",
					ImageID:       "image-id",
				}},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "success",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-step-push",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 0,
					},
				},
				ImageID: "image-id",
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 0,
						}},
					Name:          "step-push",
					ContainerName: "step-step-push",
					ImageID:       "image-id",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "running",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodRunning,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-running-step",
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Running: &corev1.ContainerStateRunning{},
					},
					Name:          "running-step",
					ContainerName: "step-running-step",
				}},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "failure-terminated",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodFailed,
			InitContainerStatuses: []corev1.ContainerStatus{{
				// creds-init status; ignored
				ImageID: "ignore-me",
			}},
			ContainerStatuses: []corev1.ContainerStatus{{
				Name:    "step-failure",
				ImageID: "image-id",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 123,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "\"step-failure\" exited with code 123 (image: \"image-id\"); for logs run: kubectl -n foo logs pod -c step-failure\n"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 123,
						}},

					Name:          "failure",
					ContainerName: "step-failure",
					ImageID:       "image-id",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "failure-message",
		podStatus: corev1.PodStatus{
			Phase:   corev1.PodFailed,
			Message: "boom",
		},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "boom"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "failed with OOM",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-step-push",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Reason:   "OOMKilled",
						ExitCode: 0,
					},
				},
				ImageID: "image-id",
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "OOMKilled"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Reason:   "OOMKilled",
							ExitCode: 0,
						}},
					Name:          "step-push",
					ContainerName: "step-step-push",
					ImageID:       "image-id",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc:      "failure-unspecified",
		podStatus: corev1.PodStatus{Phase: corev1.PodFailed},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "build failed for unspecified reasons."),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "pending-waiting-message",
		podStatus: corev1.PodStatus{
			Phase:                 corev1.PodPending,
			InitContainerStatuses: []corev1.ContainerStatus{{
				// creds-init status; ignored
			}},
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-status-name",
				State: corev1.ContainerState{
					Waiting: &corev1.ContainerStateWaiting{
						Message: "i'm pending",
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusPending("Pending", `build step "step-status-name" is pending with reason "i'm pending"`),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Waiting: &corev1.ContainerStateWaiting{
							Message: "i'm pending",
						},
					},
					Name:          "status-name",
					ContainerName: "step-status-name",
				}},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "pending-pod-condition",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodPending,
			Conditions: []corev1.PodCondition{{
				Status:  corev1.ConditionUnknown,
				Type:    "the type",
				Message: "the message",
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusPending("Pending", `pod status "the type":"Unknown"; message: "the message"`),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "pending-message",
		podStatus: corev1.PodStatus{
			Phase:   corev1.PodPending,
			Message: "pod status message",
		},
		want: v1beta1.TaskRunStatus{
			Status: statusPending("Pending", "pod status message"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc:      "pending-no-message",
		podStatus: corev1.PodStatus{Phase: corev1.PodPending},
		want: v1beta1.TaskRunStatus{
			Status: statusPending("Pending", "Pending"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "pending-not-enough-node-resources",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodPending,
			Conditions: []corev1.PodCondition{{
				Reason:  corev1.PodReasonUnschedulable,
				Message: "0/1 nodes are available: 1 Insufficient cpu.",
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusPending(ReasonExceededNodeResources, "TaskRun Pod exceeded available resources"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "pending-CreateContainerConfigError",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodPending,
			ContainerStatuses: []corev1.ContainerStatus{{
				State: corev1.ContainerState{
					Waiting: &corev1.ContainerStateWaiting{
						Reason: "CreateContainerConfigError",
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(ReasonCreateContainerConfigError, "Failed to create pod due to config error"),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps:    []v1beta1.StepState{},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}, {
		desc: "with-sidecar-running",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodRunning,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-running-step",
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{},
				},
			}, {
				Name:    "sidecar-running",
				ImageID: "image-id",
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{},
				},
				Ready: true,
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Running: &corev1.ContainerStateRunning{},
					},
					Name:          "running-step",
					ContainerName: "step-running-step",
				}},
				Sidecars: []v1beta1.SidecarState{{
					ContainerState: corev1.ContainerState{
						Running: &corev1.ContainerStateRunning{},
					},
					Name:          "running",
					ImageID:       "image-id",
					ContainerName: "sidecar-running",
				}},
			},
		},
	}, {
		desc: "with-sidecar-waiting",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodRunning,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-waiting-step",
				State: corev1.ContainerState{
					Waiting: &corev1.ContainerStateWaiting{
						Reason:  "PodInitializing",
						Message: "PodInitializing",
					},
				},
			}, {
				Name:    "sidecar-waiting",
				ImageID: "image-id",
				State: corev1.ContainerState{
					Waiting: &corev1.ContainerStateWaiting{
						Reason:  "PodInitializing",
						Message: "PodInitializing",
					},
				},
				Ready: true,
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Waiting: &corev1.ContainerStateWaiting{
							Reason:  "PodInitializing",
							Message: "PodInitializing",
						},
					},
					Name:          "waiting-step",
					ContainerName: "step-waiting-step",
				}},
				Sidecars: []v1beta1.SidecarState{{
					ContainerState: corev1.ContainerState{
						Waiting: &corev1.ContainerStateWaiting{
							Reason:  "PodInitializing",
							Message: "PodInitializing",
						},
					},
					Name:          "waiting",
					ImageID:       "image-id",
					ContainerName: "sidecar-waiting",
				}},
			},
		},
	}, {
		desc: "with-sidecar-terminated",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodRunning,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-running-step",
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{},
				},
			}, {
				Name:    "sidecar-error",
				ImageID: "image-id",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 1,
						Reason:   "Error",
						Message:  "Error",
					},
				},
				Ready: true,
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusRunning(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Running: &corev1.ContainerStateRunning{},
					},
					Name:          "running-step",
					ContainerName: "step-running-step",
				}},
				Sidecars: []v1beta1.SidecarState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 1,
							Reason:   "Error",
							Message:  "Error",
						},
					},
					Name:          "error",
					ImageID:       "image-id",
					ContainerName: "sidecar-error",
				}},
			},
		},
	}, {
		desc: "image resource updated",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-foo",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"digest","value":"sha256:12345","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:12345","resourceName":"source-image"}]`,
						}},
					Name:          "foo",
					ContainerName: "step-foo",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:12345",
					ResourceName: "source-image",
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "test result with pipeline result",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-bar",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"resultValue", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"resultValue","type":1}]`,
						}},
					Name:          "bar",
					ContainerName: "step-bar",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues("resultValue"),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "test result with pipeline result - no result type",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-banana",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"resultValue", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"resultValue","type":1}]`,
						}},
					Name:          "banana",
					ContainerName: "step-banana",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues("resultValue"),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "two test results",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-one",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultNameOne","value":"resultValueOne", "type":1}, {"key":"resultNameTwo","value":"resultValueTwo", "type":1}]`,
					},
				},
			}, {
				Name: "step-two",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultNameOne","value":"resultValueThree","type":1},{"key":"resultNameTwo","value":"resultValueTwo","type":1}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"resultNameOne","value":"resultValueOne","type":1},{"key":"resultNameTwo","value":"resultValueTwo","type":1}]`,
						}},
					Name:          "one",
					ContainerName: "step-one",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"resultNameOne","value":"resultValueThree","type":1},{"key":"resultNameTwo","value":"resultValueTwo","type":1}]`,
						}},
					Name:          "two",
					ContainerName: "step-two",
				}},
				Sidecars: []v1beta1.SidecarState{},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultNameOne",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues("resultValueThree"),
				}, {
					Name:  "resultNameTwo",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues("resultValueTwo"),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "taskrun status set to failed if task fails",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodFailed,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-mango",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "build failed for unspecified reasons."),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "mango",
					ContainerName: "step-mango",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "termination message not adhering to pipelineresourceresult format is filtered from taskrun termination message",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-pineapple",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"invalid":"resultName","invalid":"resultValue"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "pineapple",
					ContainerName: "step-pineapple",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "filter internaltektonresult",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-pear",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultNameOne","value":"","type":2}, {"key":"resultNameTwo","value":"","type":3}, {"key":"resultNameThree","value":"","type":1}]`},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"resultNameOne","value":"","type":2},{"key":"resultNameThree","value":"","type":1}]`,
						}},
					Name:          "pear",
					ContainerName: "step-pear",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:        "resultNameOne",
					Value:      "",
					ResultType: v1beta1.PipelineResourceResultType,
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultNameThree",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues(""),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "filter internaltektonresult with `type` as string",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-pear",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultNameOne","value":"","type":"PipelineResourceResult"}, {"key":"resultNameTwo","value":"","type":"InternalTektonResult"}, {"key":"resultNameThree","value":"","type":"TaskRunResult"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"resultNameOne","value":"","type":2},{"key":"resultNameThree","value":"","type":1}]`,
						}},
					Name:          "pear",
					ContainerName: "step-pear",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:        "resultNameOne",
					Value:      "",
					ResultType: v1beta1.PipelineResourceResultType,
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultNameThree",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues(""),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "correct TaskRun status step order regardless of pod container status order",
		pod: corev1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: "pod",
			},
			Spec: corev1.PodSpec{
				Containers: []corev1.Container{{
					Name: "step-first",
				}, {
					Name: "step-second",
				}, {
					Name: "step-third",
				}, {
					Name: "step-",
				}, {
					Name: "step-fourth",
				}},
			},
			Status: corev1.PodStatus{
				Phase: corev1.PodSucceeded,
				ContainerStatuses: []corev1.ContainerStatus{{
					Name: "step-second",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}, {
					Name: "step-fourth",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}, {
					Name: "step-",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}, {
					Name: "step-first",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}, {
					Name: "step-third",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}},
			},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
					Name:          "first",
					ContainerName: "step-first",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "second",
					ContainerName: "step-second",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "third",
					ContainerName: "step-third",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "",
					ContainerName: "step-",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{}},
					Name:          "fourth",
					ContainerName: "step-fourth",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "include non zero exit code in a container termination message if entrypoint is set to ignore the error",
		pod: corev1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: "pod",
			},
			Spec: corev1.PodSpec{
				Containers: []corev1.Container{{
					Name: "step-first",
				}, {
					Name: "step-second",
				}},
			},
			Status: corev1.PodStatus{
				Phase: corev1.PodSucceeded,
				ContainerStatuses: []corev1.ContainerStatus{{
					Name: "step-first",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"ExitCode","value":"11","type":"InternalTektonResult"}]`,
						},
					},
				}, {
					Name: "step-second",
					State: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{},
					},
				}},
			},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 11,
						},
					},
					Name:          "first",
					ContainerName: "step-first",
				}, {
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							ExitCode: 0,
						}},
					Name:          "second",
					ContainerName: "step-second",
				}},
				Sidecars: []v1beta1.SidecarState{},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "when pod is pending because of pulling image then the error should bubble up to taskrun status",
		pod: corev1.Pod{
			ObjectMeta: metav1.ObjectMeta{
				Name: "pod",
			},
			Spec: corev1.PodSpec{
				Containers: []corev1.Container{{
					Name: "step-first",
				}},
			},
			Status: corev1.PodStatus{
				Phase: corev1.PodPending,
				ContainerStatuses: []corev1.ContainerStatus{{
					Name: "step-first",
					State: corev1.ContainerState{
						Waiting: &corev1.ContainerStateWaiting{
							Reason:  "ImagePullBackOff",
							Message: "Back-off pulling image xxxxxxx",
						},
					},
				}},
			},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusPending("PullImageFailed", `build step "step-first" is pending with reason "Back-off pulling image xxxxxxx"`),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Waiting: &corev1.ContainerStateWaiting{
							Reason:  "ImagePullBackOff",
							Message: "Back-off pulling image xxxxxxx",
						},
					},
					Name:          "first",
					ContainerName: "step-first",
				}},
				Sidecars: []v1beta1.SidecarState{},
			},
		},
	}} {
		t.Run(c.desc, func(t *testing.T) {
			now := metav1.Now()
			if cmp.Diff(c.pod, corev1.Pod{}) == "" {
				c.pod = corev1.Pod{
					ObjectMeta: metav1.ObjectMeta{
						Name:              "pod",
						Namespace:         "foo",
						CreationTimestamp: now,
					},
					Status: c.podStatus,
				}
			}

			startTime := time.Date(2010, 1, 1, 1, 1, 1, 1, time.UTC)
			tr := v1beta1.TaskRun{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "task-run",
					Namespace: "foo",
				},
				Status: v1beta1.TaskRunStatus{
					TaskRunStatusFields: v1beta1.TaskRunStatusFields{
						StartTime: &metav1.Time{Time: startTime},
					},
				},
			}
			logger, _ := logging.NewLogger("", "status")
			got, err := MakeTaskRunStatus(logger, tr, &c.pod)
			if err != nil {
				t.Errorf("MakeTaskRunResult: %s", err)
			}

			// Common traits, set for test case brevity.
			c.want.PodName = "pod"
			c.want.StartTime = &metav1.Time{Time: startTime}

			ensureTimeNotNil := cmp.Comparer(func(x, y *metav1.Time) bool {
				if x == nil {
					return y == nil
				}
				return y != nil
			})
			if d := cmp.Diff(c.want, got, ignoreVolatileTime, ensureTimeNotNil); d != "" {
				t.Errorf("Diff %s", diff.PrintWantGot(d))
			}
			if tr.Status.StartTime.Time != c.want.StartTime.Time {
				t.Errorf("Expected TaskRun startTime to be unchanged but was %s", tr.Status.StartTime)
			}
		})
	}
}

func TestMakeTaskRunStatusAlpha(t *testing.T) {
	for _, c := range []struct {
		desc      string
		podStatus corev1.PodStatus
		pod       corev1.Pod
		want      v1beta1.TaskRunStatus
	}{{
		desc: "test empty result",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-bar",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"","type":1}]`,
						}},
					Name:          "bar",
					ContainerName: "step-bar",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues(""),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "test string result",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-bar",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"hello", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"hello","type":1}]`,
						}},
					Name:          "bar",
					ContainerName: "step-bar",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeString,
					Value: *v1beta1.NewStructuredValues("hello"),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "test array result",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-bar",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"[\"hello\",\"world\"]", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"[\"hello\",\"world\"]","type":1}]`,
						}},
					Name:          "bar",
					ContainerName: "step-bar",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeArray,
					Value: *v1beta1.NewStructuredValues("hello", "world"),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}, {
		desc: "test object result",
		podStatus: corev1.PodStatus{
			Phase: corev1.PodSucceeded,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name: "step-bar",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						Message: `[{"key":"resultName","value":"{\"hello\":\"world\"}", "type":1}, {"key":"digest","value":"sha256:1234","resourceName":"source-image"}]`,
					},
				},
			}},
		},
		want: v1beta1.TaskRunStatus{
			Status: statusSuccess(),
			TaskRunStatusFields: v1beta1.TaskRunStatusFields{
				Steps: []v1beta1.StepState{{
					ContainerState: corev1.ContainerState{
						Terminated: &corev1.ContainerStateTerminated{
							Message: `[{"key":"digest","value":"sha256:1234","resourceName":"source-image"},{"key":"resultName","value":"{\"hello\":\"world\"}","type":1}]`,
						}},
					Name:          "bar",
					ContainerName: "step-bar",
				}},
				Sidecars: []v1beta1.SidecarState{},
				ResourcesResult: []v1beta1.PipelineResourceResult{{
					Key:          "digest",
					Value:        "sha256:1234",
					ResourceName: "source-image",
				}},
				TaskRunResults: []v1beta1.TaskRunResult{{
					Name:  "resultName",
					Type:  v1beta1.ResultsTypeObject,
					Value: *v1beta1.NewObject(map[string]string{"hello": "world"}),
				}},
				// We don't actually care about the time, just that it's not nil
				CompletionTime: &metav1.Time{Time: time.Now()},
			},
		},
	}} {
		t.Run(c.desc, func(t *testing.T) {
			now := metav1.Now()
			if cmp.Diff(c.pod, corev1.Pod{}) == "" {
				c.pod = corev1.Pod{
					ObjectMeta: metav1.ObjectMeta{
						Name:              "pod",
						Namespace:         "foo",
						CreationTimestamp: now,
					},
					Status: c.podStatus,
				}
			}

			startTime := time.Date(2010, 1, 1, 1, 1, 1, 1, time.UTC)
			tr := v1beta1.TaskRun{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "task-run",
					Namespace: "foo",
				},
				Status: v1beta1.TaskRunStatus{
					TaskRunStatusFields: v1beta1.TaskRunStatusFields{
						StartTime: &metav1.Time{Time: startTime},
					},
				},
			}
			logger, _ := logging.NewLogger("", "status")
			got, err := MakeTaskRunStatus(logger, tr, &c.pod)
			if err != nil {
				t.Errorf("MakeTaskRunResult: %s", err)
			}

			// Common traits, set for test case brevity.
			c.want.PodName = "pod"
			c.want.StartTime = &metav1.Time{Time: startTime}

			ensureTimeNotNil := cmp.Comparer(func(x, y *metav1.Time) bool {
				if x == nil {
					return y == nil
				}
				return y != nil
			})
			if d := cmp.Diff(c.want, got, ignoreVolatileTime, ensureTimeNotNil); d != "" {
				t.Errorf("Diff %s", diff.PrintWantGot(d))
			}
			if tr.Status.StartTime.Time != c.want.StartTime.Time {
				t.Errorf("Expected TaskRun startTime to be unchanged but was %s", tr.Status.StartTime)
			}
		})
	}

}

func TestMakeRunStatusJSONError(t *testing.T) {

	pod := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "pod",
			Namespace: "foo",
		},
		Spec: corev1.PodSpec{
			Containers: []corev1.Container{{
				Name: "step-non-json",
			}, {
				Name: "step-after-non-json",
			}, {
				Name: "step-this-step-might-panic",
			}, {
				Name: "step-foo",
			}},
		},
		Status: corev1.PodStatus{
			Phase: corev1.PodFailed,
			ContainerStatuses: []corev1.ContainerStatus{{
				Name:    "step-this-step-might-panic",
				ImageID: "image",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{},
				},
			}, {
				Name:    "step-foo",
				ImageID: "image",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{},
				},
			}, {
				Name:    "step-non-json",
				ImageID: "image",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 1,
						Message:  "this is a non-json termination message. dont panic!",
					},
				},
			}, {
				Name:    "step-after-non-json",
				ImageID: "image",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{},
				},
			}},
		},
	}
	wantTr := v1beta1.TaskRunStatus{
		Status: statusFailure(v1beta1.TaskRunReasonFailed.String(), "\"step-non-json\" exited with code 1 (image: \"image\"); for logs run: kubectl -n foo logs pod -c step-non-json\n"),
		TaskRunStatusFields: v1beta1.TaskRunStatusFields{
			PodName: "pod",
			Steps: []v1beta1.StepState{{
				ContainerState: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 1,
						Message:  "this is a non-json termination message. dont panic!",
					}},
				Name:          "non-json",
				ContainerName: "step-non-json",
				ImageID:       "image",
			}, {
				ContainerState: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{}},
				Name:          "after-non-json",
				ContainerName: "step-after-non-json",
				ImageID:       "image",
			}, {
				ContainerState: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{}},
				Name:          "this-step-might-panic",
				ContainerName: "step-this-step-might-panic",
				ImageID:       "image",
			}, {
				ContainerState: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{}},
				Name:          "foo",
				ContainerName: "step-foo",
				ImageID:       "image",
			}},
			Sidecars: []v1beta1.SidecarState{},
			// We don't actually care about the time, just that it's not nil
			CompletionTime: &metav1.Time{Time: time.Now()},
		},
	}
	tr := v1beta1.TaskRun{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "task-run",
			Namespace: "foo",
		},
	}

	logger, _ := logging.NewLogger("", "status")
	gotTr, err := MakeTaskRunStatus(logger, tr, pod)
	if err == nil {
		t.Error("Expected error, got nil")
	}

	ensureTimeNotNil := cmp.Comparer(func(x, y *metav1.Time) bool {
		if x == nil {
			return y == nil
		}
		return y != nil
	})
	if d := cmp.Diff(wantTr, gotTr, ignoreVolatileTime, ensureTimeNotNil); d != "" {
		t.Errorf("Diff %s", diff.PrintWantGot(d))
	}

}

func TestSidecarsReady(t *testing.T) {
	for _, c := range []struct {
		desc     string
		statuses []corev1.ContainerStatus
		want     bool
	}{{
		desc: "no sidecars",
		statuses: []corev1.ContainerStatus{
			{Name: "step-ignore-me"},
			{Name: "step-ignore-me"},
			{Name: "step-ignore-me"},
		},
		want: true,
	}, {
		desc: "both sidecars ready",
		statuses: []corev1.ContainerStatus{
			{Name: "step-ignore-me"},
			{
				Name:  "sidecar-bar",
				Ready: true,
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{
						StartedAt: metav1.NewTime(time.Now()),
					},
				},
			},
			{Name: "step-ignore-me"},
			{
				Name: "sidecar-stopped-baz",
				State: corev1.ContainerState{
					Terminated: &corev1.ContainerStateTerminated{
						ExitCode: 99,
					},
				},
			},
			{Name: "step-ignore-me"},
		},
		want: true,
	}, {
		desc: "one sidecar ready, one not running",
		statuses: []corev1.ContainerStatus{
			{Name: "step-ignore-me"},
			{
				Name:  "sidecar-ready",
				Ready: true,
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{
						StartedAt: metav1.NewTime(time.Now()),
					},
				},
			},
			{Name: "step-ignore-me"},
			{
				Name: "sidecar-unready",
				State: corev1.ContainerState{
					Waiting: &corev1.ContainerStateWaiting{},
				},
			},
			{Name: "step-ignore-me"},
		},
		want: false,
	}, {
		desc: "one sidecar running but not ready",
		statuses: []corev1.ContainerStatus{
			{Name: "step-ignore-me"},
			{
				Name:  "sidecar-running-not-ready",
				Ready: false, // Not ready.
				State: corev1.ContainerState{
					Running: &corev1.ContainerStateRunning{
						StartedAt: metav1.NewTime(time.Now()),
					},
				},
			},
			{Name: "step-ignore-me"},
		},
		want: false,
	}} {
		t.Run(c.desc, func(t *testing.T) {
			got := SidecarsReady(corev1.PodStatus{
				Phase:             corev1.PodRunning,
				ContainerStatuses: c.statuses,
			})
			if got != c.want {
				t.Errorf("SidecarsReady got %t, want %t", got, c.want)
			}
		})
	}
}

func TestMarkStatusRunning(t *testing.T) {
	trs := v1beta1.TaskRunStatus{}
	markStatusRunning(&trs, v1beta1.TaskRunReasonRunning.String(), "Not all Steps in the Task have finished executing")

	expected := &apis.Condition{
		Type:    apis.ConditionSucceeded,
		Status:  corev1.ConditionUnknown,
		Reason:  v1beta1.TaskRunReasonRunning.String(),
		Message: "Not all Steps in the Task have finished executing",
	}

	if d := cmp.Diff(expected, trs.GetCondition(apis.ConditionSucceeded), cmpopts.IgnoreFields(apis.Condition{}, "LastTransitionTime.Inner.Time")); d != "" {
		t.Errorf("Unexpected status: %s", diff.PrintWantGot(d))
	}
}

func TestMarkStatusFailure(t *testing.T) {
	trs := v1beta1.TaskRunStatus{}
	markStatusFailure(&trs, v1beta1.TaskRunReasonFailed.String(), "failure message")

	expected := &apis.Condition{
		Type:    apis.ConditionSucceeded,
		Status:  corev1.ConditionFalse,
		Reason:  v1beta1.TaskRunReasonFailed.String(),
		Message: "failure message",
	}

	if d := cmp.Diff(expected, trs.GetCondition(apis.ConditionSucceeded), cmpopts.IgnoreFields(apis.Condition{}, "LastTransitionTime.Inner.Time")); d != "" {
		t.Errorf("Unexpected status: %s", diff.PrintWantGot(d))
	}
}

func TestMarkStatusSuccess(t *testing.T) {
	trs := v1beta1.TaskRunStatus{}
	markStatusSuccess(&trs)

	expected := &apis.Condition{
		Type:    apis.ConditionSucceeded,
		Status:  corev1.ConditionTrue,
		Reason:  v1beta1.TaskRunReasonSuccessful.String(),
		Message: "All Steps have completed executing",
	}

	if d := cmp.Diff(expected, trs.GetCondition(apis.ConditionSucceeded), cmpopts.IgnoreFields(apis.Condition{}, "LastTransitionTime.Inner.Time")); d != "" {
		t.Errorf("Unexpected status: %s", diff.PrintWantGot(d))
	}
}

func statusRunning() duckv1beta1.Status {
	var trs v1beta1.TaskRunStatus
	markStatusRunning(&trs, v1beta1.TaskRunReasonRunning.String(), "Not all Steps in the Task have finished executing")
	return trs.Status
}

func statusFailure(reason, message string) duckv1beta1.Status {
	var trs v1beta1.TaskRunStatus
	markStatusFailure(&trs, reason, message)
	return trs.Status
}

func statusSuccess() duckv1beta1.Status {
	var trs v1beta1.TaskRunStatus
	markStatusSuccess(&trs)
	return trs.Status
}

func statusPending(reason, message string) duckv1beta1.Status {
	return duckv1beta1.Status{
		Conditions: []apis.Condition{{
			Type:    apis.ConditionSucceeded,
			Status:  corev1.ConditionUnknown,
			Reason:  reason,
			Message: message,
		}},
	}
}

// TestSortPodContainerStatuses checks that a complex list of container statuses is
// sorted in the way that we expect them to be according to their step order. This
// exercises a specific failure mode we observed where the image-digest-exporter
// status was inserted before user step statuses, which is not a valid ordering.
// See github issue https://github.com/tektoncd/pipeline/issues/3677 for the full
// details of the bug.
func TestSortPodContainerStatuses(t *testing.T) {
	containerNames := []string{
		"step-create-dir-notification-g2fjb",
		"step-create-dir-builtgcsfetcherimage-68lnn",
		"step-create-dir-builtpullrequestinitimage-nr6gc",
		"step-create-dir-builtdigestexporterimage-mlj2j",
		"step-create-dir-builtwebhookimage-zldcx",
		"step-create-dir-builtcontrollerimage-4nncs",
		"step-create-dir-builtgitinitimage-jbdwk",
		"step-create-dir-builtcredsinitimage-mtrcp",
		"step-create-dir-builtkubeconfigwriterimage-nnfrl",
		"step-create-dir-builtnopimage-c9k2k",
		"step-create-dir-builtentrypointimage-dd7vw",
		"step-create-dir-bucket-jr2lk",
		"step-git-source-source-fkrcz",
		"step-create-dir-bucket-gtw4k",
		"step-fetch-bucket-llqdh",
		"step-create-ko-yaml",
		"step-link-input-bucket-to-output",
		"step-ensure-release-dir-exists",
		"step-run-ko",
		"step-copy-to-latest-bucket",
		"step-tag-images",
		"step-image-digest-exporter-vcqhc",
		"step-source-mkdir-bucket-ljkcz",
		"step-source-copy-bucket-5mwpq",
		"step-upload-bucket-kt9b4",
	}
	containerStatusNames := []string{
		"step-copy-to-latest-bucket",
		"step-create-dir-bucket-gtw4k",
		"step-create-dir-bucket-jr2lk",
		"step-create-dir-builtcontrollerimage-4nncs",
		"step-create-dir-builtcredsinitimage-mtrcp",
		"step-create-dir-builtdigestexporterimage-mlj2j",
		"step-create-dir-builtentrypointimage-dd7vw",
		"step-create-dir-builtgcsfetcherimage-68lnn",
		"step-create-dir-builtgitinitimage-jbdwk",
		"step-create-dir-builtkubeconfigwriterimage-nnfrl",
		"step-create-dir-builtnopimage-c9k2k",
		"step-create-dir-builtpullrequestinitimage-nr6gc",
		"step-create-dir-builtwebhookimage-zldcx",
		"step-create-dir-notification-g2fjb",
		"step-create-ko-yaml",
		"step-ensure-release-dir-exists",
		"step-fetch-bucket-llqdh",
		"step-git-source-source-fkrcz",
		"step-image-digest-exporter-vcqhc",
		"step-link-input-bucket-to-output",
		"step-run-ko",
		"step-source-copy-bucket-5mwpq",
		"step-source-mkdir-bucket-ljkcz",
		"step-tag-images",
		"step-upload-bucket-kt9b4",
	}
	containers := []corev1.Container{}
	statuses := []corev1.ContainerStatus{}
	for _, s := range containerNames {
		containers = append(containers, corev1.Container{
			Name: s,
		})
	}
	for _, s := range containerStatusNames {
		statuses = append(statuses, corev1.ContainerStatus{
			Name: s,
		})
	}
	sortPodContainerStatuses(statuses, containers)
	for i := range statuses {
		if statuses[i].Name != containers[i].Name {
			t.Errorf("container status out of order: want %q got %q", containers[i].Name, statuses[i].Name)
		}
	}
}


text:
require 'dm-transactions/adapters/dm-do-adapter'

module DataMapper
  class Transaction

    module SqlserverAdapter
      include DataObjectsAdapter
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.nutz.dao.impl.jdbc.psql;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.nutz.dao.DB;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.MappingField;
import org.nutz.dao.entity.PkType;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.impl.jdbc.AbstractJdbcExpert;
import org.nutz.dao.impl.jdbc.BlobValueAdaptor3;
import org.nutz.dao.jdbc.JdbcExpertConfigFile;
import org.nutz.dao.jdbc.Jdbcs;
import org.nutz.dao.jdbc.ValueAdaptor;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Pojo;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Pojos;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class PsqlJdbcExpert extends AbstractJdbcExpert {

    private static final Log log = Logs.get();

    public PsqlJdbcExpert(JdbcExpertConfigFile conf) {
        super(conf);
    }

    public String getDatabaseType() {
        return DB.PSQL.name();
    }

    public void formatQuery(Pojo pojo) {
        Pager pager = pojo.getContext().getPager();
        // 需要进行分页
        if (null != pager && pager.getPageNumber() > 0)
            pojo.append(Pojos.Items.wrapf(" LIMIT %d OFFSET %d",
                                          pager.getPageSize(),
                                          pager.getOffset()));
    }

    public void formatQuery(Sql sql) {
        Pager pager = sql.getContext().getPager();
        if (null != pager && pager.getPageNumber() > 0) {
            sql.setSourceSql(sql.getSourceSql()
                             + String.format(" LIMIT %d OFFSET %d",
                                             pager.getPageSize(),
                                             pager.getOffset()));
        }
    }

    public boolean createEntity(Dao dao, Entity<?> en) {
        StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "(");
        // 创建字段
        for (MappingField mf : en.getMappingFields()) {
            if (mf.isReadonly())
                continue;
            sb.append('\n').append(mf.getColumnNameInSql());
            // 自增主键特殊形式关键字
            if (mf.isId() && mf.isAutoIncreasement()) {
                sb.append(" SERIAL");
            } else {
                sb.append(' ').append(evalFieldType(mf));
                // 非主键的 @Name,应该加入唯一性约束
                if (mf.isName() && en.getPkType() != PkType.NAME) {
                    sb.append(" UNIQUE NOT NULL");
                }
                // 普通字段
                else {
                    if (mf.isUnsigned())
                        sb.append(" UNSIGNED");
                    if (mf.isNotNull())
                        sb.append(" NOT NULL");
                    if (mf.isAutoIncreasement())
                        throw Lang.noImplement();
                    if (mf.hasDefaultValue())
                        addDefaultValue(sb, mf);
                }
            }
            sb.append(',');
        }
        // 创建主键
        List<MappingField> pks = en.getPks();
        if (!pks.isEmpty()) {
            sb.append('\n');
            sb.append(String.format("CONSTRAINT %s_pkey PRIMARY KEY (",
                                    en.getTableName().replace('.', '_').replace('"', '_')));
            for (MappingField pk : pks) {
                sb.append(pk.getColumnNameInSql()).append(',');
            }
            sb.setCharAt(sb.length() - 1, ')');
            sb.append("\n ");
        }

        // 结束表字段设置
        sb.setCharAt(sb.length() - 1, ')');

        // 执行创建语句
        dao.execute(Sqls.create(sb.toString()));

        // 创建索引
        dao.execute(createIndexs(en).toArray(new Sql[0]));

        // 创建关联表
        createRelation(dao, en);

        // 添加注释(表注释与字段注释)
        addComment(dao, en);

        return true;
    }

    public String evalFieldType(MappingField mf) {
        if (mf.getCustomDbType() != null)
            return mf.getCustomDbType();
        switch (mf.getColumnType()) {
        case INT:
            // 用户自定义了宽度
            if (mf.getWidth() > 0)
                return "NUMERIC(" + mf.getWidth() + ")";
            // 用数据库的默认宽度
            return "INT";

        case FLOAT:
            // 用户自定义了精度
            if (mf.getWidth() > 0 && mf.getPrecision() > 0) {
                return "NUMERIC(" + mf.getWidth() + "," + mf.getPrecision() + ")";
            }
            // 用默认精度
            if (mf.getMirror().isDouble())
                return "NUMERIC(15,10)";
            return "NUMERIC";

        case BINARY:
            return "BYTEA";

        case DATETIME:
            return "TIMESTAMP";

        case PSQL_JSON:
            return "JSON";

        case PSQL_ARRAY:
            return "ARRAY";

        default:
            break;
        }
        return super.evalFieldType(mf);
    }

    protected String createResultSetMetaSql(Entity<?> en) {
        return "SELECT * FROM " + en.getViewName() + " LIMIT 1";
    }

    @Override
    public ValueAdaptor getAdaptor(MappingField ef) {
        if (ef.getMirror().isOf(Blob.class)) {
            return new BlobValueAdaptor3(Jdbcs.getFilePool());
        } else if (ColType.PSQL_JSON == ef.getColumnType()) {
            return new PsqlJsonAdaptor();
        } else if (ColType.PSQL_ARRAY == ef.getColumnType()) {
            return new PsqlArrayAdaptor(ef.getCustomDbType());
        } else {
            return super.getAdaptor(ef);
        }
    }

    public String wrapKeyword(String columnName, boolean force) {
        if (force || keywords.contains(columnName.toUpperCase()))
            return "\"" + columnName + "\"";
        return null;
    }

    @Override
    public void checkDataSource(Connection conn) throws SQLException {
        if (log.isDebugEnabled()) {
            String sql = "SELECT * FROM information_schema.character_sets";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                for (String name : Arrays.asList("character_set_catalog",
                                                 "character_set_schema",
                                                 "character_set_name",
                                                 "character_repertoire",
                                                 "form_of_use",
                                                 "default_collate_catalog",
                                                 "default_collate_schema",
                                                 "default_collate_name")) {
                    log.debugf("Postgresql : %s=%s", name, rs.getString(name));
                }
            }
            rs.close();
            // 打印当前数据库名称
            rs = stmt.executeQuery("SELECT CURRENT_DATABASE()");
            if (rs.next()) {
                log.debug("Postgresql : database=" + rs.getString(1));
            }
            rs.close();
            // 打印当前连接用户名
            rs = stmt.executeQuery("SELECT CURRENT_USER");
            if (rs.next()) {
                log.debug("Postgresql : user=" + rs.getString(1));
            }
            rs.close();
            stmt.close();
        }
    }

    /**
     * @author enzozhong( haowen.zhong@foxmail.com )
     */
    @Override
    public List<String> getIndexNames(Entity<?> en, Connection conn) throws SQLException {

        String tableName = en.getTableName();
        String sql = "SELECT * FROM pg_indexes WHERE tablename='" + tableName + "'";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        ArrayList<String> indexNames = new ArrayList<String>(17);
        while (rs.next()) {
            indexNames.add(rs.getString("indexname"));
        }

        return indexNames;
    }
}


text:
package aQute.bnd.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.CLASS)
@Target({
	ElementType.PACKAGE
})
public @interface Version {
	String value();
}


text:
namespace csis3700 {

  sprite::sprite(float initial_x, float initial_y) {
    position = vec2d(initial_x, initial_y);
    time = 0;
  }

  void sprite::set_image_sequence(image_sequence *s) {
    sequence = s;
  }

  sprite::~sprite() {
  }

  int sprite::get_width() const {
    return sequence->get_width();
  }

  int sprite::get_height() const {
    return sequence->get_height();
  }

  float sprite::get_x() const {
    return position.get_x();
  }

  float sprite::get_y() const {
    return position.get_y();
  }

  void sprite::draw() {
    sequence->draw(time, get_x(), get_y());
  }

  rectangle sprite::bounding_box() const {
    return rectangle(position, get_width(), get_height());
  }

  rectangle sprite::collision_rectangle(const sprite& other) const {
    return bounding_box().intersection(other.bounding_box());
  }

  bool sprite::collides_with(const sprite& other) const {
    return !collision_rectangle(other).is_degenerate();
  }

  void sprite::advance_by_time(double dt) {
    time += dt;
  }

  bool sprite::is_passive() const {
    return true;
  }

  vec2d sprite::get_position() const {
    return position;
  }

  void sprite::set_position(vec2d p) {
    position = p;
  }

}


text:
from __future__ import annotations
from typing import Sequence, Optional
import abc
from ezdxf.lldxf import const
from ezdxf.entities.mtext import MText, MTextColumns
from ezdxf.enums import (
    MTextParagraphAlignment,
)
from ezdxf.tools import text_layout as tl, fonts
from ezdxf.tools.text import (
    MTextParser,
    MTextContext,
    TokenType,
    ParagraphProperties,
    AbstractFont,
    estimate_mtext_extents,
)

__all__ = ["AbstractMTextRenderer"]

ALIGN = {
    MTextParagraphAlignment.LEFT: tl.ParagraphAlignment.LEFT,
    MTextParagraphAlignment.RIGHT: tl.ParagraphAlignment.RIGHT,
    MTextParagraphAlignment.CENTER: tl.ParagraphAlignment.CENTER,
    MTextParagraphAlignment.JUSTIFIED: tl.ParagraphAlignment.JUSTIFIED,
    MTextParagraphAlignment.DISTRIBUTED: tl.ParagraphAlignment.JUSTIFIED,
    MTextParagraphAlignment.DEFAULT: tl.ParagraphAlignment.LEFT,
}

ATTACHMENT_POINT_TO_ALIGN = {
    const.MTEXT_TOP_LEFT: tl.ParagraphAlignment.LEFT,
    const.MTEXT_MIDDLE_LEFT: tl.ParagraphAlignment.LEFT,
    const.MTEXT_BOTTOM_LEFT: tl.ParagraphAlignment.LEFT,
    const.MTEXT_TOP_CENTER: tl.ParagraphAlignment.CENTER,
    const.MTEXT_MIDDLE_CENTER: tl.ParagraphAlignment.CENTER,
    const.MTEXT_BOTTOM_CENTER: tl.ParagraphAlignment.CENTER,
    const.MTEXT_TOP_RIGHT: tl.ParagraphAlignment.RIGHT,
    const.MTEXT_MIDDLE_RIGHT: tl.ParagraphAlignment.RIGHT,
    const.MTEXT_BOTTOM_RIGHT: tl.ParagraphAlignment.RIGHT,
}

STACKING = {
    "^": tl.Stacking.OVER,
    "/": tl.Stacking.LINE,
    "#": tl.Stacking.SLANTED,
}

def make_default_tab_stops(cap_height: float, width: float) -> list[tl.TabStop]:
    tab_stops = []
    step = 4.0 * cap_height
    pos = step
    while pos < width:
        tab_stops.append(tl.TabStop(pos, tl.TabStopType.LEFT))
        pos += step
    return tab_stops

def append_default_tab_stops(
    tab_stops: list[tl.TabStop], default_stops: Sequence[tl.TabStop]
) -> None:
    last_pos = 0.0
    if tab_stops:
        last_pos = tab_stops[-1].pos
    tab_stops.extend(stop for stop in default_stops if stop.pos > last_pos)

def make_tab_stops(
    cap_height: float,
    width: float,
    tab_stops: Sequence,
    default_stops: Sequence[tl.TabStop],
) -> list[tl.TabStop]:
    _tab_stops = []
    for stop in tab_stops:
        if isinstance(stop, str):
            value = float(stop[1:])
            if stop[0] == "c":
                kind = tl.TabStopType.CENTER
            else:
                kind = tl.TabStopType.RIGHT
        else:
            kind = tl.TabStopType.LEFT
            value = float(stop)
        pos = value * cap_height
        if pos < width:
            _tab_stops.append(tl.TabStop(pos, kind))

    append_default_tab_stops(_tab_stops, default_stops)
    return _tab_stops

def get_stroke(ctx: MTextContext) -> int:
    stroke = 0
    if ctx.underline:
        stroke += tl.Stroke.UNDERLINE
    if ctx.strike_through:
        stroke += tl.Stroke.STRIKE_THROUGH
    if ctx.overline:
        stroke += tl.Stroke.OVERLINE
    if ctx.continue_stroke:
        stroke += tl.Stroke.CONTINUE
    return stroke

def new_paragraph(
    cells: list,
    ctx: MTextContext,
    cap_height: float,
    line_spacing: float = 1,
    width: float = 0,
    default_stops: Optional[Sequence[tl.TabStop]] = None,
):
    if cells:
        p = ctx.paragraph
        align = ALIGN.get(p.align, tl.ParagraphAlignment.LEFT)
        left = p.left * cap_height
        right = p.right * cap_height
        first = left + p.indent * cap_height  # relative to left
        _default_stops: Sequence[tl.TabStop] = default_stops or []
        tab_stops = _default_stops
        if p.tab_stops:
            tab_stops = make_tab_stops(
                cap_height, width, p.tab_stops, _default_stops
            )
        paragraph = tl.Paragraph(
            align=align,
            indent=(first, left, right),
            line_spacing=line_spacing,
            tab_stops=tab_stops,
        )
        paragraph.append_content(cells)
    else:
        paragraph = tl.EmptyParagraph(  # type: ignore
            cap_height=ctx.cap_height, line_spacing=line_spacing
        )
    return paragraph

def super_glue():
    return tl.NonBreakingSpace(width=0, min_width=0, max_width=0)

def defined_width(mtext: MText) -> float:
    width = mtext.dxf.get("width", 0.0)
    if width < 1e-6:
        width, height = estimate_mtext_extents(mtext)
    return width

def column_heights(columns: MTextColumns) -> list[Optional[float]]:
    heights: list[Optional[float]]
    if columns.heights:  # dynamic manual
        heights = list(columns.heights)
        # last height has to be auto height = None
        heights[-1] = None
    else:  # static, dynamic auto
        heights = [columns.defined_height] * columns.count
    return heights

class AbstractMTextRenderer(abc.ABC):
    def __init__(self) -> None:
        self._font_cache: dict[tuple[str, float, float], AbstractFont] = {}

    @abc.abstractmethod
    def word(self, test: str, ctx: MTextContext) -> tl.ContentCell:
        ...

    @abc.abstractmethod
    def fraction(
        self, data: tuple[str, str, str], ctx: MTextContext
    ) -> tl.ContentCell:
        ...

    @abc.abstractmethod
    def get_font_face(self, mtext: MText) -> fonts.FontFace:
        ...

    @abc.abstractmethod
    def make_bg_renderer(self, mtext: MText) -> tl.ContentRenderer:
        ...

    def make_mtext_context(self, mtext: MText) -> MTextContext:
        ctx = MTextContext()
        ctx.paragraph = ParagraphProperties(
            align=ATTACHMENT_POINT_TO_ALIGN.get(  # type: ignore
                mtext.dxf.attachment_point, tl.ParagraphAlignment.LEFT
            )
        )
        ctx.font_face = self.get_font_face(mtext)
        ctx.cap_height = mtext.dxf.char_height
        ctx.aci = mtext.dxf.color
        rgb = mtext.rgb
        if rgb is not None:
            ctx.rgb = rgb
        return ctx

    def get_font(self, ctx: MTextContext) -> fonts.AbstractFont:
        ttf = fonts.find_ttf_path(ctx.font_face)  # 1st call is very slow
        key = (ttf, ctx.cap_height, ctx.width_factor)
        font = self._font_cache.get(key)
        if font is None:
            font = fonts.make_font(ttf, ctx.cap_height, ctx.width_factor)
            self._font_cache[key] = font
        return font

    def get_stroke(self, ctx: MTextContext) -> int:
        return get_stroke(ctx)

    def get_stacking(self, type_: str) -> tl.Stacking:
        return STACKING.get(type_, tl.Stacking.LINE)

    def space_width(self, ctx: MTextContext) -> float:
        return self.get_font(ctx).space_width()

    def space(self, ctx: MTextContext):
        return tl.Space(width=self.space_width(ctx))

    def tabulator(self, ctx: MTextContext):
        return tl.Tabulator(width=self.space_width(ctx))

    def non_breaking_space(self, ctx: MTextContext):
        return tl.NonBreakingSpace(width=self.space_width(ctx))

    def layout_engine(self, mtext: MText) -> tl.Layout:
        initial_cap_height = mtext.dxf.char_height
        line_spacing = mtext.dxf.line_spacing_factor

        def append_paragraph():
            paragraph = new_paragraph(
                cells,
                ctx,
                initial_cap_height,
                line_spacing,
                width,
                default_stops,
            )
            layout.append_paragraphs([paragraph])
            cells.clear()

        bg_renderer = self.make_bg_renderer(mtext)
        width = defined_width(mtext)
        default_stops = make_default_tab_stops(initial_cap_height, width)
        layout = tl.Layout(width=width)
        if mtext.has_columns:
            columns = mtext.columns
            assert columns is not None
            for height in column_heights(columns):
                layout.append_column(
                    width=columns.width,
                    height=height,
                    gutter=columns.gutter_width,
                    renderer=bg_renderer,
                )
        else:
            # column with auto height and default width
            layout.append_column(renderer=bg_renderer)

        content = mtext.all_columns_raw_content()
        ctx = self.make_mtext_context(mtext)
        cells: list[tl.Cell] = []
        for token in MTextParser(content, ctx):
            ctx = token.ctx
            if token.type == TokenType.NEW_PARAGRAPH:
                append_paragraph()
            elif token.type == TokenType.NEW_COLUMN:
                append_paragraph()
                layout.next_column()
            elif token.type == TokenType.SPACE:
                cells.append(self.space(ctx))
            elif token.type == TokenType.NBSP:
                cells.append(self.non_breaking_space(ctx))
            elif token.type == TokenType.TABULATOR:
                cells.append(self.tabulator(ctx))
            elif token.type == TokenType.WORD:
                if cells and isinstance(cells[-1], (tl.Text, tl.Fraction)):
                    # Create an unbreakable connection between those two parts.
                    cells.append(super_glue())
                cells.append(self.word(token.data, ctx))
            elif token.type == TokenType.STACK:
                if cells and isinstance(cells[-1], (tl.Text, tl.Fraction)):
                    # Create an unbreakable connection between those two parts.
                    cells.append(super_glue())
                cells.append(self.fraction(token.data, ctx))

        if cells:
            append_paragraph()

        return layout


text:
package org.apache.axis2.dataretrieval;

import org.apache.axiom.om.OMNode;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.util.XMLUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.commons.schema.XmlSchema;

import javax.xml.stream.XMLStreamException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Axis 2 Data Locator responsibles for retrieving Schema metadata. The class is
 * created as model for schema specific data locator; and also easier for any
 * future implementation schema specific data retrieval logic.
 */

public class SchemaDataLocator extends BaseAxisDataLocator implements
        AxisDataLocator {

    private String requestIdentifier = null;

    private String serviceEPR = null;

    /**
     *
     */
    private static final Log LOG = LogFactory.getLog(SchemaDataLocator.class
            .getClass().getName());

    protected SchemaDataLocator() {

    }

    /**
     * Constructor
     */
    protected SchemaDataLocator(ServiceData[] data) {
        dataList = data;
    }

    public Data[] getData(DataRetrievalRequest request,
            MessageContext msgContext) throws DataRetrievalException {

        requestIdentifier = request.getIdentifier();
        serviceEPR = msgContext.getTo().getAddress();

        OutputForm outputForm = request.getOutputForm();
        if (outputForm == null) {
            outputForm = OutputForm.INLINE_FORM;
        }

        Data[] data;

        if (outputForm == OutputForm.INLINE_FORM) {
            data = outputInlineForm(msgContext, dataList);

        } else if (outputForm == OutputForm.LOCATION_FORM) {
            data = outputLocationForm(dataList);

        } else {
            data = outputReferenceForm(msgContext, dataList);
        }

        return data;
    }

    protected Data[] outputInlineForm(MessageContext msgContext,
            ServiceData[] serviceData) throws DataRetrievalException {

        Data[] data = super.outputInlineForm(msgContext, serviceData);

        if (data.length != 0) {
            return data;
        }

        AxisService axisService = msgContext.getAxisService();
        ArrayList schemaList = axisService.getSchema();

        ArrayList results = new ArrayList();
        XmlSchema schema;

        for (Iterator iterator = schemaList.iterator(); iterator.hasNext();) {
            schema = (XmlSchema) iterator.next();

            if (requestIdentifier != null) {
                if (requestIdentifier.equals(schema.getTargetNamespace())) {
                    results.add(new Data(convertToOM(schema), requestIdentifier));
                }
            } else {
                results.add(new Data(convertToOM(schema), null));
            }
        }

        return (Data[]) results.toArray(new Data[results.size()]);
    }

    protected Data[] outputLocationForm(ServiceData[] serviceData)
            throws DataRetrievalException {

        Data[] data = super.outputLocationForm(serviceData);

        if (data != null && data.length != 0) {
            return data;
        }
        return new Data[] { new Data(serviceEPR + "?xsd", requestIdentifier) };
    }

    private OMNode convertToOM(XmlSchema schema) throws DataRetrievalException {
        StringWriter writer = new StringWriter();
        schema.write(writer);

        StringReader reader = new StringReader(writer.toString());
        try {
            return XMLUtils.toOM(reader);
        } catch (XMLStreamException e) {
            throw new DataRetrievalException(
                    "Can't convert XmlSchema object to an OMElement", e);
        }
    }
}


text:
package org.jboss.aerogear.test;

import at.ftec.aerogear.exception.AerogearHelperException;
import org.jboss.aerogear.test.builders.PushApplicationBuilder;
import org.jboss.aerogear.unifiedpush.api.PushApplication;

import java.util.Observable;
import java.util.UUID;

/**
 * Loader for MOCK apps.
 * Notifies its list of {@link java.util.Observer}s everytime a new app is created or if the creation has failed.
 */
public class MockAppLoader extends Observable implements Runnable {
    private String APPNAME_PATTERN = "Test App %d";
    private String DEVELOPER_PATTERN = "Developer %d";
    private String DESCRIPTION_PATTERN = "Test App %d";
    private String MASTER_SECRET = "Shhh!!! Don't tell anyone!!";

    private final int appCount;

    private final AerogearAdminServiceProvider provider;

    /**
     * Initializes the loader.
     * @param provider provider to be used to authenticate to UPS
     * @param appCount number of apps to be created
     */
    MockAppLoader(final AerogearAdminServiceProvider provider, final int appCount) {
        this.provider = provider;
        this.appCount = appCount;
    }

    /**
     * Runs the loader
     */
    public void run() {

        provider.setCacheAnswer(false);

        for (int i = 0; i < appCount; i++) {
            // Whatever the creation succeeds or fails, the change state must be true to notify the observers
            setChanged();
            String appId = UUID.randomUUID().toString();
            String appName = String.format(APPNAME_PATTERN, i);

            try {

                PushApplicationBuilder builder =
                    PushApplicationBuilder.forApplication(appId, appName)
                        .withDescription(String.format(DESCRIPTION_PATTERN, i))
                        .withDeveloper(String.format(DEVELOPER_PATTERN, i))
                        .withMasterSecret(MASTER_SECRET)
                        .withPushApplicationID(appId);

                PushApplication app = provider.getAdminService().createPushApplication(builder.build());

                // App created: notify the observers and pass the newly created app§
                notifyObservers(app);
            } catch (AerogearHelperException re) {

                // Creation failed: notify the observers and pass the exception
                notifyObservers(re);
            }
        }
    }
}


text:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('mnist_data/', one_hot=True)

import tensorflow as tf

tf.reset_default_graph()
# Parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
display_step = 1

# Network parameters
n_hidden_1 = 256
n_input = 784
n_classes = 10

# Input graph
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])

# Create Model for multi layer perceptron

def multilayer_perceptron(x, weights, biases):

    # Hidden layer 1
    hidden_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    hidden_activated = tf.nn.relu(hidden_1)
    output = tf.add(tf.matmul(hidden_activated, weights['out']), biases['out'])
    return output

# Store weights and biases
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes]))
}

biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

logits = multilayer_perceptron(x, weights, biases)
# Loss

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits= \
    logits, labels=y))

"""
softmax = tf.nn.softmax(logits)
cost = tf.reduce_mean(tf.reduce_sum(-y*tf.log(softmax),reduction_indices=[1]))
"""

save_file = './train_model.ckpt'

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

correct_prediction = tf.equal(tf.argmax(logits,1),tf.argmax(y,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

init = tf.initialize_all_variables()

saver = tf.train.Saver()

def save_model():
    with tf.Session() as sess:
        sess.run(init)
        # Training cycle
        for epoch in range(training_epochs):
            avg_cost = 0
            total_batch = int(mnist.train.num_examples/batch_size)
            # Loop over all batches
            for i in range(total_batch):
                batch_x,batch_y = mnist.train.next_batch(batch_size)
                # Run optimizer
                _,c = sess.run([optimizer,cost],feed_dict={x:batch_x,y:batch_y})
                avg_cost += c/total_batch
            if epoch % display_step == 0:
                print "Epoch:", '%04d' % (epoch+1), "cost=", \
                    "{:.9f}".format(avg_cost)
                validation_accuracy = sess.run(
                        accuracy,
                        feed_dict={
                            x: mnist.validation.images,
                            y: mnist.validation.labels
                        }
                        )
                print('Epoch {:<3} - Validation Accuracy: {}'.format(
                    epoch,
                    validation_accuracy))

        print "Optimization Finished!"

        # Test model
        correct_test_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
        # Calculate accuracy
        test_accuracy = tf.reduce_mean(tf.cast(correct_test_prediction, "float"))
        print "Accuracy:", test_accuracy.eval({x: mnist.test.images,
                                                y: mnist.test.labels})
        saver.save(sess, save_file)
        print('Trained Model saved')

def load_model():
    with tf.Session() as sess:
        saver.restore(sess, save_file)

        test_accuracy = sess.run(
            accuracy,
            feed_dict={x: mnist.test.images, y: mnist.test.labels})

    print('Test Accuracy: {}'.format(test_accuracy))

if __name__=='__main__':
    save_model()


text:
OpenLayers.Control.ArcGisRestIdentify = OpenLayers.Class(OpenLayers.Control, {
        layerid:null,
        eventListeners:null,
        url:null,
        clickTolerance:0,
        EVENT_TYPES: ["resultarrived", "arcfeaturequery"],
        outFields : "",

        defaultHandlerOptions: {
                'single': true,
                'double': false,
                'pixelTolerance': 0,
                'stopSingle': false,
                'stopDouble': false,
                'sr' : 4326
        },

        initialize: function(options) {
                this.EVENT_TYPES =
                OpenLayers.Control.ArcGisRestIdentify .prototype.EVENT_TYPES.concat(
                        OpenLayers.Control.prototype.EVENT_TYPES
                );
                this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                );
                OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                );
                var callbacks = {};
                callbacks['click'] = this.doQuery;
                this.handler = new OpenLayers.Handler.Click(
                        this,
                        callbacks,
                        this.handlerOptions
                );
        },

        activate: function () {
                if (!this.active) {
                        this.handler.activate();
                }
                return OpenLayers.Control.prototype.activate.apply(
                        this, arguments
                );
        },

        deactivate: function () {
                return OpenLayers.Control.prototype.deactivate.apply(
                        this, arguments
                );
        },

        /*trigger: function(e) {
                var lonlat = map.getLonLatFromViewPortPx(e.xy);
                alert("You clicked near " + lonlat.lat + " N, " +
                                                                  + lonlat.lon + " E");*/

        buildOptions: function(clickPosition,url){

                evtlonlat = this.map.getLonLatFromPixel(clickPosition);
                var spatialRel = "esriSpatialRelIntersects";
                var geometryType = "esriGeometryPoint";
                var geometry = evtlonlat.lon+","+evtlonlat.lat;
                //If there is a click tolerance, let's calculate an envelope to use to check for any results.
                if(this.clickTolerance > 0)
                {
                  var urXY = new OpenLayers.Pixel();
                  urXY.x = clickPosition.x + this.clickTolerance;
                  urXY.y = clickPosition.y + this.clickTolerance;
                  var urUR = this.map.getLonLatFromPixel(urXY);

                  var llXY = new OpenLayers.Pixel();
                  llXY.x = clickPosition.x - this.clickTolerance;
                  llXY.y = clickPosition.y - this.clickTolerance;
                  var llLL = this.map.getLonLatFromPixel(llXY);

                  geometryType = "esriGeometryEnvelope";
                  geometry = llLL.lon + "," + llLL.lat + "," + urUR.lon + "," + urUR.lat;
                }
                var queryoptions =
                {
                  geometry : geometry,
                  geometryType : geometryType,
                  inSR : this.sr,
                  outSR : this.sr,
                  spatialRel : spatialRel,
                  f : "json",
                  returnGeometry:"true",
                  outFields : this.outFields
                };

                var query = {
                        url:url,
                        headers: {"Content-type" : "application/json"},
                        params : queryoptions,
                        proxy: '/proxy/get_legend_json/?url=',
                        callback: function(request)
                        {
                          this.handleresult(request,clickPosition);
                        },
                        scope: this
                };
                return query
        },

        handleresult: function(result,xy){
                this.events.triggerEvent("resultarrived",{
                        text:result.responseText,
                        xy:xy
                });
        },

        request: function(clickPosition){
                queryOptions = this.buildOptions(clickPosition,this.url);
                var request = OpenLayers.Request.GET(queryOptions);
        },

        doQuery: function(e){
          var makeRequest = this.events.triggerEvent("arcfeaturequery",{});
          if (makeRequest !== false) {
            this.request(e.xy);
          }
        }
});


text:
desc_pl=DHCP - Serwer
<<<<<<< HEAD
longdesc_pl=Zarz±dzaj udostêpnianiem sieci, podsieci, hostów i grup dla ISC DHCPD.
=======
longdesc_pl=Zarządzaj udostępnianiem sieci, podsieci, hostów i grup dla ISC DHCPD.
>>>>>>> upstream/master


text:
@interface MJTestViewController : UIViewController

@end


text:
/********************************************************************************
*
* File CCOLLTST.C
*
* Modification History:
*        Name                     Description
*     Madhu Katragadda               Creation
*********************************************************************************
*/
#include <stdio.h>

#include "unicode/utypes.h"

#if !UCONFIG_NO_COLLATION

#include "cintltst.h"
#include "ccolltst.h"
#include "unicode/ucol.h"
#include "unicode/ustring.h"
#include "cmemory.h"

void addCollTest(TestNode** root);

void addCollTest(TestNode** root)
{
    addCollAPITest(root);
    addCurrencyCollTest(root);
#if !UCONFIG_NO_NORMALIZATION
    addNormTest(root);
#endif
    addGermanCollTest(root);
    addSpanishCollTest(root);
    addFrenchCollTest(root);
    addKannaCollTest(root);
    addTurkishCollTest(root);
    addEnglishCollTest(root);
    addFinnishCollTest(root);

    /* WEIVTODO: return tests here */
    addRuleBasedCollTest(root);
    addCollIterTest(root);
    addAllCollTest(root);
    addMiscCollTest(root);
#if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILE_IO
    addSearchTest(root);
#endif
}

/*Internal functions used*/
static char* dumpSk(uint8_t *sourceKey, char *sk) {
    uint32_t kLen = (uint32_t)strlen((const char *)sourceKey);
    uint32_t i = 0;

    *sk = 0;

    for(i = 0; i<kLen; i++) {
        sprintf(sk+2*i, "%02X", sourceKey[i]);
    }
    return sk;
}

static const char *getCompareResult(UCollationResult result)
{
    if (result == UCOL_LESS)
    {
        return "LESS";
    }
    else if (result == UCOL_EQUAL)
    {
        return "EQUAL";
    }
    else if (result == UCOL_GREATER)
    {
        return "GREATER";
    }
    return "invalid UCollationResult?";
}

void reportCResult( const UChar source[], const UChar target[],
                         uint8_t *sourceKey, uint8_t *targetKey,
                         UCollationResult compareResult,
                         UCollationResult keyResult,
                         UCollationResult incResult,
                         UCollationResult expectedResult )
{
    if (expectedResult < -1 || expectedResult > 1)
    {
        log_err("***** invalid call to reportCResult ****\n");
        return;
    }

    if (compareResult != expectedResult)
    {
        log_err("Compare(%s , %s) returned: %s expected: %s\n", aescstrdup(source,-1), aescstrdup(target,-1),
            getCompareResult(compareResult), getCompareResult(expectedResult) );
    }

    if (incResult != expectedResult)
    {
        log_err("incCompare(%s , %s) returned: %s expected: %s\n", aescstrdup(source,-1), aescstrdup(target,-1),
            getCompareResult(incResult), getCompareResult(expectedResult) );
    }

    if (keyResult != expectedResult)
    {
        log_err("KeyCompare(%s , %s) returned: %s expected: %s\n", aescstrdup(source,-1), aescstrdup(target,-1),
            getCompareResult(keyResult), getCompareResult(expectedResult) );
    }

    if (keyResult != compareResult)
    {
        log_err("difference between sortkey and compare result for (%s , %s) Keys: %s compare %s\n", aescstrdup(source,-1), aescstrdup(target,-1),
            getCompareResult(keyResult), getCompareResult(compareResult));
    }

    if(keyResult != expectedResult || keyResult != compareResult)
    {
        char sk[10000];
        log_verbose("SortKey1: %s\n", dumpSk(sourceKey, sk));
        log_verbose("SortKey2: %s\n", dumpSk(targetKey, sk));
    }
}

#endif /* #if !UCONFIG_NO_COLLATION */


text:
package graphene.export.anb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

public class AttributeClass {

	private String attrName;
	private String attrType;
	private Boolean attrShowValue;
	private Boolean attrVisible;
	private Boolean attrUserCanAdd;
	private Boolean attrUserCanRemove;
	private String attrPrefix;
	private Boolean attrShowPrefix;
	private Font font;

	//------------------------------------------------------------------------------------------------------------------

    public AttributeClass() {}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrName(String attrName) {
		this.attrName = attrName;
	}

	//------------------------------------------------------------------------------------------------------------------

	public String setAttrName() {
		return this.attrName;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrType(String attrType) {
		this.attrType = attrType;
	}

	//------------------------------------------------------------------------------------------------------------------

	public String setAttrType() {
		return this.attrType;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrShowValue(Boolean attrShowValue) {
		this.attrShowValue = attrShowValue;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Boolean setAttrShowValue() {
		return this.attrShowValue;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrVisible(Boolean attrVisible) {
		this.attrVisible = attrVisible;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Boolean setAttrVisible() {
		return this.attrVisible;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrUserCanAdd(Boolean attrUserCanAdd) {
		this.attrUserCanAdd = attrUserCanAdd;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Boolean setAttrUserCanAdd() {
		return this.attrUserCanAdd;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrUserCanRemove(Boolean attrUserCanRemove) {
		this.attrUserCanRemove = attrUserCanRemove;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Boolean setAttrUserCanRemove() {
		return this.attrUserCanRemove;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrPrefix(String attrPrefix) {
		this.attrPrefix = attrPrefix;
	}

	//------------------------------------------------------------------------------------------------------------------

	public String setAttrPrefix() {
		return this.attrPrefix;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlAttribute
    public void setAttrShowPrefix(Boolean attrShowPrefix) {
		this.attrShowPrefix = attrShowPrefix;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Boolean setAttrShowPrefix() {
		return this.attrShowPrefix;
	}

	//------------------------------------------------------------------------------------------------------------------

	@XmlElement
	public void setFont(Font font) {
		this.font = font;
	}

	//------------------------------------------------------------------------------------------------------------------

	public Font getFont() {
		return this.font;
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.economicsl</groupId>
    <artifactId>esl-auctions</artifactId>
    <packaging>jar</packaging>
    <version>0.2.0-SNAPSHOT</version>
    <name>esl-auctions</name>
    <url>http://maven.apache.org</url>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <encoding>UTF-8</encoding>
        <scala.version>2.12.1</scala.version>
    </properties>

    <build>
        <plugins>
            <plugin>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>scala-compile</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>add-source</goal>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>scala-test-compile</id>
                    <phase>process-test-resources</phase>
                    <goals>
                      <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.scalactic</groupId>
            <artifactId>scalactic_2.12</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_2.12</artifactId>
            <version>3.0.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <version>3.2.2</version>
        </dependency>
    </dependencies>
</project>