text:
package v1_test

import (
	"encoding/json"
	"reflect"
	"testing"

	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
)

func roundTrip(t *testing.T, obj runtime.Object) runtime.Object {
	codec := api.Codecs.LegacyCodec(v1.SchemeGroupVersion)
	data, err := runtime.Encode(codec, obj)
	if err != nil {
		t.Errorf("%v\n %#v", err, obj)
		return nil
	}
	obj2, err := runtime.Decode(codec, data)
	if err != nil {
		t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj)
		return nil
	}
	obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)
	err = api.Scheme.Convert(obj2, obj3, nil)
	if err != nil {
		t.Errorf("%v\nSource: %#v", err, obj2)
		return nil
	}
	return obj3
}

func TestSetDefaultReplicationController(t *testing.T) {
	tests := []struct {
		rc             *v1.ReplicationController
		expectLabels   bool
		expectSelector bool
	}{
		{
			rc: &v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectLabels:   true,
			expectSelector: true,
		},
		{
			rc: &v1.ReplicationController{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"bar": "foo",
					},
				},
				Spec: v1.ReplicationControllerSpec{
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectLabels:   false,
			expectSelector: true,
		},
		{
			rc: &v1.ReplicationController{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"bar": "foo",
					},
				},
				Spec: v1.ReplicationControllerSpec{
					Selector: map[string]string{
						"some": "other",
					},
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectLabels:   false,
			expectSelector: false,
		},
		{
			rc: &v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Selector: map[string]string{
						"some": "other",
					},
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectLabels:   true,
			expectSelector: false,
		},
	}

	for _, test := range tests {
		rc := test.rc
		obj2 := roundTrip(t, runtime.Object(rc))
		rc2, ok := obj2.(*v1.ReplicationController)
		if !ok {
			t.Errorf("unexpected object: %v", rc2)
			t.FailNow()
		}
		if test.expectSelector != reflect.DeepEqual(rc2.Spec.Selector, rc2.Spec.Template.Labels) {
			if test.expectSelector {
				t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Spec.Selector)
			} else {
				t.Errorf("unexpected equality: %v", rc.Spec.Selector)
			}
		}
		if test.expectLabels != reflect.DeepEqual(rc2.Labels, rc2.Spec.Template.Labels) {
			if test.expectLabels {
				t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Labels)
			} else {
				t.Errorf("unexpected equality: %v", rc.Labels)
			}
		}
	}
}

func newInt(val int32) *int32 {
	p := new(int32)
	*p = val
	return p
}

func TestSetDefaultReplicationControllerReplicas(t *testing.T) {
	tests := []struct {
		rc             v1.ReplicationController
		expectReplicas int32
	}{
		{
			rc: v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectReplicas: 1,
		},
		{
			rc: v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Replicas: newInt(0),
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectReplicas: 0,
		},
		{
			rc: v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Replicas: newInt(3),
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Labels: map[string]string{
								"foo": "bar",
							},
						},
					},
				},
			},
			expectReplicas: 3,
		},
	}

	for _, test := range tests {
		rc := &test.rc
		obj2 := roundTrip(t, runtime.Object(rc))
		rc2, ok := obj2.(*v1.ReplicationController)
		if !ok {
			t.Errorf("unexpected object: %v", rc2)
			t.FailNow()
		}
		if rc2.Spec.Replicas == nil {
			t.Errorf("unexpected nil Replicas")
		} else if test.expectReplicas != *rc2.Spec.Replicas {
			t.Errorf("expected: %d replicas, got: %d", test.expectReplicas, *rc2.Spec.Replicas)
		}
	}
}

func TestSetDefaultReplicationControllerImagePullPolicy(t *testing.T) {
	containersWithoutPullPolicy, _ := json.Marshal([]map[string]interface{}{
		{
			"name":  "install",
			"image": "busybox:latest",
		},
	})

	containersWithPullPolicy, _ := json.Marshal([]map[string]interface{}{
		{
			"name":            "install",
			"imagePullPolicy": "IfNotPresent",
		},
	})

	tests := []struct {
		rc               v1.ReplicationController
		expectPullPolicy v1.PullPolicy
	}{
		{
			rc: v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Annotations: map[string]string{
								"pod.beta.kubernetes.io/init-containers": string(containersWithoutPullPolicy),
							},
						},
					},
				},
			},
			expectPullPolicy: v1.PullAlways,
		},
		{
			rc: v1.ReplicationController{
				Spec: v1.ReplicationControllerSpec{
					Template: &v1.PodTemplateSpec{
						ObjectMeta: metav1.ObjectMeta{
							Annotations: map[string]string{
								"pod.beta.kubernetes.io/init-containers": string(containersWithPullPolicy),
							},
						},
					},
				},
			},
			expectPullPolicy: v1.PullIfNotPresent,
		},
	}

	for _, test := range tests {
		rc := &test.rc
		obj2 := roundTrip(t, runtime.Object(rc))
		rc2, ok := obj2.(*v1.ReplicationController)
		if !ok {
			t.Errorf("unexpected object: %v", rc2)
			t.FailNow()
		}
		if test.expectPullPolicy != rc2.Spec.Template.Spec.InitContainers[0].ImagePullPolicy {
			t.Errorf("expected ImagePullPolicy: %s, got: %s",
				test.expectPullPolicy,
				rc2.Spec.Template.Spec.InitContainers[0].ImagePullPolicy,
			)
		}
	}
}

func TestSetDefaultService(t *testing.T) {
	svc := &v1.Service{}
	obj2 := roundTrip(t, runtime.Object(svc))
	svc2 := obj2.(*v1.Service)
	if svc2.Spec.SessionAffinity != v1.ServiceAffinityNone {
		t.Errorf("Expected default session affinity type:%s, got: %s", v1.ServiceAffinityNone, svc2.Spec.SessionAffinity)
	}
	if svc2.Spec.Type != v1.ServiceTypeClusterIP {
		t.Errorf("Expected default type:%s, got: %s", v1.ServiceTypeClusterIP, svc2.Spec.Type)
	}
}

func TestSetDefaultSecretVolumeSource(t *testing.T) {
	s := v1.PodSpec{}
	s.Volumes = []v1.Volume{
		{
			VolumeSource: v1.VolumeSource{
				Secret: &v1.SecretVolumeSource{},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	output := roundTrip(t, runtime.Object(pod))
	pod2 := output.(*v1.Pod)
	defaultMode := pod2.Spec.Volumes[0].VolumeSource.Secret.DefaultMode
	expectedMode := v1.SecretVolumeSourceDefaultMode

	if defaultMode == nil || *defaultMode != expectedMode {
		t.Errorf("Expected secret DefaultMode %v, got %v", expectedMode, defaultMode)
	}
}

func TestSetDefaultConfigMapVolumeSource(t *testing.T) {
	s := v1.PodSpec{}
	s.Volumes = []v1.Volume{
		{
			VolumeSource: v1.VolumeSource{
				ConfigMap: &v1.ConfigMapVolumeSource{},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	output := roundTrip(t, runtime.Object(pod))
	pod2 := output.(*v1.Pod)
	defaultMode := pod2.Spec.Volumes[0].VolumeSource.ConfigMap.DefaultMode
	expectedMode := v1.ConfigMapVolumeSourceDefaultMode

	if defaultMode == nil || *defaultMode != expectedMode {
		t.Errorf("Expected ConfigMap DefaultMode %v, got %v", expectedMode, defaultMode)
	}
}

func TestSetDefaultDownwardAPIVolumeSource(t *testing.T) {
	s := v1.PodSpec{}
	s.Volumes = []v1.Volume{
		{
			VolumeSource: v1.VolumeSource{
				DownwardAPI: &v1.DownwardAPIVolumeSource{},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	output := roundTrip(t, runtime.Object(pod))
	pod2 := output.(*v1.Pod)
	defaultMode := pod2.Spec.Volumes[0].VolumeSource.DownwardAPI.DefaultMode
	expectedMode := v1.DownwardAPIVolumeSourceDefaultMode

	if defaultMode == nil || *defaultMode != expectedMode {
		t.Errorf("Expected DownwardAPI DefaultMode %v, got %v", expectedMode, defaultMode)
	}
}

func TestSetDefaultProjectedVolumeSource(t *testing.T) {
	s := v1.PodSpec{}
	s.Volumes = []v1.Volume{
		{
			VolumeSource: v1.VolumeSource{
				Projected: &v1.ProjectedVolumeSource{},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	output := roundTrip(t, runtime.Object(pod))
	pod2 := output.(*v1.Pod)
	defaultMode := pod2.Spec.Volumes[0].VolumeSource.Projected.DefaultMode
	expectedMode := v1.ProjectedVolumeSourceDefaultMode

	if defaultMode == nil || *defaultMode != expectedMode {
		t.Errorf("Expected ProjectedVolumeSource DefaultMode %v, got %v", expectedMode, defaultMode)
	}
}

func TestSetDefaultSecret(t *testing.T) {
	s := &v1.Secret{}
	obj2 := roundTrip(t, runtime.Object(s))
	s2 := obj2.(*v1.Secret)

	if s2.Type != v1.SecretTypeOpaque {
		t.Errorf("Expected secret type %v, got %v", v1.SecretTypeOpaque, s2.Type)
	}
}

func TestSetDefaultPersistentVolume(t *testing.T) {
	pv := &v1.PersistentVolume{}
	obj2 := roundTrip(t, runtime.Object(pv))
	pv2 := obj2.(*v1.PersistentVolume)

	if pv2.Status.Phase != v1.VolumePending {
		t.Errorf("Expected volume phase %v, got %v", v1.VolumePending, pv2.Status.Phase)
	}
	if pv2.Spec.PersistentVolumeReclaimPolicy != v1.PersistentVolumeReclaimRetain {
		t.Errorf("Expected pv reclaim policy %v, got %v", v1.PersistentVolumeReclaimRetain, pv2.Spec.PersistentVolumeReclaimPolicy)
	}
}

func TestSetDefaultPersistentVolumeClaim(t *testing.T) {
	pvc := &v1.PersistentVolumeClaim{}
	obj2 := roundTrip(t, runtime.Object(pvc))
	pvc2 := obj2.(*v1.PersistentVolumeClaim)

	if pvc2.Status.Phase != v1.ClaimPending {
		t.Errorf("Expected claim phase %v, got %v", v1.ClaimPending, pvc2.Status.Phase)
	}
}

func TestSetDefaulEndpointsProtocol(t *testing.T) {
	in := &v1.Endpoints{Subsets: []v1.EndpointSubset{
		{Ports: []v1.EndpointPort{{}, {Protocol: "UDP"}, {}}},
	}}
	obj := roundTrip(t, runtime.Object(in))
	out := obj.(*v1.Endpoints)

	for i := range out.Subsets {
		for j := range out.Subsets[i].Ports {
			if in.Subsets[i].Ports[j].Protocol == "" {
				if out.Subsets[i].Ports[j].Protocol != v1.ProtocolTCP {
					t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Subsets[i].Ports[j].Protocol)
				}
			} else {
				if out.Subsets[i].Ports[j].Protocol != in.Subsets[i].Ports[j].Protocol {
					t.Errorf("Expected protocol %s, got %s", in.Subsets[i].Ports[j].Protocol, out.Subsets[i].Ports[j].Protocol)
				}
			}
		}
	}
}

func TestSetDefaulServiceTargetPort(t *testing.T) {
	in := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{Port: 1234}}}}
	obj := roundTrip(t, runtime.Object(in))
	out := obj.(*v1.Service)
	if out.Spec.Ports[0].TargetPort != intstr.FromInt(1234) {
		t.Errorf("Expected TargetPort to be defaulted, got %v", out.Spec.Ports[0].TargetPort)
	}

	in = &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{Port: 1234, TargetPort: intstr.FromInt(5678)}}}}
	obj = roundTrip(t, runtime.Object(in))
	out = obj.(*v1.Service)
	if out.Spec.Ports[0].TargetPort != intstr.FromInt(5678) {
		t.Errorf("Expected TargetPort to be unchanged, got %v", out.Spec.Ports[0].TargetPort)
	}
}

func TestSetDefaultServicePort(t *testing.T) {
	// Unchanged if set.
	in := &v1.Service{Spec: v1.ServiceSpec{
		Ports: []v1.ServicePort{
			{Protocol: "UDP", Port: 9376, TargetPort: intstr.FromString("p")},
			{Protocol: "UDP", Port: 8675, TargetPort: intstr.FromInt(309)},
		},
	}}
	out := roundTrip(t, runtime.Object(in)).(*v1.Service)
	if out.Spec.Ports[0].Protocol != v1.ProtocolUDP {
		t.Errorf("Expected protocol %s, got %s", v1.ProtocolUDP, out.Spec.Ports[0].Protocol)
	}
	if out.Spec.Ports[0].TargetPort != intstr.FromString("p") {
		t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort)
	}
	if out.Spec.Ports[1].Protocol != v1.ProtocolUDP {
		t.Errorf("Expected protocol %s, got %s", v1.ProtocolUDP, out.Spec.Ports[1].Protocol)
	}
	if out.Spec.Ports[1].TargetPort != intstr.FromInt(309) {
		t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort)
	}

	// Defaulted.
	in = &v1.Service{Spec: v1.ServiceSpec{
		Ports: []v1.ServicePort{
			{Protocol: "", Port: 9376, TargetPort: intstr.FromString("")},
			{Protocol: "", Port: 8675, TargetPort: intstr.FromInt(0)},
		},
	}}
	out = roundTrip(t, runtime.Object(in)).(*v1.Service)
	if out.Spec.Ports[0].Protocol != v1.ProtocolTCP {
		t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Spec.Ports[0].Protocol)
	}
	if out.Spec.Ports[0].TargetPort != intstr.FromInt(int(in.Spec.Ports[0].Port)) {
		t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort)
	}
	if out.Spec.Ports[1].Protocol != v1.ProtocolTCP {
		t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Spec.Ports[1].Protocol)
	}
	if out.Spec.Ports[1].TargetPort != intstr.FromInt(int(in.Spec.Ports[1].Port)) {
		t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort)
	}
}

