text:
package interpodaffinity

import (
	"context"
	"reflect"
	"strings"
	"testing"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubernetes/pkg/scheduler/apis/config"
	"k8s.io/kubernetes/pkg/scheduler/framework"
	"k8s.io/kubernetes/pkg/scheduler/framework/plugins/feature"
	plugintesting "k8s.io/kubernetes/pkg/scheduler/framework/plugins/testing"
	frameworkruntime "k8s.io/kubernetes/pkg/scheduler/framework/runtime"
	"k8s.io/kubernetes/pkg/scheduler/internal/cache"
)

var nsLabelT1 = map[string]string{"team": "team1"}
var nsLabelT2 = map[string]string{"team": "team2"}
var namespaces = []runtime.Object{
	&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "subteam1.team1", Labels: nsLabelT1}},
	&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "subteam2.team1", Labels: nsLabelT1}},
	&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "subteam1.team2", Labels: nsLabelT2}},
	&v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "subteam2.team2", Labels: nsLabelT2}},
}

func TestPreferredAffinity(t *testing.T) {
	labelRgChina := map[string]string{
		"region": "China",
	}
	labelRgIndia := map[string]string{
		"region": "India",
	}
	labelAzAz1 := map[string]string{
		"az": "az1",
	}
	labelAzAz2 := map[string]string{
		"az": "az2",
	}
	labelRgChinaAzAz1 := map[string]string{
		"region": "China",
		"az":     "az1",
	}
	podLabelSecurityS1 := map[string]string{
		"security": "S1",
	}
	podLabelSecurityS2 := map[string]string{
		"security": "S2",
	}
	// considered only preferredDuringSchedulingIgnoredDuringExecution in pod affinity
	stayWithS1InRegion := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S1"},
								},
							},
						},
						TopologyKey: "region",
					},
				},
			},
		},
	}
	stayWithS2InRegion := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 6,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S2"},
								},
							},
						},
						TopologyKey: "region",
					},
				},
			},
		},
	}
	affinity3 := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 8,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpNotIn,
									Values:   []string{"S1"},
								}, {
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S2"},
								},
							},
						},
						TopologyKey: "region",
					},
				}, {
					Weight: 2,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpExists,
								}, {
									Key:      "wrongkey",
									Operator: metav1.LabelSelectorOpDoesNotExist,
								},
							},
						},
						TopologyKey: "region",
					},
				},
			},
		},
	}
	hardAffinity := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
				{
					LabelSelector: &metav1.LabelSelector{
						MatchExpressions: []metav1.LabelSelectorRequirement{
							{
								Key:      "security",
								Operator: metav1.LabelSelectorOpIn,
								Values:   []string{"S1", "value2"},
							},
						},
					},
					TopologyKey: "region",
				}, {
					LabelSelector: &metav1.LabelSelector{
						MatchExpressions: []metav1.LabelSelectorRequirement{
							{
								Key:      "security",
								Operator: metav1.LabelSelectorOpExists,
							}, {
								Key:      "wrongkey",
								Operator: metav1.LabelSelectorOpDoesNotExist,
							},
						},
					},
					TopologyKey: "region",
				},
			},
		},
	}
	awayFromS1InAz := &v1.Affinity{
		PodAntiAffinity: &v1.PodAntiAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S1"},
								},
							},
						},
						TopologyKey: "az",
					},
				},
			},
		},
	}
	// to stay away from security S2 in any az.
	awayFromS2InAz := &v1.Affinity{
		PodAntiAffinity: &v1.PodAntiAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S2"},
								},
							},
						},
						TopologyKey: "az",
					},
				},
			},
		},
	}
	// to stay with security S1 in same region, stay away from security S2 in any az.
	stayWithS1InRegionAwayFromS2InAz := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 8,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S1"},
								},
							},
						},
						TopologyKey: "region",
					},
				},
			},
		},
		PodAntiAffinity: &v1.PodAntiAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S2"},
								},
							},
						},
						TopologyKey: "az",
					},
				},
			},
		},
	}

	affinityNamespaceSelector := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S1"},
								},
							},
						},
						TopologyKey: "region",
						Namespaces:  []string{"subteam2.team2"},
						NamespaceSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "team",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"team1"},
								},
							},
						},
					},
				},
			},
		},
	}
	antiAffinityNamespaceSelector := &v1.Affinity{
		PodAntiAffinity: &v1.PodAntiAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"S1"},
								},
							},
						},
						TopologyKey: "region",
						Namespaces:  []string{"subteam2.team2"},
						NamespaceSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "team",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"team1"},
								},
							},
						},
					},
				},
			},
		},
	}
	invalidAffinityLabels := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 8,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"{{.bad-value.}}"},
								},
							},
						},
						TopologyKey: "region",
					},
				},
			},
		},
	}
	invalidAntiAffinityLabels := &v1.Affinity{
		PodAntiAffinity: &v1.PodAntiAffinity{
			PreferredDuringSchedulingIgnoredDuringExecution: []v1.WeightedPodAffinityTerm{
				{
					Weight: 5,
					PodAffinityTerm: v1.PodAffinityTerm{
						LabelSelector: &metav1.LabelSelector{
							MatchExpressions: []metav1.LabelSelectorRequirement{
								{
									Key:      "security",
									Operator: metav1.LabelSelectorOpIn,
									Values:   []string{"{{.bad-value.}}"},
								},
							},
						},
						TopologyKey: "az",
					},
				},
			},
		},
	}

	tests := []struct {
		pod               *v1.Pod
		pods              []*v1.Pod
		nodes             []*v1.Node
		expectedList      framework.NodeScoreList
		name              string
		wantStatus        *framework.Status
		disableNSSelector bool
	}{
		{
			name: "all machines are same priority as Affinity is nil",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: 0}},
		},
		// the node(machine1) that have the label {"region": "China"} (match the topology key) and that have existing pods that match the labelSelector get high score
		// the node(machine3) that don't have the label {"region": "whatever the value is"} (mismatch the topology key) but that have existing pods that match the labelSelector get low score
		// the node(machine2) that have the label {"region": "China"} (match the topology key) but that have existing pods that mismatch the labelSelector get low score
		{
			name: "Affinity: pod that matches topology key & pods in nodes will get high score comparing to others" +
				"which doesn't match either pods in nodes or in topology key",
			pod: &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS1InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: 0}},
		},
		// the node1(machine1) that have the label {"region": "China"} (match the topology key) and that have existing pods that match the labelSelector get high score
		// the node2(machine2) that have the label {"region": "China"}, match the topology key and have the same label value with node1, get the same high score with node1
		// the node3(machine3) that have the label {"region": "India"}, match the topology key but have a different label value, don't have existing pods that match the labelSelector,
		// get a low score.
		{
			name: "All the nodes that have the same topology key & label value with one of them has an existing pod that match the affinity rules, have the same score",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS1InRegion}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChinaAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
		// there are 2 regions, say regionChina(machine1,machine3,machine4) and regionIndia(machine2,machine5), both regions have nodes that match the preference.
		// But there are more nodes(actually more existing pods) in regionChina that match the preference than regionIndia.
		// Then, nodes in regionChina get higher score than nodes in regionIndia, and all the nodes in regionChina should get a same score(high score),
		// while all the nodes in regionIndia should get another same score(low score).
		{
			name: "Affinity: nodes in one region has more matching pods comparing to other region, so the region which has more matches will get high score",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS2InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine4"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine4", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine5", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: framework.MaxNodeScore}, {Name: "machine4", Score: framework.MaxNodeScore}, {Name: "machine5", Score: 0}},
		},
		// Test with the different operators and values for pod affinity scheduling preference, including some match failures.
		{
			name: "Affinity: different Label operators and values for pod affinity scheduling preference, including some match failures ",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: affinity3}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 20}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
		// Test the symmetry cases for affinity, the difference between affinity and symmetry is not the pod wants to run together with some existing pods,
		// but the existing pods have the inter pod affinity preference while the pod to schedule satisfy the preference.
		{
			name: "Affinity symmetry: considered only the preferredDuringSchedulingIgnoredDuringExecution in pod affinity symmetry",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: stayWithS1InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: stayWithS2InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
		{
			name: "Affinity symmetry with namespace selector",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: affinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: stayWithS2InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: 0}},
		},
		{
			name: "AntiAffinity symmetry with namespace selector",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: antiAffinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: stayWithS2InRegion}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: framework.MaxNodeScore}},
		},
		{
			name: "Affinity symmetry: considered RequiredDuringSchedulingIgnoredDuringExecution in pod affinity symmetry",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardAffinity}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardAffinity}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},

		// The pod to schedule prefer to stay away from some existing pods at node level using the pod anti affinity.
		// the nodes that have the label {"node": "bar"} (match the topology key) and that have existing pods that match the labelSelector get low score
		// the nodes that don't have the label {"node": "whatever the value is"} (mismatch the topology key) but that have existing pods that match the labelSelector get high score
		// the nodes that have the label {"node": "bar"} (match the topology key) but that have existing pods that mismatch the labelSelector get high score
		// there are 2 nodes, say node1 and node2, both nodes have pods that match the labelSelector and have topology-key in node.Labels.
		// But there are more pods on node1 that match the preference than node2. Then, node1 get a lower score than node2.
		{
			name: "Anti Affinity: pod that does not match existing pods in node will get high score ",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: awayFromS1InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChina}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
		{
			name: "Anti Affinity: pod that does not match topology key & match the pods in nodes will get higher score comparing to others ",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: awayFromS1InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChina}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
		{
			name: "Anti Affinity: one node has more matching pods comparing to other node, so the node which has more unmatches will get high score",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: awayFromS1InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
		// Test the symmetry cases for anti affinity
		{
			name: "Anti Affinity symmetry: the existing pods in node which has anti affinity match will get high score",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: awayFromS2InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: awayFromS1InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelAzAz2}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
		// Test both  affinity and anti-affinity
		{
			name: "Affinity and Anti Affinity: considered only preferredDuringSchedulingIgnoredDuringExecution in both pod affinity & anti affinity",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS1InRegionAwayFromS2InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelAzAz1}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}},
		},
		// Combined cases considering both affinity and anti-affinity, the pod to schedule and existing pods have the same labels (they are in the same RC/service),
		// the pod prefer to run together with its brother pods in the same region, but wants to stay away from them at node level,
		// so that all the pods of a RC/service can stay in a same region but trying to separate with each other
		// machine-1,machine-3,machine-4 are in ChinaRegion others machine-2,machine-5 are in IndiaRegion
		{
			name: "Affinity and Anti Affinity: considering both affinity and anti-affinity, the pod to schedule and existing pods have the same labels",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS1InRegionAwayFromS2InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine4"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChinaAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine4", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine5", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: framework.MaxNodeScore}, {Name: "machine4", Score: framework.MaxNodeScore}, {Name: "machine5", Score: 0}},
		},
		// Consider Affinity, Anti Affinity and symmetry together.
		// for Affinity, the weights are:                8,  0,  0,  0
		// for Anti Affinity, the weights are:           0, -5,  0,  0
		// for Affinity symmetry, the weights are:       0,  0,  8,  0
		// for Anti Affinity symmetry, the weights are:  0,  0,  0, -5
		{
			name: "Affinity and Anti Affinity and symmetry: considered only preferredDuringSchedulingIgnoredDuringExecution in both pod affinity & anti affinity & symmetry",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: stayWithS1InRegionAwayFromS2InAz}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS2}},
				{Spec: v1.PodSpec{NodeName: "machine3", Affinity: stayWithS1InRegionAwayFromS2InAz}},
				{Spec: v1.PodSpec{NodeName: "machine4", Affinity: awayFromS1InAz}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelAzAz1}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine4", Labels: labelAzAz2}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: framework.MaxNodeScore}, {Name: "machine4", Score: 0}},
		},
		// Cover https://github.com/kubernetes/kubernetes/issues/82796 which panics upon:
		// 1. Some nodes in a topology don't have pods with affinity, but other nodes in the same topology have.
		// 2. The incoming pod doesn't have affinity.
		{
			name: "Avoid panic when partial nodes in a topology don't have pods with affinity",
			pod:  &v1.Pod{Spec: v1.PodSpec{NodeName: ""}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: stayWithS1InRegionAwayFromS2InAz}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChina}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: 0}},
		},
		{
			name:       "invalid Affinity fails PreScore",
			pod:        &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: invalidAffinityLabels}},
			wantStatus: framework.NewStatus(framework.Error, `Invalid value: "{{.bad-value.}}"`),
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChina}},
			},
		},
		{
			name:       "invalid AntiAffinity fails PreScore",
			pod:        &v1.Pod{Spec: v1.PodSpec{NodeName: "", Affinity: invalidAntiAffinityLabels}},
			wantStatus: framework.NewStatus(framework.Error, `Invalid value: "{{.bad-value.}}"`),
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgChina}},
			},
		},
		{
			name: "Affinity with pods matching NamespaceSelector",
			pod:  &v1.Pod{Spec: v1.PodSpec{Affinity: affinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team2", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team1", Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}},
		},
		{
			name: "Affinity with pods matching both NamespaceSelector and Namespaces fields",
			pod:  &v1.Pod{Spec: v1.PodSpec{Affinity: affinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team2", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team1", Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: 0}},
		},
		{
			name: "Affinity with pods matching NamespaceSelector",
			pod:  &v1.Pod{Spec: v1.PodSpec{Affinity: antiAffinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team2", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team1", Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
		{
			name: "Affinity with pods matching both NamespaceSelector and Namespaces fields",
			pod:  &v1.Pod{Spec: v1.PodSpec{Affinity: antiAffinityNamespaceSelector}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team2", Labels: podLabelSecurityS1}},
				{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team1", Labels: podLabelSecurityS1}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
			},
			expectedList: []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: framework.MaxNodeScore}},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			ctx := context.Background()
			state := framework.NewCycleState()
			fts := feature.Features{EnablePodAffinityNamespaceSelector: !test.disableNSSelector}
			p := plugintesting.SetupPluginWithInformers(ctx, t, frameworkruntime.FactoryAdapter(fts, New), &config.InterPodAffinityArgs{HardPodAffinityWeight: 1}, cache.NewSnapshot(test.pods, test.nodes), namespaces)
			status := p.(framework.PreScorePlugin).PreScore(ctx, state, test.pod, test.nodes)
			if !status.IsSuccess() {
				if !strings.Contains(status.Message(), test.wantStatus.Message()) {
					t.Errorf("unexpected error: %v", status)
				}
			} else {
				var gotList framework.NodeScoreList
				for _, n := range test.nodes {
					nodeName := n.ObjectMeta.Name
					score, status := p.(framework.ScorePlugin).Score(ctx, state, test.pod, nodeName)
					if !status.IsSuccess() {
						t.Errorf("unexpected error: %v", status)
					}
					gotList = append(gotList, framework.NodeScore{Name: nodeName, Score: score})
				}

				status = p.(framework.ScorePlugin).ScoreExtensions().NormalizeScore(ctx, state, test.pod, gotList)
				if !status.IsSuccess() {
					t.Errorf("unexpected error: %v", status)
				}

				if !reflect.DeepEqual(test.expectedList, gotList) {
					t.Errorf("expected:\n\t%+v,\ngot:\n\t%+v", test.expectedList, gotList)
				}
			}

		})
	}
}

