text:
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/docker/docker/pkg/integration/checker"
	icmd "github.com/docker/docker/pkg/integration/cmd"
	"github.com/docker/docker/pkg/stringid"
	"github.com/go-check/check"
)

func (s *DockerSuite) TestPsListContainersBase(c *check.C) {
	out, _ := runSleepingContainer(c, "-d")
	firstID := strings.TrimSpace(out)

	out, _ = runSleepingContainer(c, "-d")
	secondID := strings.TrimSpace(out)

	// not long running
	out, _ = dockerCmd(c, "run", "-d", "busybox", "true")
	thirdID := strings.TrimSpace(out)

	out, _ = runSleepingContainer(c, "-d")
	fourthID := strings.TrimSpace(out)

	// make sure the second is running
	c.Assert(waitRun(secondID), checker.IsNil)

	// make sure third one is not running
	dockerCmd(c, "wait", thirdID)

	// make sure the forth is running
	c.Assert(waitRun(fourthID), checker.IsNil)

	// all
	out, _ = dockerCmd(c, "ps", "-a")
	c.Assert(assertContainerList(out, []string{fourthID, thirdID, secondID, firstID}), checker.Equals, true, check.Commentf("ALL: Container list is not in the correct order: \n%s", out))

	// running
	out, _ = dockerCmd(c, "ps")
	c.Assert(assertContainerList(out, []string{fourthID, secondID, firstID}), checker.Equals, true, check.Commentf("RUNNING: Container list is not in the correct order: \n%s", out))

	// limit
	out, _ = dockerCmd(c, "ps", "-n=2", "-a")
	expected := []string{fourthID, thirdID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-n=2")
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("LIMIT: Container list is not in the correct order: \n%s", out))

	// filter since
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-a")
	expected = []string{fourthID, thirdID, secondID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID)
	expected = []string{fourthID, secondID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+thirdID)
	expected = []string{fourthID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))

	// filter before
	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-a")
	expected = []string{thirdID, secondID, firstID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID)
	expected = []string{secondID, firstID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID)
	expected = []string{secondID, firstID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter: Container list is not in the correct order: \n%s", out))

	// filter since & before
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a")
	expected = []string{thirdID, secondID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID)
	expected = []string{secondID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter: Container list is not in the correct order: \n%s", out))

	// filter since & limit
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a")
	expected = []string{fourthID, thirdID}

	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2")
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, LIMIT: Container list is not in the correct order: \n%s", out))

	// filter before & limit
	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a")
	expected = []string{thirdID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1")
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))

	// filter since & filter before & limit
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a")
	expected = []string{thirdID}
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1")
	c.Assert(assertContainerList(out, expected), checker.Equals, true, check.Commentf("SINCE filter, BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))

}

func assertContainerList(out string, expected []string) bool {
	lines := strings.Split(strings.Trim(out, "\n "), "\n")

	if len(lines)-1 != len(expected) {
		return false
	}

	containerIDIndex := strings.Index(lines[0], "CONTAINER ID")
	for i := 0; i < len(expected); i++ {
		foundID := lines[i+1][containerIDIndex : containerIDIndex+12]
		if foundID != expected[i][:12] {
			return false
		}
	}

	return true
}

// FIXME(vdemeester) Move this into a unit test in daemon package
func (s *DockerSuite) TestPsListContainersInvalidFilterName(c *check.C) {
	out, _, err := dockerCmdWithError("ps", "-f", "invalidFilter=test")
	c.Assert(err, checker.NotNil)
	c.Assert(out, checker.Contains, "Invalid filter")
}

func (s *DockerSuite) TestPsListContainersSize(c *check.C) {
	// Problematic on Windows as it doesn't report the size correctly @swernli
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "busybox")

	baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1")
	baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n")
	baseSizeIndex := strings.Index(baseLines[0], "SIZE")
	baseFoundsize := baseLines[1][baseSizeIndex:]
	baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, " ")[0])
	c.Assert(err, checker.IsNil)

	name := "test_size"
	dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test")
	id, err := getIDByName(name)
	c.Assert(err, checker.IsNil)

	runCmd := exec.Command(dockerBinary, "ps", "-s", "-n=1")
	var out string

	wait := make(chan struct{})
	go func() {
		out, _, err = runCommandWithOutput(runCmd)
		close(wait)
	}()
	select {
	case <-wait:
	case <-time.After(3 * time.Second):
		c.Fatalf("Calling \"docker ps -s\" timed out!")
	}
	c.Assert(err, checker.IsNil)
	lines := strings.Split(strings.Trim(out, "\n "), "\n")
	c.Assert(lines, checker.HasLen, 2, check.Commentf("Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines)))
	sizeIndex := strings.Index(lines[0], "SIZE")
	idIndex := strings.Index(lines[0], "CONTAINER ID")
	foundID := lines[1][idIndex : idIndex+12]
	c.Assert(foundID, checker.Equals, id[:12], check.Commentf("Expected id %s, got %s", id[:12], foundID))
	expectedSize := fmt.Sprintf("%d B", (2 + baseBytes))
	foundSize := lines[1][sizeIndex:]
	c.Assert(foundSize, checker.Contains, expectedSize, check.Commentf("Expected size %q, got %q", expectedSize, foundSize))
}

func (s *DockerSuite) TestPsListContainersFilterStatus(c *check.C) {
	// start exited container
	out, _ := dockerCmd(c, "run", "-d", "busybox")
	firstID := strings.TrimSpace(out)

	// make sure the exited container is not running
	dockerCmd(c, "wait", firstID)

	// start running container
	out, _ = dockerCmd(c, "run", "-itd", "busybox")
	secondID := strings.TrimSpace(out)

	// filter containers by exited
	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=exited")
	containerOut := strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, firstID)

	out, _ = dockerCmd(c, "ps", "-a", "--no-trunc", "-q", "--filter=status=running")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, secondID)

	result := dockerCmdWithTimeout(time.Second*60, "ps", "-a", "-q", "--filter=status=rubbish")
	c.Assert(result, icmd.Matches, icmd.Expected{
		ExitCode: 1,
		Err:      "Unrecognised filter value for status",
	})

	// Windows doesn't support pausing of containers
	if daemonPlatform != "windows" {
		// pause running container
		out, _ = dockerCmd(c, "run", "-itd", "busybox")
		pausedID := strings.TrimSpace(out)
		dockerCmd(c, "pause", pausedID)
		// make sure the container is unpaused to let the daemon stop it properly
		defer func() { dockerCmd(c, "unpause", pausedID) }()

		out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=paused")
		containerOut = strings.TrimSpace(out)
		c.Assert(containerOut, checker.Equals, pausedID)
	}
}

func (s *DockerSuite) TestPsListContainersFilterHealth(c *check.C) {
	// Test legacy no health check
	out, _ := runSleepingContainer(c, "--name=none_legacy")
	containerID := strings.TrimSpace(out)

	waitForContainer(containerID)

	out, _ = dockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none")
	containerOut := strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected id %s, got %s for legacy none filter, output: %q", containerID, containerOut, out))

	// Test no health check specified explicitly
	out, _ = runSleepingContainer(c, "--name=none", "--no-healthcheck")
	containerID = strings.TrimSpace(out)

	waitForContainer(containerID)

	out, _ = dockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected id %s, got %s for none filter, output: %q", containerID, containerOut, out))

	// Test failing health check
	out, _ = runSleepingContainer(c, "--name=failing_container", "--health-cmd=exit 1", "--health-interval=1s")
	containerID = strings.TrimSpace(out)

	waitForHealthStatus(c, "failing_container", "starting", "unhealthy")

	out, _ = dockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=unhealthy")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected containerID %s, got %s for unhealthy filter, output: %q", containerID, containerOut, out))

	// Check passing healthcheck
	out, _ = runSleepingContainer(c, "--name=passing_container", "--health-cmd=exit 0", "--health-interval=1s")
	containerID = strings.TrimSpace(out)

	waitForHealthStatus(c, "passing_container", "starting", "healthy")

	out, _ = dockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=healthy")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, containerID, check.Commentf("Expected containerID %s, got %s for healthy filter, output: %q", containerID, containerOut, out))
}

func (s *DockerSuite) TestPsListContainersFilterID(c *check.C) {
	// start container
	out, _ := dockerCmd(c, "run", "-d", "busybox")
	firstID := strings.TrimSpace(out)

	// start another container
	runSleepingContainer(c)

	// filter containers by id
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID)
	containerOut := strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, firstID[:12], check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out))
}

func (s *DockerSuite) TestPsListContainersFilterName(c *check.C) {
	// start container
	dockerCmd(c, "run", "--name=a_name_to_match", "busybox")
	id, err := getIDByName("a_name_to_match")
	c.Assert(err, check.IsNil)

	// start another container
	runSleepingContainer(c, "--name=b_name_to_match")

	// filter containers by name
	out, _ := dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match")
	containerOut := strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, id[:12], check.Commentf("Expected id %s, got %s for exited filter, output: %q", id[:12], containerOut, out))
}

