text:
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/build"
	"go/doc"
	"go/parser"
	"go/token"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"runtime"
	"sort"
	"strings"
	"text/template"
	"time"
	"unicode"
	"unicode/utf8"
)

// Break init loop.
func init() {
	cmdTest.Run = runTest
}

var cmdTest = &Command{
	CustomFlags: true,
	UsageLine:   "test [-c] [-i] [build and test flags] [packages] [flags for test binary]",
	Short:       "test packages",
	Long: `
'Go test' automates testing the packages named by the import paths.
It prints a summary of the test results in the format:

	ok   archive/tar   0.011s
	FAIL archive/zip   0.022s
	ok   compress/gzip 0.033s
	...

followed by detailed output for each failed package.

'Go test' recompiles each package along with any files with names matching
the file pattern "*_test.go".
Files whose names begin with "_" (including "_test.go") or "." are ignored.
These additional files can contain test functions, benchmark functions, and
example functions.  See 'go help testfunc' for more.
Each listed package causes the execution of a separate test binary.

Test files that declare a package with the suffix "_test" will be compiled as a
separate package, and then linked and run with the main test binary.

By default, go test needs no arguments.  It compiles and tests the package
with source in the current directory, including tests, and runs the tests.

The package is built in a temporary directory so it does not interfere with the
non-test installation.

In addition to the build flags, the flags handled by 'go test' itself are:

	-c  Compile the test binary to pkg.test but do not run it.
	    (Where pkg is the last element of the package's import path.)

	-i
	    Install packages that are dependencies of the test.
	    Do not run the test.

	-exec xprog
	    Run the test binary using xprog. The behavior is the same as
	    in 'go run'. See 'go help run' for details.

The test binary also accepts flags that control execution of the test; these
flags are also accessible by 'go test'.  See 'go help testflag' for details.

If the test binary needs any other flags, they should be presented after the
package names. The go tool treats as a flag the first argument that begins with
a minus sign that it does not recognize itself; that argument and all subsequent
arguments are passed as arguments to the test binary.

For more about build flags, see 'go help build'.
For more about specifying packages, see 'go help packages'.

See also: go build, go vet.
`,
}

var helpTestflag = &Command{
	UsageLine: "testflag",
	Short:     "description of testing flags",
	Long: `
The 'go test' command takes both flags that apply to 'go test' itself
and flags that apply to the resulting test binary.

Several of the flags control profiling and write an execution profile
suitable for "go tool pprof"; run "go tool pprof help" for more
information.  The --alloc_space, --alloc_objects, and --show_bytes
options of pprof control how the information is presented.

The following flags are recognized by the 'go test' command and
control the execution of any test:

	-bench regexp
	    Run benchmarks matching the regular expression.
	    By default, no benchmarks run. To run all benchmarks,
	    use '-bench .' or '-bench=.'.

	-benchmem
	    Print memory allocation statistics for benchmarks.

	-benchtime t
	    Run enough iterations of each benchmark to take t, specified
	    as a time.Duration (for example, -benchtime 1h30s).
	    The default is 1 second (1s).

	-blockprofile block.out
	    Write a goroutine blocking profile to the specified file
	    when all tests are complete.

	-blockprofilerate n
	    Control the detail provided in goroutine blocking profiles by
	    calling runtime.SetBlockProfileRate with n.
	    See 'godoc runtime SetBlockProfileRate'.
	    The profiler aims to sample, on average, one blocking event every
	    n nanoseconds the program spends blocked.  By default,
	    if -test.blockprofile is set without this flag, all blocking events
	    are recorded, equivalent to -test.blockprofilerate=1.

	-cover
	    Enable coverage analysis.

	-covermode set,count,atomic
	    Set the mode for coverage analysis for the package[s]
	    being tested. The default is "set" unless -race is enabled,
	    in which case it is "atomic".
	    The values:
		set: bool: does this statement run?
		count: int: how many times does this statement run?
		atomic: int: count, but correct in multithreaded tests;
			significantly more expensive.
	    Sets -cover.

	-coverpkg pkg1,pkg2,pkg3
	    Apply coverage analysis in each test to the given list of packages.
	    The default is for each test to analyze only the package being tested.
	    Packages are specified as import paths.
	    Sets -cover.

	-coverprofile cover.out
	    Write a coverage profile to the specified file after all tests
	    have passed.
	    Sets -cover.

	-cpu 1,2,4
	    Specify a list of GOMAXPROCS values for which the tests or
	    benchmarks should be executed.  The default is the current value
	    of GOMAXPROCS.

	-cpuprofile cpu.out
	    Write a CPU profile to the specified file before exiting.

	-memprofile mem.out
	    Write a memory profile to the specified file after all tests
	    have passed.

	-memprofilerate n
	    Enable more precise (and expensive) memory profiles by setting
	    runtime.MemProfileRate.  See 'godoc runtime MemProfileRate'.
	    To profile all memory allocations, use -test.memprofilerate=1
	    and pass --alloc_space flag to the pprof tool.

	-outputdir directory
	    Place output files from profiling in the specified directory,
	    by default the directory in which "go test" is running.

	-parallel n
	    Allow parallel execution of test functions that call t.Parallel.
	    The value of this flag is the maximum number of tests to run
	    simultaneously; by default, it is set to the value of GOMAXPROCS.

	-run regexp
	    Run only those tests and examples matching the regular
	    expression.

	-short
	    Tell long-running tests to shorten their run time.
	    It is off by default but set during all.bash so that installing
	    the Go tree can run a sanity check but not spend time running
	    exhaustive tests.

	-timeout t
	    If a test runs longer than t, panic.

	-v
	    Verbose output: log all tests as they are run. Also print all
	    text from Log and Logf calls even if the test succeeds.

The test binary, called pkg.test where pkg is the name of the
directory containing the package sources, can be invoked directly
after building it with 'go test -c'. When invoking the test binary
directly, each of the standard flag names must be prefixed with 'test.',
as in -test.run=TestMyFunc or -test.v.

When running 'go test', flags not listed above are passed through
unaltered. For instance, the command

	go test -x -v -cpuprofile=prof.out -dir=testdata -update

will compile the test binary and then run it as

	pkg.test -test.v -test.cpuprofile=prof.out -dir=testdata -update

The test flags that generate profiles (other than for coverage) also
leave the test binary in pkg.test for use when analyzing the profiles.

Flags not recognized by 'go test' must be placed after any specified packages.
`,
}

var helpTestfunc = &Command{
	UsageLine: "testfunc",
	Short:     "description of testing functions",
	Long: `
The 'go test' command expects to find test, benchmark, and example functions
in the "*_test.go" files corresponding to the package under test.

A test function is one named TestXXX (where XXX is any alphanumeric string
not starting with a lower case letter) and should have the signature,

	func TestXXX(t *testing.T) { ... }

A benchmark function is one named BenchmarkXXX and should have the signature,

	func BenchmarkXXX(b *testing.B) { ... }

An example function is similar to a test function but, instead of using
*testing.T to report success or failure, prints output to os.Stdout.
That output is compared against the function's "Output:" comment, which
must be the last comment in the function body (see example below). An
example with no such comment, or with no text after "Output:" is compiled
but not executed.

Godoc displays the body of ExampleXXX to demonstrate the use
of the function, constant, or variable XXX.  An example of a method M with
receiver type T or *T is named ExampleT_M.  There may be multiple examples
for a given function, constant, or variable, distinguished by a trailing _xxx,
where xxx is a suffix not beginning with an upper case letter.

Here is an example of an example:

	func ExamplePrintln() {
		Println("The output of\nthis example.")
		// Output: The output of
		// this example.
	}

The entire test file is presented as the example when it contains a single
example function, at least one other function, type, variable, or constant
declaration, and no test or benchmark functions.

See the documentation of the testing package for more information.
`,
}

var (
	testC            bool       // -c flag
	testCover        bool       // -cover flag
	testCoverMode    string     // -covermode flag
	testCoverPaths   []string   // -coverpkg flag
	testCoverPkgs    []*Package // -coverpkg flag
	testProfile      bool       // some profiling flag
	testNeedBinary   bool       // profile needs to keep binary around
	testI            bool       // -i flag
	testV            bool       // -v flag
	testFiles        []string   // -file flag(s)  TODO: not respected
	testTimeout      string     // -timeout flag
	testArgs         []string
	testBench        bool
	testStreamOutput bool // show output as it is generated
	testShowPass     bool // show passing output

	testKillTimeout = 10 * time.Minute
)

var testMainDeps = map[string]bool{
	// Dependencies for testmain.
	"testing": true,
	"regexp":  true,
}