func TestPreferredAffinityWithHardPodAffinitySymmetricWeight(t *testing.T) {
	podLabelServiceS1 := map[string]string{
		"service": "S1",
	}
	labelRgChina := map[string]string{
		"region": "China",
	}
	labelRgIndia := map[string]string{
		"region": "India",
	}
	labelAzAz1 := map[string]string{
		"az": "az1",
	}
	hardPodAffinity := &v1.Affinity{
		PodAffinity: &v1.PodAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
				{
					LabelSelector: &metav1.LabelSelector{
						MatchExpressions: []metav1.LabelSelectorRequirement{
							{
								Key:      "service",
								Operator: metav1.LabelSelectorOpIn,
								Values:   []string{"S1"},
							},
						},
					},
					Namespaces: []string{"", "subteam2.team2"},
					NamespaceSelector: &metav1.LabelSelector{
						MatchExpressions: []metav1.LabelSelectorRequirement{
							{
								Key:      "team",
								Operator: metav1.LabelSelectorOpIn,
								Values:   []string{"team1"},
							},
						},
					},
					TopologyKey: "region",
				},
			},
		},
	}
	tests := []struct {
		pod                   *v1.Pod
		pods                  []*v1.Pod
		nodes                 []*v1.Node
		hardPodAffinityWeight int32
		expectedList          framework.NodeScoreList
		name                  string
		disableNSSelector     bool
	}{
		{
			name: "with default weight",
			pod:  &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: podLabelServiceS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardPodAffinity}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardPodAffinity}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight,
			expectedList:          []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
		{
			name: "with zero weight",
			pod:  &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: podLabelServiceS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardPodAffinity}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardPodAffinity}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			hardPodAffinityWeight: 0,
			expectedList:          []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: 0}},
		},
		{
			name: "with no matching namespace",
			pod:  &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team2", Labels: podLabelServiceS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardPodAffinity}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardPodAffinity}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight,
			expectedList:          []framework.NodeScore{{Name: "machine1", Score: 0}, {Name: "machine2", Score: 0}, {Name: "machine3", Score: 0}},
		},
		{
			name: "with matching NamespaceSelector",
			pod:  &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "subteam1.team1", Labels: podLabelServiceS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardPodAffinity}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardPodAffinity}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight,
			expectedList:          []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
		{
			name: "with matching Namespaces",
			pod:  &v1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "subteam2.team2", Labels: podLabelServiceS1}},
			pods: []*v1.Pod{
				{Spec: v1.PodSpec{NodeName: "machine1", Affinity: hardPodAffinity}},
				{Spec: v1.PodSpec{NodeName: "machine2", Affinity: hardPodAffinity}},
			},
			nodes: []*v1.Node{
				{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labelRgChina}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labelRgIndia}},
				{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labelAzAz1}},
			},
			hardPodAffinityWeight: v1.DefaultHardPodAffinitySymmetricWeight,
			expectedList:          []framework.NodeScore{{Name: "machine1", Score: framework.MaxNodeScore}, {Name: "machine2", Score: framework.MaxNodeScore}, {Name: "machine3", Score: 0}},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			ctx := context.Background()
			state := framework.NewCycleState()
			fts := feature.Features{EnablePodAffinityNamespaceSelector: !test.disableNSSelector}
			p := plugintesting.SetupPluginWithInformers(ctx, t, frameworkruntime.FactoryAdapter(fts, New), &config.InterPodAffinityArgs{HardPodAffinityWeight: test.hardPodAffinityWeight}, cache.NewSnapshot(test.pods, test.nodes), namespaces)
			status := p.(framework.PreScorePlugin).PreScore(ctx, state, test.pod, test.nodes)
			if !status.IsSuccess() {
				t.Errorf("unexpected error: %v", status)
			}
			var gotList framework.NodeScoreList
			for _, n := range test.nodes {
				nodeName := n.ObjectMeta.Name
				score, status := p.(framework.ScorePlugin).Score(ctx, state, test.pod, nodeName)
				if !status.IsSuccess() {
					t.Errorf("unexpected error: %v", status)
				}
				gotList = append(gotList, framework.NodeScore{Name: nodeName, Score: score})
			}

			status = p.(framework.ScorePlugin).ScoreExtensions().NormalizeScore(ctx, state, test.pod, gotList)
			if !status.IsSuccess() {
				t.Errorf("unexpected error: %v", status)
			}

			if !reflect.DeepEqual(test.expectedList, gotList) {
				t.Errorf("expected:\n\t%+v,\ngot:\n\t%+v", test.expectedList, gotList)
			}
		})
	}
}