func TestSetDefaultNamespace(t *testing.T) {
	s := &v1.Namespace{}
	obj2 := roundTrip(t, runtime.Object(s))
	s2 := obj2.(*v1.Namespace)

	if s2.Status.Phase != v1.NamespaceActive {
		t.Errorf("Expected phase %v, got %v", v1.NamespaceActive, s2.Status.Phase)
	}
}

func TestSetDefaultPodSpecHostNetwork(t *testing.T) {
	portNum := int32(8080)
	s := v1.PodSpec{}
	s.HostNetwork = true
	s.Containers = []v1.Container{
		{
			Ports: []v1.ContainerPort{
				{
					ContainerPort: portNum,
				},
			},
		},
	}
	s.InitContainers = []v1.Container{
		{
			Ports: []v1.ContainerPort{
				{
					ContainerPort: portNum,
				},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	obj2 := roundTrip(t, runtime.Object(pod))
	pod2 := obj2.(*v1.Pod)
	s2 := pod2.Spec

	hostPortNum := s2.Containers[0].Ports[0].HostPort
	if hostPortNum != portNum {
		t.Errorf("Expected container port to be defaulted, was made %d instead of %d", hostPortNum, portNum)
	}

	hostPortNum = s2.InitContainers[0].Ports[0].HostPort
	if hostPortNum != portNum {
		t.Errorf("Expected container port to be defaulted, was made %d instead of %d", hostPortNum, portNum)
	}
}

func TestSetDefaultNodeExternalID(t *testing.T) {
	name := "node0"
	n := &v1.Node{}
	n.Name = name
	obj2 := roundTrip(t, runtime.Object(n))
	n2 := obj2.(*v1.Node)
	if n2.Spec.ExternalID != name {
		t.Errorf("Expected default External ID: %s, got: %s", name, n2.Spec.ExternalID)
	}
	if n2.Spec.ProviderID != "" {
		t.Errorf("Expected empty default Cloud Provider ID, got: %s", n2.Spec.ProviderID)
	}
}

func TestSetDefaultNodeStatusAllocatable(t *testing.T) {
	capacity := v1.ResourceList{
		v1.ResourceCPU:    resource.MustParse("1000m"),
		v1.ResourceMemory: resource.MustParse("10G"),
	}
	allocatable := v1.ResourceList{
		v1.ResourceCPU:    resource.MustParse("500m"),
		v1.ResourceMemory: resource.MustParse("5G"),
	}
	tests := []struct {
		capacity            v1.ResourceList
		allocatable         v1.ResourceList
		expectedAllocatable v1.ResourceList
	}{{ // Everything set, no defaulting.
		capacity:            capacity,
		allocatable:         allocatable,
		expectedAllocatable: allocatable,
	}, { // Allocatable set, no defaulting.
		capacity:            nil,
		allocatable:         allocatable,
		expectedAllocatable: allocatable,
	}, { // Capacity set, allocatable defaults to capacity.
		capacity:            capacity,
		allocatable:         nil,
		expectedAllocatable: capacity,
	}, { // Nothing set, allocatable "defaults" to capacity.
		capacity:            nil,
		allocatable:         nil,
		expectedAllocatable: nil,
	}}

	copyResourceList := func(rl v1.ResourceList) v1.ResourceList {
		if rl == nil {
			return nil
		}
		copy := make(v1.ResourceList, len(rl))
		for k, v := range rl {
			copy[k] = *v.Copy()
		}
		return copy
	}

	resourceListsEqual := func(a v1.ResourceList, b v1.ResourceList) bool {
		if len(a) != len(b) {
			return false
		}
		for k, v := range a {
			vb, found := b[k]
			if !found {
				return false
			}
			if v.Cmp(vb) != 0 {
				return false
			}
		}
		return true
	}

	for i, testcase := range tests {
		node := v1.Node{
			Status: v1.NodeStatus{
				Capacity:    copyResourceList(testcase.capacity),
				Allocatable: copyResourceList(testcase.allocatable),
			},
		}
		node2 := roundTrip(t, runtime.Object(&node)).(*v1.Node)
		actual := node2.Status.Allocatable
		expected := testcase.expectedAllocatable
		if !resourceListsEqual(expected, actual) {
			t.Errorf("[%d] Expected NodeStatus.Allocatable: %+v; Got: %+v", i, expected, actual)
		}
	}
}

func TestSetDefaultObjectFieldSelectorAPIVersion(t *testing.T) {
	s := v1.PodSpec{
		Containers: []v1.Container{
			{
				Env: []v1.EnvVar{
					{
						ValueFrom: &v1.EnvVarSource{
							FieldRef: &v1.ObjectFieldSelector{},
						},
					},
				},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	obj2 := roundTrip(t, runtime.Object(pod))
	pod2 := obj2.(*v1.Pod)
	s2 := pod2.Spec

	apiVersion := s2.Containers[0].Env[0].ValueFrom.FieldRef.APIVersion
	if apiVersion != "v1" {
		t.Errorf("Expected default APIVersion v1, got: %v", apiVersion)
	}
}

func TestSetMinimumScalePod(t *testing.T) {
	// verify we default if limits are specified (and that request=0 is preserved)
	s := v1.PodSpec{}
	s.Containers = []v1.Container{
		{
			Resources: v1.ResourceRequirements{
				Requests: v1.ResourceList{
					v1.ResourceMemory: resource.MustParse("1n"),
				},
				Limits: v1.ResourceList{
					v1.ResourceCPU: resource.MustParse("2n"),
				},
			},
		},
	}
	s.InitContainers = []v1.Container{
		{
			Resources: v1.ResourceRequirements{
				Requests: v1.ResourceList{
					v1.ResourceMemory: resource.MustParse("1n"),
				},
				Limits: v1.ResourceList{
					v1.ResourceCPU: resource.MustParse("2n"),
				},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	v1.SetObjectDefaults_Pod(pod)

	if expect := resource.MustParse("1m"); expect.Cmp(pod.Spec.Containers[0].Resources.Requests[v1.ResourceMemory]) != 0 {
		t.Errorf("did not round resources: %#v", pod.Spec.Containers[0].Resources)
	}
	if expect := resource.MustParse("1m"); expect.Cmp(pod.Spec.InitContainers[0].Resources.Requests[v1.ResourceMemory]) != 0 {
		t.Errorf("did not round resources: %#v", pod.Spec.InitContainers[0].Resources)
	}
}

func TestSetDefaultRequestsPod(t *testing.T) {
	// verify we default if limits are specified (and that request=0 is preserved)
	s := v1.PodSpec{}
	s.Containers = []v1.Container{
		{
			Resources: v1.ResourceRequirements{
				Requests: v1.ResourceList{
					v1.ResourceMemory: resource.MustParse("0"),
				},
				Limits: v1.ResourceList{
					v1.ResourceCPU:    resource.MustParse("100m"),
					v1.ResourceMemory: resource.MustParse("1Gi"),
				},
			},
		},
	}
	s.InitContainers = []v1.Container{
		{
			Resources: v1.ResourceRequirements{
				Requests: v1.ResourceList{
					v1.ResourceMemory: resource.MustParse("0"),
				},
				Limits: v1.ResourceList{
					v1.ResourceCPU:    resource.MustParse("100m"),
					v1.ResourceMemory: resource.MustParse("1Gi"),
				},
			},
		},
	}
	pod := &v1.Pod{
		Spec: s,
	}
	output := roundTrip(t, runtime.Object(pod))
	pod2 := output.(*v1.Pod)
	defaultRequest := pod2.Spec.Containers[0].Resources.Requests
	if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "100m" {
		t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String())
	}
	if requestValue := defaultRequest[v1.ResourceMemory]; requestValue.String() != "0" {
		t.Errorf("Expected request memory: %s, got: %s", "0", requestValue.String())
	}
	defaultRequest = pod2.Spec.InitContainers[0].Resources.Requests
	if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "100m" {
		t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String())
	}
	if requestValue := defaultRequest[v1.ResourceMemory]; requestValue.String() != "0" {
		t.Errorf("Expected request memory: %s, got: %s", "0", requestValue.String())
	}

	// verify we do nothing if no limits are specified
	s = v1.PodSpec{}
	s.Containers = []v1.Container{{}}
	s.InitContainers = []v1.Container{{}}
	pod = &v1.Pod{
		Spec: s,
	}
	output = roundTrip(t, runtime.Object(pod))
	pod2 = output.(*v1.Pod)
	defaultRequest = pod2.Spec.Containers[0].Resources.Requests
	if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "0" {
		t.Errorf("Expected 0 request value, got: %s", requestValue.String())
	}
	defaultRequest = pod2.Spec.InitContainers[0].Resources.Requests
	if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "0" {
		t.Errorf("Expected 0 request value, got: %s", requestValue.String())
	}
}

func TestDefaultRequestIsNotSetForReplicationController(t *testing.T) {
	s := v1.PodSpec{}
	s.Containers = []v1.Container{
		{
			Resources: v1.ResourceRequirements{
				Limits: v1.ResourceList{
					v1.ResourceCPU: resource.MustParse("100m"),
				},
			},
		},
	}
	rc := &v1.ReplicationController{
		Spec: v1.ReplicationControllerSpec{
			Replicas: newInt(3),
			Template: &v1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"foo": "bar",
					},
				},
				Spec: s,
			},
		},
	}
	output := roundTrip(t, runtime.Object(rc))
	rc2 := output.(*v1.ReplicationController)
	defaultRequest := rc2.Spec.Template.Spec.Containers[0].Resources.Requests
	requestValue := defaultRequest[v1.ResourceCPU]
	if requestValue.String() != "0" {
		t.Errorf("Expected 0 request value, got: %s", requestValue.String())
	}
}

func TestSetDefaultLimitRangeItem(t *testing.T) {
	limitRange := &v1.LimitRange{
		ObjectMeta: metav1.ObjectMeta{
			Name: "test-defaults",
		},
		Spec: v1.LimitRangeSpec{
			Limits: []v1.LimitRangeItem{{
				Type: v1.LimitTypeContainer,
				Max: v1.ResourceList{
					v1.ResourceCPU: resource.MustParse("100m"),
				},
				Min: v1.ResourceList{
					v1.ResourceMemory: resource.MustParse("100Mi"),
				},
				Default:        v1.ResourceList{},
				DefaultRequest: v1.ResourceList{},
			}},
		},
	}

	output := roundTrip(t, runtime.Object(limitRange))
	limitRange2 := output.(*v1.LimitRange)
	defaultLimit := limitRange2.Spec.Limits[0].Default
	defaultRequest := limitRange2.Spec.Limits[0].DefaultRequest

	// verify that default cpu was set to the max
	defaultValue := defaultLimit[v1.ResourceCPU]
	if defaultValue.String() != "100m" {
		t.Errorf("Expected default cpu: %s, got: %s", "100m", defaultValue.String())
	}
	// verify that default request was set to the limit
	requestValue := defaultRequest[v1.ResourceCPU]
	if requestValue.String() != "100m" {
		t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String())
	}
	// verify that if a min is provided, it will be the default if no limit is specified
	requestMinValue := defaultRequest[v1.ResourceMemory]
	if requestMinValue.String() != "100Mi" {
		t.Errorf("Expected request memory: %s, got: %s", "100Mi", requestMinValue.String())
	}
}

func TestSetDefaultProbe(t *testing.T) {
	originalProbe := v1.Probe{}
	expectedProbe := v1.Probe{
		InitialDelaySeconds: 0,
		TimeoutSeconds:      1,
		PeriodSeconds:       10,
		SuccessThreshold:    1,
		FailureThreshold:    3,
	}

	pod := &v1.Pod{
		Spec: v1.PodSpec{
			Containers: []v1.Container{{LivenessProbe: &originalProbe}},
		},
	}

	output := roundTrip(t, runtime.Object(pod)).(*v1.Pod)
	actualProbe := *output.Spec.Containers[0].LivenessProbe
	if actualProbe != expectedProbe {
		t.Errorf("Expected probe: %+v\ngot: %+v\n", expectedProbe, actualProbe)
	}
}

func TestSetDefaultSchedulerName(t *testing.T) {
	pod := &v1.Pod{}

	output := roundTrip(t, runtime.Object(pod)).(*v1.Pod)
	if output.Spec.SchedulerName != v1.DefaultSchedulerName {
		t.Errorf("Expected scheduler name: %+v\ngot: %+v\n", v1.DefaultSchedulerName, output.Spec.SchedulerName)
	}
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html

module Stratosphere.ResourceProperties.S3BucketMetricsConfiguration where

import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.S3BucketTagFilter

-- | Full data type definition for S3BucketMetricsConfiguration. See
-- 's3BucketMetricsConfiguration' for a more convenient constructor.
data S3BucketMetricsConfiguration =
  S3BucketMetricsConfiguration
  { _s3BucketMetricsConfigurationId :: Val Text
  , _s3BucketMetricsConfigurationPrefix :: Maybe (Val Text)
  , _s3BucketMetricsConfigurationTagFilters :: Maybe [S3BucketTagFilter]
  } deriving (Show, Eq)

instance ToJSON S3BucketMetricsConfiguration where
  toJSON S3BucketMetricsConfiguration{..} =
    object $
    catMaybes
    [ (Just . ("Id",) . toJSON) _s3BucketMetricsConfigurationId
    , fmap (("Prefix",) . toJSON) _s3BucketMetricsConfigurationPrefix
    , fmap (("TagFilters",) . toJSON) _s3BucketMetricsConfigurationTagFilters
    ]

-- | Constructor for 'S3BucketMetricsConfiguration' containing required fields
-- as arguments.
s3BucketMetricsConfiguration
  :: Val Text -- ^ 'sbmcId'
  -> S3BucketMetricsConfiguration
s3BucketMetricsConfiguration idarg =
  S3BucketMetricsConfiguration
  { _s3BucketMetricsConfigurationId = idarg
  , _s3BucketMetricsConfigurationPrefix = Nothing
  , _s3BucketMetricsConfigurationTagFilters = Nothing
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-id
sbmcId :: Lens' S3BucketMetricsConfiguration (Val Text)
sbmcId = lens _s3BucketMetricsConfigurationId (\s a -> s { _s3BucketMetricsConfigurationId = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-prefix
sbmcPrefix :: Lens' S3BucketMetricsConfiguration (Maybe (Val Text))
sbmcPrefix = lens _s3BucketMetricsConfigurationPrefix (\s a -> s { _s3BucketMetricsConfigurationPrefix = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-tagfilters
sbmcTagFilters :: Lens' S3BucketMetricsConfiguration (Maybe [S3BucketTagFilter])
sbmcTagFilters = lens _s3BucketMetricsConfigurationTagFilters (\s a -> s { _s3BucketMetricsConfigurationTagFilters = a })

redpajama_set_name: RedPajamaGithub


text:
"""UE measurements module."""

import time

from construct import Struct, Int16ub, Int8ub, Int8sb, Container

import empower.managers.ranmanager.vbsp as vbsp

from empower.apps.uemeasurements import RRCReportAmount, RRCReportInterval
from empower.managers.ranmanager.vbsp.lteapp import ELTEApp
from empower.managers.ranmanager.vbsp import MSG_TYPE_RESPONSE, RESULT_FAIL

PT_UE_MEASUREMENTS_SERVICE = 0x03

TLV_MEASUREMENTS_SERVICE_CONFIG = 0x08
TLV_MEASUREMENTS_SERVICE_REPORT = 0x09
TLV_MEASUREMENTS_SERVICE_MEAS_ID = 0x0B

UE_MEASUREMENTS_SERVICE_CONFIG = Struct(
    "rnti" / Int16ub,
    "meas_id" / Int8ub,
    "interval" / Int8ub,
    "amount" / Int8ub,
)
UE_MEASUREMENTS_SERVICE_CONFIG.name = "ue_measurements_service_request"

UE_MEASUREMENTS_SERVICE_MEAS_ID = Struct(
    "rnti" / Int16ub,
    "meas_id" / Int8ub,
)
UE_MEASUREMENTS_SERVICE_MEAS_ID.name = "ue_measurements_service_meas_id"

UE_MEASUREMENTS_SERVICE_REPORT = Struct(
    "rnti" / Int16ub,
    "meas_id" / Int8ub,
    "rsrp" / Int8sb,
    "rsrq" / Int8sb,
)
UE_MEASUREMENTS_SERVICE_REPORT.name = "ue_measurements_service_report"

class UEMeasurements(ELTEApp):
    """UE Measurements Primitive.

    Perform UE Measurements for the current cell (Serving Cell).

    Parameters:
        imsi: the UE IMSI (mandatory)
        interval: the reporting interval (mandatory)
        amount: the number of reports (mandatory)

    Example:
        POST /api/v1/projects/52313ecb-9d00-4b7d-b873-b55d3d9ada26/apps
        {
            "name": "empower.apps.uemeasurements.uemeasurements",
            "params": {
                "imsi": "429011234567890",
                "interval": "MS480",
                "amount": "INFINITY"
            }
        }
    """

    def __init__(self, context, service_id, meas_id, imsi, interval, amount,
                 every):

        super().__init__(context=context,
                         service_id=service_id,
                         meas_id=meas_id,
                         imsi=imsi,
                         interval=interval,
                         amount=amount,
                         every=every)

        # Register messages
        parser = (vbsp.PACKET, "ue_measurements_service")
        vbsp.register_message(PT_UE_MEASUREMENTS_SERVICE, parser)

        # Data structures
        self.rsrp = None
        self.rsrq = None

        # Last seen time
        self.last = None

    def __eq__(self, other):
        return super().__eq__(other) and self.meas_id == other.meas_id \
            and self.imsi == other.imsi

    def start(self):
        """Start app."""

        vbsp.register_callback(PT_UE_MEASUREMENTS_SERVICE,
                               self.handle_response)

        super().start()

        if self.imsi in self.context.users:
            user = self.context.users[self.imsi]
            self.handle_ue_join(user)

    def stop(self):
        """Stop app."""

        if self.imsi in self.context.users:
            user = self.context.users[self.imsi]
            self.handle_ue_leave(user)

        super().stop()

        vbsp.unregister_callback(PT_UE_MEASUREMENTS_SERVICE,
                                 self.handle_response)

    @property
    def meas_id(self):
        """ Return the meas id. """

        return self.params['meas_id']

    @meas_id.setter
    def meas_id(self, value):
        """Set the meas id. """

        self.params['meas_id'] = self.validate_param('meas_id', int(value))

    @property
    def imsi(self):
        """ Return the UE IMSI. """

        return self.params['imsi']

    @imsi.setter
    def imsi(self, imsi):
        """ Set the UE IMSI. """

        self.params['imsi'] = self.validate_param('imsi', imsi)

    @property
    def interval(self):
        """ Return the interval. """

        return self.params['interval']

    @interval.setter
    def interval(self, value):
        """Set the interval. """

        self.params['interval'] = \
            self.validate_param('interval', value)

    @property
    def amount(self):
        """ Return the amount. """

        return self.params['amount']

    @amount.setter
    def amount(self, value):
        """ Set the amount. """

        self.params['amount'] = \
            self.validate_param('amount', value)

    def loop(self):
        """Periodic loop."""

    def to_dict(self):
        """ Return a JSON-serializable."""

        out = super().to_dict()

        out['rsrp'] = self.rsrp
        out['rsrq'] = self.rsrq

        return out

    def handle_ue_join(self, user):
        """Called when a UE joins the network."""

        interval = RRCReportInterval[self.interval].value
        amount = RRCReportAmount[self.amount].value

        rrc_measurement_tlv = \
            Container(rnti=user.rnti,
                      meas_id=self.meas_id,
                      interval=interval,
                      amount=amount)

        value = UE_MEASUREMENTS_SERVICE_CONFIG.build(rrc_measurement_tlv)

        tlv = Container()
        tlv.type = TLV_MEASUREMENTS_SERVICE_CONFIG
        tlv.length = 4 + len(value)
        tlv.value = value

        user.vbs.connection.send_message(action=PT_UE_MEASUREMENTS_SERVICE,
                                         msg_type=vbsp.MSG_TYPE_REQUEST,
                                         crud_result=vbsp.OP_CREATE,
                                         tlvs=[tlv],
                                         callback=self.handle_add_response)

    def handle_ue_leave(self, user):
        """Called when a UE leaves the network."""

        rrc_measurement_tlv = \
            Container(rnti=user.rnti, meas_id=self.meas_id)

        value = UE_MEASUREMENTS_SERVICE_MEAS_ID.build(rrc_measurement_tlv)

        tlv = Container()
        tlv.type = TLV_MEASUREMENTS_SERVICE_MEAS_ID
        tlv.length = 4 + len(value)
        tlv.value = value

        user.vbs.connection.send_message(action=PT_UE_MEASUREMENTS_SERVICE,
                                         msg_type=vbsp.MSG_TYPE_REQUEST,
                                         crud_result=vbsp.OP_DELETE,
                                         tlvs=[tlv],
                                         callback=self.handle_del_response)

    def handle_add_response(self, msg, vbs, _):
        """Handle an incoming UE_MEASUREMENTS_SERVICE message."""

        # if not a response then ignore
        if msg.flags.msg_type != MSG_TYPE_RESPONSE:
            self.log.warning("Not a response, ignoring.")
            return

        # there should be only one tlv
        for tlv in msg.tlvs:

            if tlv.type == TLV_MEASUREMENTS_SERVICE_MEAS_ID:

                parser = UE_MEASUREMENTS_SERVICE_MEAS_ID
                option = parser.parse(tlv.value)

                # if result is fail then ignore
                if msg.tsrc.crud_result == RESULT_FAIL:
                    msg = "Error creating UE meas: %u" % option.meas_id
                else:
                    msg = "Success creating UE meas: %u" % option.meas_id

                self.log.warning(msg)

    def handle_del_response(self, msg, vbs, _):
        """Handle an incoming UE_MEASUREMENTS_SERVICE message."""

        # if not a response then ignore
        if msg.flags.msg_type != MSG_TYPE_RESPONSE:
            self.log.warning("Not a response, ignoring.")
            return

        # there should be only one tlv
        for tlv in msg.tlvs:

            if tlv.type == TLV_MEASUREMENTS_SERVICE_MEAS_ID:

                parser = UE_MEASUREMENTS_SERVICE_MEAS_ID
                option = parser.parse(tlv.value)

                # if result is fail then ignore
                if msg.tsrc.crud_result == RESULT_FAIL:
                    msg = "Error removing UE meas: %u" % option.meas_id
                else:
                    msg = "Success removing UE meas: %u" % option.meas_id

                self.log.warning(msg)

    def handle_response(self, msg, _):
        """Handle an incoming UE_MEASUREMENTS_SERVICE message."""

        # if not a response then ignore
        if msg.flags.msg_type != MSG_TYPE_RESPONSE:
            self.log.warning("Not a response, ignoring.")
            return

        # if result is fail then ignore
        if msg.tsrc.crud_result == RESULT_FAIL:
            self.log.warning("Error creating UE measurement, ignoring.")
            return

        # must be a success, parse TLVs
        for tlv in msg.tlvs:

            if tlv.type != TLV_MEASUREMENTS_SERVICE_REPORT:
                continue

            # set last iteration time
            self.last = time.time()

            parser = UE_MEASUREMENTS_SERVICE_REPORT
            option = parser.parse(tlv.value)

            self.log.debug("Processing options %s", parser.name)

            user = self.context.users[self.imsi]

            if option.rnti != user.rnti:
                continue

            if option.meas_id != self.meas_id:
                continue

            self.rsrp = option.rsrp - 140
            self.rsrq = int(option.rsrq/2 - 19.5)

            self.log.debug("Received RSRP %u RSRQ %u", self.rsrp, self.rsrq)

            user.ue_measurements = {
                "rsrp": self.rsrp,
                "rsrq": self.rsrq,
            }

        # handle callbacks
        self.handle_callbacks()

        # set last iteration time
        self.last = time.time()

def launch(context, service_id, meas_id, imsi, interval, amount, every=-1):
    """ Initialize the module. """

    return UEMeasurements(context=context, service_id=service_id,
                          meas_id=meas_id, imsi=imsi, interval=interval,
                          amount=amount, every=every)


text:
package org.uberfire.ext.security.management.client.screens.home;

import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.Widget;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.UberView;
import org.uberfire.ext.security.management.client.resources.i18n.UsersManagementWorkbenchConstants;
import org.uberfire.ext.security.management.client.screens.BaseScreen;

@Dependent
@WorkbenchScreen(identifier = SecurityManagementHomeScreen.SCREEN_ID )
public class SecurityManagementHomeScreen {

    public static final String SCREEN_ID = "SecurityManagementHomeScreen";

    public interface View extends UberView<SecurityManagementHomeScreen> {

    }

    @Inject
    BaseScreen baseScreen;

    @Inject
    View view;

    @PostConstruct
    public void init() {
        view.init(this);
        baseScreen.init(view);
    }

    @WorkbenchPartTitle
    public String getTitle() {
        return UsersManagementWorkbenchConstants.INSTANCE.securityManagement();
    }

    @WorkbenchPartView
    public Widget getWidget() {
        return baseScreen.asWidget();
    }
}


text:
.dark-green {
    background: green !important;
}

.green {
    background: rgba(102, 187, 106, 1) !important;
}

.yellow {
    background: #FFCA28 !important;
}

.orange {
    background: orange !important;
}

.red {
    background: rgba(239,83,80, 1) !important;
}


text:
In the previous section we ran some queries. They are quite good and all, but
the one for timeline can be quite slow at times.

Consider users that follow an absurd number of people. Talking here about
hundred of thousands of people. In this case the timeline would take a long
time to process.

This is what we call a supernode problem, and there a couple of ways we can
handle it.

We can both identify the supernodes and give them some sort of special
treatment or we can simply use an efficient way to identify the most relevant
information we need to retrieve in any given step of our query.

Either way, we do need to go through most of our graph and potentially run
quite complex formulation (well, at least complex for billions of users).

A way to accomplish this with acceptable performance is by means of hadoop.

##  GremlinHadoop

JanusGraph is tighly integrated with the Tinkerpop stak. This stak provides
GremlinHadoop, which is what actually handles the hadoop side of JanusGraph.

The way it works is by

1. divide the graph into partitions (the details on this is beyound my
   understanding)
2. filter the data in those partitions.
3. for each filtered partition run your own code, where:
  * worker is initialized
  * for each contained vertex in this partition run an specific method
  * worker is finalized.

This is a super basic overview of what this stack is capable of, but serves as
a simple way to get started. You can effectively do complex map&reduce tasks
with this and gremlin comes with a couple of quite complex examples.

To learn it in detail, please reffer to the [official
docs](http://tinkerpop.apache.org/docs/current/reference/#graphcomputer) as
usual.

## Our code

On our previous timeline code, we had the following query:

```java
    return getUser().
        aggregate("users").
        out(FOLLOWS).
        aggregate("users").
        cap("users").
        unfold().
        as(userVertex).
        outE(POSTS).
        as(postsEdge).
        order().by(CREATED_AT, decr).
        limit(limit).
        inV().
        as(statusUpdateVertex).
        select(userVertex, postsEdge, statusUpdateVertex);
```

If the user follows way too many people we will load our memory with undesired
content. Therefore we need to rank the most relevant users to appear in this
timeline.

What `most relevant` means is a complex subject on its own and I don't
recommend using the following formulation in a real life application. There are
companies specialized on this and you are probably better off using machine
learning, trying to improve the problem of engagement.

With that said:

* **user:** to whom we want to provide recommendation
* **followedUser:** user we are trying to score for **user**.

Considere all numbers as double precision floats.

```java
dayThreshold = max(oneWeekAgo, startedFollowingAt)

postsCount = countPostsSince(dayThreshold)
postsPerDay = postsCount/daysFrom(dayThreshold)

followedCounts = countCommonFollowed(user, followedUsers)

relevance = (postsPerDay + followedCounts) / 2
```

The final reelevance formulation considers both how active the user has been
recently and how many commong people both users follows.

Adding such weight to the `follows` edge, we can change the query to:

```java
    return getUser().
        aggregate("users").
        local(
            __.outE(FOLLOWS).
                order().by(CreateWeightIndex.WEIGHT, decr).
                dedup().
                limit(50).
                inV()
        ).
        aggregate("users").
        cap("users").
        unfold().
        as(userVertex).
        outE(POSTS).
        dedup().
        as(postsEdge).
        order().by(CREATED_AT, decr).
        limit(limit).
        inV().
        as(statusUpdateVertex).
        select(userVertex, postsEdge, statusUpdateVertex);
```

This way we limit the number of users we retrieve for the timeline, even if our
recommendation is for our biggest supernode.

The `local()` step is to make sure its internall `limit()` will do what we want: reutrn only the most relevant users
for this query.

## Before we Start

Before we run, there are a couple of changes that we need to do. First, during
my experiments cassandra kept crashing. Also, ElasticSearch comes with dynamic
scripting disabled, which is required by JanusGraph to update values.

To fix both issues, first make sure JanusGraph is not running:

```bash
./stop_janus.sh
```

Then enter the JanusGraph working dir:

```bash
cd work/janusgraph-0.1.0-hadoop2/
```

Now, open the file `conf/es/elasticsearch.yml` in a text editor and add the
following line to the end of it:

```yml
script.disable_dynamic: false
```

With that done, run both cassandra and elasticsearch in two different
terminals.

```bash
./bin/elasticsearch
./bin/cassandra
```

Doing this also gives you a perspective of what components should be optimized
in a production environment. Also, hadoop leverages the concurrency veatures of
both cassandra and elasticsearch, so this exposure is also good for
understanding this.

And at last, notice we do not have the main JanusGraph server running. Instead,
our Java code has the JanusGraph code built in and uses it to connect to the
servers.

## Running

If you got this far in this tutorial I am assuming you are familiar on how to
run the code by hand now. If not, go back and study the `run.sh` file for each
example.

Here we have 3 main programs:

* **create-index:** will create the *weight* index.
* **compute-weight:** run spark with the built-in spark
* **old-timeline:** print the timeline for a specific user using the old script.
* **new-timeline:** print the timeline for a specific user using the new script.

Make sure to run the commands in the presented order.

## Results

The final code ensures we return in a predictable way even if the user is following way to many users.

This is, by no means, the best solution. The query actually takes a little bit longer to execute than the previous
one for users following only a few people. The advantage is when we have supernodes.

Also, the weight is being indexed in a centralized index inside elasticsearch; not the most efficient way for doing this.

In the next section, [05-indexing-for-performance](../05-indexing-for-performance) we will describe a way to improve the
new query time.


text:
@interface CPBannerView ()<UIScrollViewDelegate>

@property(nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong) NSMutableArray *bannerSource;
@property(nonatomic, strong) NSMutableArray *titleArray;
@property(nonatomic, strong) NSTimer *timer;

@end

@implementation CPBannerView

#pragma mark -initMethod

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:({
            self.scrollView = [[UIScrollView alloc] initWithFrame:frame];
            _scrollView.delegate = self;
            _scrollView.showsHorizontalScrollIndicator = NO;
            _scrollView.showsVerticalScrollIndicator = NO;
            _scrollView.pagingEnabled = YES;
            _scrollView;
        })];
        // 构建轮播图
        [self buildBanner];
        [self startTimer];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame bannerSource:(NSMutableArray *)bannerSource{
    if (bannerSource) {
        self.bannerSource = bannerSource;
        self = [self initWithFrame:frame];
        return self;
    }
    return nil;
}

- (instancetype)initWithBannerSource:(NSMutableArray *)bannerSource ImageTitle:(NSMutableArray *)titleArray Frame:(CGRect)frame{
    if (bannerSource && titleArray) {
        self.bannerSource = bannerSource;
        self.titleArray = titleArray;
        self = [self initWithFrame:frame];
        return self;
    }
    return nil;
}

#pragma mark -BannerMethod

// 创建轮播图
- (void)buildBanner{
    if (_titleArray) {
        id firstTitle = self.titleArray.firstObject;
        [self.titleArray insertObject:self.titleArray.lastObject atIndex:0];
        [self.titleArray addObject:firstTitle];
    }
    // 将数组第一个元素取出
    id firstObject = self.bannerSource.firstObject;

    // 将数组最后一个复制一份插入到数组第一个位置
    [self.bannerSource insertObject:self.bannerSource.lastObject atIndex:0];

    // 将第一个元素复制一份添加到最后一个
    [self.bannerSource addObject:firstObject];

    // 设置滚动视图
    NSInteger imageCount = self.bannerSource.count;
    self.scrollView.contentSize = CGSizeMake(self.frame.size.width * imageCount, self.frame.size.height);

    for (int i = 0; i < imageCount; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        if (_titleArray) {
            if (_titleArray[i]) {
                UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 40, self.frame.size.width, 40)];
                titleView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
                UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.frame.size.width, titleView.frame.size.height)];
                lblTitle.textColor = [UIColor whiteColor];
                lblTitle.text = _titleArray[i];
                [titleView addSubview:lblTitle];
                [imageView addSubview:titleView];
            }
        }
        // 判断资源是什么类型
        id item = self.bannerSource[i];
        if ([item isKindOfClass:[UIImage class]]) {

            imageView.image = item;

        }else if([item isKindOfClass:[NSURL class]]){
            // 子线程中加载网络图片数据
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData *data = [NSData dataWithContentsOfURL:item];
                // 加载完成后回到主线程更新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImage *image = [UIImage imageWithData:data];
                    imageView.image = image;
                });
            });
        }else if ([item isKindOfClass:[NSString class]]){
            // 判断是否是本地图片资源
            UIImage *imageWithName = [UIImage imageNamed:item];
            if (imageWithName) {
                imageView.image = imageWithName;
            }else{
                // 子线程中加载网络图片数据
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item]];
                    // 加载完成后回到主线程更新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [UIImage imageWithData:data];
                        imageView.image = image;
                    });
                });
            }
        }else{
            NSAssert(0, @"没有匹配的数据类型!");
        }
        CGRect frame = _scrollView.frame;
        imageView.frame = CGRectMake(frame.size.width * i, 0, frame.size.width, frame.size.height);
        [_scrollView addSubview:imageView];
        // 给每一张图片添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView:)];
        imageView.userInteractionEnabled = YES;
        // 让第一张图片的tag为1000
        [imageView setTag:BASE_TAG + i - 1];
        [imageView addGestureRecognizer:tap];
    }
    _scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
}