func runTest(cmd *Command, args []string) {
	var pkgArgs []string
	pkgArgs, testArgs = testFlags(args)

	findExecCmd() // initialize cached result

	raceInit()
	pkgs := packagesForBuild(pkgArgs)
	if len(pkgs) == 0 {
		fatalf("no packages to test")
	}

	if testC && len(pkgs) != 1 {
		fatalf("cannot use -c flag with multiple packages")
	}
	if testProfile && len(pkgs) != 1 {
		fatalf("cannot use test profile flag with multiple packages")
	}

	// If a test timeout was given and is parseable, set our kill timeout
	// to that timeout plus one minute.  This is a backup alarm in case
	// the test wedges with a goroutine spinning and its background
	// timer does not get a chance to fire.
	if dt, err := time.ParseDuration(testTimeout); err == nil && dt > 0 {
		testKillTimeout = dt + 1*time.Minute
	}

	// show passing test output (after buffering) with -v flag.
	// must buffer because tests are running in parallel, and
	// otherwise the output will get mixed.
	testShowPass = testV

	// stream test output (no buffering) when no package has
	// been given on the command line (implicit current directory)
	// or when benchmarking.
	// Also stream if we're showing output anyway with a
	// single package under test.  In that case, streaming the
	// output produces the same result as not streaming,
	// just more immediately.
	testStreamOutput = len(pkgArgs) == 0 || testBench ||
		(len(pkgs) <= 1 && testShowPass)

	var b builder
	b.init()

	if testI {
		buildV = testV

		deps := make(map[string]bool)
		for dep := range testMainDeps {
			deps[dep] = true
		}

		for _, p := range pkgs {
			// Dependencies for each test.
			for _, path := range p.Imports {
				deps[path] = true
			}
			for _, path := range p.TestImports {
				deps[path] = true
			}
			for _, path := range p.XTestImports {
				deps[path] = true
			}
		}

		// translate C to runtime/cgo
		if deps["C"] {
			delete(deps, "C")
			deps["runtime/cgo"] = true
			if buildContext.GOOS == runtime.GOOS && buildContext.GOARCH == runtime.GOARCH {
				deps["cmd/cgo"] = true
			}
		}
		// Ignore pseudo-packages.
		delete(deps, "unsafe")

		all := []string{}
		for path := range deps {
			if !build.IsLocalImport(path) {
				all = append(all, path)
			}
		}
		sort.Strings(all)

		a := &action{}
		for _, p := range packagesForBuild(all) {
			a.deps = append(a.deps, b.action(modeInstall, modeInstall, p))
		}
		b.do(a)
		if !testC || a.failed {
			return
		}
		b.init()
	}

	var builds, runs, prints []*action

	if testCoverPaths != nil {
		// Load packages that were asked about for coverage.
		// packagesForBuild exits if the packages cannot be loaded.
		testCoverPkgs = packagesForBuild(testCoverPaths)

		// Warn about -coverpkg arguments that are not actually used.
		used := make(map[string]bool)
		for _, p := range pkgs {
			used[p.ImportPath] = true
			for _, dep := range p.Deps {
				used[dep] = true
			}
		}
		for _, p := range testCoverPkgs {
			if !used[p.ImportPath] {
				log.Printf("warning: no packages being tested depend on %s", p.ImportPath)
			}
		}

		// Mark all the coverage packages for rebuilding with coverage.
		for _, p := range testCoverPkgs {
			p.Stale = true // rebuild
			p.fake = true  // do not warn about rebuild
			p.coverMode = testCoverMode
			var coverFiles []string
			coverFiles = append(coverFiles, p.GoFiles...)
			coverFiles = append(coverFiles, p.CgoFiles...)
			p.coverVars = declareCoverVars(p.ImportPath, coverFiles...)
		}
	}

	// Prepare build + run + print actions for all packages being tested.
	for _, p := range pkgs {
		buildTest, runTest, printTest, err := b.test(p)
		if err != nil {
			str := err.Error()
			if strings.HasPrefix(str, "\n") {
				str = str[1:]
			}
			failed := fmt.Sprintf("FAIL\t%s [setup failed]\n", p.ImportPath)

			if p.ImportPath != "" {
				errorf("# %s\n%s\n%s", p.ImportPath, str, failed)
			} else {
				errorf("%s\n%s", str, failed)
			}
			continue
		}
		builds = append(builds, buildTest)
		runs = append(runs, runTest)
		prints = append(prints, printTest)
	}

	// Ultimately the goal is to print the output.
	root := &action{deps: prints}

	// Force the printing of results to happen in order,
	// one at a time.
	for i, a := range prints {
		if i > 0 {
			a.deps = append(a.deps, prints[i-1])
		}
	}

	// Force benchmarks to run in serial.
	if !testC && testBench {
		// The first run must wait for all builds.
		// Later runs must wait for the previous run's print.
		for i, run := range runs {
			if i == 0 {
				run.deps = append(run.deps, builds...)
			} else {
				run.deps = append(run.deps, prints[i-1])
			}
		}
	}

	// If we are building any out-of-date packages other
	// than those under test, warn.
	okBuild := map[*Package]bool{}
	for _, p := range pkgs {
		okBuild[p] = true
	}
	warned := false
	for _, a := range actionList(root) {
		if a.p == nil || okBuild[a.p] {
			continue
		}
		okBuild[a.p] = true // warn at most once

		// Don't warn about packages being rebuilt because of
		// things like coverage analysis.
		for _, p1 := range a.p.imports {
			if p1.fake {
				a.p.fake = true
			}
		}

		if a.f != nil && !okBuild[a.p] && !a.p.fake && !a.p.local {
			if !warned {
				fmt.Fprintf(os.Stderr, "warning: building out-of-date packages:\n")
				warned = true
			}
			fmt.Fprintf(os.Stderr, "\t%s\n", a.p.ImportPath)
		}
	}
	if warned {
		args := strings.Join(pkgArgs, " ")
		if args != "" {
			args = " " + args
		}
		extraOpts := ""
		if buildRace {
			extraOpts = "-race "
		}
		fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args)
	}

	b.do(root)
}

func contains(x []string, s string) bool {
	for _, t := range x {
		if t == s {
			return true
		}
	}
	return false
}

func (b *builder) test(p *Package) (buildAction, runAction, printAction *action, err error) {
	if len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
		build := &action{p: p}
		run := &action{p: p, deps: []*action{build}}
		print := &action{f: (*builder).notest, p: p, deps: []*action{run}}
		return build, run, print, nil
	}

	// Build Package structs describing:
	//	ptest - package + test files
	//	pxtest - package of external test files
	//	pmain - pkg.test binary
	var ptest, pxtest, pmain *Package

	var imports, ximports []*Package
	var stk importStack
	stk.push(p.ImportPath + "_test")
	for _, path := range p.TestImports {
		p1 := loadImport(path, p.Dir, &stk, p.build.TestImportPos[path])
		if p1.Error != nil {
			return nil, nil, nil, p1.Error
		}
		imports = append(imports, p1)
	}
	for _, path := range p.XTestImports {
		if path == p.ImportPath {
			continue
		}
		p1 := loadImport(path, p.Dir, &stk, p.build.XTestImportPos[path])
		if p1.Error != nil {
			return nil, nil, nil, p1.Error
		}
		ximports = append(ximports, p1)
	}
	stk.pop()

	// Use last element of import path, not package name.
	// They differ when package name is "main".
	// But if the import path is "command-line-arguments",
	// like it is during 'go run', use the package name.
	var elem string
	if p.ImportPath == "command-line-arguments" {
		elem = p.Name
	} else {
		_, elem = path.Split(p.ImportPath)
	}
	testBinary := elem + ".test"

	// The ptest package needs to be importable under the
	// same import path that p has, but we cannot put it in
	// the usual place in the temporary tree, because then
	// other tests will see it as the real package.
	// Instead we make a _test directory under the import path
	// and then repeat the import path there.  We tell the
	// compiler and linker to look in that _test directory first.
	//
	// That is, if the package under test is unicode/utf8,
	// then the normal place to write the package archive is
	// $WORK/unicode/utf8.a, but we write the test package archive to
	// $WORK/unicode/utf8/_test/unicode/utf8.a.
	// We write the external test package archive to
	// $WORK/unicode/utf8/_test/unicode/utf8_test.a.
	testDir := filepath.Join(b.work, filepath.FromSlash(p.ImportPath+"/_test"))
	ptestObj := buildToolchain.pkgpath(testDir, p)

	// Create the directory for the .a files.
	ptestDir, _ := filepath.Split(ptestObj)
	if err := b.mkdir(ptestDir); err != nil {
		return nil, nil, nil, err
	}

	// Should we apply coverage analysis locally,
	// only for this package and only for this test?
	// Yes, if -cover is on but -coverpkg has not specified
	// a list of packages for global coverage.
	localCover := testCover && testCoverPaths == nil

	// Test package.
	if len(p.TestGoFiles) > 0 || localCover || p.Name == "main" {
		ptest = new(Package)
		*ptest = *p
		ptest.GoFiles = nil
		ptest.GoFiles = append(ptest.GoFiles, p.GoFiles...)
		ptest.GoFiles = append(ptest.GoFiles, p.TestGoFiles...)
		ptest.target = ""
		ptest.Imports = stringList(p.Imports, p.TestImports)
		ptest.imports = append(append([]*Package{}, p.imports...), imports...)
		ptest.pkgdir = testDir
		ptest.fake = true
		ptest.forceLibrary = true
		ptest.Stale = true
		ptest.build = new(build.Package)
		*ptest.build = *p.build
		m := map[string][]token.Position{}
		for k, v := range p.build.ImportPos {
			m[k] = append(m[k], v...)
		}
		for k, v := range p.build.TestImportPos {
			m[k] = append(m[k], v...)
		}
		ptest.build.ImportPos = m

		if localCover {
			ptest.coverMode = testCoverMode
			var coverFiles []string
			coverFiles = append(coverFiles, ptest.GoFiles...)
			coverFiles = append(coverFiles, ptest.CgoFiles...)
			ptest.coverVars = declareCoverVars(ptest.ImportPath, coverFiles...)
		}
	} else {
		ptest = p
	}

	// External test package.
	if len(p.XTestGoFiles) > 0 {
		pxtest = &Package{
			Name:        p.Name + "_test",
			ImportPath:  p.ImportPath + "_test",
			localPrefix: p.localPrefix,
			Root:        p.Root,
			Dir:         p.Dir,
			GoFiles:     p.XTestGoFiles,
			Imports:     p.XTestImports,
			build: &build.Package{
				ImportPos: p.build.XTestImportPos,
			},
			imports: append(ximports, ptest),
			pkgdir:  testDir,
			fake:    true,
			Stale:   true,
		}
	}

	// Action for building pkg.test.
	pmain = &Package{
		Name:       "main",
		Dir:        testDir,
		GoFiles:    []string{"_testmain.go"},
		ImportPath: "testmain",
		Root:       p.Root,
		imports:    []*Package{ptest},
		build:      &build.Package{Name: "main"},
		pkgdir:     testDir,
		fake:       true,
		Stale:      true,
		omitDWARF:  !testC && !testNeedBinary,
	}
	if pxtest != nil {
		pmain.imports = append(pmain.imports, pxtest)
	}

	// The generated main also imports testing and regexp.
	stk.push("testmain")
	for dep := range testMainDeps {
		if ptest.ImportPath != dep {
			p1 := loadImport("testing", "", &stk, nil)
			if p1.Error != nil {
				return nil, nil, nil, p1.Error
			}
			pmain.imports = append(pmain.imports, p1)
		}
	}

	if testCoverPkgs != nil {
		// Add imports, but avoid duplicates.
		seen := map[*Package]bool{p: true, ptest: true}
		for _, p1 := range pmain.imports {
			seen[p1] = true
		}
		for _, p1 := range testCoverPkgs {
			if !seen[p1] {
				seen[p1] = true
				pmain.imports = append(pmain.imports, p1)
			}
		}
	}

	if ptest != p && localCover {
		// We have made modifications to the package p being tested
		// and are rebuilding p (as ptest), writing it to the testDir tree.
		// Arrange to rebuild, writing to that same tree, all packages q
		// such that the test depends on q, and q depends on p.
		// This makes sure that q sees the modifications to p.
		// Strictly speaking, the rebuild is only necessary if the
		// modifications to p change its export metadata, but
		// determining that is a bit tricky, so we rebuild always.
		//
		// This will cause extra compilation, so for now we only do it
		// when testCover is set. The conditions are more general, though,
		// and we may find that we need to do it always in the future.
		recompileForTest(pmain, p, ptest, testDir)
	}

	if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), pmain, ptest); err != nil {
		return nil, nil, nil, err
	}

	computeStale(pmain)

	if ptest != p {
		a := b.action(modeBuild, modeBuild, ptest)
		a.objdir = testDir + string(filepath.Separator) + "_obj_test" + string(filepath.Separator)
		a.objpkg = ptestObj
		a.target = ptestObj
		a.link = false
	}

	if pxtest != nil {
		a := b.action(modeBuild, modeBuild, pxtest)
		a.objdir = testDir + string(filepath.Separator) + "_obj_xtest" + string(filepath.Separator)
		a.objpkg = buildToolchain.pkgpath(testDir, pxtest)
		a.target = a.objpkg
	}

	a := b.action(modeBuild, modeBuild, pmain)
	a.objdir = testDir + string(filepath.Separator)
	a.objpkg = filepath.Join(testDir, "main.a")
	a.target = filepath.Join(testDir, testBinary) + exeSuffix
	pmainAction := a

	if testC || testNeedBinary {
		// -c or profiling flag: create action to copy binary to ./test.out.
		runAction = &action{
			f:      (*builder).install,
			deps:   []*action{pmainAction},
			p:      pmain,
			target: filepath.Join(cwd, testBinary+exeSuffix),
		}
		pmainAction = runAction // in case we are running the test
	}
	if testC {
		printAction = &action{p: p, deps: []*action{runAction}} // nop
	} else {
		// run test
		runAction = &action{
			f:          (*builder).runTest,
			deps:       []*action{pmainAction},
			p:          p,
			ignoreFail: true,
		}
		cleanAction := &action{
			f:    (*builder).cleanTest,
			deps: []*action{runAction},
			p:    p,
		}
		printAction = &action{
			f:    (*builder).printTest,
			deps: []*action{cleanAction},
			p:    p,
		}
	}

	return pmainAction, runAction, printAction, nil
}