// Test for the ancestor filter for ps.
// There is also the same test but with image:tag@digest in docker_cli_by_digest_test.go
//
// What the test setups :
// - Create 2 image based on busybox using the same repository but different tags
// - Create an image based on the previous image (images_ps_filter_test2)
// - Run containers for each of those image (busybox, images_ps_filter_test1, images_ps_filter_test2)
// - Filter them out :P
func (s *DockerSuite) TestPsListContainersFilterAncestorImage(c *check.C) {
	// Build images
	imageName1 := "images_ps_filter_test1"
	imageID1, err := buildImage(imageName1,
		`FROM busybox
		 LABEL match me 1`, true)
	c.Assert(err, checker.IsNil)

	imageName1Tagged := "images_ps_filter_test1:tag"
	imageID1Tagged, err := buildImage(imageName1Tagged,
		`FROM busybox
		 LABEL match me 1 tagged`, true)
	c.Assert(err, checker.IsNil)

	imageName2 := "images_ps_filter_test2"
	imageID2, err := buildImage(imageName2,
		fmt.Sprintf(`FROM %s
		 LABEL match me 2`, imageName1), true)
	c.Assert(err, checker.IsNil)

	// start containers
	dockerCmd(c, "run", "--name=first", "busybox", "echo", "hello")
	firstID, err := getIDByName("first")
	c.Assert(err, check.IsNil)

	// start another container
	dockerCmd(c, "run", "--name=second", "busybox", "echo", "hello")
	secondID, err := getIDByName("second")
	c.Assert(err, check.IsNil)

	// start third container
	dockerCmd(c, "run", "--name=third", imageName1, "echo", "hello")
	thirdID, err := getIDByName("third")
	c.Assert(err, check.IsNil)

	// start fourth container
	dockerCmd(c, "run", "--name=fourth", imageName1Tagged, "echo", "hello")
	fourthID, err := getIDByName("fourth")
	c.Assert(err, check.IsNil)

	// start fifth container
	dockerCmd(c, "run", "--name=fifth", imageName2, "echo", "hello")
	fifthID, err := getIDByName("fifth")
	c.Assert(err, check.IsNil)

	var filterTestSuite = []struct {
		filterName  string
		expectedIDs []string
	}{
		// non existent stuff
		{"nonexistent", []string{}},
		{"nonexistent:tag", []string{}},
		// image
		{"busybox", []string{firstID, secondID, thirdID, fourthID, fifthID}},
		{imageName1, []string{thirdID, fifthID}},
		{imageName2, []string{fifthID}},
		// image:tag
		{fmt.Sprintf("%s:latest", imageName1), []string{thirdID, fifthID}},
		{imageName1Tagged, []string{fourthID}},
		// short-id
		{stringid.TruncateID(imageID1), []string{thirdID, fifthID}},
		{stringid.TruncateID(imageID2), []string{fifthID}},
		// full-id
		{imageID1, []string{thirdID, fifthID}},
		{imageID1Tagged, []string{fourthID}},
		{imageID2, []string{fifthID}},
	}

	var out string
	for _, filter := range filterTestSuite {
		out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+filter.filterName)
		checkPsAncestorFilterOutput(c, out, filter.filterName, filter.expectedIDs)
	}

	// Multiple ancestor filter
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageName2, "--filter=ancestor="+imageName1Tagged)
	checkPsAncestorFilterOutput(c, out, imageName2+","+imageName1Tagged, []string{fourthID, fifthID})
}

func checkPsAncestorFilterOutput(c *check.C, out string, filterName string, expectedIDs []string) {
	actualIDs := []string{}
	if out != "" {
		actualIDs = strings.Split(out[:len(out)-1], "\n")
	}
	sort.Strings(actualIDs)
	sort.Strings(expectedIDs)

	c.Assert(actualIDs, checker.HasLen, len(expectedIDs), check.Commentf("Expected filtered container(s) for %s ancestor filter to be %v:%v, got %v:%v", filterName, len(expectedIDs), expectedIDs, len(actualIDs), actualIDs))
	if len(expectedIDs) > 0 {
		same := true
		for i := range expectedIDs {
			if actualIDs[i] != expectedIDs[i] {
				c.Logf("%s, %s", actualIDs[i], expectedIDs[i])
				same = false
				break
			}
		}
		c.Assert(same, checker.Equals, true, check.Commentf("Expected filtered container(s) for %s ancestor filter to be %v, got %v", filterName, expectedIDs, actualIDs))
	}
}

func (s *DockerSuite) TestPsListContainersFilterLabel(c *check.C) {
	// start container
	dockerCmd(c, "run", "--name=first", "-l", "match=me", "-l", "second=tag", "busybox")
	firstID, err := getIDByName("first")
	c.Assert(err, check.IsNil)

	// start another container
	dockerCmd(c, "run", "--name=second", "-l", "match=me too", "busybox")
	secondID, err := getIDByName("second")
	c.Assert(err, check.IsNil)

	// start third container
	dockerCmd(c, "run", "--name=third", "-l", "nomatch=me", "busybox")
	thirdID, err := getIDByName("third")
	c.Assert(err, check.IsNil)

	// filter containers by exact match
	out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me")
	containerOut := strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, firstID, check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))

	// filter containers by two labels
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, firstID, check.Commentf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))

	// filter containers by two labels, but expect not found because of AND behavior
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Equals, "", check.Commentf("Expected nothing, got %s for exited filter, output: %q", containerOut, out))

	// filter containers by exact key
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match")
	containerOut = strings.TrimSpace(out)
	c.Assert(containerOut, checker.Contains, firstID)
	c.Assert(containerOut, checker.Contains, secondID)
	c.Assert(containerOut, checker.Not(checker.Contains), thirdID)
}

func (s *DockerSuite) TestPsListContainersFilterExited(c *check.C) {
	runSleepingContainer(c, "--name=sleep")

	dockerCmd(c, "run", "--name", "zero1", "busybox", "true")
	firstZero, err := getIDByName("zero1")
	c.Assert(err, checker.IsNil)

	dockerCmd(c, "run", "--name", "zero2", "busybox", "true")
	secondZero, err := getIDByName("zero2")
	c.Assert(err, checker.IsNil)

	out, _, err := dockerCmdWithError("run", "--name", "nonzero1", "busybox", "false")
	c.Assert(err, checker.NotNil, check.Commentf("Should fail.", out, err))

	firstNonZero, err := getIDByName("nonzero1")
	c.Assert(err, checker.IsNil)

	out, _, err = dockerCmdWithError("run", "--name", "nonzero2", "busybox", "false")
	c.Assert(err, checker.NotNil, check.Commentf("Should fail.", out, err))
	secondNonZero, err := getIDByName("nonzero2")
	c.Assert(err, checker.IsNil)

	// filter containers by exited=0
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0")
	ids := strings.Split(strings.TrimSpace(out), "\n")
	c.Assert(ids, checker.HasLen, 2, check.Commentf("Should be 2 zero exited containers got %d: %s", len(ids), out))
	c.Assert(ids[0], checker.Equals, secondZero, check.Commentf("First in list should be %q, got %q", secondZero, ids[0]))
	c.Assert(ids[1], checker.Equals, firstZero, check.Commentf("Second in list should be %q, got %q", firstZero, ids[1]))

	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1")
	ids = strings.Split(strings.TrimSpace(out), "\n")
	c.Assert(ids, checker.HasLen, 2, check.Commentf("Should be 2 zero exited containers got %d", len(ids)))
	c.Assert(ids[0], checker.Equals, secondNonZero, check.Commentf("First in list should be %q, got %q", secondNonZero, ids[0]))
	c.Assert(ids[1], checker.Equals, firstNonZero, check.Commentf("Second in list should be %q, got %q", firstNonZero, ids[1]))

}

func (s *DockerSuite) TestPsRightTagName(c *check.C) {
	// TODO Investigate further why this fails on Windows to Windows CI
	testRequires(c, DaemonIsLinux)
	tag := "asybox:shmatest"
	dockerCmd(c, "tag", "busybox", tag)

	var id1 string
	out, _ := runSleepingContainer(c)
	id1 = strings.TrimSpace(string(out))

	var id2 string
	out, _ = runSleepingContainerInImage(c, tag)
	id2 = strings.TrimSpace(string(out))

	var imageID string
	out = inspectField(c, "busybox", "Id")
	imageID = strings.TrimSpace(string(out))

	var id3 string
	out, _ = runSleepingContainerInImage(c, imageID)
	id3 = strings.TrimSpace(string(out))

	out, _ = dockerCmd(c, "ps", "--no-trunc")
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	// skip header
	lines = lines[1:]
	c.Assert(lines, checker.HasLen, 3, check.Commentf("There should be 3 running container, got %d", len(lines)))
	for _, line := range lines {
		f := strings.Fields(line)
		switch f[0] {
		case id1:
			c.Assert(f[1], checker.Equals, "busybox", check.Commentf("Expected %s tag for id %s, got %s", "busybox", id1, f[1]))
		case id2:
			c.Assert(f[1], checker.Equals, tag, check.Commentf("Expected %s tag for id %s, got %s", tag, id2, f[1]))
		case id3:
			c.Assert(f[1], checker.Equals, imageID, check.Commentf("Expected %s imageID for id %s, got %s", tag, id3, f[1]))
		default:
			c.Fatalf("Unexpected id %s, expected %s and %s and %s", f[0], id1, id2, id3)
		}
	}
}

func (s *DockerSuite) TestPsLinkedWithNoTrunc(c *check.C) {
	// Problematic on Windows as it doesn't support links as of Jan 2016
	testRequires(c, DaemonIsLinux)
	runSleepingContainer(c, "--name=first")
	runSleepingContainer(c, "--name=second", "--link=first:first")

	out, _ := dockerCmd(c, "ps", "--no-trunc")
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	// strip header
	lines = lines[1:]
	expected := []string{"second", "first,second/first"}
	var names []string
	for _, l := range lines {
		fields := strings.Fields(l)
		names = append(names, fields[len(fields)-1])
	}
	c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array: %v, got: %v", expected, names))
}

