text:
import { TestBed, ComponentFixture, tick, fakeAsync } from '@angular/core/testing';
import { Component } from '@angular/core';
import { createGenericTestComponent, selectElements, dispatchKeyboardEvent } from '../../../test/util';
import { NglCarouselModule } from './module';
import { LEFT_ARROW, RIGHT_ARROW } from '@angular/cdk/keycodes';

const createTestComponent = (html?: string, detectChanges?: boolean) =>
  createGenericTestComponent(TestComponent, html, detectChanges) as ComponentFixture<TestComponent>;

function getPlayButton(element: HTMLElement): HTMLInputElement {
  return element.querySelector('.slds-carousel__autoplay > button');
}

function getImages(element: HTMLElement): HTMLElement[] {
  return selectElements(element, '.slds-carousel__panel');
}

function getIndicators(element: HTMLElement): HTMLElement[] {
  return selectElements(element, '.slds-carousel__indicator-action');
}

function expectActive(element: HTMLElement, index: number) {

  const panelsEl = element.querySelector('.slds-carousel__panels') as HTMLDivElement;
  expect(panelsEl.style.transform).toEqual(`translateX(${-index * 100}%)`);

  const images = getImages(element);
  images.forEach((image, i) => {
    expect(image.getAttribute('aria-hidden')).toEqual(`${index !== i}`);
  });

  const indicators = getIndicators(element);
  indicators.forEach((indicator, i) => {
    expect(indicator.getAttribute('aria-selected')).toEqual(`${index === i}`);
    expect(indicator.getAttribute('tabindex')).toEqual(`${index === i ? 0 : -1}`);
  });
}

describe('`NglCarousel`', () => {

  beforeEach(() => TestBed.configureTestingModule({ declarations: [TestComponent], imports: [NglCarouselModule] }));

  it('should render correctly', () => {
    const fixture = createTestComponent();
    const { nativeElement } = fixture;

    expect(nativeElement.firstElementChild).toHaveCssClass('slds-carousel');

    expect(getPlayButton(nativeElement)).toBeTruthy();

    const images = getImages(nativeElement);
    const indicators = getIndicators(nativeElement);
    expect(images.length).toBe(3);
    expect(indicators.length).toBe(3);
    for (let i = 0; i < 3; i++) {
      expect(images[i].getAttribute('aria-labelledby')).toEqual(indicators[i].getAttribute('id'));
      expect(images[i].getAttribute('id')).toEqual(indicators[i].getAttribute('aria-controls'));
    }
  });

  it('should display activate image based on input', () => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    expectActive(nativeElement, 0);

    componentInstance.active = 1;
    fixture.detectChanges();
    expectActive(nativeElement, 1);
  });

  it('should display next image after default time', fakeAsync(() => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    expectActive(nativeElement, 0);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    tick(5000);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(1);
  }));

  it('should activate with keyboard', () => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    const indicatorsEl = nativeElement.querySelector('.slds-carousel__indicators');

    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    dispatchKeyboardEvent(indicatorsEl, 'keydown', LEFT_ARROW);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(2);

    dispatchKeyboardEvent(indicatorsEl, 'keydown', RIGHT_ARROW);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(1);
  });

  it('should activate by clicking indicators', () => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    const indicators = getIndicators(nativeElement);

    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    // Do not notify for clicking already active indicator
    indicators[0].click();
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    indicators[2].click();
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(2);

    indicators[1].click();
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(1);
  });

  it('should not cycle images if no `autoRefresh`', () => {
    const fixture = createTestComponent(`
      <ngl-carousel [active]="active" (activeChange)="onActiveChange($event)" autoRefresh="false">
        <ngl-carousel-image *ngFor="let i of images" [src]="i.src" [header]="i.header" [description]="i.desc" [alternativeText]="i.alt"></ngl-carousel-image>
      </ngl-carousel>
    `);
    const { componentInstance, nativeElement } = fixture;

    const indicatorsEl = nativeElement.querySelector('.slds-carousel__indicators');

    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    dispatchKeyboardEvent(indicatorsEl, 'keydown', LEFT_ARROW);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    componentInstance.active = 2;
    fixture.detectChanges();
    dispatchKeyboardEvent(indicatorsEl, 'keydown', RIGHT_ARROW);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
  });

  it('should not display next images if no `autoScroll`', fakeAsync(() => {
    const fixture = createTestComponent(`
      <ngl-carousel [active]="active" (activeChange)="onActiveChange($event)" autoScroll="false">
        <ngl-carousel-image *ngFor="let i of images" [src]="i.src" [header]="i.header" [description]="i.desc" [alternativeText]="i.alt"></ngl-carousel-image>
      </ngl-carousel>
    `);
    const { componentInstance, nativeElement } = fixture;

    expectActive(nativeElement, 0);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    tick(5000);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
  }));

  it('should reset timer when active changes', fakeAsync(() => {
    const fixture = createTestComponent();
    const { componentInstance } = fixture;

    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    tick(2000);

    componentInstance.active = 1;
    fixture.detectChanges();
    tick(3000);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    tick(2000);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(2);
  }));

  it('should reset timer when duration changes', fakeAsync(() => {
    const fixture = createTestComponent(`
      <ngl-carousel [active]="active" (activeChange)="onActiveChange($event)" [scrollDuration]="duration">
        <ngl-carousel-image *ngFor="let i of images" [src]="i.src" [header]="i.header" [description]="i.desc" [alternativeText]="i.alt"></ngl-carousel-image>
      </ngl-carousel>
    `, false);
    const { componentInstance } = fixture;
    componentInstance.duration = 5000;
    fixture.detectChanges();

    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    tick(2000);

    componentInstance.duration = 10;
    fixture.detectChanges();
    tick(3000);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    tick(7000);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(1);
  }));

  it('should start/pause auto-play using button', fakeAsync(() => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    const button = getPlayButton(nativeElement);
    expect(button.getAttribute('aria-pressed')).toBe('false');
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();
    tick(2000);

    button.click();
    fixture.detectChanges();
    expect(button.getAttribute('aria-pressed')).toBe('true');
    tick(3000);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    button.click();
    fixture.detectChanges();
    expect(button.getAttribute('aria-pressed')).toBe('false');
    tick(2000);
    expect(componentInstance.onActiveChange).not.toHaveBeenCalled();

    tick(3000);
    expect(componentInstance.onActiveChange).toHaveBeenCalledWith(1);
  }));

  it('should move focus to active indicator', () => {
    const fixture = createTestComponent();
    const { componentInstance, nativeElement } = fixture;

    const indicators = getIndicators(nativeElement);
    indicators[0].focus();
    expect(document.activeElement).toBe(indicators[0]);

    componentInstance.active = 1;
    fixture.detectChanges();
    expect(document.activeElement).toBe(indicators[1]);
  });

});

@Component({
  template: `
    <ngl-carousel [active]="active" (activeChange)="onActiveChange($event)">
      <ngl-carousel-image *ngFor="let i of images" [src]="i.src" [header]="i.header" [description]="i.desc" [alternativeText]="i.alt"></ngl-carousel-image>
    </ngl-carousel>
  `,
})
export class TestComponent {
  active: number;
  autoScroll: boolean;
  autoRefresh: boolean;
  duration: number;

  images = [
    { src: 'assets/images/carousel/carousel-01.jpg', header: 'First', desc: 'First description', alt: 'Alt First' },
    { src: 'assets/images/carousel/carousel-02.jpg', header: 'Second', desc: 'Second description', alt: 'Alt Second' },
    { src: 'assets/images/carousel/carousel-03.jpg', header: 'Third', desc: 'Third description', alt: 'Alt Third' },
  ];

  onActiveChange: jasmine.Spy = jasmine.createSpy();
}


text:
package exec_test

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"internal/poll"
	"internal/testenv"
	"io"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"testing"
	"time"
)

func helperCommandContext(t *testing.T, ctx context.Context, s ...string) (cmd *exec.Cmd) {
	testenv.MustHaveExec(t)

	cs := []string{"-test.run=TestHelperProcess", "--"}
	cs = append(cs, s...)
	if ctx != nil {
		cmd = exec.CommandContext(ctx, os.Args[0], cs...)
	} else {
		cmd = exec.Command(os.Args[0], cs...)
	}
	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
	return cmd
}

func helperCommand(t *testing.T, s ...string) *exec.Cmd {
	return helperCommandContext(t, nil, s...)
}

func TestEcho(t *testing.T) {
	bs, err := helperCommand(t, "echo", "foo bar", "baz").Output()
	if err != nil {
		t.Errorf("echo: %v", err)
	}
	if g, e := string(bs), "foo bar baz\n"; g != e {
		t.Errorf("echo: want %q, got %q", e, g)
	}
}

func TestCommandRelativeName(t *testing.T) {
	testenv.MustHaveExec(t)

	// Run our own binary as a relative path
	// (e.g. "_test/exec.test") our parent directory.
	base := filepath.Base(os.Args[0]) // "exec.test"
	dir := filepath.Dir(os.Args[0])   // "/tmp/go-buildNNNN/os/exec/_test"
	if dir == "." {
		t.Skip("skipping; running test at root somehow")
	}
	parentDir := filepath.Dir(dir) // "/tmp/go-buildNNNN/os/exec"
	dirBase := filepath.Base(dir)  // "_test"
	if dirBase == "." {
		t.Skipf("skipping; unexpected shallow dir of %q", dir)
	}

	cmd := exec.Command(filepath.Join(dirBase, base), "-test.run=TestHelperProcess", "--", "echo", "foo")
	cmd.Dir = parentDir
	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}

	out, err := cmd.Output()
	if err != nil {
		t.Errorf("echo: %v", err)
	}
	if g, e := string(out), "foo\n"; g != e {
		t.Errorf("echo: want %q, got %q", e, g)
	}
}

func TestCatStdin(t *testing.T) {
	// Cat, testing stdin and stdout.
	input := "Input string\nLine 2"
	p := helperCommand(t, "cat")
	p.Stdin = strings.NewReader(input)
	bs, err := p.Output()
	if err != nil {
		t.Errorf("cat: %v", err)
	}
	s := string(bs)
	if s != input {
		t.Errorf("cat: want %q, got %q", input, s)
	}
}

func TestEchoFileRace(t *testing.T) {
	cmd := helperCommand(t, "echo")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		t.Fatalf("StdinPipe: %v", err)
	}
	if err := cmd.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}
	wrote := make(chan bool)
	go func() {
		defer close(wrote)
		fmt.Fprint(stdin, "echo\n")
	}()
	if err := cmd.Wait(); err != nil {
		t.Fatalf("Wait: %v", err)
	}
	<-wrote
}

func TestCatGoodAndBadFile(t *testing.T) {
	// Testing combined output and error values.
	bs, err := helperCommand(t, "cat", "/bogus/file.foo", "exec_test.go").CombinedOutput()
	if _, ok := err.(*exec.ExitError); !ok {
		t.Errorf("expected *exec.ExitError from cat combined; got %T: %v", err, err)
	}
	s := string(bs)
	sp := strings.SplitN(s, "\n", 2)
	if len(sp) != 2 {
		t.Fatalf("expected two lines from cat; got %q", s)
	}
	errLine, body := sp[0], sp[1]
	if !strings.HasPrefix(errLine, "Error: open /bogus/file.foo") {
		t.Errorf("expected stderr to complain about file; got %q", errLine)
	}
	if !strings.Contains(body, "func TestHelperProcess(t *testing.T)") {
		t.Errorf("expected test code; got %q (len %d)", body, len(body))
	}
}