text:
package pow.backend.action;

import pow.backend.GameBackend;
import pow.backend.MessageLog;
import pow.backend.SpellParams;
import pow.backend.actors.Actor;

import java.util.ArrayList;
import java.util.List;

public class SpellAction implements Action {

    private final Action action;
    private final SpellParams params;

    public SpellAction(Action action, SpellParams params) {
        this.action = action;
        this.params = params;
    }

    @Override
    public ActionResult process(GameBackend backend) {
        Actor actor = action.getActor();
        if (actor.getMana() < params.requiredMana) {
            backend.logMessage(actor.getNoun() + " doesn't have enough mana.",
                    MessageLog.MessageType.USER_ERROR);
            return ActionResult.failed();
        }

        // Use the mana, then requeue the actual spell action.
        actor.useMana(params.requiredMana);
        backend.logMessage(params.getCastMessage(actor), MessageLog.MessageType.COMBAT_NEUTRAL);

        List<Action> subactions = new ArrayList<>();
        subactions.add(action);
        subactions.add(new CompletedAction(actor));
        return ActionResult.failed(subactions);
    }

    @Override
    public boolean consumesEnergy() { return false; }

    @Override
    public Actor getActor() {
        return action.getActor();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import orderBy from 'lodash.orderby';
import { storiesOf } from '@storybook/react';
import { text, boolean, number } from '@storybook/addon-knobs';
import { Menu, Panel, SearchBox } from 'react-instantsearch-dom';
import { WrapWithHits } from './util';

const stories = storiesOf('Menu', module);

stories
  .add('default', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Menu attribute="brand" />
    </WrapWithHits>
  ))
  .add('with default selected item', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Menu attribute="brand" defaultRefinement="Apple" />
    </WrapWithHits>
  ))
  .add('with show more', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Menu attribute="brand" limit={2} showMoreLimit={5} showMore={true} />
    </WrapWithHits>
  ))
  .add('with search inside items', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Menu
        attribute="brand"
        searchable
        transformItems={(items) =>
          orderBy(
            items,
            ['isRefined', 'count', 'label'],
            ['desc', 'desc', 'asc']
          )
        }
      />
    </WrapWithHits>
  ))
  .add('with the sort strategy changed', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Menu
        attribute="brand"
        transformItems={(items) =>
          orderBy(items, ['label', 'count'], ['asc', 'desc'])
        }
      />
    </WrapWithHits>
  ))
  .add('with Panel', () => (
    <WrapWithHits hasPlayground={true} linkedStoryGroup="Menu.stories.js">
      <Panel header="Menu" footer="Footer">
        <Menu attribute="brand" />
      </Panel>
    </WrapWithHits>
  ))
  .add('with Panel but no refinement', () => (
    <WrapWithHits
      searchBox={false}
      hasPlayground={true}
      linkedStoryGroup="Menu.stories.js"
    >
      <Panel header="Menu" footer="Footer">
        <Menu attribute="brand" />
      </Panel>

      <div style={{ display: 'none' }}>
        <SearchBox defaultRefinement="dkjsakdjskajdksjakdjaskj" />
      </div>
    </WrapWithHits>
  ))
  .add('playground', () => (
    <WrapWithHits linkedStoryGroup="Menu.stories.js">
      <Menu
        attribute="brand"
        defaultRefinement={text('defaultSelectedItem', 'Apple')}
        limit={number('limit', 10)}
        showMoreLimit={number('showMoreLimit', 20)}
        showMore={boolean('showMore', true)}
      />
    </WrapWithHits>
  ));


text:
void MT4LIInitialize(const void* pText);
void MT4LIStart(HWND handle, const void* pSymbol, int period, int digits, double lotSize);
void StartA(HWND handle, const char* pSymbol, int period, int digits, double lotSize);
void StartW(HWND handle, const wchar_t* pSymbol, int period, int digits, double lotSize);
void MT4LIStop(HWND handle);


text:
@implementation CHTCollectionViewWaterfallCell

#pragma mark - Accessors
- (UILabel *)displayLabel {
	if (!_displayLabel) {
		_displayLabel = [[UILabel alloc] initWithFrame:self.contentView.bounds];
		_displayLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
		_displayLabel.backgroundColor = [UIColor lightGrayColor];
		_displayLabel.textColor = [UIColor whiteColor];
		_displayLabel.textAlignment = NSTextAlignmentCenter;
	}
	return _displayLabel;
}

- (void)setDisplayString:(NSString *)displayString {
	if (![_displayString isEqualToString:displayString]) {
		_displayString = [displayString copy];
		self.displayLabel.text = _displayString;
	}
}