// 处理轮播图点击手势
- (void)clickImageView:(UITapGestureRecognizer *)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(bannerView:bannerDidSelectIndex:)]) {
        // 让计时器重新计时
        [self stopTimer];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startTimer];
        });
        // 设置偏移量为当前点击的图片
        NSInteger currentPage = sender.view.tag - BASE_TAG;
        if (currentPage == _bannerSource.count - 2) {
            currentPage = 0;
        }
        _scrollView.contentOffset = CGPointMake(self.frame.size.width * (currentPage + 1), 0);
        [_delegate bannerView:self bannerDidSelectIndex:(currentPage)];
    }
}

// 滑动到下一个imageView
- (void)scrollNextImageView{
    CGPoint currentOffset = _scrollView.contentOffset;
    currentOffset.x += self.scrollView.frame.size.width;
    [_scrollView setContentOffset:currentOffset animated:YES];
    [self scrollViewDidEndDecelerating:_scrollView];
}

#pragma mark -UIScrollViewDelegate
// 滑动结束
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    NSInteger imageCount = _bannerSource.count;
    if (point.x == scrollView.frame.size.width * (imageCount - 1)) {
        scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0);
    }else if(point.x == 0){
        [scrollView setContentOffset:CGPointMake(scrollView.frame.size.width * (imageCount - 2), 0) animated:NO];
    }
}