func recompileForTest(pmain, preal, ptest *Package, testDir string) {
	// The "test copy" of preal is ptest.
	// For each package that depends on preal, make a "test copy"
	// that depends on ptest. And so on, up the dependency tree.
	testCopy := map[*Package]*Package{preal: ptest}
	for _, p := range packageList([]*Package{pmain}) {
		// Copy on write.
		didSplit := false
		split := func() {
			if didSplit {
				return
			}
			didSplit = true
			if p.pkgdir != testDir {
				p1 := new(Package)
				testCopy[p] = p1
				*p1 = *p
				p1.imports = make([]*Package, len(p.imports))
				copy(p1.imports, p.imports)
				p = p1
				p.pkgdir = testDir
				p.target = ""
				p.fake = true
				p.Stale = true
			}
		}

		// Update p.deps and p.imports to use at test copies.
		for i, dep := range p.deps {
			if p1 := testCopy[dep]; p1 != nil && p1 != dep {
				split()
				p.deps[i] = p1
			}
		}
		for i, imp := range p.imports {
			if p1 := testCopy[imp]; p1 != nil && p1 != imp {
				split()
				p.imports[i] = p1
			}
		}
	}
}

var coverIndex = 0

// isTestFile reports whether the source file is a set of tests and should therefore
// be excluded from coverage analysis.
func isTestFile(file string) bool {
	// We don't cover tests, only the code they test.
	return strings.HasSuffix(file, "_test.go")
}

// declareCoverVars attaches the required cover variables names
// to the files, to be used when annotating the files.
func declareCoverVars(importPath string, files ...string) map[string]*CoverVar {
	coverVars := make(map[string]*CoverVar)
	for _, file := range files {
		if isTestFile(file) {
			continue
		}
		coverVars[file] = &CoverVar{
			File: filepath.Join(importPath, file),
			Var:  fmt.Sprintf("GoCover_%d", coverIndex),
		}
		coverIndex++
	}
	return coverVars
}

// runTest is the action for running a test binary.
func (b *builder) runTest(a *action) error {
	args := stringList(findExecCmd(), a.deps[0].target, testArgs)
	a.testOutput = new(bytes.Buffer)

	if buildN || buildX {
		b.showcmd("", "%s", strings.Join(args, " "))
		if buildN {
			return nil
		}
	}

	if a.failed {
		// We were unable to build the binary.
		a.failed = false
		fmt.Fprintf(a.testOutput, "FAIL\t%s [build failed]\n", a.p.ImportPath)
		setExitStatus(1)
		return nil
	}

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = a.p.Dir
	cmd.Env = envForDir(cmd.Dir)
	var buf bytes.Buffer
	if testStreamOutput {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	} else {
		cmd.Stdout = &buf
		cmd.Stderr = &buf
	}

	// If there are any local SWIG dependencies, we want to load
	// the shared library from the build directory.
	if a.p.usesSwig() {
		env := cmd.Env
		found := false
		prefix := "LD_LIBRARY_PATH="
		for i, v := range env {
			if strings.HasPrefix(v, prefix) {
				env[i] = v + ":."
				found = true
				break
			}
		}
		if !found {
			env = append(env, "LD_LIBRARY_PATH=.")
		}
		cmd.Env = env
	}

	t0 := time.Now()
	err := cmd.Start()

	// This is a last-ditch deadline to detect and
	// stop wedged test binaries, to keep the builders
	// running.
	if err == nil {
		tick := time.NewTimer(testKillTimeout)
		startSigHandlers()
		done := make(chan error)
		go func() {
			done <- cmd.Wait()
		}()
	Outer:
		select {
		case err = <-done:
			// ok
		case <-tick.C:
			if signalTrace != nil {
				// Send a quit signal in the hope that the program will print
				// a stack trace and exit. Give it five seconds before resorting
				// to Kill.
				cmd.Process.Signal(signalTrace)
				select {
				case err = <-done:
					fmt.Fprintf(&buf, "*** Test killed with %v: ran too long (%v).\n", signalTrace, testKillTimeout)
					break Outer
				case <-time.After(5 * time.Second):
				}
			}
			cmd.Process.Kill()
			err = <-done
			fmt.Fprintf(&buf, "*** Test killed: ran too long (%v).\n", testKillTimeout)
		}
		tick.Stop()
	}
	out := buf.Bytes()
	t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())
	if err == nil {
		if testShowPass {
			a.testOutput.Write(out)
		}
		fmt.Fprintf(a.testOutput, "ok  \t%s\t%s%s\n", a.p.ImportPath, t, coveragePercentage(out))
		return nil
	}

	setExitStatus(1)
	if len(out) > 0 {
		a.testOutput.Write(out)
		// assume printing the test binary's exit status is superfluous
	} else {
		fmt.Fprintf(a.testOutput, "%s\n", err)
	}
	fmt.Fprintf(a.testOutput, "FAIL\t%s\t%s\n", a.p.ImportPath, t)

	return nil
}

// coveragePercentage returns the coverage results (if enabled) for the
// test. It uncovers the data by scanning the output from the test run.
func coveragePercentage(out []byte) string {
	if !testCover {
		return ""
	}
	// The string looks like
	//	test coverage for encoding/binary: 79.9% of statements
	// Extract the piece from the percentage to the end of the line.
	re := regexp.MustCompile(`coverage: (.*)\n`)
	matches := re.FindSubmatch(out)
	if matches == nil {
		// Probably running "go test -cover" not "go test -cover fmt".
		// The coverage output will appear in the output directly.
		return ""
	}
	return fmt.Sprintf("\tcoverage: %s", matches[1])
}

// cleanTest is the action for cleaning up after a test.
func (b *builder) cleanTest(a *action) error {
	if buildWork {
		return nil
	}
	run := a.deps[0]
	testDir := filepath.Join(b.work, filepath.FromSlash(run.p.ImportPath+"/_test"))
	os.RemoveAll(testDir)
	return nil
}

// printTest is the action for printing a test result.
func (b *builder) printTest(a *action) error {
	clean := a.deps[0]
	run := clean.deps[0]
	os.Stdout.Write(run.testOutput.Bytes())
	run.testOutput = nil
	return nil
}

// notest is the action for testing a package with no test files.
func (b *builder) notest(a *action) error {
	fmt.Printf("?   \t%s\t[no test files]\n", a.p.ImportPath)
	return nil
}