func TestNoExistExecutable(t *testing.T) {
	// Can't run a non-existent executable
	err := exec.Command("/no-exist-executable").Run()
	if err == nil {
		t.Error("expected error from /no-exist-executable")
	}
}

func TestExitStatus(t *testing.T) {
	// Test that exit values are returned correctly
	cmd := helperCommand(t, "exit", "42")
	err := cmd.Run()
	want := "exit status 42"
	switch runtime.GOOS {
	case "plan9":
		want = fmt.Sprintf("exit status: '%s %d: 42'", filepath.Base(cmd.Path), cmd.ProcessState.Pid())
	}
	if werr, ok := err.(*exec.ExitError); ok {
		if s := werr.Error(); s != want {
			t.Errorf("from exit 42 got exit %q, want %q", s, want)
		}
	} else {
		t.Fatalf("expected *exec.ExitError from exit 42; got %T: %v", err, err)
	}
}

func TestExitCode(t *testing.T) {
	// Test that exit code are returned correctly
	cmd := helperCommand(t, "exit", "42")
	cmd.Run()
	want := 42
	if runtime.GOOS == "plan9" {
		want = 1
	}
	got := cmd.ProcessState.ExitCode()
	if want != got {
		t.Errorf("ExitCode got %d, want %d", got, want)
	}

	cmd = helperCommand(t, "/no-exist-executable")
	cmd.Run()
	want = 2
	if runtime.GOOS == "plan9" {
		want = 1
	}
	got = cmd.ProcessState.ExitCode()
	if want != got {
		t.Errorf("ExitCode got %d, want %d", got, want)
	}

	cmd = helperCommand(t, "exit", "255")
	cmd.Run()
	want = 255
	if runtime.GOOS == "plan9" {
		want = 1
	}
	got = cmd.ProcessState.ExitCode()
	if want != got {
		t.Errorf("ExitCode got %d, want %d", got, want)
	}

	cmd = helperCommand(t, "cat")
	cmd.Run()
	want = 0
	got = cmd.ProcessState.ExitCode()
	if want != got {
		t.Errorf("ExitCode got %d, want %d", got, want)
	}

	// Test when command does not call Run().
	cmd = helperCommand(t, "cat")
	want = -1
	got = cmd.ProcessState.ExitCode()
	if want != got {
		t.Errorf("ExitCode got %d, want %d", got, want)
	}
}

func TestPipes(t *testing.T) {
	check := func(what string, err error) {
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
	}
	// Cat, testing stdin and stdout.
	c := helperCommand(t, "pipetest")
	stdin, err := c.StdinPipe()
	check("StdinPipe", err)
	stdout, err := c.StdoutPipe()
	check("StdoutPipe", err)
	stderr, err := c.StderrPipe()
	check("StderrPipe", err)

	outbr := bufio.NewReader(stdout)
	errbr := bufio.NewReader(stderr)
	line := func(what string, br *bufio.Reader) string {
		line, _, err := br.ReadLine()
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
		return string(line)
	}

	err = c.Start()
	check("Start", err)

	_, err = stdin.Write([]byte("O:I am output\n"))
	check("first stdin Write", err)
	if g, e := line("first output line", outbr), "O:I am output"; g != e {
		t.Errorf("got %q, want %q", g, e)
	}

	_, err = stdin.Write([]byte("E:I am error\n"))
	check("second stdin Write", err)
	if g, e := line("first error line", errbr), "E:I am error"; g != e {
		t.Errorf("got %q, want %q", g, e)
	}

	_, err = stdin.Write([]byte("O:I am output2\n"))
	check("third stdin Write 3", err)
	if g, e := line("second output line", outbr), "O:I am output2"; g != e {
		t.Errorf("got %q, want %q", g, e)
	}

	stdin.Close()
	err = c.Wait()
	check("Wait", err)
}

const stdinCloseTestString = "Some test string."

// Issue 6270.
func TestStdinClose(t *testing.T) {
	check := func(what string, err error) {
		if err != nil {
			t.Fatalf("%s: %v", what, err)
		}
	}
	cmd := helperCommand(t, "stdinClose")
	stdin, err := cmd.StdinPipe()
	check("StdinPipe", err)
	// Check that we can access methods of the underlying os.File.`
	if _, ok := stdin.(interface {
		Fd() uintptr
	}); !ok {
		t.Error("can't access methods of underlying *os.File")
	}
	check("Start", cmd.Start())
	go func() {
		_, err := io.Copy(stdin, strings.NewReader(stdinCloseTestString))
		check("Copy", err)
		// Before the fix, this next line would race with cmd.Wait.
		check("Close", stdin.Close())
	}()
	check("Wait", cmd.Wait())
}

// Issue 17647.
// It used to be the case that TestStdinClose, above, would fail when
// run under the race detector. This test is a variant of TestStdinClose
// that also used to fail when run under the race detector.
// This test is run by cmd/dist under the race detector to verify that
// the race detector no longer reports any problems.
func TestStdinCloseRace(t *testing.T) {
	cmd := helperCommand(t, "stdinClose")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		t.Fatalf("StdinPipe: %v", err)
	}
	if err := cmd.Start(); err != nil {
		t.Fatalf("Start: %v", err)
	}
	go func() {
		// We don't check the error return of Kill. It is
		// possible that the process has already exited, in
		// which case Kill will return an error "process
		// already finished". The purpose of this test is to
		// see whether the race detector reports an error; it
		// doesn't matter whether this Kill succeeds or not.
		cmd.Process.Kill()
	}()
	go func() {
		// Send the wrong string, so that the child fails even
		// if the other goroutine doesn't manage to kill it first.
		// This test is to check that the race detector does not
		// falsely report an error, so it doesn't matter how the
		// child process fails.
		io.Copy(stdin, strings.NewReader("unexpected string"))
		if err := stdin.Close(); err != nil {
			t.Errorf("stdin.Close: %v", err)
		}
	}()
	if err := cmd.Wait(); err == nil {
		t.Fatalf("Wait: succeeded unexpectedly")
	}
}

// Issue 5071
func TestPipeLookPathLeak(t *testing.T) {
	// If we are reading from /proc/self/fd we (should) get an exact result.
	tolerance := 0

	// Reading /proc/self/fd is more reliable than calling lsof, so try that
	// first.
	numOpenFDs := func() (int, []byte, error) {
		fds, err := ioutil.ReadDir("/proc/self/fd")
		if err != nil {
			return 0, nil, err
		}
		return len(fds), nil, nil
	}
	want, before, err := numOpenFDs()
	if err != nil {
		// We encountered a problem reading /proc/self/fd (we might be on
		// a platform that doesn't have it). Fall back onto lsof.
		t.Logf("using lsof because: %v", err)
		numOpenFDs = func() (int, []byte, error) {
			// Android's stock lsof does not obey the -p option,
			// so extra filtering is needed.
			// https://golang.org/issue/10206
			if runtime.GOOS == "android" {
				// numOpenFDsAndroid handles errors itself and
				// might skip or fail the test.
				n, lsof := numOpenFDsAndroid(t)
				return n, lsof, nil
			}
			lsof, err := exec.Command("lsof", "-b", "-n", "-p", strconv.Itoa(os.Getpid())).Output()
			return bytes.Count(lsof, []byte("\n")), lsof, err
		}

		// lsof may see file descriptors associated with the fork itself,
		// so we allow some extra margin if we have to use it.
		// https://golang.org/issue/19243
		tolerance = 5

		// Retry reading the number of open file descriptors.
		want, before, err = numOpenFDs()
		if err != nil {
			t.Log(err)
			t.Skipf("skipping test; error finding or running lsof")
		}
	}

	for i := 0; i < 6; i++ {
		cmd := exec.Command("something-that-does-not-exist-executable")
		cmd.StdoutPipe()
		cmd.StderrPipe()
		cmd.StdinPipe()
		if err := cmd.Run(); err == nil {
			t.Fatal("unexpected success")
		}
	}
	got, after, err := numOpenFDs()
	if err != nil {
		// numOpenFDs has already succeeded once, it should work here.
		t.Errorf("unexpected failure: %v", err)
	}
	if got-want > tolerance {
		t.Errorf("number of open file descriptors changed: got %v, want %v", got, want)
		if before != nil {
			t.Errorf("before:\n%v\n", before)
		}
		if after != nil {
			t.Errorf("after:\n%v\n", after)
		}
	}
}

func numOpenFDsAndroid(t *testing.T) (n int, lsof []byte) {
	raw, err := exec.Command("lsof").Output()
	if err != nil {
		t.Skip("skipping test; error finding or running lsof")
	}

	// First find the PID column index by parsing the first line, and
	// select lines containing pid in the column.
	pid := []byte(strconv.Itoa(os.Getpid()))
	pidCol := -1

	s := bufio.NewScanner(bytes.NewReader(raw))
	for s.Scan() {
		line := s.Bytes()
		fields := bytes.Fields(line)
		if pidCol < 0 {
			for i, v := range fields {
				if bytes.Equal(v, []byte("PID")) {
					pidCol = i
					break
				}
			}
			lsof = append(lsof, line...)
			continue
		}
		if bytes.Equal(fields[pidCol], pid) {
			lsof = append(lsof, '\n')
			lsof = append(lsof, line...)
		}
	}
	if pidCol < 0 {
		t.Fatal("error processing lsof output: unexpected header format")
	}
	if err := s.Err(); err != nil {
		t.Fatalf("error processing lsof output: %v", err)
	}
	return bytes.Count(lsof, []byte("\n")), lsof
}

var testedAlreadyLeaked = false

// basefds returns the number of expected file descriptors
// to be present in a process at start.
// stdin, stdout, stderr, epoll/kqueue, maybe testlog
func basefds() uintptr {
	n := os.Stderr.Fd() + 1
	// The poll (epoll/kqueue) descriptor can be numerically
	// either between stderr and the testlog-fd, or after
	// testlog-fd.
	if poll.IsPollDescriptor(n) {
		n++
	}
	for _, arg := range os.Args {
		if strings.HasPrefix(arg, "-test.testlogfile=") {
			n++
		}
	}
	return n
}

func closeUnexpectedFds(t *testing.T, m string) {
	for fd := basefds(); fd <= 101; fd++ {
		if poll.IsPollDescriptor(fd) {
			continue
		}
		err := os.NewFile(fd, "").Close()
		if err == nil {
			t.Logf("%s: Something already leaked - closed fd %d", m, fd)
		}
	}
}