// 手动拖拽时停止自动滚动
// 即将拖拽的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}

// 拖拽结束的时候
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self startTimer];
}

#pragma mark -timerMethod

- (void)startTimer{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollNextImageView) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}

@end


text:
"""Script to update the dependencies in various configuration files."""

import os
import sys

# Change PYTHONPATH to include dependencies and projects.
sys.path.insert(0, u'.')

import utils.dependencies  # pylint: disable=wrong-import-position
import utils.projects  # pylint: disable=wrong-import-position

# pylint: disable=redefined-outer-name

class DependencyFileWriter(object):
  """Dependency file writer."""

  def __init__(self, project_definition, dependency_helper):
    """Initializes a dependency file writer.

    Args:
      project_definition (ProjectDefinition): project definition.
      dependency_helper (DependencyHelper): dependency helper.
    """
    super(DependencyFileWriter, self).__init__()
    self._dependency_helper = dependency_helper
    self._project_definition = project_definition

class AppveyorYmlWriter(DependencyFileWriter):
  """Appveyor.yml file writer."""

  _PATH = os.path.join(u'appveyor.yml')

  _VERSION_PYWIN32 = u'220'
  _VERSION_WMI = u'1.4.9'

  _DOWNLOAD_PIP = (
      u'  - ps: (new-object net.webclient).DownloadFile('
      u'\'https://bootstrap.pypa.io/get-pip.py\', '
      u'\'C:\\Projects\\get-pip.py\')')

  _DOWNLOAD_PYWIN32 = (
      u'  - ps: (new-object net.webclient).DownloadFile('
      u'\'https://github.com/log2timeline/l2tbinaries/raw/master/win32/'
      u'pywin32-{0:s}.win32-py2.7.exe\', '
      u'\'C:\\Projects\\pywin32-{0:s}.win32-py2.7.exe\')').format(
          _VERSION_PYWIN32)

  _DOWNLOAD_WMI = (
      u'  - ps: (new-object net.webclient).DownloadFile('
      u'\'https://github.com/log2timeline/l2tbinaries/raw/master/win32/'
      u'WMI-{0:s}.win32.exe\', \'C:\\Projects\\WMI-{0:s}.win32.exe\')').format(
          _VERSION_WMI)

  _INSTALL_PIP = (
      u'  - cmd: "%PYTHON%\\\\python.exe C:\\\\Projects\\\\get-pip.py"')

  _INSTALL_PYWIN32 = (
      u'  - cmd: "%PYTHON%\\\\Scripts\\\\easy_install.exe '
      u'C:\\\\Projects\\\\pywin32-{0:s}.win32-py2.7.exe"').format(
          _VERSION_PYWIN32)

  _INSTALL_WMI = (
      u'  - cmd: "%PYTHON%\\\\Scripts\\\\easy_install.exe '
      u'C:\\\\Projects\\\\WMI-{0:s}.win32.exe"').format(_VERSION_WMI)

  _DOWNLOAD_L2TDEVTOOLS = (
      u'  - cmd: git clone https://github.com/log2timeline/l2tdevtools.git && '
      u'move l2tdevtools ..\\')

  _FILE_HEADER = [
      u'environment:',
      u'  matrix:',
      u'    - PYTHON: "C:\\\\Python27"',
      u'',
      u'install:',
      (u'  - cmd: \'"C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\'
       u'SetEnv.cmd" /x86 /release\''),
      _DOWNLOAD_PIP,
      _DOWNLOAD_PYWIN32,
      _DOWNLOAD_WMI,
      _INSTALL_PIP,
      _INSTALL_PYWIN32,
      _INSTALL_WMI,
      _DOWNLOAD_L2TDEVTOOLS]

  _L2TDEVTOOLS_UPDATE = (
      u'  - cmd: mkdir dependencies && set PYTHONPATH=..\\l2tdevtools && '
      u'"%PYTHON%\\\\python.exe" ..\\l2tdevtools\\tools\\update.py '
      u'--download-directory dependencies --machine-type x86 '
      u'--msi-targetdir "%PYTHON%" {0:s}')

  _FILE_FOOTER = [
      u'',
      u'build: off',
      u'',
      u'test_script:',
      u'  - "%PYTHON%\\\\python.exe run_tests.py"',
      u'']

  def Write(self):
    """Writes an appveyor.yml file."""
    file_content = []
    file_content.extend(self._FILE_HEADER)

    dependencies = self._dependency_helper.GetL2TBinaries()
    dependencies.extend([u'funcsigs', u'mock', u'pbr', u'six'])
    dependencies = u' '.join(dependencies)

    l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format(dependencies)
    file_content.append(l2tdevtools_update)

    file_content.extend(self._FILE_FOOTER)

    file_content = u'\n'.join(file_content)
    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