// isTest tells whether name looks like a test (or benchmark, according to prefix).
// It is a Test (say) if there is a character after Test that is not a lower-case letter.
// We don't want TesticularCancer.
func isTest(name, prefix string) bool {
	if !strings.HasPrefix(name, prefix) {
		return false
	}
	if len(name) == len(prefix) { // "Test" is ok
		return true
	}
	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
	return !unicode.IsLower(rune)
}

type coverInfo struct {
	Package *Package
	Vars    map[string]*CoverVar
}

// writeTestmain writes the _testmain.go file for package p to
// the file named out.
func writeTestmain(out string, pmain, p *Package) error {
	var cover []coverInfo
	for _, cp := range pmain.imports {
		if len(cp.coverVars) > 0 {
			cover = append(cover, coverInfo{cp, cp.coverVars})
		}
	}

	t := &testFuncs{
		Package: p,
		Cover:   cover,
	}
	for _, file := range p.TestGoFiles {
		if err := t.load(filepath.Join(p.Dir, file), "_test", &t.NeedTest); err != nil {
			return err
		}
	}
	for _, file := range p.XTestGoFiles {
		if err := t.load(filepath.Join(p.Dir, file), "_xtest", &t.NeedXtest); err != nil {
			return err
		}
	}

	f, err := os.Create(out)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := testmainTmpl.Execute(f, t); err != nil {
		return err
	}

	return nil
}

type testFuncs struct {
	Tests      []testFunc
	Benchmarks []testFunc
	Examples   []testFunc
	Package    *Package
	NeedTest   bool
	NeedXtest  bool
	Cover      []coverInfo
}

func (t *testFuncs) CoverMode() string {
	return testCoverMode
}

func (t *testFuncs) CoverEnabled() bool {
	return testCover
}

// Covered returns a string describing which packages are being tested for coverage.
// If the covered package is the same as the tested package, it returns the empty string.
// Otherwise it is a comma-separated human-readable list of packages beginning with
// " in", ready for use in the coverage message.
func (t *testFuncs) Covered() string {
	if testCoverPaths == nil {
		return ""
	}
	return " in " + strings.Join(testCoverPaths, ", ")
}

// Tested returns the name of the package being tested.
func (t *testFuncs) Tested() string {
	return t.Package.Name
}

type testFunc struct {
	Package string // imported package name (_test or _xtest)
	Name    string // function name
	Output  string // output, for examples
}

var testFileSet = token.NewFileSet()

func (t *testFuncs) load(filename, pkg string, seen *bool) error {
	f, err := parser.ParseFile(testFileSet, filename, nil, parser.ParseComments)
	if err != nil {
		return expandScanner(err)
	}
	for _, d := range f.Decls {
		n, ok := d.(*ast.FuncDecl)
		if !ok {
			continue
		}
		if n.Recv != nil {
			continue
		}
		name := n.Name.String()
		switch {
		case isTest(name, "Test"):
			t.Tests = append(t.Tests, testFunc{pkg, name, ""})
			*seen = true
		case isTest(name, "Benchmark"):
			t.Benchmarks = append(t.Benchmarks, testFunc{pkg, name, ""})
			*seen = true
		}
	}
	ex := doc.Examples(f)
	sort.Sort(byOrder(ex))
	for _, e := range ex {
		if e.Output == "" && !e.EmptyOutput {
			// Don't run examples with no output.
			continue
		}
		t.Examples = append(t.Examples, testFunc{pkg, "Example" + e.Name, e.Output})
		*seen = true
	}
	return nil
}

type byOrder []*doc.Example

func (x byOrder) Len() int           { return len(x) }
func (x byOrder) Swap(i, j int)      { x[i], x[j] = x[j], x[i] }
func (x byOrder) Less(i, j int) bool { return x[i].Order < x[j].Order }

var testmainTmpl = template.Must(template.New("main").Parse(`
package main

import (
	"regexp"
	"testing"

{{if .NeedTest}}
	_test {{.Package.ImportPath | printf "%q"}}
{{end}}
{{if .NeedXtest}}
	_xtest {{.Package.ImportPath | printf "%s_test" | printf "%q"}}
{{end}}
{{range $i, $p := .Cover}}
	_cover{{$i}} {{$p.Package.ImportPath | printf "%q"}}
{{end}}
)

var tests = []testing.InternalTest{
{{range .Tests}}
	{"{{.Name}}", {{.Package}}.{{.Name}}},
{{end}}
}

var benchmarks = []testing.InternalBenchmark{
{{range .Benchmarks}}
	{"{{.Name}}", {{.Package}}.{{.Name}}},
{{end}}
}

var examples = []testing.InternalExample{
{{range .Examples}}
	{"{{.Name}}", {{.Package}}.{{.Name}}, {{.Output | printf "%q"}}},
{{end}}
}

var matchPat string
var matchRe *regexp.Regexp

func matchString(pat, str string) (result bool, err error) {
	if matchRe == nil || matchPat != pat {
		matchPat = pat
		matchRe, err = regexp.Compile(matchPat)
		if err != nil {
			return
		}
	}
	return matchRe.MatchString(str), nil
}

{{if .CoverEnabled}}

// Only updated by init functions, so no need for atomicity.
var (
	coverCounters = make(map[string][]uint32)
	coverBlocks = make(map[string][]testing.CoverBlock)
)

func init() {
	{{range $i, $p := .Cover}}
	{{range $file, $cover := $p.Vars}}
	coverRegisterFile({{printf "%q" $cover.File}}, _cover{{$i}}.{{$cover.Var}}.Count[:], _cover{{$i}}.{{$cover.Var}}.Pos[:], _cover{{$i}}.{{$cover.Var}}.NumStmt[:])
	{{end}}
	{{end}}
}

func coverRegisterFile(fileName string, counter []uint32, pos []uint32, numStmts []uint16) {
	if 3*len(counter) != len(pos) || len(counter) != len(numStmts) {
		panic("coverage: mismatched sizes")
	}
	if coverCounters[fileName] != nil {
		// Already registered.
		return
	}
	coverCounters[fileName] = counter
	block := make([]testing.CoverBlock, len(counter))
	for i := range counter {
		block[i] = testing.CoverBlock{
			Line0: pos[3*i+0],
			Col0: uint16(pos[3*i+2]),
			Line1: pos[3*i+1],
			Col1: uint16(pos[3*i+2]>>16),
			Stmts: numStmts[i],
		}
	}
	coverBlocks[fileName] = block
}
{{end}}

func main() {
{{if .CoverEnabled}}
	testing.RegisterCover(testing.Cover{
		Mode: {{printf "%q" .CoverMode}},
		Counters: coverCounters,
		Blocks: coverBlocks,
		CoveredPackages: {{printf "%q" .Covered}},
	})
{{end}}
	testing.Main(matchString, tests, benchmarks, examples)
}

`))


text:
package jetstream_output

import "github.com/prometheus/client_golang/prometheus"

var jetStreamNumberOfSentMsgs = prometheus.NewCounterVec(prometheus.CounterOpts{
	Namespace: "gnmic",
	Subsystem: "jetstream_output",
	Name:      "number_of_jetstream_msgs_sent_success_total",
	Help:      "Number of msgs successfully sent by gnmic jetstream output",
}, []string{"publisher_id", "subject"})

var jetStreamNumberOfSentBytes = prometheus.NewCounterVec(prometheus.CounterOpts{
	Namespace: "gnmic",
	Subsystem: "jetstream_output",
	Name:      "number_of_written_jetstream_bytes_total",
	Help:      "Number of bytes written by gnmic jetstream output",
}, []string{"publisher_id", "subject"})

var jetStreamNumberOfFailSendMsgs = prometheus.NewCounterVec(prometheus.CounterOpts{
	Namespace: "gnmic",
	Subsystem: "jetstream_output",
	Name:      "number_of_jetstream_msgs_sent_fail_total",
	Help:      "Number of failed msgs sent by gnmic jetstream output",
}, []string{"publisher_id", "reason"})

var jetStreamSendDuration = prometheus.NewGaugeVec(prometheus.GaugeOpts{
	Namespace: "gnmic",
	Subsystem: "jetstream_output",
	Name:      "msg_send_duration_ns",
	Help:      "gnmic jetstream output send duration in ns",
}, []string{"publisher_id"})

func initMetrics() {
	jetStreamNumberOfSentMsgs.WithLabelValues("", "").Add(0)
	jetStreamNumberOfSentBytes.WithLabelValues("", "").Add(0)
	jetStreamNumberOfFailSendMsgs.WithLabelValues("", "").Add(0)
	jetStreamSendDuration.WithLabelValues("").Set(0)
}