func TestExtraFilesFDShuffle(t *testing.T) {
	t.Skip("flaky test; see https://golang.org/issue/5780")
	switch runtime.GOOS {
	case "darwin":
		// TODO(cnicolaou): https://golang.org/issue/2603
		// leads to leaked file descriptors in this test when it's
		// run from a builder.
		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
	case "netbsd":
		// https://golang.org/issue/3955
		closeUnexpectedFds(t, "TestExtraFilesFDShuffle")
	case "windows":
		t.Skip("no operating system support; skipping")
	}

	// syscall.StartProcess maps all the FDs passed to it in
	// ProcAttr.Files (the concatenation of stdin,stdout,stderr and
	// ExtraFiles) into consecutive FDs in the child, that is:
	// Files{11, 12, 6, 7, 9, 3} should result in the file
	// represented by FD 11 in the parent being made available as 0
	// in the child, 12 as 1, etc.
	//
	// We want to test that FDs in the child do not get overwritten
	// by one another as this shuffle occurs. The original implementation
	// was buggy in that in some data dependent cases it would overwrite
	// stderr in the child with one of the ExtraFile members.
	// Testing for this case is difficult because it relies on using
	// the same FD values as that case. In particular, an FD of 3
	// must be at an index of 4 or higher in ProcAttr.Files and
	// the FD of the write end of the Stderr pipe (as obtained by
	// StderrPipe()) must be the same as the size of ProcAttr.Files;
	// therefore we test that the read end of this pipe (which is what
	// is returned to the parent by StderrPipe() being one less than
	// the size of ProcAttr.Files, i.e. 3+len(cmd.ExtraFiles).
	//
	// Moving this test case around within the overall tests may
	// affect the FDs obtained and hence the checks to catch these cases.
	npipes := 2
	c := helperCommand(t, "extraFilesAndPipes", strconv.Itoa(npipes+1))
	rd, wr, _ := os.Pipe()
	defer rd.Close()
	if rd.Fd() != 3 {
		t.Errorf("bad test value for test pipe: fd %d", rd.Fd())
	}
	stderr, _ := c.StderrPipe()
	wr.WriteString("_LAST")
	wr.Close()

	pipes := make([]struct {
		r, w *os.File
	}, npipes)
	data := []string{"a", "b"}

	for i := 0; i < npipes; i++ {
		r, w, err := os.Pipe()
		if err != nil {
			t.Fatalf("unexpected error creating pipe: %s", err)
		}
		pipes[i].r = r
		pipes[i].w = w
		w.WriteString(data[i])
		c.ExtraFiles = append(c.ExtraFiles, pipes[i].r)
		defer func() {
			r.Close()
			w.Close()
		}()
	}
	// Put fd 3 at the end.
	c.ExtraFiles = append(c.ExtraFiles, rd)

	stderrFd := int(stderr.(*os.File).Fd())
	if stderrFd != ((len(c.ExtraFiles) + 3) - 1) {
		t.Errorf("bad test value for stderr pipe")
	}

	expected := "child: " + strings.Join(data, "") + "_LAST"

	err := c.Start()
	if err != nil {
		t.Fatalf("Run: %v", err)
	}
	ch := make(chan string, 1)
	go func(ch chan string) {
		buf := make([]byte, 512)
		n, err := stderr.Read(buf)
		if err != nil {
			t.Errorf("Read: %s", err)
			ch <- err.Error()
		} else {
			ch <- string(buf[:n])
		}
		close(ch)
	}(ch)
	select {
	case m := <-ch:
		if m != expected {
			t.Errorf("Read: '%s' not '%s'", m, expected)
		}
	case <-time.After(5 * time.Second):
		t.Errorf("Read timedout")
	}
	c.Wait()
}

func TestExtraFiles(t *testing.T) {
	testenv.MustHaveExec(t)

	if runtime.GOOS == "windows" {
		t.Skipf("skipping test on %q", runtime.GOOS)
	}

	// Ensure that file descriptors have not already been leaked into
	// our environment.
	if !testedAlreadyLeaked {
		testedAlreadyLeaked = true
		closeUnexpectedFds(t, "TestExtraFiles")
	}

	// Force network usage, to verify the epoll (or whatever) fd
	// doesn't leak to the child,
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer ln.Close()

	// Make sure duplicated fds don't leak to the child.
	f, err := ln.(*net.TCPListener).File()
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()
	ln2, err := net.FileListener(f)
	if err != nil {
		t.Fatal(err)
	}
	defer ln2.Close()

	// Force TLS root certs to be loaded (which might involve
	// cgo), to make sure none of that potential C code leaks fds.
	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	// quiet expected TLS handshake error "remote error: bad certificate"
	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
	ts.StartTLS()
	defer ts.Close()
	_, err = http.Get(ts.URL)
	if err == nil {
		t.Errorf("success trying to fetch %s; want an error", ts.URL)
	}

	tf, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatalf("TempFile: %v", err)
	}
	defer os.Remove(tf.Name())
	defer tf.Close()

	const text = "Hello, fd 3!"
	_, err = tf.Write([]byte(text))
	if err != nil {
		t.Fatalf("Write: %v", err)
	}
	_, err = tf.Seek(0, io.SeekStart)
	if err != nil {
		t.Fatalf("Seek: %v", err)
	}

	c := helperCommand(t, "read3")
	var stdout, stderr bytes.Buffer
	c.Stdout = &stdout
	c.Stderr = &stderr
	c.ExtraFiles = []*os.File{tf}
	err = c.Run()
	if err != nil {
		t.Fatalf("Run: %v; stdout %q, stderr %q", err, stdout.Bytes(), stderr.Bytes())
	}
	if stdout.String() != text {
		t.Errorf("got stdout %q, stderr %q; want %q on stdout", stdout.String(), stderr.String(), text)
	}
}

func TestExtraFilesRace(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("no operating system support; skipping")
	}
	listen := func() net.Listener {
		ln, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			t.Fatal(err)
		}
		return ln
	}
	listenerFile := func(ln net.Listener) *os.File {
		f, err := ln.(*net.TCPListener).File()
		if err != nil {
			t.Fatal(err)
		}
		return f
	}
	runCommand := func(c *exec.Cmd, out chan<- string) {
		bout, err := c.CombinedOutput()
		if err != nil {
			out <- "ERROR:" + err.Error()
		} else {
			out <- string(bout)
		}
	}

	for i := 0; i < 10; i++ {
		la := listen()
		ca := helperCommand(t, "describefiles")
		ca.ExtraFiles = []*os.File{listenerFile(la)}
		lb := listen()
		cb := helperCommand(t, "describefiles")
		cb.ExtraFiles = []*os.File{listenerFile(lb)}
		ares := make(chan string)
		bres := make(chan string)
		go runCommand(ca, ares)
		go runCommand(cb, bres)
		if got, want := <-ares, fmt.Sprintf("fd3: listener %s\n", la.Addr()); got != want {
			t.Errorf("iteration %d, process A got:\n%s\nwant:\n%s\n", i, got, want)
		}
		if got, want := <-bres, fmt.Sprintf("fd3: listener %s\n", lb.Addr()); got != want {
			t.Errorf("iteration %d, process B got:\n%s\nwant:\n%s\n", i, got, want)
		}
		la.Close()
		lb.Close()
		for _, f := range ca.ExtraFiles {
			f.Close()
		}
		for _, f := range cb.ExtraFiles {
			f.Close()
		}

	}
}

// TestHelperProcess isn't a real test. It's used as a helper process
// for TestParameterRun.
func TestHelperProcess(*testing.T) {
	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
		return
	}
	defer os.Exit(0)

	// Determine which command to use to display open files.
	ofcmd := "lsof"
	switch runtime.GOOS {
	case "dragonfly", "freebsd", "netbsd", "openbsd":
		ofcmd = "fstat"
	case "plan9":
		ofcmd = "/bin/cat"
	case "aix":
		ofcmd = "procfiles"
	}

	args := os.Args
	for len(args) > 0 {
		if args[0] == "--" {
			args = args[1:]
			break
		}
		args = args[1:]
	}
	if len(args) == 0 {
		fmt.Fprintf(os.Stderr, "No command\n")
		os.Exit(2)
	}

	cmd, args := args[0], args[1:]
	switch cmd {
	case "echo":
		iargs := []interface{}{}
		for _, s := range args {
			iargs = append(iargs, s)
		}
		fmt.Println(iargs...)
	case "echoenv":
		for _, s := range args {
			fmt.Println(os.Getenv(s))
		}
		os.Exit(0)
	case "cat":
		if len(args) == 0 {
			io.Copy(os.Stdout, os.Stdin)
			return
		}
		exit := 0
		for _, fn := range args {
			f, err := os.Open(fn)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error: %v\n", err)
				exit = 2
			} else {
				defer f.Close()
				io.Copy(os.Stdout, f)
			}
		}
		os.Exit(exit)
	case "pipetest":
		bufr := bufio.NewReader(os.Stdin)
		for {
			line, _, err := bufr.ReadLine()
			if err == io.EOF {
				break
			} else if err != nil {
				os.Exit(1)
			}
			if bytes.HasPrefix(line, []byte("O:")) {
				os.Stdout.Write(line)
				os.Stdout.Write([]byte{'\n'})
			} else if bytes.HasPrefix(line, []byte("E:")) {
				os.Stderr.Write(line)
				os.Stderr.Write([]byte{'\n'})
			} else {
				os.Exit(1)
			}
		}
	case "stdinClose":
		b, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		if s := string(b); s != stdinCloseTestString {
			fmt.Fprintf(os.Stderr, "Error: Read %q, want %q", s, stdinCloseTestString)
			os.Exit(1)
		}
		os.Exit(0)
	case "read3": // read fd 3
		fd3 := os.NewFile(3, "fd3")
		bs, err := ioutil.ReadAll(fd3)
		if err != nil {
			fmt.Printf("ReadAll from fd 3: %v", err)
			os.Exit(1)
		}
		switch runtime.GOOS {
		case "dragonfly":
			// TODO(jsing): Determine why DragonFly is leaking
			// file descriptors...
		case "darwin":
			// TODO(bradfitz): broken? Sometimes.
			// https://golang.org/issue/2603
			// Skip this additional part of the test for now.
		case "netbsd":
			// TODO(jsing): This currently fails on NetBSD due to
			// the cloned file descriptors that result from opening
			// /dev/urandom.
			// https://golang.org/issue/3955
		case "illumos", "solaris":
			// TODO(aram): This fails on Solaris because libc opens
			// its own files, as it sees fit. Darwin does the same,
			// see: https://golang.org/issue/2603
		default:
			// Now verify that there are no other open fds.
			var files []*os.File
			for wantfd := basefds() + 1; wantfd <= 100; wantfd++ {
				if poll.IsPollDescriptor(wantfd) {
					continue
				}
				f, err := os.Open(os.Args[0])
				if err != nil {
					fmt.Printf("error opening file with expected fd %d: %v", wantfd, err)
					os.Exit(1)
				}
				if got := f.Fd(); got != wantfd {
					fmt.Printf("leaked parent file. fd = %d; want %d\n", got, wantfd)
					var args []string
					switch runtime.GOOS {
					case "plan9":
						args = []string{fmt.Sprintf("/proc/%d/fd", os.Getpid())}
					case "aix":
						args = []string{fmt.Sprint(os.Getpid())}
					default:
						args = []string{"-p", fmt.Sprint(os.Getpid())}
					}
					out, _ := exec.Command(ofcmd, args...).CombinedOutput()
					fmt.Print(string(out))
					os.Exit(1)
				}
				files = append(files, f)
			}
			for _, f := range files {
				f.Close()
			}
		}
		// Referring to fd3 here ensures that it is not
		// garbage collected, and therefore closed, while
		// executing the wantfd loop above. It doesn't matter
		// what we do with fd3 as long as we refer to it;
		// closing it is the easy choice.
		fd3.Close()
		os.Stdout.Write(bs)
	case "exit":
		n, _ := strconv.Atoi(args[0])
		os.Exit(n)
	case "describefiles":
		f := os.NewFile(3, fmt.Sprintf("fd3"))
		ln, err := net.FileListener(f)
		if err == nil {
			fmt.Printf("fd3: listener %s\n", ln.Addr())
			ln.Close()
		}
		os.Exit(0)
	case "extraFilesAndPipes":
		n, _ := strconv.Atoi(args[0])
		pipes := make([]*os.File, n)
		for i := 0; i < n; i++ {
			pipes[i] = os.NewFile(uintptr(3+i), strconv.Itoa(i))
		}
		response := ""
		for i, r := range pipes {
			ch := make(chan string, 1)
			go func(c chan string) {
				buf := make([]byte, 10)
				n, err := r.Read(buf)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Child: read error: %v on pipe %d\n", err, i)
					os.Exit(1)
				}
				c <- string(buf[:n])
				close(c)
			}(ch)
			select {
			case m := <-ch:
				response = response + m
			case <-time.After(5 * time.Second):
				fmt.Fprintf(os.Stderr, "Child: Timeout reading from pipe: %d\n", i)
				os.Exit(1)
			}
		}
		fmt.Fprintf(os.Stderr, "child: %s", response)
		os.Exit(0)
	case "exec":
		cmd := exec.Command(args[1])
		cmd.Dir = args[0]
		output, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Child: %s %s", err, string(output))
			os.Exit(1)
		}
		fmt.Printf("%s", string(output))
		os.Exit(0)
	case "lookpath":
		p, err := exec.LookPath(args[0])
		if err != nil {
			fmt.Fprintf(os.Stderr, "LookPath failed: %v\n", err)
			os.Exit(1)
		}
		fmt.Print(p)
		os.Exit(0)
	case "stderrfail":
		fmt.Fprintf(os.Stderr, "some stderr text\n")
		os.Exit(1)
	case "sleep":
		time.Sleep(3 * time.Second)
		os.Exit(0)
	default:
		fmt.Fprintf(os.Stderr, "Unknown command %q\n", cmd)
		os.Exit(2)
	}
}