func (s *DockerSuite) TestPsGroupPortRange(c *check.C) {
	// Problematic on Windows as it doesn't support port ranges as of Jan 2016
	testRequires(c, DaemonIsLinux)
	portRange := "3850-3900"
	dockerCmd(c, "run", "-d", "--name", "porttest", "-p", portRange+":"+portRange, "busybox", "top")

	out, _ := dockerCmd(c, "ps")

	c.Assert(string(out), checker.Contains, portRange, check.Commentf("docker ps output should have had the port range %q: %s", portRange, string(out)))

}

func (s *DockerSuite) TestPsWithSize(c *check.C) {
	// Problematic on Windows as it doesn't report the size correctly @swernli
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "sizetest", "busybox", "top")

	out, _ := dockerCmd(c, "ps", "--size")
	c.Assert(out, checker.Contains, "virtual", check.Commentf("docker ps with --size should show virtual size of container"))
}

func (s *DockerSuite) TestPsListContainersFilterCreated(c *check.C) {
	// create a container
	out, _ := dockerCmd(c, "create", "busybox")
	cID := strings.TrimSpace(out)
	shortCID := cID[:12]

	// Make sure it DOESN'T show up w/o a '-a' for normal 'ps'
	out, _ = dockerCmd(c, "ps", "-q")
	c.Assert(out, checker.Not(checker.Contains), shortCID, check.Commentf("Should have not seen '%s' in ps output:\n%s", shortCID, out))

	// Make sure it DOES show up as 'Created' for 'ps -a'
	out, _ = dockerCmd(c, "ps", "-a")

	hits := 0
	for _, line := range strings.Split(out, "\n") {
		if !strings.Contains(line, shortCID) {
			continue
		}
		hits++
		c.Assert(line, checker.Contains, "Created", check.Commentf("Missing 'Created' on '%s'", line))
	}

	c.Assert(hits, checker.Equals, 1, check.Commentf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out))

	// filter containers by 'create' - note, no -a needed
	out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created")
	containerOut := strings.TrimSpace(out)
	c.Assert(cID, checker.HasPrefix, containerOut)
}

func (s *DockerSuite) TestPsFormatMultiNames(c *check.C) {
	// Problematic on Windows as it doesn't support link as of Jan 2016
	testRequires(c, DaemonIsLinux)
	//create 2 containers and link them
	dockerCmd(c, "run", "--name=child", "-d", "busybox", "top")
	dockerCmd(c, "run", "--name=parent", "--link=child:linkedone", "-d", "busybox", "top")

	//use the new format capabilities to only list the names and --no-trunc to get all names
	out, _ := dockerCmd(c, "ps", "--format", "{{.Names}}", "--no-trunc")
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	expected := []string{"parent", "child,parent/linkedone"}
	var names []string
	names = append(names, lines...)
	c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with non-truncated names: %v, got: %v", expected, names))

	//now list without turning off truncation and make sure we only get the non-link names
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}}")
	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	expected = []string{"parent", "child"}
	var truncNames []string
	truncNames = append(truncNames, lines...)
	c.Assert(expected, checker.DeepEquals, truncNames, check.Commentf("Expected array with truncated names: %v, got: %v", expected, truncNames))
}

// Test for GitHub issue #21772
func (s *DockerSuite) TestPsNamesMultipleTime(c *check.C) {
	runSleepingContainer(c, "--name=test1")
	runSleepingContainer(c, "--name=test2")

	//use the new format capabilities to list the names twice
	out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Names}}")
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	expected := []string{"test2 test2", "test1 test1"}
	var names []string
	names = append(names, lines...)
	c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with names displayed twice: %v, got: %v", expected, names))
}

func (s *DockerSuite) TestPsFormatHeaders(c *check.C) {
	// make sure no-container "docker ps" still prints the header row
	out, _ := dockerCmd(c, "ps", "--format", "table {{.ID}}")
	c.Assert(out, checker.Equals, "CONTAINER ID\n", check.Commentf(`Expected 'CONTAINER ID\n', got %v`, out))

	// verify that "docker ps" with a container still prints the header row also
	runSleepingContainer(c, "--name=test")
	out, _ = dockerCmd(c, "ps", "--format", "table {{.Names}}")
	c.Assert(out, checker.Equals, "NAMES\ntest\n", check.Commentf(`Expected 'NAMES\ntest\n', got %v`, out))
}

func (s *DockerSuite) TestPsDefaultFormatAndQuiet(c *check.C) {
	config := `{
		"psFormat": "default {{ .ID }}"
}`
	d, err := ioutil.TempDir("", "integration-cli-")
	c.Assert(err, checker.IsNil)
	defer os.RemoveAll(d)

	err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644)
	c.Assert(err, checker.IsNil)

	out, _ := runSleepingContainer(c, "--name=test")
	id := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "--config", d, "ps", "-q")
	c.Assert(id, checker.HasPrefix, strings.TrimSpace(out), check.Commentf("Expected to print only the container id, got %v\n", out))
}

// Test for GitHub issue #12595
func (s *DockerSuite) TestPsImageIDAfterUpdate(c *check.C) {
	// TODO: Investigate why this fails on Windows to Windows CI further.
	testRequires(c, DaemonIsLinux)
	originalImageName := "busybox:TestPsImageIDAfterUpdate-original"
	updatedImageName := "busybox:TestPsImageIDAfterUpdate-updated"

	runCmd := exec.Command(dockerBinary, "tag", "busybox:latest", originalImageName)
	out, _, err := runCommandWithOutput(runCmd)
	c.Assert(err, checker.IsNil)

	originalImageID, err := getIDByName(originalImageName)
	c.Assert(err, checker.IsNil)

	runCmd = exec.Command(dockerBinary, append([]string{"run", "-d", originalImageName}, sleepCommandForDaemonPlatform()...)...)
	out, _, err = runCommandWithOutput(runCmd)
	c.Assert(err, checker.IsNil)
	containerID := strings.TrimSpace(out)

	linesOut, err := exec.Command(dockerBinary, "ps", "--no-trunc").CombinedOutput()
	c.Assert(err, checker.IsNil)

	lines := strings.Split(strings.TrimSpace(string(linesOut)), "\n")
	// skip header
	lines = lines[1:]
	c.Assert(len(lines), checker.Equals, 1)

	for _, line := range lines {
		f := strings.Fields(line)
		c.Assert(f[1], checker.Equals, originalImageName)
	}

	runCmd = exec.Command(dockerBinary, "commit", containerID, updatedImageName)
	out, _, err = runCommandWithOutput(runCmd)
	c.Assert(err, checker.IsNil)

	runCmd = exec.Command(dockerBinary, "tag", updatedImageName, originalImageName)
	out, _, err = runCommandWithOutput(runCmd)
	c.Assert(err, checker.IsNil)

	linesOut, err = exec.Command(dockerBinary, "ps", "--no-trunc").CombinedOutput()
	c.Assert(err, checker.IsNil)

	lines = strings.Split(strings.TrimSpace(string(linesOut)), "\n")
	// skip header
	lines = lines[1:]
	c.Assert(len(lines), checker.Equals, 1)

	for _, line := range lines {
		f := strings.Fields(line)
		c.Assert(f[1], checker.Equals, originalImageID)
	}

}

func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *check.C) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "--name=foo", "-d", "-p", "5000:5000", "busybox", "top")
	c.Assert(waitRun("foo"), checker.IsNil)
	out, _ := dockerCmd(c, "ps")
	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	expected := "0.0.0.0:5000->5000/tcp"
	fields := strings.Fields(lines[1])
	c.Assert(fields[len(fields)-2], checker.Equals, expected, check.Commentf("Expected: %v, got: %v", expected, fields[len(fields)-2]))

	dockerCmd(c, "kill", "foo")
	dockerCmd(c, "wait", "foo")
	out, _ = dockerCmd(c, "ps", "-l")
	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	fields = strings.Fields(lines[1])
	c.Assert(fields[len(fields)-2], checker.Not(checker.Equals), expected, check.Commentf("Should not got %v", expected))
}