func registerMetrics(reg *prometheus.Registry) error {
	initMetrics()
	var err error
	if err = reg.Register(jetStreamNumberOfSentMsgs); err != nil {
		return err
	}
	if err = reg.Register(jetStreamNumberOfSentBytes); err != nil {
		return err
	}
	if err = reg.Register(jetStreamNumberOfFailSendMsgs); err != nil {
		return err
	}
	if err = reg.Register(jetStreamSendDuration); err != nil {
		return err
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
import Vue from 'vue';
import { mapState } from 'vuex';

Vue.component('wifi-loading', {
    computed: mapState('guestWifi', {
        loading: function(state) {
            return state.loading;
        }
    }),
    template: `

                Loading Guest Wifi Status

    `
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Xaml;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.LanguageServices.Xaml.Features.AutoInsert;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler
{
    [ExportStatelessXamlLspService(typeof(OnAutoInsertHandler)), Shared]
    [Method(VSInternalMethods.OnAutoInsertName)]
    internal class OnAutoInsertHandler : ILspServiceRequestHandler<VSInternalDocumentOnAutoInsertParams, VSInternalDocumentOnAutoInsertResponseItem?>
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public OnAutoInsertHandler()
        {
        }

        public bool MutatesSolutionState => false;
        public bool RequiresLSPSolution => true;

        public TextDocumentIdentifier GetTextDocumentIdentifier(VSInternalDocumentOnAutoInsertParams request) => request.TextDocument;

        public async Task<VSInternalDocumentOnAutoInsertResponseItem?> HandleRequestAsync(VSInternalDocumentOnAutoInsertParams request, RequestContext context, CancellationToken cancellationToken)
        {
            var document = context.Document;
            if (document == null)
            {
                return null;
            }

            var insertService = document.Project.Services.GetService<IXamlAutoInsertService>();
            if (insertService == null)
            {
                return null;
            }

            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
            var offset = text.Lines.GetPosition(ProtocolConversions.PositionToLinePosition(request.Position));
            var result = await insertService.GetAutoInsertAsync(document, request.Character[0], offset, cancellationToken).ConfigureAwait(false);
            if (result == null)
            {
                return null;
            }

            Contract.ThrowIfNull(result.TextChange.NewText);
            var insertText = result.TextChange.NewText;
            var insertFormat = InsertTextFormat.Plaintext;
            if (result.CaretOffset.HasValue)
            {
                insertFormat = InsertTextFormat.Snippet;
                insertText = insertText.Insert(result.CaretOffset.Value, "$0");
            }

            return new VSInternalDocumentOnAutoInsertResponseItem
            {
                TextEditFormat = insertFormat,
                TextEdit = new TextEdit
                {
                    NewText = insertText,
                    Range = ProtocolConversions.TextSpanToRange(result.TextChange.Span, text)
                }
            };
        }
    }
}


text:
package org.docksidestage.hanger.dbflute.cbean;

import org.docksidestage.hanger.dbflute.cbean.bs.BsVendor$DollarCB;

/**
 * The condition-bean of VENDOR_$_DOLLAR.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class Vendor$DollarCB extends BsVendor$DollarCB {
}


text:
import { Observable } from 'rxjs/Observable';
import { UserStoryComponent } from './../user-story/user-story.component';
import { AngularFireAuth } from 'angularfire2/auth';
import { Game } from './../model/game';
import { UserGameService } from './../services/user-game.service';
import { GameService } from './../services/game.service';
import { Component, OnInit, Input, ViewChild, SimpleChanges } from '@angular/core';
import { Router } from "@angular/router";
import { ToastrService } from 'ngx-toastr';
import { GameComponent } from './../game/game.component';
import { ModalComponent } from "ng2-bs3-modal/components/modal";
import { Story } from 'app/model/story';
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-saved-games',
  templateUrl: './saved-games.component.html',
  styleUrls: ['./saved-games.component.css'],

})
export class SavedGamesComponent implements OnInit {
  @ViewChild(UserStoryComponent)
  UserStoryComponent: UserStoryComponent;
  storyToEdit: Story = new Story();
  game: Game = new Game();
  games: any[];
  currentUsersGame: boolean = false;
  gameSubscription: Subscription;

  constructor(private router: Router, private gameService: GameService, private usergameService: UserGameService, private toastrService: ToastrService, protected auth: AngularFireAuth) {
    console.log('we are in the constructor for saved games')

    // Brian's code before I "fixed" it ??
    //this.gameSubscription = this.gameService.getGames()
    //  .subscribe(gamesData => { this.games = gamesData.slice().reverse() });

    this.gameSubscription = this.usergameService.getUserGames()
      .subscribe(gamesData => { this.games = gamesData.slice().reverse() });

  }

  showSuccess() {
    this.toastrService.success('Hello world!', 'Toastr fun!');

  }

  deleteGame(game) {

    console.log("game to delete = ", game.name, game.$key);
    this.gameService.deleteGame(game.$key);
    this.usergameService.deleteUserGame(game.$key, this.auth.auth.currentUser.uid);

  }

  selectGame(game) {
    //this.gameService.createGame(this.newGame);
    this.router.navigate(['game', game.$key]);
    //this.gameService.addUserToGame(game.$key, this.auth.auth.currentUser.uid);
  }

  joinGame(game) {
    //this.gameService.addUserToGame(game.$key, this.auth.auth.currentUser.uid);
    console.log("game key: ", game.$key);
    this.router.navigate(['game', game.$key]);
  }

  addStories(game) {
    this.gameSubscription.unsubscribe();
    console.log("game name ", game.name);
    this.UserStoryComponent.open(game, this.storyToEdit, "AddFromCreateGame");
    this.UserStoryComponent.modal.onDismiss.subscribe(() => {
      this.gameSubscription = this.gameService.getGames()
        .subscribe(gamesData => { this.games = gamesData.slice().reverse() })
      console.log("getting games");
    });

  }

  // trackCreateDate(index, selectedGame) {
  //   //console.log(hero);
  //   return selectedGame ? selectedGame.createdDate : undefined;

  // }

  ngOnInit() {

  }

  // public ngOnChanges(changes: SimpleChanges): void {
  //   console.log('list changed', changes);
  //   this.games.reverse();
  // }

}


text:
package de.linearbits.jhpl.test;

import de.linearbits.jhpl.Lattice;
import de.linearbits.jhpl.PredictiveProperty;
import de.linearbits.jhpl.PredictiveProperty.Direction;

/**
 * Test class
 * @author Fabian Prasser
 *
 */
public class Test2 {

    /**
     * Main
     * @param args
     */
    public static void main(String[] args) {
        test2();
    }

    /**
     * Test method
     */
    private static void test2() {

        System.out.println("");
        System.out.println("**************************");
        System.out.println("* TEST    2              *");
        System.out.println("**************************");
        System.out.println("");

        // Elements per dimension
        String[][] elements = new String[][]{ {"A", "B", "C", "D"},
                                              {"A", "B"},
                                              {"A", "B", "C"}};

        // Create lattice with String-keys and Integer-values
        Lattice<String, Integer> lattice = new Lattice<String, Integer>(elements);

        // Store a predictive property
        PredictiveProperty property1 = new PredictiveProperty("Property1", Direction.UP);
        lattice.putProperty(lattice.nodes().getBottom(), property1);
        System.out.println(lattice.hasProperty(lattice.nodes().getTop(), property1));
        lattice.putProperty(lattice.nodes().build().next("B").next("B").next("C").create(), property1);
        System.out.println(lattice.hasProperty(lattice.nodes().build().next("B").next("B").next("B").create(), property1));
    }
}


text:
using System.Web.Mvc;

namespace Ext.Net.MVC.Examples.Areas.GridPanel_FilterHeader
{
    public class GridPanel_FilterHeaderAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "GridPanel_FilterHeader";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "GridPanel_FilterHeader_default",
                "GridPanel_FilterHeader/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


text:
package com.haskforce.psi.impl;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.haskforce.psi.HaskellTypes.*;
import com.haskforce.psi.*;

public class HaskellCtypeImpl extends HaskellCompositeElementImpl implements HaskellCtype {

  public HaskellCtypeImpl(ASTNode node) {
    super(node);
  }

  public void accept(@NotNull HaskellVisitor visitor) {
    visitor.visitCtype(this);
  }

  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof HaskellVisitor) accept((HaskellVisitor)visitor);
    else super.accept(visitor);
  }

  @Override
  @Nullable
  public HaskellClscontext getClscontext() {
    return PsiTreeUtil.getChildOfType(this, HaskellClscontext.class);
  }

  @Override
  @Nullable
  public HaskellCtype getCtype() {
    return PsiTreeUtil.getChildOfType(this, HaskellCtype.class);
  }

  @Override
  @NotNull
  public List<HaskellTvBndr> getTvBndrList() {
    return PsiTreeUtil.getChildrenOfTypeAsList(this, HaskellTvBndr.class);
  }

  @Override
  @Nullable
  public HaskellTypee getTypee() {
    return PsiTreeUtil.getChildOfType(this, HaskellTypee.class);
  }

  @Override
  @Nullable
  public PsiElement getForalltoken() {
    return findChildByType(FORALLTOKEN);
  }

  @Override
  @Nullable
  public PsiElement getDoublearrow() {
    return findChildByType(DOUBLEARROW);
  }

  @Override
  @Nullable
  public PsiElement getPeriod() {
    return findChildByType(PERIOD);
  }

}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BinanceConsoleApp.Controllers
{
    internal class GetAccountInfo : IHandleCommand
    {
        public async Task<bool> HandleAsync(string command, CancellationToken token = default)
        {
            if (!command.Equals("account", StringComparison.OrdinalIgnoreCase) &&
                !command.Equals("balances", StringComparison.OrdinalIgnoreCase))
                return false;

            if (Program.User == null)
            {
                Program.PrintApiNotice();
                return true;
            }

            var account = await Program.Api.GetAccountInfoAsync(Program.User, token: token);

            Program.Display(account);

            return true;
        }
    }
}


text:
class Sequence;
class SequenceGroup;

class GroupCmd: public Command
{
	public:

		GroupCmd(Project *,const QList<Sequence *> &,const QList<SequenceGroup*> &,const QColor &,const QString &);
		virtual ~GroupCmd();

		virtual void redo();
		virtual void undo();

	private:
		QList<Sequence *>  seqs_;
		QList<SequenceGroup *> mergeGroups_;
		SequenceGroup    *newGroup_;
		QColor groupColour_;
};

#endif


text:
package org.apache.sysml.test.integration.functions.codegen;

import java.io.File;
import java.util.HashMap;

import org.junit.Test;
import org.apache.sysml.api.DMLScript;
import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
import org.apache.sysml.hops.OptimizerUtils;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;

public class SumProductChainTest extends AutomatedTestBase
{
	private static final String TEST_NAME1 = "SumProductChain";
	private static final String TEST_NAME2 = "SumAdditionChain";
	private static final String TEST_DIR = "functions/codegen/";
	private static final String TEST_CLASS_DIR = TEST_DIR + SumProductChainTest.class.getSimpleName() + "/";
	private final static String TEST_CONF = "SystemML-config-codegen.xml";
	private final static File   TEST_CONF_FILE = new File(SCRIPT_DIR + TEST_DIR, TEST_CONF);

	private static final int rows = 1191;
	private static final int cols1 = 1;
	private static final int cols2 = 31;
	private static final double sparsity1 = 0.9;
	private static final double sparsity2 = 0.09;
	private static final double eps = Math.pow(10, -10);

	@Override
	public void setUp() {
		TestUtils.clearAssertionInformation();
		addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { "R" }) );
		addTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { "R" }) );
	}

	@Test
	public void testSumProductVectorsDense() {
		testSumProductChain( TEST_NAME1, true, false, false, ExecType.CP );
	}

	@Test
	public void testSumProductVectorsSparse() {
		testSumProductChain( TEST_NAME1, true, true, false, ExecType.CP );
	}

	@Test
	public void testSumProductMatrixDense() {
		testSumProductChain( TEST_NAME1, false, false, false, ExecType.CP );
	}

	@Test
	public void testSumProductMatrixSparse() {
		testSumProductChain( TEST_NAME1, false, true, false, ExecType.CP );
	}

	@Test
	public void testSumAdditionVectorsDense() {
		testSumProductChain( TEST_NAME2, true, false, false, ExecType.CP );
	}

	@Test
	public void testSumAdditionVectorsSparse() {
		testSumProductChain( TEST_NAME2, true, true, false, ExecType.CP );
	}

	@Test
	public void testSumAdditionMatrixDense() {
		testSumProductChain( TEST_NAME2, false, false, false, ExecType.CP );
	}

	@Test
	public void testSumAdditionMatrixSparse() {
		testSumProductChain( TEST_NAME2, false, true, false, ExecType.CP );
	}

	private void testSumProductChain(String testname, boolean vectors, boolean sparse, boolean rewrites, ExecType instType)
	{
		boolean oldRewrites = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;
		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
		RUNTIME_PLATFORM platformOld = setRuntimePlatform(instType);
		if(shouldSkipTest())
			return;

		try
		{
			OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites;

			TestConfiguration config = getTestConfiguration(testname);
			loadTestConfiguration(config);

			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + testname + ".dml";
			programArgs = new String[]{"-explain", "hops", "-stats",
					"-args", input("X"), output("R") };

			fullRScriptName = HOME + testname + ".R";
			rCmd = getRCmd(inputDir(), expectedDir());

			//generate input data
			int cols = vectors ? cols1 : cols2;
			double sparsity = sparse ? sparsity2 : sparsity1;
			double[][] X = getRandomMatrix(rows, cols, -1, 1, sparsity, 7);
			writeInputMatrixWithMTD("X", X, true);

			//run tests
			runTest(true, false, null, -1);
			runRScript(true);

			//compare matrices
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("R");
			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("R");
			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
			if( vectors || !sparse  )
				assertTrue(heavyHittersContainsSubString("spoofCell")
						|| heavyHittersContainsSubString("sp_spoofCell"));
		}
		finally {
			rtplatform = platformOld;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
			OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = oldRewrites;
			OptimizerUtils.ALLOW_AUTO_VECTORIZATION = true;
			OptimizerUtils.ALLOW_OPERATOR_FUSION = true;
		}
	}

	/**
	 * Override default configuration with custom test configuration to ensure
	 * scratch space and local temporary directory locations are also updated.
	 */
	@Override
	protected File getConfigTemplateFile() {
		// Instrumentation in this test's output log to show custom configuration file used for template.
		System.out.println("This test case overrides default configuration with " + TEST_CONF_FILE.getPath());
		return TEST_CONF_FILE;
	}
}