type delayedInfiniteReader struct{}

func (delayedInfiniteReader) Read(b []byte) (int, error) {
	time.Sleep(100 * time.Millisecond)
	for i := range b {
		b[i] = 'x'
	}
	return len(b), nil
}

// Issue 9173: ignore stdin pipe writes if the program completes successfully.
func TestIgnorePipeErrorOnSuccess(t *testing.T) {
	testenv.MustHaveExec(t)

	// We really only care about testing this on Unixy and Windowsy things.
	if runtime.GOOS == "plan9" {
		t.Skipf("skipping test on %q", runtime.GOOS)
	}

	testWith := func(r io.Reader) func(*testing.T) {
		return func(t *testing.T) {
			cmd := helperCommand(t, "echo", "foo")
			var out bytes.Buffer
			cmd.Stdin = r
			cmd.Stdout = &out
			if err := cmd.Run(); err != nil {
				t.Fatal(err)
			}
			if got, want := out.String(), "foo\n"; got != want {
				t.Errorf("output = %q; want %q", got, want)
			}
		}
	}
	t.Run("10MB", testWith(strings.NewReader(strings.Repeat("x", 10<<20))))
	t.Run("Infinite", testWith(delayedInfiniteReader{}))
}

type badWriter struct{}

func (w *badWriter) Write(data []byte) (int, error) {
	return 0, io.ErrUnexpectedEOF
}

func TestClosePipeOnCopyError(t *testing.T) {
	testenv.MustHaveExec(t)

	if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
		t.Skipf("skipping test on %s - no yes command", runtime.GOOS)
	}
	cmd := exec.Command("yes")
	cmd.Stdout = new(badWriter)
	c := make(chan int, 1)
	go func() {
		err := cmd.Run()
		if err == nil {
			t.Errorf("yes completed successfully")
		}
		c <- 1
	}()
	select {
	case <-c:
		// ok
	case <-time.After(5 * time.Second):
		t.Fatalf("yes got stuck writing to bad writer")
	}
}

func TestOutputStderrCapture(t *testing.T) {
	testenv.MustHaveExec(t)

	cmd := helperCommand(t, "stderrfail")
	_, err := cmd.Output()
	ee, ok := err.(*exec.ExitError)
	if !ok {
		t.Fatalf("Output error type = %T; want ExitError", err)
	}
	got := string(ee.Stderr)
	want := "some stderr text\n"
	if got != want {
		t.Errorf("ExitError.Stderr = %q; want %q", got, want)
	}
}

func TestContext(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	c := helperCommandContext(t, ctx, "pipetest")
	stdin, err := c.StdinPipe()
	if err != nil {
		t.Fatal(err)
	}
	stdout, err := c.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	if err := c.Start(); err != nil {
		t.Fatal(err)
	}

	if _, err := stdin.Write([]byte("O:hi\n")); err != nil {
		t.Fatal(err)
	}
	buf := make([]byte, 5)
	n, err := io.ReadFull(stdout, buf)
	if n != len(buf) || err != nil || string(buf) != "O:hi\n" {
		t.Fatalf("ReadFull = %d, %v, %q", n, err, buf[:n])
	}
	waitErr := make(chan error, 1)
	go func() {
		waitErr <- c.Wait()
	}()
	cancel()
	select {
	case err := <-waitErr:
		if err == nil {
			t.Fatal("expected Wait failure")
		}
	case <-time.After(3 * time.Second):
		t.Fatal("timeout waiting for child process death")
	}
}

func TestContextCancel(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	c := helperCommandContext(t, ctx, "cat")

	r, w, err := os.Pipe()
	if err != nil {
		t.Fatal(err)
	}
	c.Stdin = r

	stdout, err := c.StdoutPipe()
	if err != nil {
		t.Fatal(err)
	}
	readDone := make(chan struct{})
	go func() {
		defer close(readDone)
		var a [1024]byte
		for {
			n, err := stdout.Read(a[:])
			if err != nil {
				if err != io.EOF {
					t.Errorf("unexpected read error: %v", err)
				}
				return
			}
			t.Logf("%s", a[:n])
		}
	}()

	if err := c.Start(); err != nil {
		t.Fatal(err)
	}

	if err := r.Close(); err != nil {
		t.Fatal(err)
	}

	if _, err := io.WriteString(w, "echo"); err != nil {
		t.Fatal(err)
	}

	cancel()

	// Calling cancel should have killed the process, so writes
	// should now fail.  Give the process a little while to die.
	start := time.Now()
	for {
		if _, err := io.WriteString(w, "echo"); err != nil {
			break
		}
		if time.Since(start) > time.Second {
			t.Fatal("canceling context did not stop program")
		}
		time.Sleep(time.Millisecond)
	}

	if err := w.Close(); err != nil {
		t.Errorf("error closing write end of pipe: %v", err)
	}
	<-readDone

	if err := c.Wait(); err == nil {
		t.Error("program unexpectedly exited successfully")
	} else {
		t.Logf("exit status: %v", err)
	}
}

// test that environment variables are de-duped.
func TestDedupEnvEcho(t *testing.T) {
	testenv.MustHaveExec(t)

	cmd := helperCommand(t, "echoenv", "FOO")
	cmd.Env = append(cmd.Env, "FOO=bad", "FOO=good")
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	if got, want := strings.TrimSpace(string(out)), "good"; got != want {
		t.Errorf("output = %q; want %q", got, want)
	}
}

func TestString(t *testing.T) {
	echoPath, err := exec.LookPath("echo")
	if err != nil {
		t.Skip(err)
	}
	tests := [...]struct {
		path string
		args []string
		want string
	}{
		{"echo", nil, echoPath},
		{"echo", []string{"a"}, echoPath + " a"},
		{"echo", []string{"a", "b"}, echoPath + " a b"},
	}
	for _, test := range tests {
		cmd := exec.Command(test.path, test.args...)
		if got := cmd.String(); got != test.want {
			t.Errorf("String(%q, %q) = %q, want %q", test.path, test.args, got, test.want)
		}
	}
}

func TestStringPathNotResolved(t *testing.T) {
	_, err := exec.LookPath("makemeasandwich")
	if err == nil {
		t.Skip("wow, thanks")
	}
	cmd := exec.Command("makemeasandwich", "-lettuce")
	want := "makemeasandwich -lettuce"
	if got := cmd.String(); got != want {
		t.Errorf("String(%q, %q) = %q, want %q", "makemeasandwich", "-lettuce", got, want)
	}
}

// start a child process without the user code explicitly starting
// with a copy of the parent's. (The Windows SYSTEMROOT issue: Issue
// 25210)
func TestChildCriticalEnv(t *testing.T) {
	testenv.MustHaveExec(t)
	if runtime.GOOS != "windows" {
		t.Skip("only testing on Windows")
	}
	cmd := helperCommand(t, "echoenv", "SYSTEMROOT")
	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	if strings.TrimSpace(string(out)) == "" {
		t.Error("no SYSTEMROOT found")
	}
}

redpajama_set_name: RedPajamaGithub


text:
package io.apiman.manager.api.rest.impl.util;

import io.apiman.manager.api.rest.contract.exceptions.InvalidNameException;
import io.apiman.manager.api.rest.impl.i18n.Messages;

import org.apache.commons.lang.StringUtils;

/**
 * Validates the name of an entity.
 *
 * @author eric.wittmann@redhat.com
 */
public class FieldValidator {

    private FieldValidator() {
    }

    /**
     * Validates an entity name.
     * @param name
     * @throws InvalidNameException
     */
    public static void validateName(String name) throws InvalidNameException {
        if (StringUtils.isEmpty(name)) {
            throw ExceptionFactory.invalidNameException(Messages.i18n.format("FieldValidator.EmptyNameError")); //$NON-NLS-1$
        }
    }

    /**
     * Validates an version.
     * @param name
     * @throws InvalidNameException
     */
    public static void validateVersion(String name) throws InvalidNameException {
        if (StringUtils.isEmpty(name)) {
            throw ExceptionFactory.invalidVersionException(Messages.i18n.format("FieldValidator.EmptyVersionError")); //$NON-NLS-1$
        }
    }

}


text:
include $(RTE_SDK)/mk/rte.vars.mk

#
# library name
#
LIB = libethdev.a

CFLAGS += -O3
CFLAGS += $(WERROR_FLAGS)

SRCS-y += rte_ethdev.c

#
# Export include files
#
SYMLINK-y-include += rte_ether.h
SYMLINK-y-include += rte_ethdev.h
SYMLINK-y-include += rte_eth_ctrl.h

# this lib depends upon:
DEPDIRS-y += lib/librte_eal lib/librte_mempool lib/librte_ring lib/librte_mbuf

include $(RTE_SDK)/mk/rte.lib.mk