func (s *DockerSuite) TestPsShowMounts(c *check.C) {
	prefix, slash := getPrefixAndSlashFromDaemonPlatform()

	mp := prefix + slash + "test"

	dockerCmd(c, "volume", "create", "ps-volume-test")
	// volume mount containers
	runSleepingContainer(c, "--name=volume-test-1", "--volume", "ps-volume-test:"+mp)
	c.Assert(waitRun("volume-test-1"), checker.IsNil)
	runSleepingContainer(c, "--name=volume-test-2", "--volume", mp)
	c.Assert(waitRun("volume-test-2"), checker.IsNil)
	// bind mount container
	var bindMountSource string
	var bindMountDestination string
	if DaemonIsWindows.Condition() {
		bindMountSource = "c:\\"
		bindMountDestination = "c:\\t"
	} else {
		bindMountSource = "/tmp"
		bindMountDestination = "/t"
	}
	runSleepingContainer(c, "--name=bind-mount-test", "-v", bindMountSource+":"+bindMountDestination)
	c.Assert(waitRun("bind-mount-test"), checker.IsNil)

	out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}")

	lines := strings.Split(strings.TrimSpace(string(out)), "\n")
	c.Assert(lines, checker.HasLen, 3)

	fields := strings.Fields(lines[0])
	c.Assert(fields, checker.HasLen, 2)
	c.Assert(fields[0], checker.Equals, "bind-mount-test")
	c.Assert(fields[1], checker.Equals, bindMountSource)

	fields = strings.Fields(lines[1])
	c.Assert(fields, checker.HasLen, 2)

	annonymounsVolumeID := fields[1]

	fields = strings.Fields(lines[2])
	c.Assert(fields[1], checker.Equals, "ps-volume-test")

	// filter by volume name
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test")

	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	c.Assert(lines, checker.HasLen, 1)

	fields = strings.Fields(lines[0])
	c.Assert(fields[1], checker.Equals, "ps-volume-test")

	// empty results filtering by unknown volume
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist")
	c.Assert(strings.TrimSpace(string(out)), checker.HasLen, 0)

	// filter by mount destination
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp)

	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	c.Assert(lines, checker.HasLen, 2)

	fields = strings.Fields(lines[0])
	c.Assert(fields[1], checker.Equals, annonymounsVolumeID)
	fields = strings.Fields(lines[1])
	c.Assert(fields[1], checker.Equals, "ps-volume-test")

	// filter by bind mount source
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource)

	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	c.Assert(lines, checker.HasLen, 1)

	fields = strings.Fields(lines[0])
	c.Assert(fields, checker.HasLen, 2)
	c.Assert(fields[0], checker.Equals, "bind-mount-test")
	c.Assert(fields[1], checker.Equals, bindMountSource)

	// filter by bind mount destination
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination)

	lines = strings.Split(strings.TrimSpace(string(out)), "\n")
	c.Assert(lines, checker.HasLen, 1)

	fields = strings.Fields(lines[0])
	c.Assert(fields, checker.HasLen, 2)
	c.Assert(fields[0], checker.Equals, "bind-mount-test")
	c.Assert(fields[1], checker.Equals, bindMountSource)

	// empty results filtering by unknown mount point
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted")
	c.Assert(strings.TrimSpace(string(out)), checker.HasLen, 0)
}

func (s *DockerSuite) TestPsFormatSize(c *check.C) {
	testRequires(c, DaemonIsLinux)
	runSleepingContainer(c)

	out, _ := dockerCmd(c, "ps", "--format", "table {{.Size}}")
	lines := strings.Split(out, "\n")
	c.Assert(lines[1], checker.Not(checker.Equals), "0 B", check.Commentf("Should not display a size of 0 B"))

	out, _ = dockerCmd(c, "ps", "--size", "--format", "table {{.Size}}")
	lines = strings.Split(out, "\n")
	c.Assert(lines[0], checker.Equals, "SIZE", check.Commentf("Should only have one size column"))

	out, _ = dockerCmd(c, "ps", "--size", "--format", "raw")
	lines = strings.Split(out, "\n")
	c.Assert(lines[8], checker.HasPrefix, "size:", check.Commentf("Size should be appended on a newline"))
}

func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) {
	// TODO default network on Windows is not called "bridge", and creating a
	// custom network fails on Windows fails with "Error response from daemon: plugin not found")
	testRequires(c, DaemonIsLinux)

	// create some containers
	runSleepingContainer(c, "--net=bridge", "--name=onbridgenetwork")
	runSleepingContainer(c, "--net=none", "--name=onnonenetwork")

	// Filter docker ps on non existing network
	out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist")
	containerOut := strings.TrimSpace(string(out))
	lines := strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have no containers
	c.Assert(lines, checker.HasLen, 0)

	// Filter docker ps on network bridge
	out, _ = dockerCmd(c, "ps", "--filter", "network=bridge")
	containerOut = strings.TrimSpace(string(out))

	lines = strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have only one container
	c.Assert(lines, checker.HasLen, 1)

	// Making sure onbridgenetwork is on the output
	c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on network\n"))

	// Filter docker ps on networks bridge and none
	out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none")
	containerOut = strings.TrimSpace(string(out))

	lines = strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	//ps output should have both the containers
	c.Assert(lines, checker.HasLen, 2)

	// Making sure onbridgenetwork and onnonenetwork is on the output
	c.Assert(containerOut, checker.Contains, "onnonenetwork", check.Commentf("Missing the container on none network\n"))
	c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on bridge network\n"))

	nwID, _ := dockerCmd(c, "network", "inspect", "--format", "{{.ID}}", "bridge")

	// Filter by network ID
	out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID)
	containerOut = strings.TrimSpace(string(out))

	c.Assert(containerOut, checker.Contains, "onbridgenetwork")
}

func (s *DockerSuite) TestPsByOrder(c *check.C) {
	name1 := "xyz-abc"
	out, err := runSleepingContainer(c, "--name", name1)
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
	container1 := strings.TrimSpace(out)

	name2 := "xyz-123"
	out, err = runSleepingContainer(c, "--name", name2)
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
	container2 := strings.TrimSpace(out)

	name3 := "789-abc"
	out, err = runSleepingContainer(c, "--name", name3)
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")

	name4 := "789-123"
	out, err = runSleepingContainer(c, "--name", name4)
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")

	// Run multiple time should have the same result
	out, err = dockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz")
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Equals, fmt.Sprintf("%s\n%s", container2, container1))

	// Run multiple time should have the same result
	out, err = dockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz")
	c.Assert(err, checker.NotNil)
	c.Assert(strings.TrimSpace(out), checker.Equals, fmt.Sprintf("%s\n%s", container2, container1))
}

func (s *DockerSuite) TestPsFilterMissingArgErrorCode(c *check.C) {
	_, errCode, _ := dockerCmdWithError("ps", "--filter")
	c.Assert(errCode, checker.Equals, 125)
}


text:
package me.lucko.luckperms.commands.group.subcommands;

import me.lucko.luckperms.LuckPermsPlugin;
import me.lucko.luckperms.commands.CommandResult;
import me.lucko.luckperms.commands.Predicate;
import me.lucko.luckperms.commands.Sender;
import me.lucko.luckperms.commands.SubCommand;
import me.lucko.luckperms.constants.Message;
import me.lucko.luckperms.constants.Permission;
import me.lucko.luckperms.data.LogEntry;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import me.lucko.luckperms.groups.Group;
import me.lucko.luckperms.utils.ArgumentChecker;

import java.util.List;

public class GroupUnsetTempInherit extends SubCommand<Group> {
    public GroupUnsetTempInherit() {
        super("unsettempinherit", "Unsets another group for this group to inherit permissions from",
                "/%s group <group> unsettempinherit <group> [server] [world]", Permission.GROUP_UNSET_TEMP_INHERIT,
                Predicate.notInRange(1, 3));
    }