class DPKGControlWriter(DependencyFileWriter):
  """Dpkg control file writer."""

  _PATH = os.path.join(u'config', u'dpkg', u'control')

  _FILE_CONTENT = u'\n'.join([
      u'Source: {project_name:s}',
      u'Section: python',
      u'Priority: extra',
      u'Maintainer: {maintainer:s}',
      (u'Build-Depends: debhelper (>= 7), python-all (>= 2.7~), '
       u'python-setuptools, python3-all (>= 3.4~), python3-setuptools'),
      u'Standards-Version: 3.9.5',
      u'X-Python-Version: >= 2.7',
      u'X-Python3-Version: >= 3.4',
      u'Homepage: {homepage_url:s}',
      u'',
      u'Package: python-{project_name:s}',
      u'Architecture: all',
      (u'Depends: {python2_dependencies:s}${{python:Depends}}, '
       u'${{misc:Depends}}'),
      u'Description: Python 2 module of log2reviewtools',
      u'{description_long:s}',
      u'',
      u'Package: python3-{project_name:s}',
      u'Architecture: all',
      (u'Depends: {python3_dependencies:s}${{python3:Depends}}, '
       u'${{misc:Depends}}'),
      u'Description: Python 3 module of log2reviewtools',
      u'{description_long:s}',
      u'',
      u'Package: {project_name:s}-tools',
      u'Architecture: all',
      (u'Depends: python-{project_name:s}, python (>= 2.7~), '
       u'${{python:Depends}}, ${{misc:Depends}}'),
      u'Description: tools for code reviews in log2timeline projects'
      u'{description_long:s}',
      u''])

  def Write(self):
    """Writes a dpkg control file."""
    dependencies = self._dependency_helper.GetDPKGDepends()

    description_long = self._project_definition.description_long
    description_long = u'\n'.join([
        u' {0:s}'.format(line) for line in description_long.split(u'\n')])

    python2_dependencies = u', '.join(dependencies)
    if python2_dependencies:
      python2_dependencies = u'{0:s}, '.format(python2_dependencies)

    python3_dependencies = u', '.join(dependencies).replace(
        u'python', u'python3')
    if python3_dependencies:
      python3_dependencies = u'{0:s}, '.format(python3_dependencies)

    kwargs = {
        u'description_long': description_long,
        u'description_short': self._project_definition.description_short,
        u'homepage_url': self._project_definition.homepage_url,
        u'maintainer': self._project_definition.maintainer,
        u'project_name': self._project_definition.name,
        u'python2_dependencies': python2_dependencies,
        u'python3_dependencies': python3_dependencies}
    file_content = self._FILE_CONTENT.format(**kwargs)

    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