#pragma mark - Life Cycle
- (void)dealloc {
	[_displayLabel removeFromSuperview];
	_displayLabel = nil;
}

- (id)initWithFrame:(CGRect)frame {
	if (self = [super initWithFrame:frame]) {
		[self.contentView addSubview:self.displayLabel];
	}
	return self;
}

@end


text:
package br.com.alinesolutions.marthalanches.rest;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityExistsException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;

import br.com.alinesolutions.marthalanches.model.Produto;
import br.com.alinesolutions.marthalanches.service.produto.ProdutoService;
import br.com.alinesolutions.marthalanches.util.ServiceFactory;

@Stateless
@Path("/produtos")
public class ProdutoEndpoint {

	private ProdutoService service;

	public ProdutoEndpoint() {
		service = ServiceFactory.getService(ProdutoService.class);
	}

	@POST
	@Consumes("application/json")
	public Response create(Produto entity) {
		try {
			Response build = null;
			try {
				service.persist(entity);
				build = Response.created(UriBuilder.fromResource(ProdutoEndpoint.class).path(String.valueOf(entity.getId())).build()).build();
			} catch (EntityExistsException e) {
				build = Response.status(Status.CONFLICT).build();
			}
			return build;
		} catch (Exception e) {
			throw e;
		}
	}

	@DELETE
	@Path("/{id:[0-9][0-9]*}")
	public Response deleteById(@PathParam("id") Long id) {
		Produto entity = service.find(id);
		if (entity == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		service.remove(entity);
		return Response.noContent().build();
	}

	@GET
	@Path("/{id:[0-9][0-9]*}")
	@Produces("application/json")
	public Response findById(@PathParam("id") Long id) {
		Produto entity = service.find(id);
		if (entity == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		return Response.ok(entity).build();
	}

	@GET
	@Produces("application/json")
	public List<Produto> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult) {
		final List<Produto> results = service.listAll(startPosition, maxResult);
		return results;
	}

	@PUT
	@Path("/{id:[0-9][0-9]*}")
	@Consumes("application/json")
	public Response update(@PathParam("id") Long id, Produto entity) {
		if (entity == null) {
			return Response.status(Status.BAD_REQUEST).build();
		}
		if (!id.equals(entity.getId())) {
			return Response.status(Status.CONFLICT).entity(entity).build();
		}
		if (service.find(id) == null) {
			return Response.status(Status.NOT_FOUND).build();
		}
		service.merge(entity);
		return Response.noContent().build();
	}
}


text:
package org.apache.geode.internal;

import java.io.DataOutputStream;
import java.io.OutputStream;

/**
 * An extension of {@link DataOutputStream} that implements {@link VersionedDataStream}.
 *
 * @since GemFire 7.1
 */
public class VersionedDataOutputStream extends DataOutputStream implements VersionedDataStream {

  private final Version version;