    @Override
    public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List<String> args, String label) {
        String groupName = args.get(0).toLowerCase();

        if (ArgumentChecker.checkNode(groupName)) {
            sendUsage(sender, label);
            return CommandResult.INVALID_ARGS;
        }

        try {
            if (args.size() >= 2) {
                final String server = args.get(1).toLowerCase();
                if (ArgumentChecker.checkServer(server)) {
                    Message.SERVER_INVALID_ENTRY.send(sender);
                    return CommandResult.INVALID_ARGS;
                }

                if (args.size() == 2) {
                    group.unsetPermission("group." + groupName, server, true);
                    Message.GROUP_UNSET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, group.getName(), groupName, server);
                    LogEntry.build().actor(sender).acted(group)
                            .action("unsettempinherit " + groupName + " " + server)
                            .build().submit(plugin, sender);
                } else {
                    final String world = args.get(2).toLowerCase();
                    group.unsetPermission("group." + groupName, server, world, true);
                    Message.GROUP_UNSET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), groupName, server, world);
                    LogEntry.build().actor(sender).acted(group)
                            .action("unsettempinherit " + groupName + " " + server + " " + world)
                            .build().submit(plugin, sender);
                }

            } else {
                group.unsetPermission("group." + groupName, true);
                Message.GROUP_UNSET_TEMP_INHERIT_SUCCESS.send(sender, group.getName(), groupName);
                LogEntry.build().actor(sender).acted(group)
                        .action("unsettempinherit " + groupName)
                        .build().submit(plugin, sender);
            }

            save(group, sender, plugin);
            return CommandResult.SUCCESS;
        } catch (ObjectLacksException e) {
            Message.GROUP_DOES_NOT_TEMP_INHERIT.send(sender, group.getName(), groupName);
            return CommandResult.STATE_ERROR;
        }
    }

    @Override
    public List<String> onTabComplete(LuckPermsPlugin plugin, Sender sender, List<String> args) {
        return getGroupTabComplete(args, plugin);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace pixelmelody\phpwebtoken\contracts;

/**
 * FormatAbstract
 *
 *
 * @author PixelMelody <lab@pixelmelody.com>
 * @copyright 2015 Pixelmelody PT Portugal
 */
abstract class FormatAbstract implements FormatInterface {

    /**
     * Data array to manage
     * @var array
     */
    private $values;

    /**
     * Construtor em FormatAbstract
     */
    function __construct($contentarray = []) {
        $this->values = [];
        if (is_array($contentarray) && count($contentarray) > 0) {
            foreach ($contentarray as $k => $v) {
                $e = explode('=', $v);
                if (count($e) === 2) {
                    $this->values[strtolower($e[0])] = $e[1];
                } elseif (!is_numeric($k)) {
                    $this->values[strtolower($k)] = $v;
                }
            }
        }
    }

    /**
     * Abstract method to be implemented.
     */
    public abstract function toString();

    /**
     * Returns the property content by its name.
     *
     * If property did not exists then the execution will be silence without
     * any warning or error report.
     *
     * @param string $name property name
     * @return mixed|false content of the specifique property | FALSE not exist
     */
    public function __get($name) {
        $index = strtolower((string) $name);
        if (isset($this->values[$index])) {
            return $this->values[$index];
        }
        return false;
    }

    /**
     * Determine with PHP ISSET function if property exists
     *
     * Aldo, this is also garanted by the __get magic method that will
     * return FALSE if property does not exists.
     *
     * @param string $name property name
     * @return boolean TRUE exists FALSE does not exists
     */
    public function __isset($name) {
        return isset($this->values[(string) $name]);
    }

    /**
     * Sets the property with its value indentified by its name
     *
     * @param string $name property name
     * @param mixed|null $value content for the property | NULL to delete it
     */
    public function __set($name, $value) {
        $index = strtolower((string) $name);
        if ($value === null && isset($this->values[$index])) {
            unset($this->values[$index]);
            return;
        }
        $this->values[$index] = $value;
    }

    /**
     * Number of itens in the array of data
     * @return int
     */
    public function count() {
        return count($this->values);
    }

    public function exists($name) {
        return isset($this->values[$name]);
    }

    /**
     * Merge an array of key and its values to the content.
     * @param array $array data to be added
     */
    public function merge($array) {
        if (is_array($array)) {
            $this->values = array_merge($this->values, $array);
        }
        return $this;
    }

    /**
     * How it will react when it is treated like a string.
     *
     * Will return the implementation present in the abstract method on the
     * class that will extends this abstraction.
     *
     * @return string
     */
    public function __toString() {
        return $this->toString();
    }

    /**
     * Redefine the name of the tag and maintain the content.
     *
     * @param string $tag old tag name
     * @param string $newtag new tag name
     */
    public function renewTag($tag, $newtag) {

        $t = strtolower($tag);
        $nt = strtolower($newtag);
        if ($t !== $nt && !empty($t) && !empty($nt)) {
            foreach ($this->values as $k => $v) {
                if ($k === $t) {
                    $this->values[$nt] = $v;
                    unset($this->values[$k]);
                    break;
                }
            }
        }
        return $this;
    }

    /**
     * The array of data
     * @return array
     */
    public function toArray() {
        return $this->values;
    }

}


text:
'use strict';

var glob = require('glob');
var path = require('path');
var rindModules = require('rind-modules');

module.exports = function i18n(gulp, conf) {
  conf = conf || {};

  return function(cb) {
    cb = cb || function() {};
    rindModules(conf);
    // get any rind modules in node_modules
    var nmPath = path.join(conf.input || process.cwd(), 'node_modules', conf.scope || '');
    var mods = glob.sync('*.rind', {
      cwd: nmPath
    });
    mods.forEach(function(mod) {
      conf.input = path.join(nmPath, mod);
      rindModules(conf);
    });
    cb();
  };
};


text:
package org.immopoly.android.widget;

import java.util.ArrayList;

import org.immopoly.android.model.Flat;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

public class ImmoPlaceOverlayItem extends OverlayItem {

	ArrayList<Flat> flats;

	public ImmoPlaceOverlayItem( GeoPoint point, ArrayList<Flat> flats ) {
		super( point, "", "" );
		this.flats = flats;
	}

}


text:
package org.neo4j.kernel.configuration;

import org.junit.Test;

import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.MapUtil;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

/**
 * Test for SystemPropertiesConfiguration
 */
public class SystemPropertiesConfigurationTest
{
    @Test
    public void testThatSetValidSystemPropertiesArePickedUp()
    {
        try
        {
            assertFalse( MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ).equals(
                    new SystemPropertiesConfiguration( GraphDatabaseSettings.class ).apply( MapUtil.stringMap() ) ) );

            System.setProperty( GraphDatabaseSettings.read_only.name(), Settings.TRUE );

            assertEquals( MapUtil.stringMap( GraphDatabaseSettings.read_only.name(), Settings.TRUE ),
                          new SystemPropertiesConfiguration( GraphDatabaseSettings.class )
                                  .apply( MapUtil.stringMap() ) );

            System.setProperty( GraphDatabaseSettings.read_only.name(), "foo" );

            assertEquals( MapUtil.stringMap(),
                          new SystemPropertiesConfiguration( GraphDatabaseSettings.class )
                                  .apply( MapUtil.stringMap() ) );
        }
        finally
        {
            System.clearProperty( GraphDatabaseSettings.read_only.name() );
        }
    }

    @Test
    public void testThatSetInvalidSystemPropertiesAreNotPickedUp()
    {
        System.setProperty( "foo", "bar" );

        assertEquals( MapUtil.stringMap(),
                      new SystemPropertiesConfiguration( GraphDatabaseSettings.class ).apply( MapUtil.stringMap() ) );
    }
}


text:
using Binance.Net.Enums;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Binance.Net.Objects.Models.Futures;
using Binance.Net.Objects.Models.Futures.AlgoOrders;

namespace Binance.Net.Interfaces.Clients.UsdFuturesApi
{
    ///
    /// Binance USD-M futures trading endpoints, placing and mananging orders.
    ///
    public interface IBinanceClientUsdFuturesApiTrading
    {
        ///
        /// Places a new order
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="side">The order side (buy/sell)</param>
        /// <param name="type">The order type</param>
        /// <param name="timeInForce">Lifetime of the order (GoodTillCancel/ImmediateOrCancel/FillOrKill)</param>
        /// <param name="quantity">The quantity of the base symbol</param>
        /// <param name="positionSide">The position side</param>
        /// <param name="reduceOnly">Specify as true if the order is intended to only reduce the position</param>
        /// <param name="price">The price to use</param>
        /// <param name="newClientOrderId">Unique id for order</param>
        /// <param name="stopPrice">Used for stop orders</param>
        /// <param name="activationPrice">Used with TRAILING_STOP_MARKET orders, default as the latest price(supporting different workingType)</param>
        /// <param name="callbackRate">Used with TRAILING_STOP_MARKET orders</param>
        /// <param name="workingType">stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE"</param>
        /// <param name="closePosition">Close-All,used with STOP_MARKET or TAKE_PROFIT_MARKET.</param>
        /// <param name="orderResponseType">The response type. Default Acknowledge</param>
        /// <param name="priceProtect">If true when price reaches stopPrice, difference between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than "triggerProtect" of the symbol.</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Id's for the placed order</returns>
        Task<WebCallResult<BinanceFuturesPlacedOrder>> PlaceOrderAsync(
            string symbol,
            OrderSide side,
            FuturesOrderType type,
            decimal? quantity,
            decimal? price = null,
            PositionSide? positionSide = null,
            TimeInForce? timeInForce = null,
            bool? reduceOnly = null,
            string? newClientOrderId = null,
            decimal? stopPrice = null,
            decimal? activationPrice = null,
            decimal? callbackRate = null,
            WorkingType? workingType = null,
            bool? closePosition = null,
            OrderResponseType? orderResponseType = null,
            bool? priceProtect = null,
            int? receiveWindow = null,
            CancellationToken ct = default);

        ///
        /// Place multiple orders in one call
        /// <para></para>
        ///
        /// <param name="orders">The orders to place</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Returns a list of call results, one for each order. The order the results are in is the order the orders were sent</returns>
        Task<WebCallResult<IEnumerable<CallResult<BinanceFuturesPlacedOrder>>>> PlaceMultipleOrdersAsync(
            BinanceFuturesBatchOrder[] orders,
            int? receiveWindow = null,
            CancellationToken ct = default);