text:
namespace test {
namespace loggingapi {
namespace criteria {

typedef ::loggingapi::attributes::AttributeInterface AttrI;
typedef ::loggingapi::attributes::Attribute Attr;
typedef ::loggingapi::criteria::CriteriaChecker CC;

struct CriteriaCheckerFixture {
    CC* cc;
    std::vector<AttrI*> ecs;  // Expected criteria
    std::vector<AttrI*> ccs;  // Current criteria
    CriteriaCheckerFixture() {
        cc = new CC();
    }
    ~CriteriaCheckerFixture() {
        delete cc;

        while (!ecs.empty()) {
            delete ecs.back();
            ecs.pop_back();
        }

        while (!ccs.empty()) {
            delete ccs.back();
            ccs.pop_back();
        }
    }
};

BOOST_FIXTURE_TEST_SUITE(CriteriaCheckerFixtureTestSuite, CriteriaCheckerFixture)  // NOLINT(whitespace/line_length)

BOOST_AUTO_TEST_CASE(pass_NoExpectedCriteria) {
    BOOST_REQUIRE(cc->pass(ecs, ccs) == true);
}

BOOST_AUTO_TEST_CASE(pass_NoCurrentCriteria) {
    AttrI* e0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 10);  // NOLINT(whitespace/line_length)
    ecs.push_back(e0);
    BOOST_REQUIRE(cc->pass(ecs, ccs) == false);
}

BOOST_AUTO_TEST_CASE(pass_ExpectedCriteriaNotMatchingCurrentCriteria) {
    AttrI* e0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 10);  // NOLINT(whitespace/line_length)
    AttrI* c0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 9);  // NOLINT(whitespace/line_length)
    ecs.push_back(e0);
    ccs.push_back(c0);
    BOOST_REQUIRE(cc->pass(ecs, ccs) == false);
}

BOOST_AUTO_TEST_CASE(pass_ExpectedCriteriaMatchingCurrentCriteria) {
    AttrI* e0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 10);  // NOLINT(whitespace/line_length)
    AttrI* c0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 11);  // NOLINT(whitespace/line_length)
    ecs.push_back(e0);
    ccs.push_back(c0);
    BOOST_REQUIRE(cc->pass(ecs, ccs) == true);
}

BOOST_AUTO_TEST_CASE(pass_2ExpectedCriteriaWhom1NotMatchingCurrentCriteria) {
    AttrI* e0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 10);  // NOLINT(whitespace/line_length)
    AttrI* c0 = ::loggingapi::AttributeFactory<int>::createAttribute("attr0", 11);  // NOLINT(whitespace/line_length)
    AttrI* e1 = ::loggingapi::AttributeFactory<int>::createAttribute("attr1", 10);  // NOLINT(whitespace/line_length)
    ecs.push_back(e0);
    ecs.push_back(e1);
    ccs.push_back(c0);
    BOOST_REQUIRE(cc->pass(ecs, ccs) == false);
}

BOOST_AUTO_TEST_SUITE_END()

}}}  // namespaces


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Project.Web;
using Microsoft.VisualStudioTools.Project;

namespace Microsoft.PythonTools.Django.Debugger {
    [Export(typeof(IPythonLauncherProvider))]
    class DjangoLauncherProvider : IPythonLauncherProvider2 {
        internal readonly IEnumerable<Lazy<IPythonLauncherProvider>> _providers;

        [ImportingConstructor]
        public DjangoLauncherProvider([ImportMany]IEnumerable<Lazy<IPythonLauncherProvider>> allProviders) {
            _providers = allProviders;
        }

        #region IPythonLauncherProvider Members

        public IPythonLauncherOptions GetLauncherOptions(IPythonProject properties) {
            return new PythonWebLauncherOptions(properties);
        }

        public string Name {
            get { return "Django launcher"; }
        }

        public string LocalizedName {
            get { return Resources.DjangoLauncherName; }
        }

        public int SortPriority {
            get { return 200; }
        }

        public string Description {
            get { return Resources.DjangoLauncherDescription; }
        }

        public IProjectLauncher CreateLauncher(IPythonProject project) {
            var webLauncher = _providers.FirstOrDefault(p => p.Value.Name == PythonConstants.WebLauncherName);

            if (webLauncher == null) {
                throw new InvalidOperationException(Resources.CannotFindPythonWebLauncher);
            }

            return webLauncher.Value.CreateLauncher(project);
        }

        #endregion
    }
}


text:
package com.angcyo.github.finger;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;

import com.angcyo.github.R;

/**
 * Created by Zhangwh on 2016/12/29 0029.
 * email:616505546@qq.com
 */

public class FingerPrinterView extends View {

    public final static int STATE_NO_SCANING = 0;

    public final static int STATE_WRONG_PWD = 1;

    public final static int STATE_CORRECT_PWD = 2;

    public final static int STATE_SCANING = 3;
    public static int DEFAULT_DURATION = 700;
    public int mCurrentState = STATE_NO_SCANING;
    ValueAnimator valueAnimator;
    float scale = 1.0f;
    OnStateChangedListener listener;
    private Resources mResources;
    private Animation mShakeAnim = null; // 抖动的动画
    private float mFraction = 0f, mFraction2 = 1f;
    private int scaningCount = 0;
    private boolean isAnim = true; //判断是否要继续动画
    private boolean isScale = false; //判断是否要缩放
    private Paint mBitPaint;
    private Bitmap mFingerRed, mFingerGreen, mFingerGrey;
    private Rect mSrcRect = new Rect(), mDestRect = new Rect();
    private int mBitWidth, mBitHeight;
    private int mWidth, mHeight;

    public FingerPrinterView(Context context) {
        this(context, null);
    }

    public FingerPrinterView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FingerPrinterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mResources = getResources();
        //mShakeAnim = AnimationUtils.loadAnimation(context, R.anim.anim_lockpattern_shake_x);
        initBitmap();
        initPaint();
    }

    private void initPaint() {
        mBitPaint = new Paint();
        // 防抖动
        mBitPaint.setDither(true);
        // 开启图像过滤
        mBitPaint.setFilterBitmap(true);
    }

    private void initBitmap() {
        mFingerRed = ((BitmapDrawable) mResources.getDrawable(R.drawable.finger_red)).getBitmap();
        mFingerGreen = ((BitmapDrawable) mResources.getDrawable(R.drawable.finger_green)).getBitmap();
        mFingerGrey = ((BitmapDrawable) mResources.getDrawable(R.drawable.finger_grey)).getBitmap();
        mBitWidth = mFingerRed.getWidth();
        mBitHeight = mFingerRed.getHeight();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (heightMode == MeasureSpec.AT_MOST || heightMode== MeasureSpec.UNSPECIFIED) {
            heightSize = mBitHeight;
        }

        if (widthMode == MeasureSpec.AT_MOST || widthMode== MeasureSpec.UNSPECIFIED) {
            widthSize = mBitWidth;
        }

        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        mFingerRed = setScale(mFingerRed);
        mFingerGreen = setScale(mFingerGreen);
        mFingerGrey = setScale(mFingerGrey);
        mBitWidth = mFingerRed.getWidth();
        mBitHeight = mFingerRed.getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mBitPaint.setAlpha(255);
        mDestRect.set((int) (mBitHeight * (1 - mFraction2)), (int) (mBitHeight * (1 - mFraction2)), (int) (mBitHeight * mFraction2), (int) (mBitHeight * mFraction2));
        mSrcRect.set(0, 0, mBitWidth, mBitHeight);
        canvas.drawBitmap(mFingerGrey, mSrcRect, mDestRect, mBitPaint);
        if (mCurrentState == STATE_NO_SCANING) {
            return;
        }

        if (true) {
            if (scaningCount == 0) {
                mDestRect.set(0, 0, mBitWidth, (int) (mBitHeight * mFraction));
                mSrcRect.set(0, 0, mBitWidth, (int) (mBitHeight * mFraction));
                canvas.drawBitmap(mFingerGreen, mSrcRect, mDestRect, mBitPaint);
            } else if (scaningCount % 2 == 0) {
                if (mFraction <= 0.5) {
                    mBitPaint.setAlpha((int) (255 * (1 - mFraction)));
                    canvas.drawBitmap(mFingerRed, mSrcRect, mDestRect, mBitPaint);
                } else {
                    mBitPaint.setAlpha((int) (255 * mFraction));
                    canvas.drawBitmap(mFingerGreen, mSrcRect, mDestRect, mBitPaint);
                }
            } else {
                if (mFraction <= 0.5) {
                    mBitPaint.setAlpha((int) (255 * (1 - mFraction)));
                    canvas.drawBitmap(mFingerGreen, mSrcRect, mDestRect, mBitPaint);
                } else {
                    mBitPaint.setAlpha((int) (255 * mFraction));
                    canvas.drawBitmap(mFingerRed, mSrcRect, mDestRect, mBitPaint);
                }

            }
        }
        if (isScale) {
            if (mCurrentState == STATE_WRONG_PWD) {
                canvas.drawBitmap(mFingerRed, mSrcRect, mDestRect, mBitPaint);
            }
            if (mCurrentState == STATE_CORRECT_PWD) {
                canvas.drawBitmap(mFingerGreen, mSrcRect, mDestRect, mBitPaint);
            }
        }
    }

    public void startScaning() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.f, 100.f);
        valueAnimator.setDuration(DEFAULT_DURATION);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @SuppressLint("NewApi")
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mFraction = valueAnimator.getAnimatedFraction();
                invalidate();
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                if (isScale) {
                    isScale = false;
                }
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                mFraction = 0;
                scaningCount++;
                if (mCurrentState == STATE_WRONG_PWD && scaningCount % 2 == 1) {
                    isScale = true;
                    isAnim = false;
                    startScale();
                }
                if (mCurrentState == STATE_CORRECT_PWD && scaningCount % 2 == 0) {
                    isScale = true;
                    isAnim = false;
                    startScale();
                }
                if (isAnim) {
                    startScaning();
                }

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        if (!valueAnimator.isRunning()) {
            valueAnimator.start();
        }
    }

    private void startScale() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.f, 100.f);
        valueAnimator.setDuration(500);
        valueAnimator.setInterpolator(new OvershootInterpolator(1.2f));
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mFraction2 = 0.85f + 0.15f * valueAnimator.getAnimatedFraction();
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (listener != null) {
                    listener.onChange(mCurrentState);
                }
            }
        });
        if (!valueAnimator.isRunning()) {
            valueAnimator.start();
        }
    }

    private void startReset() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.f, 100.f);
        valueAnimator.setDuration(DEFAULT_DURATION);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mFraction = 1 - valueAnimator.getAnimatedFraction();
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);

                startScaning();
            }
        });
        if (!valueAnimator.isRunning()) {
            valueAnimator.start();
        }
    }

    public int getState() {
        return mCurrentState;
    }

    public void setState(int state) {
        mCurrentState = state;
        switch (state) {
            case STATE_SCANING:
                startScaning();
                break;
            case STATE_WRONG_PWD:

                break;
            case STATE_CORRECT_PWD:

                break;
            case STATE_NO_SCANING:
                resetConfig();
                break;
            default:
                break;
        }
    }

    /**
     * 处理图片缩放
     */
    private Bitmap setScale(Bitmap a) {
        scale = ((float) (mWidth) / mBitWidth);
        Matrix mMatrix = new Matrix();
        mMatrix.postScale(scale, scale);
        Bitmap bmp = Bitmap.createBitmap(a, 0, 0, a.getWidth(), a.getHeight(),
                mMatrix, true);
        return bmp;
    }

    public void resetConfig() {
        mCurrentState = STATE_NO_SCANING;
        startReset();
        mFraction = 0f;
        mFraction2 = 1f;
        scaningCount = 0;
        scale = 1.0f;
        isAnim = true;
        isScale = false;

    }

    public void setOnStateChangedListener(OnStateChangedListener listener) {
        this.listener = listener;
    }

    public interface OnStateChangedListener {
        public void onChange(int state);
    }

}