  /**
   * Creates a VersionedDataOutputStream that wraps the specified underlying OutputStream.
   *
   * @param out the underlying output stream
   * @param version the product version that serialized object on the given {@link OutputStream}
   */
  public VersionedDataOutputStream(OutputStream out, Version version) {
    super(out);
    this.version = version;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Version getVersion() {
    return this.version;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.Entities;
using OrchardCore.OpenId.Models;
using OrchardCore.OpenId.Settings;
using OrchardCore.Settings;

namespace OrchardCore.OpenId.Services
{
    public class OpenIdService : IOpenIdService
    {
        private readonly ISiteService _siteService;
        private readonly IStringLocalizer<OpenIdService> T;

        public OpenIdService(ISiteService siteService, IStringLocalizer<OpenIdService> stringLocalizer)
        {
            _siteService = siteService;
            T = stringLocalizer;
        }

        public async Task<OpenIdSettings> GetOpenIdSettingsAsync()
        {
            var settings = await _siteService.GetSiteSettingsAsync();

            var result = settings.As<OpenIdSettings>();
            if (result == null)
            {
                result = new OpenIdSettings();
            }

            return result;
        }

        public async Task UpdateOpenIdSettingsAsync(OpenIdSettings openIdSettings)
        {
            var settings = await _siteService.GetSiteSettingsAsync();
            settings.Properties[nameof(OpenIdSettings)] = JObject.FromObject(openIdSettings);
            await _siteService.UpdateSiteSettingsAsync(settings);
        }

        public bool IsValidOpenIdSettings(OpenIdSettings settings, ModelStateDictionary modelState)
        {
            if (settings == null)
            {
                modelState.AddModelError("", T["Settings are not stablished."]);
                return false;
            }

            if (!settings.AllowAuthorizationCodeFlow && !settings.AllowClientCredentialsFlow
                && !settings.AllowHybridFlow && !settings.AllowImplicitFlow && !settings.AllowPasswordFlow)
            {
                modelState.AddModelError("", T["At least one OpenID Connect flow must be enabled."]);
                return false;
            }

            ValidateUrisSchema(new string[] { settings.Authority }, !settings.TestingModeEnabled, modelState, "Authority");
            ValidateUrisSchema(settings.Audiences, !settings.TestingModeEnabled, modelState, "Audience");

            if (!settings.TestingModeEnabled)
            {
                if (settings.CertificateStoreName == null)
                {
                    modelState.AddModelError("CertificateStoreName", T["A Certificate Store Name is required."]);
                }
                if (settings.CertificateStoreLocation == null)
                {
                    modelState.AddModelError("CertificateStoreLocation", T["A Certificate Store Location is required."]);
                }
                if (string.IsNullOrWhiteSpace(settings.CertificateThumbPrint))
                {
                    modelState.AddModelError("CertificateThumbPrint", T["A certificate is required when testing mode is disabled."]);
                }
                if (!modelState.IsValid)
                    return false;

                var certificate = GetCertificate(settings.CertificateStoreLocation.Value, settings.CertificateStoreName.Value, settings.CertificateThumbPrint);
                if (certificate == null)
                {
                    modelState.AddModelError("CertificateThumbPrint", T["The certificate cannot be found."]);
                    return false;
                }
                if (!certificate.HasPrivateKey)
                {
                    modelState.AddModelError("CertificateThumbPrint", T["The certificate doesn't contain the required private key."]);
                    return false;
                }
                if (certificate.Archived)
                {
                    modelState.AddModelError("CertificateThumbPrint", T["The certificate is not valid because it is marked as archived."]);
                    return false;
                }
                var now = DateTime.Now;
                if (certificate.NotBefore > now || certificate.NotAfter < now)
                {
                    modelState.AddModelError("CertificateThumbPrint", T["The certificate is not valid for current date."]);
                    return false;
                }
            }

            if (settings.AllowPasswordFlow && !settings.EnableTokenEndpoint)
            {
                modelState.AddModelError("AllowPasswordFlow", T["Password Flow cannot be enabled if Token Endpoint is disabled"]);
                return false;
            }
            if (settings.AllowClientCredentialsFlow && !settings.EnableTokenEndpoint)
            {
                modelState.AddModelError("AllowClientCredentialsFlow", T["Client Credentials Flow cannot be enabled if Token Endpoint is disabled"]);
                return false;
            }
            if (settings.AllowAuthorizationCodeFlow && (!settings.EnableAuthorizationEndpoint || !settings.EnableTokenEndpoint))
            {
                modelState.AddModelError("AllowAuthorizationCodeFlow", T["Authorization Code Flow cannot be enabled if Authorization Endpoint and Token Endpoint are disabled"]);
                return false;
            }
            if (settings.AllowHybridFlow && (!settings.EnableAuthorizationEndpoint || !settings.EnableTokenEndpoint))
            {
                modelState.AddModelError("AllowAuthorizationHybridFlow", T["Authorization Hybrid cannot be enabled if Authorization Endpoint and Token Endpoint are disabled"]);
                return false;
            }
            if (settings.AllowRefreshTokenFlow)
            {
                if (!settings.EnableTokenEndpoint)
                {
                    modelState.AddModelError("AllowRefreshTokenFlow", T["Refresh Token Flow cannot be enabled if Token Endpoint is disabled"]);
                    return false;
                }
                if (!settings.AllowPasswordFlow && !settings.AllowAuthorizationCodeFlow && !settings.AllowHybridFlow)
                {
                    modelState.AddModelError("AllowRefreshTokenFlow", T["Refresh Token Flow only can be enabled if Password Flow, Authorization Code Flow or Hybrid Flow are enabled"]);
                    return false;
                }
            }
            if (settings.AllowImplicitFlow && !settings.EnableAuthorizationEndpoint)
            {
                modelState.AddModelError("AllowImplicitFlow", T["Allow Implicit Flow cannot be enabled if Authorization Endpoint is disabled"]);
                return false;
            }
            return modelState.IsValid;
        }

        private void ValidateUrisSchema(IEnumerable<string> uriStrings, bool onlyAllowHttps, ModelStateDictionary modelState, string modelStateKey)
        {
            if (uriStrings == null)
            {
                modelState.AddModelError(modelStateKey, T["Invalid url."]);
                return;
            }
            foreach (var uriString in uriStrings.Select(a => (a ?? "").Trim()))
            {
                Uri uri;
                if (!Uri.TryCreate(uriString, UriKind.Absolute, out uri) || ((onlyAllowHttps || uri.Scheme != "http") && uri.Scheme != "https"))
                {
                    var message = onlyAllowHttps ? T["Invalid url. Non https urls are only allowed in testing mode."] : T["Invalid url."];
                    modelState.AddModelError(modelStateKey, T[message]);
                }
            }
        }

        public bool IsValidOpenIdSettings(OpenIdSettings settings)
        {
            var modelState = new ModelStateDictionary();
            return IsValidOpenIdSettings(settings, modelState);
        }

        public IEnumerable<CertificateInfo> GetAvailableCertificates(bool onlyCertsWithPrivateKey)
        {
            foreach (StoreLocation storeLocation in Enum.GetValues(typeof(StoreLocation)))
            {
                foreach (StoreName storeName in Enum.GetValues(typeof(StoreName)))
                {
                    using (X509Store x509Store = new X509Store(storeName, storeLocation))
                    {
                        yield return new CertificateInfo()
                        {
                            StoreLocation = storeLocation,
                            StoreName = storeName
                        };

                        x509Store.Open(OpenFlags.ReadOnly);

                        X509Certificate2Collection col = x509Store.Certificates;
                        foreach (var cert in col)
                        {
                            if (!cert.Archived && (!onlyCertsWithPrivateKey || (onlyCertsWithPrivateKey && cert.HasPrivateKey)))
                            {
                                yield return new CertificateInfo()
                                {
                                    StoreLocation = storeLocation,
                                    StoreName = storeName,
                                    FriendlyName = cert.FriendlyName,
                                    Issuer = cert.Issuer,
                                    Subject = cert.Subject,
                                    NotBefore = cert.NotBefore,
                                    NotAfter = cert.NotAfter,
                                    ThumbPrint = cert.Thumbprint,
                                    HasPrivateKey = cert.HasPrivateKey,
                                    Archived = cert.Archived
                                };
                            }
                        }
                    }
                }
            }
        }

        public CertificateInfo GetCertificate(StoreLocation storeLocation, StoreName storeName, string certThumbprint)
        {
            using (X509Store x509Store = new X509Store(storeName, storeLocation))
            {
                x509Store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection col = x509Store.Certificates;
                foreach (var cert in col)
                {
                    if (cert.Thumbprint == certThumbprint)
                    {
                        return new CertificateInfo()
                        {
                            StoreLocation = storeLocation,
                            StoreName = storeName,
                            FriendlyName = cert.FriendlyName,
                            Issuer = cert.Issuer,
                            Subject = cert.Subject,
                            NotBefore = cert.NotBefore,
                            NotAfter = cert.NotAfter,
                            ThumbPrint = cert.Thumbprint,
                            HasPrivateKey = cert.HasPrivateKey,
                            Archived = cert.Archived
                        };
                    }
                }
            }
            return null;
        }
    }
}


text:
package com.dailystudio.system;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.dailystudio.development.Logger;

class ExecOutputASyncTask extends ExecIOASyncTask {

	private InputStream mInputStream;

	private boolean mIgnoreEmptyLines;

	private List<String> mOutputs = new ArrayList<>();

	public ExecOutputASyncTask(String tag, InputStream input) {
		super(tag);

		mInputStream = input;

		mIgnoreEmptyLines = false;
	}

	public void setIgnoreEmptyLines(boolean ignore) {
		mIgnoreEmptyLines = ignore;
	}

	void printOutput() {
		Logger.debug("mInputStream = %s", mInputStream);
		final InputStream input = mInputStream;
		if (input == null) {
			return;
		}

		final InputStreamReader reader = new InputStreamReader(input);
		final BufferedReader lineReader = new BufferedReader(reader);

		String line = null;
		try {
			while ((line = lineReader.readLine()) != null) {
				if (mEndFlag) {
					break;
				}

				if (mIgnoreEmptyLines && line.length() <= 0) {
					continue;
				}

				Logger.info("%s: [%s]", mTag, line);

				mOutputs.add(line);
			}

			lineReader.close();
		} catch (IOException e) {
			Logger.warn("[%s]: read from output failed, %s", e.toString());
		}
	}

	@Override
	protected Void doInBackground(Void... params) {
		printOutput();
		return null;
	}

	@Override
	public void stop() {
//		printOutput();
		super.stop();
	}

	public String[] getOutputs() {
		return mOutputs.toArray(new String[0]);
	}

}


text:
package org.apache.tajo.catalog.exception;

public class CatalogException extends RuntimeException {
  private static final long serialVersionUID = -26362412527118618L;

  /**
   *
   */
  public CatalogException() {
  }

  /**
   * @param message
   */
  public CatalogException(String message) {
    super(message);
  }

  /**
   * @param cause
   */
  public CatalogException(Throwable cause) {
    super(cause);
  }

  /**
   * @param message
   * @param cause
   */
  public CatalogException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
#ifndef DT_Calculator_Ramp_h
#define DT_Calculator_Ramp_h

/** @file   DT_Calculator_Ramp.h
  *   @author pmaginot
  *   @brief provide a interfaces for calculating \f$ \Delta t \f$ during time marching.  Right now only incorporates the need to
  * start with small time steps.  Could be changed/expanded to allow for adaptivity....
 */
#include "V_DT_Calculator.h"
class DT_Calculator_Ramp : public V_DT_Calculator
{
public:
  DT_Calculator_Ramp(const Input_Reader& input_reader);

  virtual ~DT_Calculator_Ramp(){}

  double calculate_dt(const int step, const double dt_old, const double adapt_criteria) override;

protected:
  const int m_n_ramp_steps;
  const double m_slope;
};

#endif


text:
opal_filter "Thread" do
  fails "StandardError is a superclass of ThreadError"
  fails "The throw keyword raises an ArgumentError if used to exit a thread"
  fails "The throw keyword clears the current exception"
  fails "Module#autoload loads the registered constant even if the constant was already loaded by another thread"
  fails "The return keyword in a Thread raises a LocalJumpError if used to exit a thread"
end


text:
package landmaster.plustic.traits;

import net.minecraft.entity.*;
import net.minecraft.item.*;
import slimeknights.tconstruct.library.traits.*;

public class Barrett extends AbstractTrait {
	public static final Barrett barrett = new Barrett();

	public Barrett() {
		super("barrett", 0x0000FF);
	}

	@Override
	public boolean isCriticalHit(ItemStack tool, EntityLivingBase player, EntityLivingBase target) {
		return random.nextFloat() < (player.getMaxHealth() - player.getHealth()) / (player.getMaxHealth() * 0.7f);
	}
}


text:
package cmd

import (
	"errors"
	"fmt"

	"github.com/garthk/nag/naglib"
	"github.com/garthk/nag/pkg/safe-colortext"
	"github.com/spf13/cobra"
)

var runCmd = &cobra.Command{
	Use:   "run",
	Short: "Run a Nagios plugin or other executable",
	Long: `
Run a Nagios plugin or other executable, constraining its output and exit
status for compatibility.

Use the -- option to end option parsing so you can give executables options.
`,
	Example: `  nag run /usr/lib/nagios/plugins/check_http http://localhost:8001
  nag run -WUX -- test -d /var/log/apache2`,
	DisableAutoGenTag: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		treatment, err := checkExitStatusFlags(cmd)
		if err != nil {
			return err
		}

		cfg, err := naglib.ParseConfig(nrpeCfgFile)
		if err != nil {
			return err
		}

		context := naglib.PluginContext{
			NagiosConfig:        cfg,
			ExitStatusTreatment: treatment,
		}

		if len(args) == 0 {
			return errors.New("nag run: executable required")
		} else {
			cmd.SilenceUsage = true
			result, err := naglib.RunPlugin(&context, args[0], args[1:]...)
			return processPluginResult(context, result, err)
		}
	},
}

func processPluginResult(context naglib.PluginContext, result naglib.PluginResult, err error) error {
	for _, msg := range context.Messages {
		printStatusLine(msg.Severity, msg.Message)
	}
	if err == nil {
		printStatusLine(result.Status, result.Output)
	}
	return err
}

func printStatusLine(status naglib.PluginStatus, msg string) {
	fmt.Printf("[")
	sc.Foreground(status.Color(), false)
	fmt.Printf("%s", status)
	sc.ResetColor()
	fmt.Printf("] %s\n", msg)
}

func init() {
	RootCmd.AddCommand(runCmd)
	addExitStatusFlags(runCmd)
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.pieShare.pieTools.piePlate.service.channel.exception;

/**
 *
 * @author sveto_000
 */
public class PieChannelException extends Exception {

	public PieChannelException(String msg, Throwable ex) {
		super(msg, ex);
	}

	public PieChannelException(Throwable ex) {
		super(ex);
	}
}


text:
require 'pg'
require 'pg/pglogical'
require 'pg/pglogical/active_record_extension'

class MiqPglogical
  include Vmdb::Logging

  REPLICATION_SET_NAME = 'miq'.freeze
  NODE_PREFIX = "region_".freeze
  ALWAYS_EXCLUDED_TABLES = %w(ar_internal_metadata schema_migrations repl_events repl_monitor repl_nodes).freeze

  attr_reader :configured_excludes

  def initialize
    @connection = ApplicationRecord.connection
    self.configured_excludes = provider? ? active_excludes : self.class.default_excludes
  end

  # Sets the tables that should be used to create the replication set using refresh_excludes
  def configured_excludes=(new_excludes)
    @configured_excludes = new_excludes | ALWAYS_EXCLUDED_TABLES
  end

  # Returns the excluded tables that are currently being used by pglogical
  # @return Array<String> the table list
  def active_excludes
    return [] unless provider?
    @connection.tables - included_tables
  end

  # Returns whether or not this server is configured as a provider node
  # @return Boolean
  def provider?
    pglogical.enabled? && pglogical.replication_sets.include?(REPLICATION_SET_NAME)
  end

  # Returns whether or not this server is configured as a subscriber node
  # @return Boolean
  def subscriber?
    pglogical.enabled? && !pglogical.subscriptions.empty?
  end

  # Returns whether or not this server is a pglogical node
  def node?
    pglogical.enabled? && pglogical.nodes.field_values("name").include?(self.class.local_node_name)
  end

  # Creates a pglogical node using the rails connection
  def create_node
    pglogical.node_create(self.class.local_node_name, connection_dsn)
  end

  # Drops the pglogical node associated with this connection
  def drop_node
    pglogical.node_drop(self.class.local_node_name, true)
  end

  # Configures the database as a pglogical replication source
  #   This includes enabling the extension, creating the
  #   node and creating the replication set
  def configure_provider
    return if provider?
    @connection.transaction(:requires_new => true) do
      pglogical.enable
      create_node unless node?
      create_replication_set
    end
  end

  # Removes the replication configuration and pglogical node from the
  # database
  def destroy_provider
    return unless provider?
    pglogical.replication_set_drop(REPLICATION_SET_NAME)
    drop_node
    pglogical.disable
  end

  # Lists the tables currently being replicated by pglogical
  # @return Array<String> the table list
  def included_tables
    pglogical.tables_in_replication_set(REPLICATION_SET_NAME)
  end

  # Creates the 'miq' replication set and refreshes the excluded tables
  def create_replication_set
    pglogical.replication_set_create(REPLICATION_SET_NAME)
    refresh_excludes
  end

  def self.refresh_excludes_queue(new_excludes)
    MiqQueue.put(
      :class_name  => "MiqPglogical",
      :method_name => "refresh_excludes",
      :args        => [new_excludes]
    )
  end

  def self.refresh_excludes(new_excludes)
    pgl = new
    pgl.configured_excludes = new_excludes
    pgl.refresh_excludes
  end

  # Aligns the contents of the 'miq' replication set with the currently configured vmdb excludes
  def refresh_excludes
    pglogical.with_replication_set_lock(REPLICATION_SET_NAME) do
      # remove newly excluded tables from replication set
      newly_excluded_tables.each do |table|
        _log.info("Removing #{table} from #{REPLICATION_SET_NAME} replication set")
        pglogical.replication_set_remove_table(REPLICATION_SET_NAME, table)
      end

      # add tables to the set which are no longer excluded (or new)
      newly_included_tables.each do |table|
        _log.info("Adding #{table} to #{REPLICATION_SET_NAME} replication set")
        pglogical.replication_set_add_table(REPLICATION_SET_NAME, table, true)
      end
    end
  end

  def replication_lag
    pglogical.lag_bytes
  end

  def replication_wal_retained
    pglogical.wal_retained_bytes
  end

  def self.local_node_name
    region_to_node_name(MiqRegion.my_region_number)
  end

  def self.region_to_node_name(region_id)
    "#{NODE_PREFIX}#{region_id}"
  end

  def self.node_name_to_region(name)
    name.sub(NODE_PREFIX, "").to_i
  end

  def self.default_excludes
    YAML.load_file(Rails.root.join("config/default_replication_exclude_tables.yml"))[:exclude_tables] | ALWAYS_EXCLUDED_TABLES
  end

  private

  def pglogical(refresh = false)
    @pglogical = nil if refresh
    @pglogical ||= @connection.pglogical
  end

  def connection_dsn
    config = @connection.raw_connection.conninfo_hash.delete_blanks
    PG::Connection.parse_connect_args(config)
  end

  # tables that are currently included, but we want them excluded
  def newly_excluded_tables
    included_tables & configured_excludes
  end

  # tables that are currently excluded, but we want them included
  def newly_included_tables
    (@connection.tables - configured_excludes) - included_tables
  end
end


text:
/***************************************************************************

    Konami 005289 - SCC sound as used in Bubblesystem

    This file is pieced together by Bryan McPhail from a combination of
    Namco Sound, Amuse by Cab, Nemesis schematics and whoever first
    figured out SCC!

    The 005289 is a 2 channel sound generator, each channel gets it's
    waveform from a prom (4 bits wide).

    (From Nemesis schematics)

    Address lines A0-A4 of the prom run to the 005289, giving 32 bytes
    per waveform.  Address lines A5-A7 of the prom run to PA5-PA7 of
    the AY8910 control port A, giving 8 different waveforms. PA0-PA3
    of the AY8910 control volume.

    The second channel is the same as above except port B is used.

    The 005289 has no data bus, so data values written don't matter.

    There are 4 unknown pins, LD1, LD2, TG1, TG2.  Two of them look to be
    the selector for changing frequency.  The other two seem unused.

***************************************************************************/

#include "emu.h"
#include "k005289.h"

#define FREQBASEBITS	16

/* this structure defines the parameters for a channel */
typedef struct
{
	int frequency;
	int counter;
	int volume;
	const unsigned char *wave;
} k005289_sound_channel;

typedef struct _k005289_state k005289_state;
struct _k005289_state
{
	k005289_sound_channel channel_list[2];

	/* global sound parameters */
	const unsigned char *sound_prom;
	sound_stream * stream;
	int mclock,rate;

	/* mixer tables and internal buffers */
	INT16 *mixer_table;
	INT16 *mixer_lookup;
	short *mixer_buffer;

	int k005289_A_frequency,k005289_B_frequency;
	int k005289_A_volume,k005289_B_volume;
	int k005289_A_waveform,k005289_B_waveform;
	int k005289_A_latch,k005289_B_latch;
};

INLINE k005289_state *get_safe_token(device_t *device)
{
	assert(device != NULL);
	assert(device->type() == K005289);
	return (k005289_state *)downcast<legacy_device_base *>(device)->token();
}

/* build a table to divide by the number of voices */
static void make_mixer_table(running_machine &machine, k005289_state *info, int voices)
{
	int count = voices * 128;
	int i;
	int gain = 16;

	/* allocate memory */
	info->mixer_table = auto_alloc_array(machine, INT16, 256 * voices);

	/* find the middle of the table */
	info->mixer_lookup = info->mixer_table + (128 * voices);

	/* fill in the table - 16 bit case */
	for (i = 0; i < count; i++)
	{
		int val = i * gain * 16 / voices;
		if (val > 32767) val = 32767;
		info->mixer_lookup[ i] = val;
		info->mixer_lookup[-i] = -val;
	}
}

/* generate sound to the mix buffer */
static STREAM_UPDATE( K005289_update )
{
	k005289_state *info = (k005289_state *)param;
	k005289_sound_channel *voice=info->channel_list;
	stream_sample_t *buffer = outputs[0];
	short *mix;
	int i,v,f;

	/* zap the contents of the mixer buffer */
	memset(info->mixer_buffer, 0, samples * sizeof(INT16));

	v=voice[0].volume;
	f=voice[0].frequency;
	if (v && f)
	{
		const unsigned char *w = voice[0].wave;
		int c = voice[0].counter;

		mix = info->mixer_buffer;

		/* add our contribution */
		for (i = 0; i < samples; i++)
		{
			int offs;

			c+=(long)((((float)info->mclock / (float)(f * 16))*(float)(1<<FREQBASEBITS)) / (float)(info->rate / 32));
			offs = (c >> 16) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		voice[0].counter = c;
	}

	v=voice[1].volume;
	f=voice[1].frequency;
	if (v && f)
	{
		const unsigned char *w = voice[1].wave;
		int c = voice[1].counter;

		mix = info->mixer_buffer;

		/* add our contribution */
		for (i = 0; i < samples; i++)
		{
			int offs;

			c+=(long)((((float)info->mclock / (float)(f * 16))*(float)(1<<FREQBASEBITS)) / (float)(info->rate / 32));
			offs = (c >> 16) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		voice[1].counter = c;
	}

	/* mix it down */
	mix = info->mixer_buffer;
	for (i = 0; i < samples; i++)
		*buffer++ = info->mixer_lookup[*mix++];
}

static DEVICE_START( k005289 )
{
	k005289_sound_channel *voice;
	k005289_state *info = get_safe_token(device);

	voice = info->channel_list;

	/* get stream channels */
	info->rate = device->clock()/16;
	info->stream = device->machine().sound().stream_alloc(*device, 0, 1, info->rate, info, K005289_update);
	info->mclock = device->clock();

	/* allocate a pair of buffers to mix into - 1 second's worth should be more than enough */
	info->mixer_buffer = auto_alloc_array(device->machine(), short, 2 * info->rate);

	/* build the mixer table */
	make_mixer_table(device->machine(), info, 2);

	info->sound_prom = *device->region();

	/* reset all the voices */
	voice[0].frequency = 0;
	voice[0].volume = 0;
	voice[0].wave = &info->sound_prom[0];
	voice[0].counter = 0;
	voice[1].frequency = 0;
	voice[1].volume = 0;
	voice[1].wave = &info->sound_prom[0x100];
	voice[1].counter = 0;
}

/********************************************************************************/

static void k005289_recompute(k005289_state *info)
{
	k005289_sound_channel *voice = info->channel_list;

	info->stream->update();	/* update the streams */

	voice[0].frequency = info->k005289_A_frequency;
	voice[1].frequency = info->k005289_B_frequency;
	voice[0].volume = info->k005289_A_volume;
	voice[1].volume = info->k005289_B_volume;
	voice[0].wave = &info->sound_prom[32 * info->k005289_A_waveform];
	voice[1].wave = &info->sound_prom[32 * info->k005289_B_waveform + 0x100];
}

WRITE8_DEVICE_HANDLER( k005289_control_A_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_A_volume=data&0xf;
	info->k005289_A_waveform=data>>5;
	k005289_recompute(info);
}

WRITE8_DEVICE_HANDLER( k005289_control_B_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_B_volume=data&0xf;
	info->k005289_B_waveform=data>>5;
	k005289_recompute(info);
}

WRITE8_DEVICE_HANDLER( k005289_pitch_A_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_A_latch = 0x1000 - offset;
}

WRITE8_DEVICE_HANDLER( k005289_pitch_B_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_B_latch = 0x1000 - offset;
}

WRITE8_DEVICE_HANDLER( k005289_keylatch_A_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_A_frequency = info->k005289_A_latch;
	k005289_recompute(info);
}

WRITE8_DEVICE_HANDLER( k005289_keylatch_B_w )
{
	k005289_state *info = get_safe_token(device);
	info->k005289_B_frequency = info->k005289_B_latch;
	k005289_recompute(info);
}

/**************************************************************************
 * Generic get_info
 **************************************************************************/

DEVICE_GET_INFO( k005289 )
{
	switch (state)
	{
		/* --- the following bits of info are returned as 64-bit signed integers --- */
		case DEVINFO_INT_TOKEN_BYTES:					info->i = sizeof(k005289_state);				break;

		/* --- the following bits of info are returned as pointers to data or functions --- */
		case DEVINFO_FCT_START:							info->start = DEVICE_START_NAME( k005289 );		break;
		case DEVINFO_FCT_STOP:							/* nothing */									break;
		case DEVINFO_FCT_RESET:							/* nothing */									break;

		/* --- the following bits of info are returned as NULL-terminated strings --- */
		case DEVINFO_STR_NAME:							strcpy(info->s, "K005289");						break;
		case DEVINFO_STR_FAMILY:					strcpy(info->s, "Konami custom");				break;
		case DEVINFO_STR_VERSION:					strcpy(info->s, "1.0");							break;
		case DEVINFO_STR_SOURCE_FILE:						strcpy(info->s, __FILE__);						break;
		case DEVINFO_STR_CREDITS:					strcpy(info->s, "Copyright Nicola Salmoria and the MAME Team"); break;
	}
}

DEFINE_LEGACY_SOUND_DEVICE(K005289, k005289);


text:
'use strict';

module.exports = {
  vendor : [
    'bower_components/angular-material/angular-material.min.css',
    'bower_components/components-font-awesome/css/font-awesome.min.css'
  ]
};


text:
MongoDB\BSON\MinKey comparisons
--FILE--
<?php

var_dump(new MongoDB\BSON\MinKey == new MongoDB\BSON\MinKey);
var_dump(new MongoDB\BSON\MinKey < new MongoDB\BSON\MinKey);
var_dump(new MongoDB\BSON\MinKey > new MongoDB\BSON\MinKey);

?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
bool(true)
bool(false)
bool(false)
===DONE===


text:
import { FunctionComponent } from 'react';
import { useAsyncFn, useEffectOnce } from 'react-use';

import { LoadingSpinner } from '@waldur/core/LoadingSpinner';
import { loadCategories } from '@waldur/dashboard/api';
import { translate } from '@waldur/i18n';
import { WorkspaceType } from '@waldur/workspace/types';

import { CategoryResources } from './CategoryResources';
import { Scope } from './types';

interface CategoryResourcesListProps<ScopeType = Scope> {
  scope: ScopeType;
  scopeType: WorkspaceType;
}

const LoadingErred = ({ loadData }) => (

{translate('Unable to load charts.')}

    <button onClick={loadData} type="button" className="btn btn-default">
       {translate('Reload')}
    </button>

);

export const CategoryResourcesList: FunctionComponent<CategoryResourcesListProps> = (
  props,
) => {
  const [{ loading, error, value }, callback] = useAsyncFn(
    () => loadCategories(props.scopeType, props.scope),
    [props.scope],
  );
  useEffectOnce(() => {
    callback();
  });

  if (loading) {
    return <LoadingSpinner />;
  }
  if (error) {
    return <LoadingErred loadData={callback} />;
  }
  return (
    <>
      {Array.isArray(value)
        ? value.map((category, index) => (
            <CategoryResources key={index} category={category} />
          ))
        : null}
    </>
  );
};


text:
package com.codingbrothers.futurimages.apiv1;

public class ImageSummary implements Response {

	private String id;
	private String createdAt;
	private String name;
	private String description;
	private boolean isPublic = true;
	private User owner;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCreatedAt() {
		return createdAt;
	}

	public void setCreatedAt(String createdAt) {
		this.createdAt = createdAt;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public boolean isPublic() {
		return isPublic;
	}

	public void setPublic(boolean isPublic) {
		this.isPublic = isPublic;
	}

	public User getOwner() {
		return owner;
	}

	public void setOwner(User owner) {
		this.owner = owner;
	}
}


text:
import sys

from twisted.internet import defer, protocol
from twisted.protocols.policies import TimeoutMixin
from zope.interface.verify import verifyObject
import six

from txHL7.receiver import IHL7Receiver

class MinimalLowerLayerProtocol(protocol.Protocol, TimeoutMixin):
    """
    Minimal Lower-Layer Protocol (MLLP) takes the form:

        <VT>[HL7 Message]<FS><CR>

    References:

    .. [1] http://www.hl7standards.com/blog/2007/05/02/hl7-mlp-minimum-layer-protocol-defined/
    .. [2] http://www.hl7standards.com/blog/2007/02/01/ack-message-original-mode-acknowledgement/
    """

    _buffer = b''
    start_block = b'\x0b'  # <VT>, vertical tab
    end_block = b'\x1c'  # <FS>, file separator
    carriage_return = b'\x0d'  # <CR>, \r

    def connectionMade(self):
        if self.factory.timeout is not None:
            self.setTimeout(self.factory.timeout)

    def dataReceived(self, data):
        self.resetTimeout()

        # success callback
        def onSuccess(message):
            self.writeMessage(message)

        # try to find a complete message(s) in the combined the buffer and data
        messages = (self._buffer + data).split(self.end_block)
        # whatever is in the last chunk is an uncompleted message, so put back
        # into the buffer
        self._buffer = messages.pop(-1)

        for raw_message in messages:
            # strip the rest of the MLLP shell from the HL7 message
            raw_message = raw_message.strip(self.start_block)

            # only pass messages with data
            if len(raw_message) > 0:
                # convert into unicode, parseMessage expects decoded string
                raw_message = self.factory.decode(raw_message)

                message_container = self.factory.parseMessage(raw_message)

                # error callback (defined here, since error depends on
                # current message).  rejects the message
                def onError(err):
                    reject = message_container.err(err)
                    self.writeMessage(reject)
                    return err

                # have the factory create a deferred and pass the message
                # to the approriate IHL7Receiver instance
                d = self.factory.handleMessage(message_container)
                d.addCallback(onSuccess)
                d.addErrback(onError)

    def writeMessage(self, message):
        if message is None:
            return
        # convert back to a byte string
        message = self.factory.encode(message)
        # wrap message in payload container
        self.transport.write(
            self.start_block + message + self.end_block + self.carriage_return
        )

class MLLPFactory(protocol.ServerFactory):
    protocol = MinimalLowerLayerProtocol

    def __init__(self, receiver):
        verifyObject(IHL7Receiver, receiver)
        self.receiver = receiver
        encoding = receiver.getCodec()
        if isinstance(encoding, tuple):
            encoding, encoding_errors = encoding
        else:
            encoding_errors = None
        self.encoding = encoding or sys.getdefaultencoding()
        self.encoding_errors = encoding_errors or 'strict'
        self.timeout = receiver.getTimeout()

    def parseMessage(self, message_str):
        return self.receiver.parseMessage(message_str)

    def handleMessage(self, message_container):
        # IHL7Receiver allows implementations to return a Deferred or the
        # result, so ensure we return a Deferred here
        return defer.maybeDeferred(self.receiver.handleMessage, message_container)

    def decode(self, value):
        # turn value into unicode using the receiver's declared codec
        if isinstance(value, six.binary_type):
            return value.decode(self.encoding, self.encoding_errors)
        return six.text_type(value)

    def encode(self, value):
        # turn value into byte string using the receiver's declared codec
        if isinstance(value, six.text_type):
            return value.encode(self.encoding, self.encoding_errors)
        return value


text:
"""Project wide templatetags."""
from django import template

register = template.Library()

@register.simple_tag
def navactive(request, url, exact=0):
    """
    Returns ``active`` if the given URL is in the url path, otherwise ''.

    Use it in your templates like so::

        {% load project_tags %}
        Home

    :param request: A request instance.
    :param url: A string representing a part of the URL that needs to exist
      in order for this method to return ``True``.
    :param exact: If ``1`` then the parameter ``url`` must be equal to
      ``request.path``, otherwise the parameter ``url`` can just be a part of
      ``request.path``.

    """
    if exact:
        if url == request.path:
            return 'active'
        return ''

    if url == '/':
        if request.path == '/':
            return 'active'
        return ''

    if url in request.path:
        return 'active'
    return ''


text:
import unittest
import os
import tempfile

from ptwit import TwitterConfig

class TestTwitterConfig(unittest.TestCase):
    def setUp(self):
        _, self.filename = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.filename)

    def test_open(self):
        filename = tempfile.mktemp()
        # Create if config file does not exist
        config = TwitterConfig(filename)
        self.assertFalse(os.path.isfile(filename))
        # If the path is a directory?
        dirname = tempfile.mkdtemp()
        config = TwitterConfig(dirname)
        self.assertRaises(IOError, config.save)
        os.removedirs(dirname)

    def test_set(self):
        config = TwitterConfig(self.filename)
        config.set("option", "value")  # Save hello=world to general section
        config.set("name", "tao", account="Tao")
        config.set("name", "mian", account="Mian")
        self.assertEqual(config.config.items("general"), [("option", "value")])
        self.assertEqual(config.config.items("Tao"), [("name", "tao")])
        self.assertEqual(config.config.items("Mian"), [("name", "mian")])

    def test_get(self):
        config = TwitterConfig(self.filename)
        config.set("option", "value")
        config.set("format", "json", account="Tao")
        self.assertEqual(config.get("option"), "value")
        self.assertEqual(config.get("format", account="Tao"), "json")

    def test_unset(self):
        config = TwitterConfig(self.filename)
        config.set("option", "value")
        config.set("format", "json", account="Tao")
        config.unset("format", account="Tao")
        config.unset("option")
        self.assertIsNone(config.get("format", account="Tao"))
        self.assertIsNone(config.get("option"))

    def test_remove_account(self):
        config = TwitterConfig(self.filename)
        config.set("option", "value", account="Tao")
        config.remove_account("Tao")

    def test_list_account(self):
        config = TwitterConfig(self.filename)
        self.assertEqual(config.list_accounts(), [])
        config.set("option", "value")
        config.set("option", "value", account="Tao")
        self.assertEqual(config.list_accounts(), ["Tao"])

    def test_save(self):
        config = TwitterConfig(self.filename)
        config.set("option", "value")
        config.set("name", "Tao", account="Tao")
        config.save()
        with open(self.filename) as fp:
            content = fp.read()
        self.assertTrue(content.find("general"))
        self.assertTrue(content.find("Tao"))
        self.assertTrue(content.find("name"))

if __name__ == "__main__":
    unittest.main()


text:
package cn.gavinliu.bus.station.widget;

import android.support.v7.widget.RecyclerView;

import java.util.List;

/**
 * Created by gavin on 2017/2/20.
 */

public abstract class BaseAdapter<E, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {

    private List<E> mData;

    public void setData(List<E> data) {
        mData = data;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

    public E getItem(int position) {
        return mData.get(position);
    }

}


text:
import d1_test.d1_test_case

class TestDataONEBaseclientV2(d1_test.d1_test_case.D1TestCase):
    pass


text:
var Image = require('../../schemas/imageSchema');
var User = require('../../schemas/userSchema');

module.exports = function (request, reply) {
  var userID = request.params.userID;

  User.findOne({
    userID: userID
  })
    .populate({
      path: 'images',
      select: 'name -_id'
    })
    .exec(function (err, user) {
      if (err) {
        throw err;
      }
      reply(user.images);
    });
}