        ///
        /// Retrieves data for a specific order. Either orderId or origClientOrderId should be provided.
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="orderId">The order id of the order</param>
        /// <param name="origClientOrderId">The client order id of the order</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>The specific order</returns>
        Task<WebCallResult<BinanceFuturesOrder>> GetOrderAsync(string symbol, long? orderId = null, string? origClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Cancels a pending order
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="orderId">The order id of the order</param>
        /// <param name="origClientOrderId">The client order id of the order</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Id's for canceled order</returns>
        Task<WebCallResult<BinanceFuturesCancelOrder>> CancelOrderAsync(string symbol, long? orderId = null, string? origClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Cancels all open orders
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Id's for canceled order</returns>
        Task<WebCallResult<BinanceFuturesCancelAllOrders>> CancelAllOrdersAsync(string symbol, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Cancel all open orders of the specified symbol at the end of the specified countdown. This rest endpoint means to ensure your open orders are canceled in case of an outage. The endpoint should be called repeatedly as heartbeats
        /// so that the existing countdown time can be canceled and replaced by a new one.
        /// <para></para>
        ///
        /// <param name="symbol">The symbol</param>
        /// <param name="countDownTime">The time after which all open orders should cancel, or 0 to cancel an existing timer</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Countdown result</returns>
        Task<WebCallResult<BinanceFuturesCountDownResult>> CancelAllOrdersAfterTimeoutAsync(string symbol, TimeSpan countDownTime, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Cancels muliple orders
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="orderIdList">The list of order ids to cancel</param>
        /// <param name="origClientOrderIdList">The list of client order ids to cancel</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>Id's for canceled order</returns>
        Task<WebCallResult<IEnumerable<CallResult<BinanceFuturesCancelOrder>>>> CancelMultipleOrdersAsync(string symbol, List<long>? orderIdList = null, List<string>? origClientOrderIdList = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Retrieves data for a specific open order. Either orderId or origClientOrderId should be provided.
        /// <para></para>
        ///
        /// <param name="symbol">The symbol the order is for</param>
        /// <param name="orderId">The order id of the order</param>
        /// <param name="origClientOrderId">The client order id of the order</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>The specific order</returns>
        Task<WebCallResult<BinanceFuturesOrder>> GetOpenOrderAsync(string symbol, long? orderId = null, string? origClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Gets a list of open orders
        /// <para></para>
        ///
        /// <param name="symbol">The symbol to get open orders for</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>List of open orders</returns>
        Task<WebCallResult<IEnumerable<BinanceFuturesOrder>>> GetOpenOrdersAsync(string? symbol = null, int? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Gets all orders for the provided symbol
        /// <para></para>
        ///
        /// <param name="symbol">The symbol to get orders for</param>
        /// <param name="orderId">If set, only orders with an order id higher than the provided will be returned</param>
        /// <param name="startTime">If set, only orders placed after this time will be returned</param>
        /// <param name="endTime">If set, only orders placed before this time will be returned</param>
        /// <param name="limit">Max number of results</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>List of orders</returns>
        Task<WebCallResult<IEnumerable<BinanceFuturesOrder>>> GetOrdersAsync(string symbol, long? orderId = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, int? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Gets a list of users forced orders
        /// <para></para>
        ///
        /// <param name="symbol">The symbol to get forced orders for</param>
        /// <param name="closeType">Filter by reason for close</param>
        /// <param name="startTime">Filter by start time</param>
        /// <param name="endTime">Filter by end time</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>List of forced orders</returns>
        Task<WebCallResult<IEnumerable<BinanceFuturesOrder>>> GetForcedOrdersAsync(string? symbol = null,
            AutoCloseType? closeType = null, DateTime? startTime = null, DateTime? endTime = null,
            int? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Gets all user trades for provided symbol
        /// <para></para>
        ///
        /// <param name="symbol">Symbol to get trades for</param>
        /// <param name="limit">The max number of results</param>
        /// <param name="fromId">TradeId to fetch from. Default gets most recent trades</param>
        /// <param name="startTime">Orders newer than this date will be retrieved</param>
        /// <param name="endTime">Orders older than this date will be retrieved</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns>List of trades</returns>
        Task<WebCallResult<IEnumerable<BinanceFuturesUsdtTrade>>> GetUserTradesAsync(string symbol, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, long? fromId = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Place a new Volume Participation order
        /// <para></para>
        ///
        /// <param name="symbol">The symbol</param>
        /// <param name="side">Order side</param>
        /// <param name="quantity">Order quantity</param>
        /// <param name="urgency">Represent the relative speed of the current execution</param>
        /// <param name="clientOrderId">Client order id</param>
        /// <param name="reduceOnly">Reduce only</param>
        /// <param name="limitPrice">Limit price of the order. If null will use market price</param>
        /// <param name="positionSide">Position side</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoOrderResult>> PlaceVolumeParticipationOrderAsync(
            string symbol,
            OrderSide side,
            decimal quantity,
            OrderUrgency urgency,
            string? clientOrderId = null,
            bool? reduceOnly = null,
            decimal? limitPrice = null,
            PositionSide? positionSide = null,
            long? receiveWindow = null,
            CancellationToken ct = default);

        ///
        /// Place a new Time Weighted Average Price order
        /// <para></para>
        ///
        /// <param name="symbol">The symbol</param>
        /// <param name="side">Order side</param>
        /// <param name="quantity">Order quantity</param>
        /// <param name="duration">Duration in seconds. Less than 5 minutes will be defaulted to 5 minutes, more than 24 hours will be defaulted to 24 hours.</param>
        /// <param name="clientOrderId">Client order id</param>
        /// <param name="reduceOnly">Reduce only</param>
        /// <param name="limitPrice">Limit price of the order. If null will use market price</param>
        /// <param name="positionSide">Position side</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoOrderResult>> PlaceTimeWeightedAveragePriceOrderAsync(
            string symbol,
            OrderSide side,
            decimal quantity,
            int duration,
            string? clientOrderId = null,
            bool? reduceOnly = null,
            decimal? limitPrice = null,
            PositionSide? positionSide = null,
            long? receiveWindow = null,
            CancellationToken ct = default);

        ///
        /// Cancel an algo order
        /// <para></para>
        ///
        /// <param name="algoOrderId">Algo id to cancel</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoResult>> CancelAlgoOrderAsync(long algoOrderId, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Get list of open algo orders
        /// <para></para>
        ///
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoOrders>> GetOpenAlgoOrdersAsync(long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Get list of closed algo orders
        /// <para></para>
        ///
        /// <param name="symbol">Filter by symbol</param>
        /// <param name="side">Filter by side</param>
        /// <param name="startTime">Fitler by start time</param>
        /// <param name="endTime">Filter by end time</param>
        /// <param name="page">Page</param>
        /// <param name="limit">Max results</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoOrders>> GetClosedAlgoOrdersAsync(string? symbol = null, OrderSide? side = null, DateTime? startTime = null, DateTime? endTime = null, int? page = null, int? limit = null, long? receiveWindow = null, CancellationToken ct = default);

        ///
        /// Get algo sub orders overview
        /// <para></para>
        ///
        /// <param name="algoId">Algo id</param>
        /// <param name="page">Page</param>
        /// <param name="limit">Max results</param>
        /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param>
        /// <param name="ct">Cancellation token</param>
        /// <returns></returns>
        Task<WebCallResult<BinanceAlgoSubOrderList>> GetAlgoSubOrdersAsync(long algoId, int? page = null, int? limit = null, long? receiveWindow = null, CancellationToken ct = default);
    }
}


text:
<?xml version="1.0"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.sakaiproject</groupId>
        <artifactId>master</artifactId>
        <version>21-SNAPSHOT</version>
        <relativePath>../master/pom.xml</relativePath>
    </parent>

    <name>sakai-assignment base pom</name>
    <groupId>org.sakaiproject.assignment</groupId>
    <artifactId>assignment</artifactId>
    <packaging>pom</packaging>

    <modules>
        <module>api</module>
        <module>impl</module>
        <module>tool</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.sakaiproject.assignment</groupId>
                <artifactId>sakai-assignment-impl</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.sakaiproject.assignment</groupId>
                <artifactId>sakai-assignment-bundles</artifactId>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>


text:
package com.ccsi.commons.dto;

import org.springframework.core.style.ToStringCreator;
import org.springframework.util.LinkedMultiValueMap;

/**
 * @author mbmartinez
 */
public class OutgoingMessageInfo extends LinkedMultiValueMap<String, Object> {

    private static final long serialVersionUID = 1L;

    protected String message_type;
    protected String mobile_number;
    protected String shortcode;
    protected String message_id;
    protected String message;
    protected String client_id;
    protected String secret_key;

    @Override
    public String toString() {
        return new ToStringCreator(this)
            .append("msg type", message_type)
            .append("mobile#", mobile_number)
            .append("shortcode", shortcode)
            .append("msg id", message_id)
            .append("msg", message)
            .append("client_id", client_id)
            .append("secret_key", secret_key)
            .toString();
    }

    public String getMessage_type() {
        return message_type;
    }
    public void setMessage_type(String message_type) {
        add("message_type", message_type);
        this.message_type = message_type;
    }
    public String getMobile_number() {
        return mobile_number;
    }
    public void setMobile_number(String mobile_number) {
        add("mobile_number", mobile_number);
        this.mobile_number = mobile_number;
    }
    public String getShortcode() {
        return shortcode;
    }
    public void setShortcode(String shortcode) {
        add("shortcode", shortcode);
        this.shortcode = shortcode;
    }
    public String getMessage_id() {
        return message_id;
    }
    public void setMessage_id(String message_id) {
        add("message_id", message_id);
        this.message_id = message_id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        add("message", message);
        this.message = message;
    }
    public String getClient_id() {
        return client_id;
    }
    public void setClient_id(String client_id) {
        add("client_id", client_id);
        this.client_id = client_id;
    }
    public String getSecret_key() {
        return secret_key;
    }
    public void setSecret_key(String secret_key) {
        add("secret_key", secret_key);
        this.secret_key = secret_key;
    }

}


text:
package org.osmdroid.samplefragments.data;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AlertDialog;

import org.osmdroid.R;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.samplefragments.BaseSampleFragment;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;

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

/**
 * @author Fabrice Fontaine
 * Sample on how to handle a click on overlapping {@link Marker}s
 * @since 6.0.3
 */
public class SampleMarkerMultiClick extends BaseSampleFragment {

    public static final String TITLE = "Overlapping Markers' click";

    private List<Marker> mClicked = new ArrayList<>();

    @Override
    public String getSampleTitle() {
        return TITLE;
    }

    @Override
    protected void addOverlays() {
        super.addOverlays();

        mMapView.getOverlays().add(new MapEventsOverlay(new MapEventsReceiver() {
            @Override
            public boolean singleTapConfirmedHelper(GeoPoint p) {
                if (mClicked.size() == 0) {
                    return false;
                }
                if (mClicked.size() == 1) {
                    message(mClicked.get(0));
                    mClicked.clear();
                    return true;
                }
                final String[] titles = new String[mClicked.size()];
                final Marker[] items = new Marker[titles.length];
                int i = 0;
                for (final Marker item : mClicked) {
                    titles[i] = item.getTitle();
                    items[i] = item;
                    i++;
                }
                new AlertDialog.Builder(getActivity())
                        .setItems(titles, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                message(items[i]);
                            }
                        })
                        .setNegativeButton("Cancel", null)
                        .show();
                mClicked.clear();
                return false;
            }

            @Override
            public boolean longPressHelper(GeoPoint p) {
                return false;
            }
        }));

        final List<SampleItemizedOverlayMultiClick.DataContainer> datas = SampleItemizedOverlayMultiClick.getData();
        final List<IGeoPoint> geoPoints = new ArrayList<>();
        final Drawable drawable = getResources().getDrawable(R.drawable.icon);
        for (final SampleItemizedOverlayMultiClick.DataContainer data : datas) {
            geoPoints.add(data.getGeoPoint());
            final Marker marker = new MyMarker(mMapView);
            marker.setPosition(new GeoPoint(data.getGeoPoint()));
            marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
            marker.setIcon(drawable);
            marker.setTitle(data.getTitle());
            marker.setSnippet(data.getSnippet());
            marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker, MapView mapView) {
                    mClicked.add(marker);
                    return false;
                }
            });
            mMapView.getOverlays().add(marker);
        }

        final BoundingBox box = BoundingBox.fromGeoPoints(geoPoints);
        mMapView.post(new Runnable() {
            @Override
            public void run() {
                mMapView.zoomToBoundingBox(box, false, 50);
            }
        });
    }

    private void message(final Marker pMarker) {
        ((MyMarker) pMarker).onMarkerClickDefault(pMarker, mMapView);
    }

    static private class MyMarker extends Marker {

        MyMarker(MapView mapView) {
            super(mapView);
        }

        @Override
        public boolean onMarkerClickDefault(Marker marker, MapView mapView) { // made public
            return super.onMarkerClickDefault(marker, mapView);
        }
    }
}


text:
package com.couchbase.workshop;

import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Centralized database configuration, to bootstrap the cluster and bucket as needed.
 */
@Configuration
public class DatabaseConfig {

    @Value("${hostname:127.0.0.1}")
    private String hostname;

    @Value("${bucketName:test-sample}")
    private String bucketName;

    @Value("${password:}")
    private String password;

    CouchbaseEnvironment couchbaseEnvironment() {
        return DefaultCouchbaseEnvironment
            .builder()
            .build();
    }

    @Bean
    public Cluster cluster() {
        return CouchbaseCluster.create(couchbaseEnvironment(), hostname);
    }

    @Bean
    public Bucket bucket() {
        return cluster().openBucket(bucketName, password);
    }

}


text:
using System;

namespace Antmicro.OptionsParser
{
    public class NumberOfElementsAttribute : Attribute
    {
        public NumberOfElementsAttribute(int max)
        {
            Max = max;
        }

        public int Max { get; set; }
    }
}


text:
namespace SPALM.SPSF.Library.Actions
{
    using System;
    using System.IO;
    using System.Windows.Forms;
    using EnvDTE;
    using Microsoft.Practices.ComponentModel;
    using Microsoft.Practices.RecipeFramework;
    using Microsoft.Practices.RecipeFramework.Services;

    [ServiceDependency(typeof(DTE))]
    public class ImportWSPFromServer : ConfigurableAction
    {
      private Project _TargetProject = null;
      private string _WSPFilename = "";

      [Input(Required = true)]
      public Project TargetProject
      {
        get { return _TargetProject; }
        set { _TargetProject = value; }
      }

        [Input(Required = true)]
      public string WSPFilename
      {
        get { return _WSPFilename; }
        set { _WSPFilename = value; }
      }

        protected string GetBasePath()
        {
          return base.GetService<IConfigurationService>(true).BasePath;
        }

        public override void Execute()
        {
          DTE dte = GetService<DTE>(true);
          string tempwspfolder = "";
          string tempwspfilename = "";
          try
          {
            //retrieve the file locally
            tempwspfolder = Path.Combine(Path.GetTempPath(), "SPSFImport" + Guid.NewGuid().ToString());
            if (!Directory.Exists(tempwspfolder))
            {
              Directory.CreateDirectory(tempwspfolder);
            }
            tempwspfilename = Path.Combine(tempwspfolder, WSPFilename);

						SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte);
						helper.ExportSolutionAsFile(WSPFilename, tempwspfilename);
          }
          catch (Exception ex)
          {
            MessageBox.Show("Could not download and save solution " + WSPFilename + " to temp folder " + tempwspfolder + ". " + ex.ToString());
          }

          if (File.Exists(tempwspfilename))
          {
            Helpers.ExtractWSPToProject(dte, tempwspfilename, _TargetProject, GetBasePath());
          }

          //clean up
          try
          {
            Directory.Delete(tempwspfolder, true);
          }
          catch (Exception ex)
          {
            MessageBox.Show("Could not delete temp folder " + tempwspfolder + ". " + ex.ToString());
          }
        }

      /// <summary>
      /// Removes the previously added reference, if it was created
      /// </summary>
      public override void Undo()
      {
      }
    }
}


text:
require 'mida/vocabulary'

module Mida
  module SchemaOrg

    autoload :Thing, 'mida/vocabularies/schemaorg/thing'
    autoload :Event, 'mida/vocabularies/schemaorg/event'

    # User interaction: Visit to a web page.
    class UserPageVisits < Mida::Vocabulary
      itemtype %r{http://schema.org/UserPageVisits}i
      include_vocabulary Mida::SchemaOrg::Thing
      include_vocabulary Mida::SchemaOrg::Event
    end

  end
end


text:
try_require_if_javascript "sprockets/es6" do
  if ExecJS.runtime.is_a?(ExecJS::RubyRhinoRuntime)
    Jekyll.logger.warn "ES6 transpiler has trouble with RubyRhino, use Node"
  end
end


text:
package com.project.service.impl;

import com.project.dao.YqmInfoMapper;
import com.project.entity.YqmInfo;
import com.project.service.YqmInfoService;
import com.project.service.util.DBContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by qiaowentao on 2016/8/25.
 */
@Service
public class YqmInfoServiceImpl implements YqmInfoService {

    @Autowired
    private YqmInfoMapper yqmInfoMapper;

    @Override
    public YqmInfo selectYqmInfoByCondition(YqmInfo yqmInfo) {
        DBContextHolder.setDataSource("dataSourceOne");
        return yqmInfoMapper.selectYqmInfoByYqm(yqmInfo);
    }
}


text:
import sbt._
import Keys._

object BuildSettings {
  val buildSettings = Defaults.defaultSettings ++ Seq(
    organization := "org.scala-lang.macroparadise",
    version := "1.0.0",
    scalacOptions ++= Seq(),
    scalaVersion := "2.11.0-SNAPSHOT",
    resolvers += Resolver.sonatypeRepo("snapshots"),
    addCompilerPlugin("org.scala-lang.plugins" % "macro-paradise" % "2.0.0-SNAPSHOT" cross CrossVersion.full)
  )
}

object MyBuild extends Build {
  import BuildSettings._

  lazy val root: Project = Project(
    "root",
    file("."),
    settings = buildSettings ++ Seq(
      run <<= run in Compile in core
    )
  ) aggregate(macros, core)

  lazy val macros: Project = Project(
    "macros",
    file("macros"),
    settings = buildSettings ++ Seq(
      libraryDependencies <+= (scalaVersion)("org.scala-lang" % "scala-reflect" % _))
  )

  lazy val core: Project = Project(
    "core",
    file("core"),
    settings = buildSettings
  ) dependsOn(macros)
}


text:
package emptyservicefx

import (
	fx "go.uber.org/fx"
	transport "go.uber.org/yarpc/api/transport"
	thrift "go.uber.org/yarpc/encoding/thrift"
	emptyserviceserver "go.uber.org/yarpc/encoding/thrift/thriftrw-plugin-yarpc/internal/tests/common/emptyserviceserver"
)

// ServerParams defines the dependencies for the EmptyService server.
type ServerParams struct {
	fx.In

	Handler emptyserviceserver.Interface
}

// ServerResult defines the output of EmptyService server module. It provides the
// procedures of a EmptyService handler to an Fx application.
//
// The procedures are provided to the "yarpcfx" value group. Dig 1.2 or newer
// must be used for this feature to work.
type ServerResult struct {
	fx.Out

	Procedures []transport.Procedure `group:"yarpcfx"`
}

// Server provides procedures for EmptyService to an Fx application. It expects a
// emptyservicefx.Interface to be present in the container.
//
// 	fx.Provide(
// 		func(h *MyEmptyServiceHandler) emptyserviceserver.Interface {
// 			return h
// 		},
// 		emptyservicefx.Server(),
// 	)
func Server(opts ...thrift.RegisterOption) interface{} {
	return func(p ServerParams) ServerResult {
		procedures := emptyserviceserver.New(p.Handler, opts...)
		return ServerResult{Procedures: procedures}
	}
}


text:
package it.unibz.krdb.obda.quest.datatypes;

import info.aduna.io.FileUtil;
import info.aduna.io.ZipUtil;
import it.unibz.krdb.obda.quest.scenarios.ScenarioManifestTestUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.JarFile;

import junit.framework.TestResult;
import junit.framework.TestSuite;

import org.openrdf.OpenRDFUtil;
import org.openrdf.model.Resource;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.repository.util.RDFInserter;
import org.openrdf.rio.ParserConfig;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicParserSettings;
import org.openrdf.rio.turtle.TurtleParser;
import org.openrdf.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QuestDatatypeTestUtils {

	static final Logger logger = LoggerFactory.getLogger(QuestDatatypeTestUtils.class);

	public static TestSuite suite(QuestDatatypeParent.Factory factory) throws Exception
	{
		final String manifestFile;
		final File tmpDir;

		URL url = ScenarioManifestTestUtils.class.getResource(factory.getMainManifestFile());

		if ("jar".equals(url.getProtocol())) {
			// Extract manifest files to a temporary directory
			try {
				tmpDir = FileUtil.createTempDir("datatype-evaluation");

				JarURLConnection con = (JarURLConnection) url.openConnection();
				JarFile jar = con.getJarFile();

				ZipUtil.extract(jar, tmpDir);

				File localFile = new File(tmpDir, con.getEntryName());
				manifestFile = localFile.toURI().toURL().toString();
			} catch (IOException e) {
				throw new AssertionError(e);
			}
		} else {
			manifestFile = url.toString();
			tmpDir = null;
		}

		TestSuite suite = new TestSuite(factory.getClass().getName()) {

			@Override
			public void run(TestResult result) {
				try {
					super.run(result);
				}
				finally {
					if (tmpDir != null) {
						try {
							FileUtil.deleteDir(tmpDir);
						}
						catch (IOException e) {
							System.err.println("Unable to clean up temporary directory '" + tmpDir + "': " + e.getMessage());
						}
					}
				}
			}
		};

		Repository manifestRep = new SailRepository(new MemoryStore());
		manifestRep.initialize();
		RepositoryConnection con = manifestRep.getConnection();

		addTurtle(con, new URL(manifestFile), manifestFile);

		String query = "SELECT DISTINCT manifestFile FROM {x} rdf:first {manifestFile} "
				+ "USING NAMESPACE mf = <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>, "
				+ "  qt = <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>";

		TupleQueryResult manifestResults = con.prepareTupleQuery(QueryLanguage.SERQL, query, manifestFile).evaluate();

		while (manifestResults.hasNext()) {
			BindingSet bindingSet = manifestResults.next();
			String subManifestFile = bindingSet.getValue("manifestFile").toString();
			suite.addTest(QuestDatatypeParent.suite(subManifestFile, factory));
		}

		manifestResults.close();
		con.close();
		manifestRep.shutDown();

		logger.info("Created aggregated test suite with " + suite.countTestCases() + " test cases.");
		return suite;
	}

	static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts)
		throws IOException, RepositoryException, RDFParseException
	{
		if (baseURI == null) {
			baseURI = url.toExternalForm();
		}

		InputStream in = url.openStream();

		try {
			OpenRDFUtil.verifyContextNotNull(contexts);
			final ValueFactory vf = con.getRepository().getValueFactory();
			RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, vf);
			ParserConfig config = rdfParser.getParserConfig();
			// To emulate DatatypeHandling.IGNORE
			config.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES);
			config.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES);
			config.addNonFatalError(BasicParserSettings.NORMALIZE_DATATYPE_VALUES);
//			rdfParser.setVerifyData(false);
//			rdfParser.setStopAtFirstError(true);
//			rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE);

			RDFInserter rdfInserter = new RDFInserter(con);
			rdfInserter.enforceContext(contexts);
			rdfParser.setRDFHandler(rdfInserter);

			con.begin();

			try {
				rdfParser.parse(in, baseURI);
			}
			catch (RDFHandlerException e) {
					con.rollback();
				// RDFInserter only throws wrapped RepositoryExceptions
				throw (RepositoryException)e.getCause();
			}
			catch (RuntimeException e) {
					con.rollback();
				throw e;
			}
			finally {
				con.commit();
			}
		}
		finally {
			in.close();
		}
	}
}