text:
set -x
# Location of cookbooks tarball to download
cookbooks_url=$1

#
# Only vendor cookbooks if the directory is absent.
# We don't want to overwrite a cookbooks tarball dropped off by the user!
#
if [[ ! -d $DIR/vendor/cookbooks/bach_repository ]]; then
  mkdir -p vendor
  curl $cookbooks_url | tar -xvz -C ./vendor
  # For some reason, tar -C changes ./vendor's permissions to 700
  chmod 755 vendor
else
  echo "Found $DIR/vendor/cookbooks/bach_repository, not invoking Berkshelf"
fi


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2d KDE — ArviZ dev documentation</title>

  <link href="../_static/css/theme.css" rel="stylesheet" />
  <link href="../_static/css/index.c5995385ac14fb8791e8eb36b4908be2.css" rel="stylesheet" />

  <link rel="stylesheet"
    href="../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
    <link rel="stylesheet" type="text/css" href="../_static/togglebutton.css" />
    <link rel="stylesheet" type="text/css" href="../_static/mystnb.css" />
    <link rel="stylesheet" type="text/css" href="../_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
    <link rel="stylesheet" type="text/css" href="../_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />

  <link rel="preload" as="script" href="../_static/js/index.1c5a1a01449ed65a7b51.js">

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="KDE quantiles" href="plot_kde_quantiles.html" />
    <link rel="prev" title="2d KDE" href="plot_kde_2d.html" />

    dev

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapsible" aria-controls="navbar-collapsible" aria-expanded="false" aria-label="Toggle navigation">

  </button>

  Getting Started

  Example Gallery

  User Guide

  API Reference

  Usage

  Contributing

  About

            GitHub

            Twitter

<form class="bd-search d-flex align-items-center" action="../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

   Autocorrelation Plot

   Bayesian p-value Posterior plot

   Bayesian p-value with median T statistic Posterior plot

   Compare Plot

   Density Plot

   Dist Plot

   ELPD Plot

   Energy Plot

   ESS Quantile Plot

   ESS Local Plot

   ESS Quantile Plot

   Forest Plot

   Ridgeplot

   Plot HDI

   Joint Plot

   KDE Plot

   2d KDE

   2d KDE

   KDE quantiles

   Pareto Shape Plot

   LOO-PIT ECDF Plot

   LOO-PIT Overlay Plot

   Quantile Monte Carlo Standard Error Plot

   Quantile MCSE Errobar Plot

   Pair Plot

   Hexbin PairPlot

   KDE Pair Plot

   Point Estimate Pairplot

   Parallel Plot

   MinMax Parallel Plot

   Normal Parallel Plot

   Rank Parallel Plot

   Posterior Plot

   Posterior Predictive Check Plot

   Posterior Predictive Check Cumulative Plot

   Rank plot

   Separation Plot

   Traceplot

   Traceplot rank_bars

   Traceplot circular variables

   Traceplot rank_vlines

   Violin plot

   Matplotlib styles

2d KDE¶

API documentation: plot_kde()

<input checked="checked" id="b4564ee4-597c-457a-8ac4-d4f7a54fd594" name="8ad61ff8-0ef5-42ba-8ac3-c51615e30c4b" type="radio">
</input>
Matplotlib

Python source code: [download source: matplotlib/mpl_plot_kde_2d_bis.py]

import matplotlib.pyplot as plt
import numpy as np

import arviz as az

az.style.use("arviz-darkgrid")

az.plot_kde(
    np.random.beta(2, 5, size=100),
    np.random.beta(2, 5, size=100),
    contour_kwargs={"colors": None, "cmap": plt.cm.viridis, "levels": 30},
    contourf_kwargs={"alpha": 0.5, "levels": 30},
)

plt.show()

    2d KDE
    KDE quantiles

    © Copyright 2018, ArviZ devs.

Created using Sphinx 3.5.4.


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.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.VisualStudio.Shell.TableManager;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog
{
    internal partial class UnusedReferencesTableProvider
    {
        internal class UnusedReferencesDataSource : ITableDataSource
        {
            public const string Name = nameof(UnusedReferencesDataSource);

            public string SourceTypeIdentifier => Name;
            public string Identifier => Name;
            public string? DisplayName => null;

            private ImmutableList<SinkManager> _managers = ImmutableList<SinkManager>.Empty;
            private ImmutableArray<UnusedReferencesEntry> _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty;

            public IDisposable Subscribe(ITableDataSink sink)
            {
                return new SinkManager(this, sink);
            }

            public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates)
            {
                var solutionName = Path.GetFileName(solution.FilePath);
                var project = solution.Projects.First(project => projectFilePath.Equals(project.FilePath, StringComparison.OrdinalIgnoreCase));
                var entries = referenceUpdates
                    .Select(update => new UnusedReferencesEntry(solutionName, project.Name, project.Language, update))
                    .ToImmutableArray();

                foreach (var manager in _managers)
                {
                    manager.Sink.AddEntries(entries);
                }

                _currentEntries = _currentEntries.AddRange(entries);
            }

            public void RemoveAllTableData()
            {
                foreach (var manager in _managers)
                {
                    manager.Sink.RemoveAllEntries();
                }

                _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty;
            }

            internal void AddSinkManager(SinkManager manager)
            {
                _managers = _managers.Add(manager);

                manager.Sink.AddEntries(_currentEntries);
            }

            internal void RemoveSinkManager(SinkManager manager)
            {
                _managers = _managers.Remove(manager);
            }

            internal sealed class SinkManager : IDisposable
            {
                internal readonly UnusedReferencesDataSource UnusedReferencesDataSource;
                internal readonly ITableDataSink Sink;

                internal SinkManager(UnusedReferencesDataSource unusedReferencesDataSource, ITableDataSink sink)
                {
                    UnusedReferencesDataSource = unusedReferencesDataSource;
                    Sink = sink;

                    UnusedReferencesDataSource.AddSinkManager(this);
                }

                public void Dispose()
                {
                    UnusedReferencesDataSource.RemoveSinkManager(this);
                }
            }

            internal class UnusedReferencesEntry : ITableEntry
            {
                public string SolutionName { get; }
                public string ProjectName { get; }
                public string Language { get; }
                public ReferenceUpdate ReferenceUpdate { get; }

                public object Identity => ReferenceUpdate;

                public UnusedReferencesEntry(string solutionName, string projectName, string language, ReferenceUpdate referenceUpdate)
                {
                    SolutionName = solutionName;
                    ProjectName = projectName;
                    Language = language;
                    ReferenceUpdate = referenceUpdate;
                }

                public bool TryGetValue(string keyName, out object? content)
                {
                    content = null;

                    switch (keyName)
                    {
                        case UnusedReferencesTableKeyNames.SolutionName:
                            content = SolutionName;
                            break;
                        case UnusedReferencesTableKeyNames.ProjectName:
                            content = ProjectName;
                            break;
                        case UnusedReferencesTableKeyNames.Language:
                            content = Language;
                            break;
                        case UnusedReferencesTableKeyNames.ReferenceType:
                            content = ReferenceUpdate.ReferenceInfo.ReferenceType;
                            break;
                        case UnusedReferencesTableKeyNames.ReferenceName:
                            // For Project and Assembly references, use the file name instead of overwhelming the user with the full path.
                            content = ReferenceUpdate.ReferenceInfo.ReferenceType != ReferenceType.Package
                                ? Path.GetFileName(ReferenceUpdate.ReferenceInfo.ItemSpecification)
                                : ReferenceUpdate.ReferenceInfo.ItemSpecification;
                            break;
                        case UnusedReferencesTableKeyNames.UpdateAction:
                            content = ReferenceUpdate.Action;
                            break;
                    }

                    return content != null;
                }

                public bool CanSetValue(string keyName)
                {
                    return keyName == UnusedReferencesTableKeyNames.UpdateAction;
                }

                public bool TrySetValue(string keyName, object content)
                {
                    if (keyName != UnusedReferencesTableKeyNames.UpdateAction || content is not UpdateAction action)
                    {
                        return false;
                    }

                    ReferenceUpdate.Action = action;
                    return true;
                }
            }
        }
    }
}


text:
package com.example.androidx.webkit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.webkit.SafeBrowsingResponseCompat;
import androidx.webkit.WebViewClientCompat;
import androidx.webkit.WebViewFeature;

/**
 * An {@link Activity} which shows a custom interstitial if {@link WebView} encounters malicious
 * resources. This class contains the logic for responding to user interaction with custom
 * interstitials. The UI for these interstitials is implemented by {@link
 * PopupInterstitialActivity}.
 */
public class CustomInterstitialActivity extends AppCompatActivity {