class RequirementsWriter(DependencyFileWriter):
  """Requirements.txt file writer."""

  _PATH = u'requirements.txt'

  _FILE_HEADER = [u'pip >= 7.0.0']

  def Write(self):
    """Writes a requirements.txt file."""
    file_content = []
    file_content.extend(self._FILE_HEADER)

    dependencies = self._dependency_helper.GetInstallRequires()
    for dependency in dependencies:
      file_content.append(u'{0:s}'.format(dependency))

    file_content = u'\n'.join(file_content)
    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

class SetupCfgWriter(DependencyFileWriter):
  """Setup.cfg file writer."""

  _PATH = u'setup.cfg'

  _FILE_HEADER = u'\n'.join([
      u'[bdist_rpm]',
      u'release = 1',
      u'packager = {maintainer:s}',
      u'doc_files = ACKNOWLEDGEMENTS',
      u'            AUTHORS',
      u'            LICENSE',
      u'            README.md',
      u'build_requires = python-setuptools'])

  def Write(self):
    """Writes a setup.cfg file."""
    kwargs = {u'maintainer': self._project_definition.maintainer}
    file_header = self._FILE_HEADER.format(**kwargs)

    file_content = [file_header]

    dependencies = self._dependency_helper.GetRPMRequires()
    for index, dependency in enumerate(dependencies):
      if index == 0:
        file_content.append(u'requires = {0:s}'.format(dependency))
      else:
        file_content.append(u'           {0:s}'.format(dependency))

    file_content.append(u'')

    file_content = u'\n'.join(file_content)
    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

class TravisBeforeInstallScriptWriter(DependencyFileWriter):
  """Travis-CI install.sh file writer."""

  _PATH = os.path.join(u'config', u'travis', u'install.sh')

  _FILE_HEADER = [
      u'#!/bin/bash',
      u'#',
      u'# Script to set up Travis-CI test VM.',
      u'',
      (u'COVERALL_DEPENDENCIES="python-coverage python-coveralls '
       u'python-docopt";'),
      u'']

  _FILE_FOOTER = [
      u'',
      u'# Exit on error.',
      u'set -e;',
      u'',
      u'if test ${TRAVIS_OS_NAME} = "osx";',
      u'then',
      u'\tgit clone https://github.com/log2timeline/l2tdevtools.git;',
      u'',
      u'\tmv l2tdevtools ../;',
      u'\tmkdir dependencies;',
      u'',
      (u'\tPYTHONPATH=../l2tdevtools ../l2tdevtools/tools/update.py '
       u'--download-directory=dependencies ${L2TBINARIES_DEPENDENCIES} '
       u'${L2TBINARIES_TEST_DEPENDENCIES};'),
      u'',
      u'elif test ${TRAVIS_OS_NAME} = "linux";',
      u'then',
      u'\tsudo add-apt-repository ppa:gift/dev -y;',
      u'\tsudo apt-get update -q;',
      u'\t# Only install the Python 2 dependencies.',
      (u'\t# Also see: https://docs.travis-ci.com/user/languages/python/'
       u'#Travis-CI-Uses-Isolated-virtualenvs'),
      (u'\tsudo apt-get install -y ${COVERALL_DEPENDENCIES} '
       u'${PYTHON2_DEPENDENCIES} ${PYTHON2_TEST_DEPENDENCIES};'),
      u'fi',
      u'']

  def Write(self):
    """Writes an install.sh file."""
    file_content = []
    file_content.extend(self._FILE_HEADER)

    dependencies = self._dependency_helper.GetL2TBinaries()
    dependencies = u' '.join(dependencies)
    file_content.append(u'L2TBINARIES_DEPENDENCIES="{0:s}";'.format(
        dependencies))

    file_content.append(u'')
    file_content.append(
        u'L2TBINARIES_TEST_DEPENDENCIES="funcsigs mock pbr six";')

    file_content.append(u'')

    dependencies = self._dependency_helper.GetDPKGDepends(exclude_version=True)
    dependencies = u' '.join(dependencies)
    file_content.append(u'PYTHON2_DEPENDENCIES="{0:s}";'.format(dependencies))

    file_content.append(u'')
    file_content.append(u'PYTHON2_TEST_DEPENDENCIES="python-mock python-tox";')

    file_content.extend(self._FILE_FOOTER)

    file_content = u'\n'.join(file_content)
    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

class ToxIniWriter(DependencyFileWriter):
  """Tox.ini file writer."""

  _PATH = u'tox.ini'

  _FILE_CONTENT = u'\n'.join([
      u'[tox]',
      u'envlist = py2, py3',
      u'',
      u'[testenv]',
      u'pip_pre = True',
      u'setenv =',
      u'    PYTHONPATH = {{toxinidir}}',
      u'deps =',
      u'    coverage',
      u'    mock',
      u'    pytest',
      u'    -rrequirements.txt',
      u'commands =',
      u'    coverage erase',
      (u'    coverage run --source={project_name:s} '
       u'--omit="*_test*,*__init__*,*test_lib*" run_tests.py'),
      u''])

  def Write(self):
    """Writes a setup.cfg file."""
    kwargs = {u'project_name': self._project_definition.name}
    file_content = self._FILE_CONTENT.format(**kwargs)

    file_content = file_content.encode(u'utf-8')

    with open(self._PATH, 'wb') as file_object:
      file_object.write(file_content)

if __name__ == u'__main__':
  project_file = os.path.abspath(__file__)
  project_file = os.path.dirname(project_file)
  project_file = os.path.dirname(project_file)
  project_file = os.path.basename(project_file)
  project_file = u'{0:s}.ini'.format(project_file)

  project_reader = utils.projects.ProjectDefinitionReader()
  with open(project_file, 'rb') as file_object:
    project_definition = project_reader.Read(file_object)

  helper = utils.dependencies.DependencyHelper()

  for writer_class in (
      AppveyorYmlWriter, DPKGControlWriter, RequirementsWriter, SetupCfgWriter,
      TravisBeforeInstallScriptWriter, ToxIniWriter):
    writer = writer_class(project_definition, helper)
    writer.Write()


text:
echo "Installing docker..."
yum update -y && yum install -y docker

echo "Formatting and mounting EBS volume..."
MOUNT_POINT=/mnt/ebs-a
STORAGE_DEVICE=/dev/xvdf
POSTGRES_VOLUMES=$MOUNT_POINT/postgres_volumes

echo "Formatting $STORAGE_DEVICE..."
mkfs -t ext4 $STORAGE_DEVICE

echo "Mounting $STORAGE_DEVICE at $MOUNT_POINT..."
mkdir -p $MOUNT_POINT
cp /etc/fstab /etc/fstab.orig
echo "$STORAGE_DEVICE   $MOUNT_POINT  ext4    defaults,nofail 0   0" | tee -a /etc/fstab
mount -a
rm /etc/fstab.orig
echo "Done mounting $STORAGE_DEVICE at $MOUNT_POINT."

echo "Creating folder for Postgres volumes..."
mkdir -p $POSTGRES_VOLUMES

# This needs to be done after the volume is mounted.
# See: https://github.com/docker/docker/issues/5489#issuecomment-141438777
echo "Starting Docker daemon.."
service docker start

# In order to use the database in the Rails application, you'll also need to seed it from
# a production Rails container.  See scripts/aws/rails/seed.sh

echo "Done provisioning Postgres instance."


text:
package timetools

import (
	"sync"
	"time"
)

// TimeProvider is an interface we use to mock time in tests.
type TimeProvider interface {
	UtcNow() time.Time
	Sleep(time.Duration)
	After(time.Duration) <-chan time.Time
}

// RealTime is a real clock time, used in production.
type RealTime struct {
}

func (*RealTime) UtcNow() time.Time {
	return time.Now().UTC()
}

func (*RealTime) Sleep(d time.Duration) {
	time.Sleep(d)
}

func (*RealTime) After(d time.Duration) <-chan time.Time {
	return time.After(d)
}

// FreezedTime is manually controlled time for use in tests.
type FreezedTime struct {
	CurrentTime time.Time
}

func (t *FreezedTime) UtcNow() time.Time {
	return t.CurrentTime
}

func (t *FreezedTime) Sleep(d time.Duration) {
	t.CurrentTime = t.CurrentTime.Add(d)
}

func (t *FreezedTime) After(d time.Duration) <-chan time.Time {
	t.Sleep(d)
	c := make(chan time.Time, 1)
	c <- t.CurrentTime
	return c
}