text:
export { ButtonCheckboxDirective } from './button-checkbox.directive';
export { ButtonRadioDirective } from './button-radio.directive';
export { ButtonsModule } from './buttons.module';
//# sourceMappingURL=index.js.map


text:
namespace Spect.Net.SpectrumEmu.Devices.Tape.Tzx
{
    /// <summary>
    /// Identified keyboard and keypad types
    /// </summary>
    public enum TzxKeyboardType : byte
    {
        KeypadForZxSpectrum128K = 0x00
    }
}


text:
import React from 'react'
import { expect } from 'chai'
import TestUtils from 'react-addons-test-utils'
import categories from './../fixtures/categories'
import questions from './../fixtures/questions'
import sinon from 'sinon'

import SurveyQuestionCategoryPager from '../../../../assets/js/components/organisms/SurveyQuestionCategoryPager'

describe('Survey Question Category Pager Test', () => {

  let component, setIndex, dispatch

  beforeEach(() => {

    setIndex = sinon.stub()
    dispatch = sinon.stub()

    component = TestUtils.renderIntoDocument(
      <SurveyQuestionCategoryPager
        categories={categories}
        question={questions[6]}
        setIndex={setIndex}
        dispatch={dispatch} />
    )

  })

  it('should exist', () => {
    expect(component).to.be.ok
  })

  describe('#getCategoryIndex', () => {

    it('should return the index of a category in an array of categories given an ID', () => {
      // it is given that the third catgeory in the array of categories
      // has an id of 3.
      const result = component.getCategoryIndex(categories, 3)
      expect(result).to.equal(2)
    })

  })

  describe('#selectCategory', () => {

    it('Should set the question pager index to that of the first question in a ' +
       'selected category', () => {
      const fakeEvent = {
        target: {
          value: '2'
        }
      }
      component.selectCategory(fakeEvent)
      sinon.assert.calledWith(setIndex, 6)
    })

  })

  describe('#nextCategory', () => {

    it('should set the question pager index to that of the first question in ' +
       'the next category', () => {
      component.nextCategory()
      sinon.assert.calledWith(setIndex, 14)
    })

  })

  describe('#prevCategory', () => {

    it('should set the question pager index to that of the first question in ' +
       'the next category', () => {
      component.prevCategory()
      sinon.assert.calledWith(setIndex, 0)
    })

  })

})