    private WebView mWebView;
    private CustomInterstitialWebViewClient mWebViewClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_interstitial);
        setTitle(R.string.custom_interstitial_activity_title);
        WebkitHelpers.appendWebViewVersionToTitle(this);

        if (WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_HIT)
                && WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_RESPONSE_PROCEED)
                && WebViewFeature.isFeatureSupported(
                WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY)) {
            mWebView = findViewById(R.id.custom_interstitial_webview);
            mWebViewClient = new CustomInterstitialWebViewClient(this);
            mWebView.setWebViewClient(mWebViewClient);
            mWebView.loadUrl(SafeBrowsingHelpers.TEST_SAFE_BROWSING_SITE);
        } else {
            WebkitHelpers.showMessageInActivity(this, R.string.webkit_api_not_available);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mWebViewClient.handleInterstitialResponse(requestCode, resultCode, data);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private static class CustomInterstitialWebViewClient extends WebViewClientCompat {
        private final Activity mActivity;
        private final SparseArray<SafeBrowsingResponseCompat> mSafeBrowsingResponseMap;
        int mActivityRequestCounter;

        CustomInterstitialWebViewClient(Activity activity) {
            mActivity = activity;
            mSafeBrowsingResponseMap = new SparseArray<>();
            mActivityRequestCounter = 0;
        }

        @Override
        @RequiresApi(21) // This won't be called on < L, so we can safely apply @RequiresApi.
        public void onSafeBrowsingHit(@NonNull WebView view, @NonNull WebResourceRequest request,
                int threatType, @NonNull SafeBrowsingResponseCompat callback) {
            mSafeBrowsingResponseMap.put(mActivityRequestCounter, callback);
            createInterstitial(threatType, request);
            mActivityRequestCounter++;
        }

        @RequiresApi(21) // for WebResourceRequest
        private void createInterstitial(int threatType, @NonNull WebResourceRequest request) {
            Intent myIntent = new Intent(mActivity, PopupInterstitialActivity.class);
            myIntent.putExtra(PopupInterstitialActivity.THREAT_TYPE, threatType);
            myIntent.putExtra(PopupInterstitialActivity.THREAT_URL,
                    Api21Impl.getUrl(request).toString());
            mActivity.startActivityForResult(myIntent, mActivityRequestCounter);
        }

        void handleInterstitialResponse(int requestCode, int resultCode, Intent data) {
            // Get the correct SafeBrowsingResponse for the given interstitial Intent (there can be
            // multiple Intents at the same time if multiple resources are malicious).
            final SafeBrowsingResponseCompat response = mSafeBrowsingResponseMap.get(requestCode);
            mSafeBrowsingResponseMap.delete(requestCode);

            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                if (response == null) {
                    return;
                }

                // Figure out what navigation action we should take.
                String result = data.getStringExtra(PopupInterstitialActivity.ACTION_RESPONSE);
                // Figure out whether we should report this event.
                boolean shouldSendReport = data.getBooleanExtra(
                        PopupInterstitialActivity.SHOULD_SEND_REPORT, false);

                switch (result) {
                    case PopupInterstitialActivity.ACTION_RESPONSE_BACK_TO_SAFETY:
                        response.backToSafety(shouldSendReport);
                        break;
                    case PopupInterstitialActivity.ACTION_RESPONSE_PROCEED:
                        response.proceed(shouldSendReport);
                        break;
                    default:
                        break;
                }
            } else if (resultCode == RESULT_CANCELED) {
                // User pressed the system's back button, treat this like backToSafety().
                response.backToSafety(false);
            } else {
                throw new IllegalStateException("PopupInterstitialActivity shouldn't return any "
                        + "nonstandard resultCodes");
            }
        }

    }
}


text:
<!DOCTYPE html>

                <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
                <meta NAME="viewport" CONTENT="width=device-width, height=device-height, initial-scale=1, user-scalable=no"/>
                <meta name="mobile-web-app-capable" content="yes">
                <meta name="apple-mobile-web-app-capable" content="yes">
                <link rel="apple-touch-icon" href="res/pm-1x.png">
                <meta name="apple-mobile-web-app-title" content="Pool M">
                <link rel="apple-touch-startup-image" href="res/pm-4x.png">
                <link rel="manifest" href="manifest.json">
                <link rel="icon" href="favicon.png">
                <title>NHL Playoffs Pool</title>

                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
                <link rel="stylesheet" href="css/main.css">


text:
#pragma once

#include <sys/time.h>

#include <atomic>
#include <memory>
#include <string>

#include "folly/IntrusiveList.h"
#include "mcrouter/AccessPoint.h"
#include "mcrouter/config.h"
#include "mcrouter/lib/McMsgRef.h"

using asox_timer_t = void*;
class fb_timer_s;
using fb_timer_t = fb_timer_s;

namespace facebook { namespace memcache { namespace mcrouter {

class ProxyClientCommon;
class ProxyClientOwner;
class ProxyClientShared;
class ProxyDestinationMap;
class dynamic_stat_t;
class proxy_t;

enum proxy_client_state_t {
  PROXY_CLIENT_UNKNOWN = 0,   // bug
  PROXY_CLIENT_NEW,           // never connected
  PROXY_CLIENT_UP,            // currently connected
  PROXY_CLIENT_TKO,           // waiting for retry timeout
  PROXY_CLIENT_NUM_STATES
};

struct proxy_client_conn_stats_t {
  char is_up;
  fb_timer_t* rtt_timer;
  uint64_t results[mc_nres];

  proxy_client_conn_stats_t();
};

struct ProxyDestination {
  static const uint64_t kDeadBeef = 0xdeadbeefdeadbeefULL;

  proxy_t* proxy{nullptr}; ///< for convenience
  AccessPoint accessPoint;
  const std::string destinationKey;///< always the same for a given (host, port)
  int rxpriority{0};
  int txpriority{0};
  const timeval_t server_timeout{0};
  const std::string pdstnKey;///< consists of ap, server_timeout
  uint64_t magic{0}; ///< to allow asserts that pdstn is still alive
  uint64_t proxy_magic{0}; ///< to allow asserts that proxy is still alive

  ProxyClientOwner* owner{nullptr};
  std::shared_ptr<ProxyClientShared> shared;

  proxy_client_conn_stats_t stats;
  dynamic_stat_t* stats_ptr{nullptr};

  bool use_ssl{false};

  static std::shared_ptr<ProxyDestination> create(proxy_t* proxy,
                                                   const ProxyClientCommon& ro,
                                                   std::string pdstnKey);

  ~ProxyDestination();

  void track_latency(int64_t latency);
  void handle_tko(mc_res_t result, const McMsgRef& reply,
                  int consecutive_errors);

  // returns non-zero on error
  int send(McMsgRef request, void* req_ctx, uint64_t senderId);
  // returns 1 if okay to send req using this client
  int may_send(const McMsgRef& req);

  proxy_client_state_t state();

  void resetInactive();

  void on_up();
  void on_down();
  void on_reply(const McMsgRef& req,
                McMsgRef reply, mc_res_t result, void* req_ctx);

  // on probe timer
  void on_timer(const asox_timer_t timer);

  size_t getPendingRequestCount() const;
  size_t getInflightRequestCount() const;

  void start_sending_probes();
  void stop_sending_probes();

 private:
  std::unique_ptr<DestinationMcClient> client_;

  int probe_delay_next_ms{0};
  bool sending_probes{false};
  McMsgRef probe_req;
  asox_timer_t probe_timer{nullptr};
  size_t consecutiveErrors_{0};
  double avgLatency_{0.0};

  char resetting{0}; // If 1 when inside on_down, the call was due to a forced
                     // mc_client_reset and not a remote connection failure.

  timeval_t up_time{0};
  timeval_t down_time{0};

  // tko behaviour
  char marked_tko{0};

  void schedule_next_probe();

  void reset_fields();

  void mark_tko();
  void unmark_tko();
  void unmark_global_tko();

  void initializeClient();

  ProxyDestination(proxy_t* proxy,
                 const ProxyClientCommon& ro,
                 std::string pdstnKey);

  // for no-network mode (debug/performance measurement only)
  void sendFakeReply(const McMsgRef& request, void* req_ctx);

  std::atomic<bool> isUsedInConfig_{false};
  void* stateList_{nullptr};
  folly::IntrusiveListHook stateListHook_;

  std::weak_ptr<ProxyDestination> selfPtr_;

  friend class ProxyDestinationMap;
};

}}}  // facebook::memcache::mcrouter


text:
if ('Element' in window && !Element.prototype.closest) {
  Element.prototype.closest = function (this: any, s: string) {
    const matches = (this.document || this.ownerDocument).querySelectorAll(s);
    let el = this;
    let i;
    // eslint-disable-next-line
    do {
      i = matches.length;
      // eslint-disable-next-line
      while (--i >= 0 && matches.item(i) !== el) {}
      el = el.parentElement;
    } while (i < 0 && el);
    return el;
  };
}

export function getPreviousCousin(node: any, selector: string) {
  let sibling = node.parentElement.previousSibling;
  let el;
  while (sibling) {
    el = sibling.querySelector(selector);
    if (el) {
      return el;
    }
    sibling = sibling.previousSibling;
  }
  return undefined;
}

export function getNextCharacter(global?: any) {
  const selection = (global || window).getSelection();
  if (!selection || !selection.anchorNode) {
    return null;
  }

  const range = selection.getRangeAt(0);
  const text = selection.anchorNode.textContent;
  const offset = range.startOffset;
  return text!.substr(offset, 1);
}


text:
package org.pentaho.di.trans.steps.xmlinputstream;

import java.io.InputStream;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;

import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;

/**
 * @author Jens Bleuel
 * @since 2011-01-13
 */
public class XMLInputStreamData extends BaseStepData implements StepDataInterface {

  public RowMetaInterface outputRowMeta;

  public XMLInputFactory staxInstance;

  public FileObject fileObject;
  public InputStream inputStream;
  public XMLEventReader xmlEventReader;

  // from meta data but replaced by variables
  public String filename;
  public long nrRowsToSkip;
  public long rowLimit;
  public String encoding;

  // runtime data
  public Long rowNumber;
  public int elementLevel;
  public Long elementID;
  public Long[] elementLevelID;
  public Long[] elementParentID;
  public String[] elementName;
  public String[] elementPath;

  // positions of fields in the row (-1: field is not included in the stream)
  public int pos_xml_filename;
  public int pos_xml_row_number;
  public int pos_xml_data_type_numeric;
  public int pos_xml_data_type_description;
  public int pos_xml_location_line;
  public int pos_xml_location_column;
  public int pos_xml_element_id;
  public int pos_xml_parent_element_id;
  public int pos_xml_element_level;
  public int pos_xml_path;
  public int pos_xml_parent_path;
  public int pos_xml_data_name;
  public int pos_xml_data_value;

  public XMLInputStreamData() {
    super();
  }
}


text:
I wrote the ZeroDiff docs using mkdocs and committed it all to github. This setup not only generates nice-looking, searchable documentation, it makes it possible to share/fork it so that ZeroDiff can be a community effort.

The mkdocs system is a self-contained, Python-based documentation tool that uses Twitter Bootstrap and scripting to generate high-quality HTML-based documentation using simple markdown files. The cool thing about mkdocs is that the repo is both the documentation set and place to generate the static, production site. The top-level mkdocs.yml file shows the documentation tree structure and configurations. If you edit this file, it will be pretty easy to see what markdown (*.md) files you need to edit in order to change the docs you want changed.

## Installing Python and mkdocs.

Please see the mkdocs website to see how to install Python and the mkdocs tools. It's pretty simple and easy to do this, but it's out-of-scope to explain that here.

## Editing the docs

From a terminal session change to the top-level directory

        >cd ~/git/zerodiff
        >mkdocs serve

Now from your browser go to the URL: http://127.0.0.1:8000

As you edit the markdown files, mkdocs automatically updates the website in realtime so that you can review your changes.

## Generating the Static Documentation Website

Once you've completed all of your edits, you need to generate the static site (not committed to git because "./site" is in .gitignore).

        >cd ~/git/zerodiff
        >mkdocs build

This will generate a static documentation site in the directory ~/git/zerodiff/site. You can validate the site by killing the "mkdocs serve" process and starting a simple Python=-based web server in that directory:

        >cd ~/git/zerodiff/site
        >python -m SimpleHTTPServer 8000

Now from your browser go to the URL: http://127.0.0.1:8000

## Commit the Static Site to Github Project Pages ("gh-pages")

        >cd ~/git/zerodiff
        >mkdocs gh-deploy --clean

This command will generate the static site and push it to the gh-pages branch so that it shows up as a searchable, shred website (on github). The url will be https://your_github_id.github.io/zerodiff/.


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;