text:
import React,{Component} from 'react';
import {render} from 'react-dom';

// components
import SearchInput from './SearchInput.js';
import Header from './Header.js';

// css
import CommonCss from '../../css/common/common.scss';

//Main App Component
class App extends Component{

  constructor(props,context){
    super(props,context)
  }

    render(){
        return(
            <div>
                 <Header/>
                 <SearchInput/>

          </div>

        )
    }
}

export default App


text:
<?php

namespace im\cms\menu;

use yii\base\Object;

class MenuDescriptor extends Object implements MenuDescriptorInterface {

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

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

    /** @var array */
    private $_items;

    /**
     * @param string $id
     */
    public function setId($id)
    {
        $this->_id = $id;
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     * @param array $items
     */
    public function setItems($items)
    {
        $this->_items = $items;
    }

    /**
     * @return array
     */
    public function getItems()
    {
        return $this->_items;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->_name = $name;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }

    //    /**
//     * @var MenuProviderInterface|array|string the provider object or the configuration for creation the provider object.
//     */
//    private $provider;

}


text:
std::unique_ptr<WCHAR[]> GetWindowsError(ULONG error_code = GetLastError())
{
	auto msg = std::make_unique<WCHAR[]>(USHRT_MAX);
	if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr))
	{
		return msg;
	}
	return nullptr;
}
void PrintWindowsError(ULONG error_code = GetLastError())
{
	if (auto error_msg = GetWindowsError(error_code))
	{
		fprintf(stderr, "%ls\n", error_msg.get());
	}
}
int __cdecl wmain(int argc, PWSTR argv[])
{
	ATLENSURE(SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32));
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
	setlocale(LC_ALL, "");

	if (argc != 3)
	{
		fputs(
			"Copy file without actual data write.\n"
			"\n"
			"reflink source destination\n"
			"\n"
			"source       Specifies a file to copy.\n"
			"             source must have placed on the ReFS volume.\n"
			"destination  Specifies new file name.\n"
			"             destination must have placed on the same volume as source.\n",
			stderr
		);
		return EXIT_FAILURE;
	}
	if (!reflink(argv[1], argv[2]))
	{
		PrintWindowsError();
		return EXIT_FAILURE;
	}
}


text:
using System;
using System.ComponentModel.Design;
using System.Net.Mail;
using System.Xml;

using Carbonfrost.Commons.Shared;
using Carbonfrost.Commons.Shared.Runtime;
using NUnit.Framework;

namespace Tests.Runtime {

    [TestFixture]
    public class TypeReferenceTests {

        [Test]
        public void simple_name_resolves() {
            TypeReference tr = TypeReference.Parse("String");
            Assert.AreEqual(typeof(string), tr.Resolve());
        }

        [Test]
        public void builtin_identifiers_resolve() {
            TypeReference tr = TypeReference.Parse("uint");
            Assert.AreEqual(typeof(UInt32), tr.Resolve());

            tr = TypeReference.Parse("long");
            Assert.AreEqual(typeof(long), tr.Resolve());

            tr = TypeReference.Parse("decimal");
            Assert.AreEqual(typeof(decimal), tr.Resolve());
        }

        [Test]
	    public void resolve_type_from_type_nominal() {
	        TypeReference tr = TypeReference.FromType(typeof(int));
	        Assert.AreEqual(typeof(int), tr.Resolve());
	    }

        [Test]
        public void name_resolves_without_assembly() {
            TypeReference tr = TypeReference.Parse("System.Net.Mail.MailAddress");
            Assert.AreEqual(typeof(MailAddress), tr.Resolve());
        }

        [Test]
        public void qualified_name_resolves() {
            string fullName = string.Format("{{{0}}} TypeReference", Xmlns.SharedRuntime2008);

            TypeReference tr = TypeReference.Parse(fullName);
            Assert.AreEqual(typeof(TypeReference), tr.Resolve());
        }

        [Test]
        public void trivial_type_resolution() {
            TypeReference tr = TypeReference.FromType(typeof(int));
            Assert.AreEqual(typeof(int), tr.Resolve());
        }

        [Test]
        public void qualified_name_using_prefix_resolves() {
            ServiceContainer services = new ServiceContainer();
            XmlNameTable table = new NameTable();
            XmlNamespaceManager mgr = new XmlNamespaceManager(table);
            services.AddService(typeof(IXmlNamespaceResolver), mgr);
            mgr.AddNamespace("f", Xmlns.SharedRuntime2008);

            TypeReference tr = TypeReference.Parse("f:TypeReference", services);
            Assert.AreEqual(typeof(TypeReference), tr.Resolve());
        }

        [Test]
        public void default_qualified_name_using_prefix_resolves() {
            ServiceContainer services = new ServiceContainer();
            XmlNameTable table = new NameTable();
            XmlNamespaceManager mgr = new XmlNamespaceManager(table);
            services.AddService(typeof(IXmlNamespaceResolver), mgr);
            mgr.AddNamespace("", Xmlns.SharedRuntime2008);

            TypeReference tr = TypeReference.Parse(":TypeReference", services);
            Assert.AreEqual(typeof(TypeReference), tr.Resolve());
        }

        [Test]
        public void missing_type_should_throw() {
            TypeReference tr = TypeReference.Parse("System.Glob");
            Assert.Throws(typeof(InvalidOperationException), () => tr.Resolve());
        }

        [Test]
        public void missing_type_should_return_null() {
            TypeReference tr = TypeReference.Parse("System.Glob");
            Assert.That(tr.TryResolve(), Is.Null);
        }
    }
}


text:
package com.alibaba.nacos.core.remote.control;

/**
 * MonitorType.
 *
 * @author liuzunfei
 * @version $Id: ClientIpMonitorKey.java, v 0.1 2021年01月20日 20:38 PM liuzunfei Exp $
 */
public class ClientIpMonitorKey extends MonitorKey {

    private static final String TYPE =  "clientIp";

    public ClientIpMonitorKey() {

    }

    public ClientIpMonitorKey(String clientIp) {
        this.key = clientIp;
    }

    @Override
    public String getType() {
        return TYPE;
    }

}


text:
"use strict";

var Vow = require( "vow" );