text:
package org.apache.camel.management.mbean;

import org.apache.camel.CamelContext;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedUnmarshalMBean;
import org.apache.camel.model.UnmarshalDefinition;
import org.apache.camel.support.processor.UnmarshalProcessor;

@ManagedResource(description = "Managed Unmarshal")
public class ManagedUnmarshal extends ManagedProcessor implements ManagedUnmarshalMBean {
    private final UnmarshalProcessor processor;

    public ManagedUnmarshal(CamelContext context, UnmarshalProcessor processor, UnmarshalDefinition definition) {
        super(context, processor, definition);
        this.processor = processor;
    }

    @Override
    public UnmarshalDefinition getDefinition() {
        return (UnmarshalDefinition) super.getDefinition();
    }

    @Override
    public String getDataFormatName() {
        String name = null;
        if (getDefinition().getDataFormatType() != null) {
            name = getDefinition().getDataFormatType().getDataFormatName();
        }
        return name;
    }
}


text:
module Mincer
  module Processors
    module PgJsonDumper
      class Processor

        def initialize(mincer, options = {})
          @mincer, @args, @relation, @options = mincer, mincer.args, mincer.relation, options
        end

        def apply
          @relation
        end

        def to_json
          if dump_supported?
            result = Mincer.connection.select_all(json_query).first['json']
            return result unless @options[:singularize]
            return (result[1..-2].presence || '{}') unless @options[:root]
            (result.sub('[', '').sub(/(\])}$/, '}').presence || '{}')
          else
            warn 'To dump data to json with postgres you need to use postgres server version >= 9.2'
          end
        end

        private

        def dump_supported?
          Mincer.postgres? && (Mincer.connection.send(:postgresql_version) >= 90200)
        end

        def json_query
          if @options[:root]
            json_query_with_root(@options[:root], @options[:meta])
          else
            basic_json_query
          end
        end

        def base_sql
          @mincer.sql
        end

        # Query for basic json generation. Ex: [{'id': 1}, {...}]
        def basic_json_query(root = 'json', meta = false)
          meta_sql = if meta
            if meta.is_a?(Hash) && meta[:total_count]
              @mincer.relation.instance_variable_set(:@total_count, meta[:total_count])
            end
            ", #{@mincer.total_pages} AS total_pages, #{@mincer.total_count} AS total_count, #{@mincer.current_page} AS current_page, #{@mincer.limit_value} AS per_page"
          else
            ''
          end
          <<-SQL
            SELECT COALESCE(array_to_json(array_agg(row_to_json(subq))), '[]') AS #{root} #{meta_sql}
            FROM (#{base_sql}) as subq
          SQL
        end

        # Generates json with root. Ex: If root = 'items' resulting json will be { 'items' => [...] }
        # When `meta` passed will add pagination data(Experimental!!!)
        def json_query_with_root(root, meta)
          <<-SQL
            SELECT row_to_json(t) as json FROM ( #{basic_json_query(root, meta)} ) as t
          SQL
        end

      end

      module Options
        extend ActiveSupport::Concern

        def to_json(options = {})
          PgJsonDumper::Processor.new(self, options).to_json
        end
      end

    end
  end
end

::Mincer.add_processor(:pg_json_dumper)