type sleepableTime struct {
	currentTime time.Time
	waiters     map[time.Time][]chan time.Time
	mu          sync.Mutex
}

// SleepProvider returns a TimeProvider that has good fakes for
// time.Sleep and time.After. Both functions will behave as if
// time is frozen until you call AdvanceTimeBy, at which point
// any calls to time.Sleep that should return do return and
// any ticks from time.After that should happen do happen.
func SleepProvider(currentTime time.Time) TimeProvider {
	return &sleepableTime{
		currentTime: currentTime,
		waiters:     make(map[time.Time][]chan time.Time),
	}
}

func (t *sleepableTime) UtcNow() time.Time {
	return t.currentTime
}

func (t *sleepableTime) Sleep(d time.Duration) {
	<-t.After(d)
}

func (t *sleepableTime) After(d time.Duration) <-chan time.Time {
	t.mu.Lock()
	defer t.mu.Unlock()

	c := make(chan time.Time, 1)
	until := t.currentTime.Add(d)
	t.waiters[until] = append(t.waiters[until], c)
	return c
}

// AdvanceTimeBy simulates advancing time by some time.Duration d.
// This function panics if st is not the result of a call to
// SleepProvider.
func AdvanceTimeBy(st TimeProvider, d time.Duration) {
	t := st.(*sleepableTime)
	t.mu.Lock()
	defer t.mu.Unlock()

	t.currentTime = t.currentTime.Add(d)
	for k, v := range t.waiters {
		if k.Before(t.currentTime) {
			for _, c := range v {
				c <- t.currentTime
			}
			delete(t.waiters, k)
		}
	}
}


text:
package dataframe

import (
	"flag"
	"log"
	"testing"

	"github.com/apache/beam/sdks/v2/go/pkg/beam"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/dataflow"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/flink"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/universal"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/testing/ptest"
	"github.com/apache/beam/sdks/v2/go/test/integration"
)

var expansionAddr string // Populate with expansion address labelled "python_transform".

func checkFlags(t *testing.T) {
	if expansionAddr == "" {
		t.Skip("No python transform expansion address provided.")
	}
}

func TestDataframe(t *testing.T) {
	integration.CheckFilters(t)
	checkFlags(t)
	p := DataframeTransform(expansionAddr)
	ptest.RunAndValidate(t, p)
}

func TestMain(m *testing.M) {
	flag.Parse()
	beam.Init()

	services := integration.NewExpansionServices()
	defer func() { services.Shutdown() }()
	addr, err := services.GetAddr("python_transform")
	if err != nil {
		log.Printf("skipping missing expansion service: %v", err)
	} else {
		expansionAddr = addr
	}

	ptest.MainRet(m)
}


text:
import { API_URL } from '../conventions';