module.exports = function( grunt ) {

    var filter = Array.prototype.filter,
        JSCS = require( "./lib/jscs" ).init( grunt );

    grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() {
        var done = this.async(),
            options = this.options(),

            // either if it was configured with that option or passed through cli command
            force = grunt.option( "force" ) || options.force,
            jscs = new JSCS( options ),
            checks = this.filesSrc.map(function( path ) {
                return jscs.check( path );
            });

        grunt.option( "force", force );

        Vow.allResolved( checks ).spread(function() {

            // Filter unsuccessful promises
            var results = filter.call( arguments, function( promise ) {
                return promise.isFulfilled();

            // Make array of errors
            }).map(function( promise ) {
                return promise.valueOf()[ 0 ];
            });

            jscs.setErrors( results ).report().notify();

            done( !jscs.count() );
        });
    });
};


text:
'use strict';
var chai = require('chai'),
  gulp = require('gulp'),
  expect = chai.expect;

var casing = require('./../slush/casing');

describe('casing-utilities', function () {
  describe('camel', function () {

    it('should camel case a string', function () {

      var input = 'I.am a.string-woot',
        output = 'i.amA.string-woot',
        operation = 'camel';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });

  describe('kebab', function () {
    it('should kebab case a string', function () {

      var input = 'I am a string',
        output = 'i-am-a-string',
        operation = 'kebab';

      expect(casing[operation](input))
        .to
        .eql(output);

    });
  });

  describe('folder', function () {
    it('should folder case a string', function () {

      var input = 'I.am a.string',
        output = 'i/am-a/string',
        operation = 'folder';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });

  describe('var', function () {
    it('should var case a string', function () {

      var input = 'I.am a.string',
        output = 'iAmAString',
        operation = 'var';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });
  describe('varName', function () {
    it('should folder case a string', function () {

      var input = 'I.am a.string',
        output = 'string',
        operation = 'varName';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });
  describe('classify', function () {
    it('should folder case a string', function () {

      var input = 'I.am a.string',
        output = 'i-am-a-string',
        operation = 'classify';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });
  describe('folderName', function () {
    it('should folder case a string', function () {

      var input = 'I.am a.string',
        output = 'string',
        operation = 'folderName';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });
  describe('snake', function () {
    it('should folder case a string', function () {

      var input = 'I.am a.string',
        output = 'i_am_a_string',
        operation = 'snake';

      expect(casing[operation](input))
        .to
        .eql(output);
    });
  });

});


text:
/*
 * Dynamic To Top Plugin
 * http://www.mattvarone.com
 *
 * By Matt Varone
 * @sksmatt
 *
 */
var mv_dynamic_to_top;
(function ($, mv_dynamic_to_top) {
    jQuery.fn.DynamicToTop = function (options) {
        var defaults = {
            text: mv_dynamic_to_top.text,
            min: parseInt(mv_dynamic_to_top.min, 10),
            fade_in: 600,
            fade_out: 400,
            speed: parseInt(mv_dynamic_to_top.speed, 10),
            easing: mv_dynamic_to_top.easing,
            version: mv_dynamic_to_top.version,
            id: 'dynamic-to-top'
        },
		settings = $.extend(defaults, options);
		if (settings.version === "" || settings.version === '0') {
            settings.text = ' ';
        }
        if ( ! $.isFunction(settings.easing) ) {
            settings.easing = 'linear';
        }
        var $toTop = $('').html(settings.text);
        $toTop.hide().appendTo('body').click(function () {
            $('html, body').stop().animate({
                scrollTop: 0
            }, settings.speed, settings.easing);
            return false;
        });
        $(window).scroll(function () {
            var sd = jQuery(window).scrollTop();
            if (typeof document.body.style.maxHeight === "undefined") {
                $toTop.css({
                    'position': 'absolute',
                    'top': sd + $(window).height() - mv_dynamic_to_top.margin
                });
            }
            if (sd > settings.min) {
                $toTop.fadeIn(settings.fade_in);
            } else {
                $toTop.fadeOut(settings.fade_out);
            }
        });
    };
    $('body').DynamicToTop();
})(jQuery, mv_dynamic_to_top);


text:
var gameId = "cosmics";
var cosmicsGame;
var frameNr = 0;
var fps = 50;
var groups = new Array('bgs', 'heros', 'floor', 'spectators', 'invaders', 'invaderbombs', 'sweepers', 'rockets', 'meteors', 'herobullets', 'fires','game');
var paused = false;
var suspended = false;
var muted = false;

var timeoutWarningMsg = "The planet is under attack! Press fire and start playing to prevent timeout.";
var timeoutMsg1 = "Timeout! Sorry, you are suspended as hero.";
var timeoutMsg2 = "Press reload to inline as spectator or try mission training.";

var dos = false;
var dosMsg = "You reloaded too often. Wait a little and try again to inline as spectator.";

var gameSize = new Array(640, 512);
var battlegroundSize = new Array(640, 480);
var fontSize = new Array(8,8);
var floorPieceSize = new Array (32, 64);
var nrFloorPieces = parseInt (gameSize[0] / floorPieceSize[0]);
var spectatorSize = new Array (9, 14);
var meteorSize = new Array (32,64);
var heroSize = new Array (32, 32);
var bulletSize = new Array (10, 20);
var invaderSize = new Array(32, 32);
var bombSize = new Array (10,20);
var rocketSize = new Array (32,32);
var sweeperSize = new Array (32,32);
var ammoSize = new Array(10,10);
var balloonSize = new Array (16,16);
var fireSize = new Array (8,4);
var nrFires = 80;

var heroId = "abc";
var heroLives = 3;
var heroScore = 0;

var enterHighscore = false;
var highscoreName = "             ";
var highscoreEnterPos = 0;
var highscoreRank = "unkown...";

var plsReload = false;

var clientContext;
var criticalHeight = gameSize[1] - floorPieceSize[1] - heroSize[1] - (heroSize[1] / 2);
//-----------------------------------------------------------------------------------
// animation data
var heroFrames = 4; // nr of frames for anim
var heroAnimSpeed = 10; // after this nr of frames the anim will move (game runs with 50 fps)
var heroGhostAnimSpeed = 5;
var heroExplodeAnimSpeed = 10;
var heroJumpAnimSpeed = 5;

var spectatorFrames = 4;
var spectatorAnimSpeed = 3;
var spectatorJumpAnimSpeed = 5;
var spectatorExplodeAnimSpeed = 20;

var balloonsPerSpectator = 20;
var balloonFrames = 4;
var balloonSpeed = 0.5;
var balloonInflateAnimSpeed = 15;
var balloonFlyAnimSpeed = 8;
var balloonExplodeAnimSpeed = 8;
var balloonMaxHeight = -balloonSize[1];

var fireFrames = 10;
var fireAnimSpeed = 10;
var burnFrames = 100;

var meteorFrames = 4;
var meteorAnimSpeed = 8;
var meteorExplodeAnimSpeed = 10;

var invaderFrames = 4;
var invaderAnimSpeed = 10;
var invaderExplodeAnimSpeed = 4;

//(bomb from invaders)
var bombFrames = 4;
var bombAnimSpeed = 5;// (normal and exploding)
var bombExplodeAnimSpeed = 5;

//(the enemy rocket from left or right)
var rocketFrames = 4;
var rocketAnimSpeed = 8;
var rocketExplodeAnimSpeed = 10;

// sweeper
var sweeperFrames = 4;
var sweeperStalkAnimSpeed = 15;  // in air (and queing back)
var sweeperSwarmAnimSpeed = 6; // greifing an
var sweeperFireAnimSpeed = 12; // firing
var sweeperExplodeAnimSpeed = 6; // exploding

// (the shoots from the sweeper)
var ammoFrames = 2;
var ammoAnimSpeed = 15;
var ammoExplodeAnimSpeed = 10;
// end animation data
//-----------------------------------------------------------------------------------
var modalFlashMinTime = 2;
var modalFlashMinFrames = modalFlashMinTime * fps;
var modalFlashStartFrame = null;
var breakMaxTime = 9;
var breakMaxFrames = breakMaxTime * fps;
var breakStartFrame = null;

var pointsBomb = 20;
var pointsAmmo = 20;
var pointsInvader = 60;
var pointsInvaderMultiplier = 1;
var pointsMeteor = 100;
var pointsSweeper = 130;
var pointsRocket = 250;

// these three could make up a planet gravity
var heroJumpHeight = 36;
var heroJumpSpeed = 3;
var heroFallFromJumpSpeed = 0.75;
//-----------------------------------------------------------------------------------
// variable level data
var nrBullets = 3;  // shooting frequency

var maxNrMeteors;
var meteorSpeed;
var nextMeteorPause ; // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
var meteorsFlip;
var meteorNoFlipHeight; // from this height on the meteors do no more flip

var maxNrRockets;
var nextRocketPause; // in seconds
var rocketAirSpeed;
var rocketGroundSpeed;

var nrInvaders;
var nrInvaderRows;
var invaderGapSize;
var invaderDownstepSize;
var invaderSpeedupAt; // remaining invaders needed for speed up

var bombSpeed;
var bombEach;  // a next bomb will be thrown each given seconds

// there are 13 possible sweeperSlots (for each row)
var sweeperSlots = new Array({x:0, y:0}, {x: 1.5 * sweeperSize[0], y:0},
                             {x: 3 * sweeperSize[0], y:0}, {x: 4.5 * sweeperSize[0], y:0},
                             {x: 6 * sweeperSize[0], y:0}, {x: 7.5 * sweeperSize[0], y:0},
                             {x: 9 * sweeperSize[0], y:0}, {x: 10.5 * sweeperSize[0], y:0},
                             {x: 12 * sweeperSize[0], y:0}, {x: 13.5 * sweeperSize[0], y:0},
                             {x: 15 * sweeperSize[0], y:0}, {x: 16.5 * sweeperSize[0], y:0},
                             {x: 18 * sweeperSize[0], y:0});
var maxNrSweepers;  // nr sweeepers
// this array should have the size of max Nr Sweepers and couldn't be bigger than sweeperSlots, it determines the used slot for each sweeper
var usedSweeperSlots;
var sweeperSpeed;
var nextSweeperPause;  // pause till next sweeper swarms out
var ammoPerSweeper;  // ammo per sweeper at one time on the screen
var sweeperFireFrequency; // secs between each ammo
var sweeperFireStateLength; // the length of the fire state of a sweeper in secs
var sweeperAmmoSpeedMultiple;

var curLevel = 1;  // dont use 0 here
var levelSlogans = [
    "", // not existent
    "welcome aboard", // 1
    "meteors approaching",
    "squids approaching", // 3
    "global attack",
    "sweepers approaching", // 5
    "global attack two",
    "super high fire frequency bonus", // 7
    "fear of sweepers", // 8
    "global attack three",
    "its springtime",  // 10
    "midnight shower",
    "global attack four", // 12
    "rainy day",
    "omnisweepers",  // 14
    "super high fire frequency bonus 2" // 15
];
var floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
//------------------------------------------------------------------------------------------------------------------------
function getLevelSlogan(nr) {
    if (nr >= levelSlogans.length) {
        return "global attack "+(nr-11);
    }
    else {
        return levelSlogans[nr];
    }
}
//------------------------------------------------------------------------------------------------------------------------
function initLevel(nr) {
    paused = false;
    modalFlashStartFrame = null;
    breakStartFrame = null;
    cosmicsGame.hud.redraw();

    switch (nr) {
        default: // generate more and more
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = maxNrRockets + 1;
            nextRocketPause = nextRocketPause - 1;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = maxNrMeteors+1;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 48;
            nrInvaderRows = 6;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 3;
            bombEach = bombEach / 2;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 3;
            usedSweeperSlots = new Array(3,5,7);
            sweeperSpeed = 3;
            nextSweeperPause = nextSweeperPause - 1;
            ammoPerSweeper = ammoPerSweeper+1;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 3;
            break;

        case 16: // hard mixture generator start
            nrBullets = 3;

            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 2;
            nextRocketPause = 8;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 4;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 48;
            nrInvaderRows = 6;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 3;
            bombEach = 0.5;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 3;
            usedSweeperSlots = new Array(3,5,7);
            sweeperSpeed = 3;
            nextSweeperPause = 7;
            ammoPerSweeper = 3;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 3;
            break;

        case 15: // bonus fun 2
            nrBullets = 10;

            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 0;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 0;
            meteorSpeed = 3;
            nextMeteorPause = new Array(3,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 240;
            nrInvaderRows = 12;
            invaderGapSize = new Array(-4, -4);
            invaderDownstepSize = Math.floor(invaderSize[1] / 16);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(61,31,16,9,4,2);

            bombSpeed = 0;
            bombEach = 999999999999;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 9999999999999999;
            ammoPerSweeper = 3;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 14:  // omnisweepers
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 8;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 40;
            nrInvaderRows = 5;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 4;
            usedSweeperSlots = new Array(1,3,5,7);
            sweeperSpeed = 4;
            nextSweeperPause = 3;
            ammoPerSweeper = 10;
            sweeperFireFrequency = 0.1;
            sweeperFireStateLength = 3;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 13: // heavy bomb alarm
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 10;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 48;
            nrInvaderRows = 6;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 8);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(25, 14, 7, 4, 2);

            bombSpeed = 2;
            bombEach = 0.15;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 2;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 3;
            nextSweeperPause = 10;
            ammoPerSweeper = 3;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break

        case 12:  // mixture 4
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 2;
            nextRocketPause = 8;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 4;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,4); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 40;
            nrInvaderRows = 5;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 3;
            bombEach = 0.5;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 3;
            usedSweeperSlots = new Array(3,5,7);
            sweeperSpeed = 3;
            nextSweeperPause = 7;
            ammoPerSweeper = 3;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 3;
            break;

        case 11: //midnight shower
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 7;
            meteorSpeed = 4;
            nextMeteorPause = new Array(0.5,0.8); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 40;
            nrInvaderRows = 5;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 2;
            bombEach = 0.5;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 2;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 7;
            ammoPerSweeper = 2;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2.5;
            break;

        case 10: //jumpfest
            floorPiecesArr = [true,false,true,false,true,false,true,false,true,false,true,false,true,false,true,false,true,false,true,false];
            maxNrRockets = 5;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 0;
            meteorSpeed = 3;
            nextMeteorPause = new Array(3,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 40;
            nrInvaderRows = 5;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 3;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 3;
            nextSweeperPause = 99999999999999999999;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 9:  // mixture 3
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 2;
            nextRocketPause = 10;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 3;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 40;
            nrInvaderRows = 5;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(21, 11, 13, 9, 5, 4, 2);

            bombSpeed = 3;
            bombEach = 0.5;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 2;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 3;
            nextSweeperPause = 7;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 8:  // fear of sweepers
            nrBullets = 3;

            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 3;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 14;
            nrInvaderRows = 1;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 8), Math.floor(invaderSize[1] / 8));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 13;
            usedSweeperSlots = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12);
            sweeperSpeed = 2;
            nextSweeperPause = 3;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 7:  // bonus
            nrBullets = 10;

            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 0;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 0;
            meteorSpeed = 3;
            nextMeteorPause = new Array(3,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 120;
            nrInvaderRows = 8;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 8), Math.floor(invaderSize[1] / 8));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(61,31,16,9,4,2);

            bombSpeed = 0;
            bombEach = 999999999999;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 9999999999999999;
            ammoPerSweeper = 2;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 6:  // mixture two
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 32;
            nrInvaderRows = 4;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(17, 13, 9, 5, 4, 2);

            bombSpeed = 2;
            bombEach = 0.5;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 2;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 7;
            ammoPerSweeper = 3;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 5:  // sweeper first
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 0;
            nextRocketPause = 20;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 24;
            nrInvaderRows = 3;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(19, 13, 9, 5, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 4;
            usedSweeperSlots = new Array(1,3,5,7);
            sweeperSpeed = 3;
            nextSweeperPause = 4;
            ammoPerSweeper = 2;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 4;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 4:  // mixture one
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 1;
            nextRocketPause = 4;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(2,5); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 24;
            nrInvaderRows = 3;
            invaderGapSize = new Array(Math.floor(invaderSize[0] / 2), Math.floor(invaderSize[1] / 2));
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(19, 13, 9, 5, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 999999999999;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 3:  // intr rockets
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 2;
            nextRocketPause = 2;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 2;

            maxNrMeteors = 0;
            meteorSpeed = 3;
            nextMeteorPause = new Array (3,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = true;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 18;
            nrInvaderRows = 2;
            invaderGapSize = new Array(Math.floor(invaderSize[0]), Math.floor(invaderSize[1]) / 4);
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(9, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 999999999999;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 2: // intr meteors
            floorPiecesArr = [true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true];
            maxNrRockets = 0;
            nextRocketPause = 20;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 2;
            meteorSpeed = 3;
            nextMeteorPause = new Array(1,2); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = false;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 18;
            nrInvaderRows = 2;
            invaderGapSize = new Array(Math.floor(invaderSize[0]), Math.floor(invaderSize[1]) / 4);
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(9, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 999999999999;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 2;
            break;

        case 1:
            nrBullets = 3;

            floorPiecesArr = [true,true,true,true,true,false,true,true,true,true,true,true,true,true,false,true,true,true,true,true];
            maxNrRockets = 0;
            nextRocketPause = 20;
            rocketAirSpeed = 2;
            rocketGroundSpeed = 3;

            maxNrMeteors = 0;
            meteorSpeed = 3;
            nextMeteorPause = new Array (3,6); // pause in seconds until next meteor, one of this values is taken randomly for each next meteor
            meteorsFlip = false;
            meteorNoFlipHeight = meteorSize[1] * 4; // from this height on the meteors do no more flip

            nrInvaders = 18;
            nrInvaderRows = 2;
            invaderGapSize = new Array(Math.floor(invaderSize[0]), Math.floor(invaderSize[1]) / 4);
            invaderDownstepSize = Math.floor(invaderSize[1] / 4);
            // remaining invaders needed for speed up
            invaderSpeedupAt = new Array(9, 4, 2);

            bombSpeed = 2;
            bombEach = 1;  // a next bomb will be thrown each given seconds

            maxNrSweepers = 0;
            usedSweeperSlots = new Array(3,5);
            sweeperSpeed = 2;
            nextSweeperPause = 999999999999;
            ammoPerSweeper = 4;
            sweeperFireFrequency = 0.2;
            sweeperFireStateLength = 7;
            sweeperAmmoSpeedMultiple = 2;
            break;

    }
    cosmicsGame.hud.setValue('level', 'value', curLevel+": "+getLevelSlogan(curLevel));
}


text: require File.dirname(__FILE__) + '/lib/validates_email_with_smtp'


text:
package com.google.errorprone.bugpatterns.nullness.testdata;

import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

public class UnsoundGenericMethod {
  public interface Marker {}

  public interface Converter<T extends Marker> {
    List<?> convert(T input);
  }

  // error below can be avoided here with "class Impl<T extends Marker> ..."
  private static class Impl<T> implements Function<T, List<?>> {
    private final Stream<Converter<? super T>> cs;

    private Impl(Stream<Converter<? super T>> cs) {
      this.cs = cs;
    }

    @Override
    public List<?> apply(T input) {
      // BUG: Diagnostic contains: Unsafe wildcard in inferred type argument
      return cs.map(c -> new Wrap<>(c).handle(input)).collect(toList());
    }
  }

  private static class Wrap<T extends Marker> {
    Wrap(Converter<? super T> unused) {}

    T handle(T input) {
      return input;
    }
  }

  public static void main(String... args) {
    // BUG: Diagnostic contains: impossible
    new Impl<>(Stream.of(null, null)).apply("boom");
  }
}