/// <summary>
/// A trace is a series of spans (often RPC calls) which form a latency tree.
///
/// Spans are usually created by instrumentation in RPC clients or servers, but
/// can also represent in-process activity. Annotations in spans are similar to
/// log statements, and are sometimes created directly by application developers
/// to indicate events of interest, such as a cache miss.
///
/// The root span is where parent_id = Nil; it usually has the longest duration
/// in the trace.
///
/// Span identifiers are packed into i64s, but should be treated opaquely.
/// String encoding is fixed-width lower-hex, to avoid signed interpretation.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public partial class Span : TBase
{
  private long _trace_id;
  private string _name;
  private long _id;
  private long _parent_id;
  private List<Annotation> _annotations;
  private List<BinaryAnnotation> _binary_annotations;
  private bool _debug;
  private long _timestamp;
  private long _duration;

  /// <summary>
  /// Unique 8-byte identifier for a trace, set on all spans within it.
  /// </summary>
  public long Trace_id
  {
    get
    {
      return _trace_id;
    }
    set
    {
      __isset.trace_id = true;
      this._trace_id = value;
    }
  }

  /// <summary>
  /// Span name in lowercase, rpc method for example. Conventionally, when the
  /// span name isn't known, name = "unknown".
  /// </summary>
  public string Name
  {
    get
    {
      return _name;
    }
    set
    {
      __isset.name = true;
      this._name = value;
    }
  }

  /// <summary>
  /// Unique 8-byte identifier of this span within a trace. A span is uniquely
  /// identified in storage by (trace_id, id).
  /// </summary>
  public long Id
  {
    get
    {
      return _id;
    }
    set
    {
      __isset.id = true;
      this._id = value;
    }
  }

  /// <summary>
  /// The parent's Span.id; absent if this the root span in a trace.
  /// </summary>
  public long Parent_id
  {
    get
    {
      return _parent_id;
    }
    set
    {
      __isset.parent_id = true;
      this._parent_id = value;
    }
  }

  /// <summary>
  /// Associates events that explain latency with a timestamp. Unlike log
  /// statements, annotations are often codes: for example SERVER_RECV("sr").
  /// Annotations are sorted ascending by timestamp.
  /// </summary>
  public List<Annotation> Annotations
  {
    get
    {
      return _annotations;
    }
    set
    {
      __isset.annotations = true;
      this._annotations = value;
    }
  }

  /// <summary>
  /// Tags a span with context, usually to support query or aggregation. For
  /// example, a binary annotation key could be "http.uri".
  /// </summary>
  public List<BinaryAnnotation> Binary_annotations
  {
    get
    {
      return _binary_annotations;
    }
    set
    {
      __isset.binary_annotations = true;
      this._binary_annotations = value;
    }
  }

  /// <summary>
  /// True is a request to store this span even if it overrides sampling policy.
  /// </summary>
  public bool Debug
  {
    get
    {
      return _debug;
    }
    set
    {
      __isset.debug = true;
      this._debug = value;
    }
  }

  /// <summary>
  /// Epoch microseconds of the start of this span, absent if this an incomplete
  /// span.
  ///
  /// This value should be set directly by instrumentation, using the most
  /// precise value possible. For example, gettimeofday or syncing nanoTime
  /// against a tick of currentTimeMillis.
  ///
  /// For compatibilty with instrumentation that precede this field, collectors
  /// or span stores can derive this via Annotation.timestamp.
  /// For example, SERVER_RECV.timestamp or CLIENT_SEND.timestamp.
  ///
  /// Timestamp is nullable for input only. Spans without a timestamp cannot be
  /// presented in a timeline: Span stores should not output spans missing a
  /// timestamp.
  ///
  /// There are two known edge-cases where this could be absent: both cases
  /// exist when a collector receives a span in parts and a binary annotation
  /// precedes a timestamp. This is possible when..
  ///  - The span is in-flight (ex not yet received a timestamp)
  ///  - The span's start event was lost
  /// </summary>
  public long Timestamp
  {
    get
    {
      return _timestamp;
    }
    set
    {
      __isset.timestamp = true;
      this._timestamp = value;
    }
  }

  /// <summary>
  /// Measurement in microseconds of the critical path, if known.
  ///
  /// This value should be set directly, as opposed to implicitly via annotation
  /// timestamps. Doing so encourages precision decoupled from problems of
  /// clocks, such as skew or NTP updates causing time to move backwards.
  ///
  /// For compatibility with instrumentation that precede this field, collectors
  /// or span stores can derive this by subtracting Annotation.timestamp.
  /// For example, SERVER_SEND.timestamp - SERVER_RECV.timestamp.
  ///
  /// If this field is persisted as unset, zipkin will continue to work, except
  /// duration query support will be implementation-specific. Similarly, setting
  /// this field non-atomically is implementation-specific.
  ///
  /// This field is i64 vs i32 to support spans longer than 35 minutes.
  /// </summary>
  public long Duration
  {
    get
    {
      return _duration;
    }
    set
    {
      __isset.duration = true;
      this._duration = value;
    }
  }

  public Isset __isset;
  #if !SILVERLIGHT
  [Serializable]
  #endif
  public struct Isset {
    public bool trace_id;
    public bool name;
    public bool id;
    public bool parent_id;
    public bool annotations;
    public bool binary_annotations;
    public bool debug;
    public bool timestamp;
    public bool duration;
  }

  public Span() {
    this._debug = false;
    this.__isset.debug = true;
  }

  public void Read (TProtocol iprot)
  {
    TField field;
    iprot.ReadStructBegin();
    while (true)
    {
      field = iprot.ReadFieldBegin();
      if (field.Type == TType.Stop) {
        break;
      }
      switch (field.ID)
      {
        case 1:
          if (field.Type == TType.I64) {
            Trace_id = iprot.ReadI64();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 3:
          if (field.Type == TType.String) {
            Name = iprot.ReadString();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 4:
          if (field.Type == TType.I64) {
            Id = iprot.ReadI64();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 5:
          if (field.Type == TType.I64) {
            Parent_id = iprot.ReadI64();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 6:
          if (field.Type == TType.List) {
            {
              Annotations = new List<Annotation>();
              TList _list0 = iprot.ReadListBegin();
              for( int _i1 = 0; _i1 < _list0.Count; ++_i1)
              {
                Annotation _elem2;
                _elem2 = new Annotation();
                _elem2.Read(iprot);
                Annotations.Add(_elem2);
              }
              iprot.ReadListEnd();
            }
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 8:
          if (field.Type == TType.List) {
            {
              Binary_annotations = new List<BinaryAnnotation>();
              TList _list3 = iprot.ReadListBegin();
              for( int _i4 = 0; _i4 < _list3.Count; ++_i4)
              {
                BinaryAnnotation _elem5;
                _elem5 = new BinaryAnnotation();
                _elem5.Read(iprot);
                Binary_annotations.Add(_elem5);
              }
              iprot.ReadListEnd();
            }
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 9:
          if (field.Type == TType.Bool) {
            Debug = iprot.ReadBool();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 10:
          if (field.Type == TType.I64) {
            Timestamp = iprot.ReadI64();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        case 11:
          if (field.Type == TType.I64) {
            Duration = iprot.ReadI64();
          } else {
            TProtocolUtil.Skip(iprot, field.Type);
          }
          break;
        default:
          TProtocolUtil.Skip(iprot, field.Type);
          break;
      }
      iprot.ReadFieldEnd();
    }
    iprot.ReadStructEnd();
  }

  public void Write(TProtocol oprot) {
    TStruct struc = new TStruct("Span");
    oprot.WriteStructBegin(struc);
    TField field = new TField();
    if (__isset.trace_id) {
      field.Name = "trace_id";
      field.Type = TType.I64;
      field.ID = 1;
      oprot.WriteFieldBegin(field);
      oprot.WriteI64(Trace_id);
      oprot.WriteFieldEnd();
    }
    if (Name != null && __isset.name) {
      field.Name = "name";
      field.Type = TType.String;
      field.ID = 3;
      oprot.WriteFieldBegin(field);
      oprot.WriteString(Name);
      oprot.WriteFieldEnd();
    }
    if (__isset.id) {
      field.Name = "id";
      field.Type = TType.I64;
      field.ID = 4;
      oprot.WriteFieldBegin(field);
      oprot.WriteI64(Id);
      oprot.WriteFieldEnd();
    }
    if (__isset.parent_id) {
      field.Name = "parent_id";
      field.Type = TType.I64;
      field.ID = 5;
      oprot.WriteFieldBegin(field);
      oprot.WriteI64(Parent_id);
      oprot.WriteFieldEnd();
    }
    if (Annotations != null && __isset.annotations) {
      field.Name = "annotations";
      field.Type = TType.List;
      field.ID = 6;
      oprot.WriteFieldBegin(field);
      {
        oprot.WriteListBegin(new TList(TType.Struct, Annotations.Count));
        foreach (Annotation _iter6 in Annotations)
        {
          _iter6.Write(oprot);
        }
        oprot.WriteListEnd();
      }
      oprot.WriteFieldEnd();
    }
    if (Binary_annotations != null && __isset.binary_annotations) {
      field.Name = "binary_annotations";
      field.Type = TType.List;
      field.ID = 8;
      oprot.WriteFieldBegin(field);
      {
        oprot.WriteListBegin(new TList(TType.Struct, Binary_annotations.Count));
        foreach (BinaryAnnotation _iter7 in Binary_annotations)
        {
          _iter7.Write(oprot);
        }
        oprot.WriteListEnd();
      }
      oprot.WriteFieldEnd();
    }
    if (__isset.debug) {
      field.Name = "debug";
      field.Type = TType.Bool;
      field.ID = 9;
      oprot.WriteFieldBegin(field);
      oprot.WriteBool(Debug);
      oprot.WriteFieldEnd();
    }
    if (__isset.timestamp) {
      field.Name = "timestamp";
      field.Type = TType.I64;
      field.ID = 10;
      oprot.WriteFieldBegin(field);
      oprot.WriteI64(Timestamp);
      oprot.WriteFieldEnd();
    }
    if (__isset.duration) {
      field.Name = "duration";
      field.Type = TType.I64;
      field.ID = 11;
      oprot.WriteFieldBegin(field);
      oprot.WriteI64(Duration);
      oprot.WriteFieldEnd();
    }
    oprot.WriteFieldStop();
    oprot.WriteStructEnd();
  }

  public override string ToString() {
    StringBuilder __sb = new StringBuilder("Span(");
    bool __first = true;
    if (__isset.trace_id) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Trace_id: ");
      __sb.Append(Trace_id);
    }
    if (Name != null && __isset.name) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Name: ");
      __sb.Append(Name);
    }
    if (__isset.id) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Id: ");
      __sb.Append(Id);
    }
    if (__isset.parent_id) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Parent_id: ");
      __sb.Append(Parent_id);
    }
    if (Annotations != null && __isset.annotations) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Annotations: ");
      __sb.Append(Annotations);
    }
    if (Binary_annotations != null && __isset.binary_annotations) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Binary_annotations: ");
      __sb.Append(Binary_annotations);
    }
    if (__isset.debug) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Debug: ");
      __sb.Append(Debug);
    }
    if (__isset.timestamp) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Timestamp: ");
      __sb.Append(Timestamp);
    }
    if (__isset.duration) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Duration: ");
      __sb.Append(Duration);
    }
    __sb.Append(")");
    return __sb.ToString();
  }

}