export default function (data) {

  return async (dispatch, getState) => {

    dispatch({ type: 'UPDATE_FORM_FETCHING' });

    try {

      let response = await fetch(`${ API_URL }/forms`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${ getState().dataEntry.token }`
        },
        body: JSON.stringify(data)
      }).then(response => response.json());

      let { success } = response;

      if (!success) throw response;

      dispatch({ type: 'UPDATE_FORM_SUCCESS' });

    } catch (error) {

      console.log(error);

      dispatch({ type: 'UPDATE_FORM_ERROR' });

    }

  }

}


text:
package ozelentok.zbackup;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;

import androidx.core.app.NavUtils;

import java.util.List;

public class SettingsActivity extends PreferenceActivity {
    private static final boolean ALWAYS_SIMPLE_PREFS = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        setupSimplePreferencesScreen();
    }

    private void setupSimplePreferencesScreen() {
        if (!isSimplePreferences(this)) {
            return;
        }

        addPreferencesFromResource(R.xml.pref_network);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this) && !isSimplePreferences(this);
    }

    /**
     * Helper method to determine if the device has an extra-large screen. For
     * example, 10" tablets are extra-large.
     */
    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }

    /**
     * Determines whether the simplified settings UI should be shown. This is
     * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device
     * doesn't have newer APIs like {@link PreferenceFragment}, or the device
     * doesn't have an extra-large screen. In these cases, a single-pane
     * "simplified" settings UI should be shown.
     */
    private static boolean isSimplePreferences(Context context) {
        return ALWAYS_SIMPLE_PREFS || !isXLargeTablet(context);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List<Header> target) {
        if (!isSimplePreferences(this)) {
            loadHeadersFromResource(R.xml.pref_headers, target);
        }
    }

    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = (preference, value) -> {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    };

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    /**
     * This fragment shows general preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class NetworkPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_network);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("server"));
            bindPreferenceSummaryToValue(findPreference("port"));
            bindPreferenceSummaryToValue(findPreference("password"));
        }
    }
}


text:
/* vim: set et sw=2 ts=2: */
'use strict';

module.exports = function () {

  var Nodash = this;

  return {

    keys: Object.keys,

    values: function (object) {
      var values = [];
      Nodash.each(function (value) {
        values.push(value);
      }, object);
      return values;
    },

    clone: function (thing) {
      if (typeof thing === 'object') {
        if (thing === null) {
          return null;
        }
        return Nodash.map(Nodash.clone, thing);
      }
      return thing;
    }

  };
};


text:
set CLASSPATH=/pkg/javautil/bsh.jar;%CLASSPATH%

java bsh.Interpreter $*


text:
Yeoman Generator for Webapp

![Tarti logo](tarti.png)

## Out of the box
- Webpack
- SCSS
	- Linter
	- [Fontawesome](http://fontawesome.io/)
	- [Gridle](http://gridle.org/)
- ES6 + Linter

## Options
- [React](https://facebook.github.io/react/)
- [React/Router](https://github.com/ReactTraining/react-router)
- Server ([Express](http://expressjs.com/))
- API
- Database ([MongoDB](https://www.mongodb.com/)) + [Mongoose](http://mongoosejs.com/)

## Installation

First, install [Yeoman](http://yeoman.io) and generator-tartiflette using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)).

```bash
npm install -g yo
npm install -g generator-tartiflette
```

Then generate your new project:

```bash
yo tartiflette
```

## Use

Run application in production mode
```bash
npm run start
```

Run application in development mode
```bash
npm run dev
```

Build application
```bash
npm run build
```

## License

MIT © [Charles Perinet](www.charles-perinet.fr)

[npm-url]: https://npmjs.org/package/generator-tartiflette
[npm-image]: http://img.shields.io/npm/v/generator-tartiflette.svg


text:
<?php

class DevelopmentLogic
{
	public function debugSwitch($do, $class, $data = null)
	{
		if ($do == 'get')
		{
			return $this->debugSwitch_get($class);
		}
		else
		{
			$debug = $data == 'true' ? true : false;
			return $this->debugSwitch_set($class, $debug);
		}
	}
	private function debugSwitch_get($class)
	{
		return is_file(DATA_PATH.'debug.'.$class.'.signal') ? true : false;
	}
	private function debugSwitch_set($class, $debug)
	{
		$file = DATA_PATH.'debug.'.$class.'.signal';
		if ($debug)
		{
			return file_put_contents($file, '');
		}
		else
		{
			return unlink($file);
		}
	}
}

?>


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Boton Rotar</title>
</head>
<body>
	<button id="rotar">rotar</button>
	<button id="subir">subir</button>
	<button id="subirAutomatico">subir automatico </button>
	<button id="actualizar">Activar Programados</button>
	<button id="borrar">Borrar Programados</button>

	<button id="borrarAnuncio">Borrar Anuncio</button>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

	<script>
		$(document).ready(function(){
			$('#rotar').click(function(){
				$.ajax({
					url:"<?php echo base_url('rotar/top'); ?>",
					success: function(response){
						console.log(response);
					}
				});
			});

			$('#subir').click(function(){
				$.ajax({
					url:"<?php echo base_url('subir/top'); ?>",
					success: function(response){
						console.log(response);
					}
				});
			});

			$('#subirAutomatico').click(function(){
				$.ajax({
					url:"<?php echo base_url('subir/automatico'); ?>",
					success: function(response){
						console.log(response);
					}
				});
			});

			$('#actualizar').click(function(){
				$.ajax({
					url:"<?php echo base_url('activar/programados'); ?>",
					success: function(response){
						console.log(response);
					}
				});
			});

			$('#borrar').click(function(){
				$.ajax({
					url:"<?php echo base_url('borrar/programados'); ?>",
					success: function(response){
						console.log(response);
					}
				});
			});

			$('#borrarAnuncio').click(function(){
				$.ajax({
					url:"<?php echo base_url('eliminar/anuncios') ?>",
					success: function(response){
						console.log(response);
					}
				});
			});
		});
	</script>
</body>
</html>


text:
namespace LinqPractise
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Core.Node")]
    public partial class Node
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Node()
        {
            ProductNodes = new HashSet<ProductNode>();
        }

        public int Id { get; set; }

        [StringLength(60)]
        public string Name { get; set; }

        public int? ParentId { get; set; }

        public Guid Rowguid { get; set; }

        [StringLength(100)]
        public string Identifier { get; set; }

        public bool IsSegment { get; set; }

        public int Ordering { get; set; }

        public string ChineseName { get; set; }

        public string JapaneseName { get; set; }

        [StringLength(100)]
        public string UrlFriendlyName { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProductNode> ProductNodes { get; set; }
    }
}


text:
__author__ = 'frankhe'

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import scipy.misc
import cPickle

def rgb2gray(rgb):
    return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])

def resize(image, size):
    return scipy.misc.imresize(image, size=size)

def imshow(photo, gray=False):
    if gray:
        plt.imshow(photo, cmap = plt.get_cmap('gray'))
    else:
        plt.imshow(photo)
    plt.show()

def show_wall_paper():
    img = mpimg.imread('wallpaper.jpg')
    gray = rgb2gray(img)
    gray = resize(gray, (1000, 1000))
    imshow(gray, True)

if __name__ == '__main__':
    f1 = open('game_images', mode='rb')
    images = cPickle.load(f1)
    print images[0].size, images[0].shape
    for i in range(1, len(images)):
        # imshow(images[i])
        # print np.sum(images[i]-images[i-1])
        raw_input()


text:
using System.Collections.Generic;

namespace Azure.Graph.Rbac.Models
{
    /// <summary> Application list operation result. </summary>
    public partial class ApplicationListResult
    {
        /// <summary> Initializes a new instance of ApplicationListResult. </summary>
        internal ApplicationListResult()
        {
        }

        /// <summary> Initializes a new instance of ApplicationListResult. </summary>
        /// <param name="value"> A collection of applications. </param>
        /// <param name="odataNextLink"> The URL to get the next set of results. </param>
        internal ApplicationListResult(IReadOnlyList<Application> value, string odataNextLink)
        {
            Value = value;
            OdataNextLink = odataNextLink;
        }

        /// <summary> A collection of applications. </summary>
        public IReadOnlyList<Application> Value { get; }
        /// <summary> The URL to get the next set of results. </summary>
        public string OdataNextLink { get; }
    }
}


text:
try:
    from urllib.parse import parse_qsl, urlencode
except ImportError:
    from urllib import urlencode
    from urlparse import parse_qsl
import requests

class OAuth2Error(Exception):
    pass

class OAuth2Client(object):

    def __init__(self, request, consumer_key, consumer_secret,
                 access_token_method,
                 access_token_url,
                 callback_url,
                 scope):
        self.request = request
        self.access_token_method = access_token_method
        self.access_token_url = access_token_url
        self.callback_url = callback_url
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.scope = ' '.join(scope)
        self.state = None

    def get_redirect_url(self, authorization_url, extra_params):
        params = {
            'client_id': self.consumer_key,
            'redirect_uri': self.callback_url,
            'scope': self.scope,
            'response_type': 'code'
        }
        if self.state:
            params['state'] = self.state
        params.update(extra_params)
        return '%s?%s' % (authorization_url, urlencode(params))

    def get_access_token(self, code):
        data = {'client_id': self.consumer_key,
                'redirect_uri': self.callback_url,
                'grant_type': 'authorization_code',
                'client_secret': self.consumer_secret,
                'scope': self.scope,
                'code': code}
        params = None
        self._strip_empty_keys(data)
        url = self.access_token_url
        if self.access_token_method == 'GET':
            params = data
            data = None
        # TODO: Proper exception handling
        resp = requests.request(self.access_token_method,
                                url,
                                params=params,
                                data=data)
        access_token = None
        if resp.status_code == 200:
            # Weibo sends json via 'text/plain;charset=UTF-8'
            if (resp.headers['content-type'].split(';')[0] == 'application/json'
                or resp.text[:2] == '{"'):
                access_token = resp.json()
            else:
                access_token = dict(parse_qsl(resp.text))
        if not access_token or 'access_token' not in access_token:
            raise OAuth2Error('Error retrieving access token: %s'
                              % resp.content)
        return access_token

    def _strip_empty_keys(self, params):
        """Added because the Dropbox OAuth2 flow doesn't
        work when scope is passed in, which is empty.
        """
        keys = [k for k, v in params.items() if v == '']
        for key in keys:
            del params[key]


text:
<?php

declare(strict_types=1);

namespace LizardsAndPumpkins\Import;

interface Projector
{
    /**
     * @param mixed $projectionSourceData
     */
    public function project($projectionSourceData);
}


text:
main();

var tsunamiRunup;

function main() {
    tsunamiRunup = new TsunamiRunup("#tsunami-runup", "data/tsunami_runup.tsv");
}


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// require: cr.js
// require: cr/ui.js
// require: cr/ui/tree.js

(function() {
  /**
   * A helper function to determine if a node is the root of its type.
   *
   * @param {!Object} node The node to check.
   */
  function isTypeRootNode(node) {
    return node.PARENT_ID === 'r' && node.UNIQUE_SERVER_TAG !== '';
  }

  /**
   * A helper function to determine if a node is a child of the given parent.
   *
   * @param {!Object} parent node.
   * @param {!Object} node The node to check.
   */
  function isChildOf(parentNode, node) {
    if (node.PARENT_ID !== '') {
      return node.PARENT_ID === parentNode.ID;
    } else {
      return node.modelType === parentNode.modelType;
    }
  }

  /**
   * A helper function to sort sync nodes.
   *
   * Sorts by position index if possible, falls back to sorting by name, and
   * finally sorting by METAHANDLE.
   *
   * If this proves to be slow and expensive, we should experiment with moving
   * this functionality to C++ instead.
   */
  function nodeComparator(nodeA, nodeB) {
    if (nodeA.hasOwnProperty('positionIndex') &&
        nodeB.hasOwnProperty('positionIndex')) {
      return nodeA.positionIndex - nodeB.positionIndex;
    } else if (nodeA.NON_UNIQUE_NAME !== nodeB.NON_UNIQUE_NAME) {
      return nodeA.NON_UNIQUE_NAME.localeCompare(nodeB.NON_UNIQUE_NAME);
    } else {
      return nodeA.METAHANDLE - nodeB.METAHANDLE;
    }
  }

  /**
   * Updates the node detail view with the details for the given node.
   * @param {!Object} node The struct representing the node we want to display.
   */
  function updateNodeDetailView(node) {
    const nodeDetailsView = $('node-details');
    nodeDetailsView.hidden = false;
    jstProcess(new JsEvalContext(node.entry_), nodeDetailsView);
  }

  /**
   * Updates the 'Last refresh time' display.
   * @param {string} str The text to display.
   */
  function setLastRefreshTime(str) {
    $('node-browser-refresh-time').textContent = str;
  }

  /**
   * Creates a new sync node tree item.
   *
   * @constructor
   * @param {!Object} node The nodeDetails object for the node as returned by
   *     chrome.sync.getAllNodes().
   * @extends {cr.ui.TreeItem}
   */
  function SyncNodeTreeItem(node) {
    const treeItem = new cr.ui.TreeItem();
    treeItem.__proto__ = SyncNodeTreeItem.prototype;

    treeItem.entry_ = node;
    treeItem.label = node.NON_UNIQUE_NAME;
    if (node.IS_DIR) {
      treeItem.mayHaveChildren_ = true;

      // Load children on expand.
      treeItem.expanded_ = false;
      treeItem.addEventListener('expand',
                                treeItem.handleExpand_.bind(treeItem));
    } else {
      treeItem.classList.add('leaf');
    }
    return treeItem;
  }

  SyncNodeTreeItem.prototype = {
    __proto__: cr.ui.TreeItem.prototype,

    /**
     * Finds the children of this node and appends them to the tree.
     */
    handleExpand_(event) {
      const treeItem = this;

      if (treeItem.expanded_) {
        return;
      }
      treeItem.expanded_ = true;

      const children = treeItem.tree.allNodes.filter(
          isChildOf.bind(undefined, treeItem.entry_));
      children.sort(nodeComparator);

      children.forEach(function(node) {
        treeItem.add(new SyncNodeTreeItem(node));
      });
    },
  };

  /**
   * Creates a new sync node tree.  Technically, it's a forest since it each
   * type has its own root node for its own tree, but it still looks and acts
   * mostly like a tree.
   *
   * @param {Object=} opt_propertyBag Optional properties.
   * @constructor
   * @extends {cr.ui.Tree}
   */
  const SyncNodeTree = cr.ui.define('tree');

  SyncNodeTree.prototype = {
    __proto__: cr.ui.Tree.prototype,

    decorate() {
      cr.ui.Tree.prototype.decorate.call(this);
      this.addEventListener('change', this.handleChange_.bind(this));
      this.allNodes = [];
    },

    populate(nodes) {
      const tree = this;

      // We store the full set of nodes in the SyncNodeTree object.
      tree.allNodes = nodes;

      const roots = tree.allNodes.filter(isTypeRootNode);
      roots.sort(nodeComparator);

      roots.forEach(function(typeRoot) {
        tree.add(new SyncNodeTreeItem(typeRoot));
      });
    },

    handleChange_(event) {
      if (this.selectedItem) {
        updateNodeDetailView(this.selectedItem);
      }
    }
  };

  /**
   * Clears any existing UI state.  Useful prior to a refresh.
   */
  function clear() {
    const treeContainer = $('sync-node-tree-container');
    while (treeContainer.firstChild) {
      treeContainer.removeChild(treeContainer.firstChild);
    }

    const nodeDetailsView = $('node-details');
    nodeDetailsView.hidden = true;
  }

  /**
   * Fetch the latest set of nodes and refresh the UI.
   */
  function refresh() {
    $('node-browser-refresh-button').disabled = true;

    clear();
    setLastRefreshTime('In progress since ' + (new Date()).toLocaleString());

    chrome.sync.getAllNodes(function(nodeMap) {
      // Put all nodes into one big list that ignores the type.
      const nodes = nodeMap
                        .map(function(x) {
                          return x.nodes;
                        })
                        .reduce(function(a, b) {
                          return a.concat(b);
                        });

      const treeContainer = $('sync-node-tree-container');
      const tree = document.createElement('tree');
      tree.setAttribute('id', 'sync-node-tree');
      tree.setAttribute('icon-visibility', 'parent');
      treeContainer.appendChild(tree);

      cr.ui.decorate(tree, SyncNodeTree);
      tree.populate(nodes);

      setLastRefreshTime((new Date()).toLocaleString());
      $('node-browser-refresh-button').disabled = false;
    });
  }

  document.addEventListener('DOMContentLoaded', function(e) {
    $('node-browser-refresh-button').addEventListener('click', refresh);
    const Splitter = cr.ui.Splitter;
    const customSplitter = cr.ui.define('div');

    customSplitter.prototype = {
      __proto__: Splitter.prototype,

      handleSplitterDragEnd(e) {
        Splitter.prototype.handleSplitterDragEnd.apply(this, arguments);
        const treeElement = $('sync-node-tree-container');
        const newWidth = parseFloat(treeElement.style.width);
        treeElement.style.minWidth = Math.max(newWidth, 50) + "px";
      }
    };

    customSplitter.decorate($("sync-node-splitter"));

    // Automatically trigger a refresh the first time this tab is selected.
    $('sync-browser-tab').addEventListener('selectedChange', function f(e) {
      if (this.selected) {
        $('sync-browser-tab').removeEventListener('selectedChange', f);
        refresh();
      }
    });
  });

})();


text:
using Shouldly.Tests.Strings;
using Xunit;

namespace Shouldly.Tests.ShouldSatisfyAllConditions
{
    public class MultipleConditionsScenario_MultiLine2
    {

        [Fact]
        public void MultipleConditionsScenario_MultiLine2ShouldFail()
        {
            int result = 4;
            Verify.ShouldFail(() =>
result.ShouldSatisfyAllConditions
(
    () => result.ShouldBeOfType<float>("Some additional context"),
    () => result.ShouldBeGreaterThan(5, "Some additional context")
),

errorWithSource:
@"result
    should satisfy all the conditions specified, but does not.
The following errors were found ...
--------------- Error 1 ---------------
    result
        should be of type
    System.Single
        but was
    System.Int32

    Additional Info:
        Some additional context

--------------- Error 2 ---------------
    result
        should be greater than
    5
        but was
    4

    Additional Info:
        Some additional context

-----------------------------------------",

errorWithoutSource:
@"4
    should satisfy all the conditions specified, but does not.
The following errors were found ...
--------------- Error 1 ---------------
    4
        should be of type
    System.Single
        but was
    System.Int32

    Additional Info:
        Some additional context

--------------- Error 2 ---------------
    4
        should be greater than
    5
        but was not

    Additional Info:
        Some additional context

-----------------------------------------");
        }

        [Fact]
        public void ShouldPass()
        {
            int result = 4;
            result.ShouldSatisfyAllConditions
                    (
                        ()
                            => result
                                .ShouldBeOfType<int>(),
                        ()
                            =>
                            result
                            .ShouldBeGreaterThan(3)
                    );
        }
    }
}