package com.redhat.ceylon.compiler.java.test.issues.bug17xx;

public interface Bug1777<Element> extends .ceylon.language.Iterable<Element, .java.lang.Object> {

    public .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777$impl<Element> $com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$impl();

    public <Result>.ceylon.language.Callable<? extends Result> foldd(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial);

    public abstract <Result>.ceylon.language.Callable<? extends Result> foldFormal(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial);
}
public final class Bug1777$impl<Element> implements .java.io.Serializable {

    public Bug1777$impl(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element, .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777<Element> $this) {
        this.$reified$Element = $reified$Element;
        this.$this = $this;
    }
    private .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element;
    private final .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777<Element> $this;

    public void $refine$(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element) {
        this.$reified$Element = $reified$Element;
    }

    public <Result>.ceylon.language.Callable<? extends Result> foldd(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return new .com.redhat.ceylon.compiler.java.language.AbstractCallable<Result>($reified$Result, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Callable.class, $reified$Result, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, $reified$Result, $reified$Element))), "Result(Result(Result, Element))", (short)-1){

            @.java.lang.Override
            public Result $call$(final .java.lang.Object $param$0) {
                final .ceylon.language.Callable<? extends Result> accumulating = (.ceylon.language.Callable<? extends Result>)(.ceylon.language.Callable)$param$0;
                Result partial = initial;
                .java.lang.Object elem$0;
                .ceylon.language.Iterator<? extends Element> elem$iterator$$1 = $this.iterator();
                loop_0: while (!((elem$0 = elem$iterator$$1.next()) instanceof .ceylon.language.Finished)) {
                    final Element elem = (Element)elem$0;
                    partial = accumulating.$call$((.java.lang.Object)partial, elem);
                }
                return partial;
            }
        };
    }
}
public abstract class Bug1777_Impl<Element> implements .com.redhat.ceylon.compiler.java.runtime.model.ReifiedType, .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777<Element>, .java.io.Serializable {

    public Bug1777_Impl(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element) {
        this.$reified$Element = $reified$Element;
        this.$com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$this$ = new .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777$impl<Element>($reified$Element, this);
        this.$ceylon$language$Iterable$this$ = new .ceylon.language.Iterable$impl($reified$Element, .ceylon.language.Null.$TypeDescriptor$, this);
        this.$ceylon$language$Category$this$ = new .ceylon.language.Category$impl<.java.lang.Object>(.ceylon.language.Object.$TypeDescriptor$, this);
    }
    private final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element;
    protected final .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777$impl<Element> $com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$this$;

    @.java.lang.Override
    public .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777$impl<Element> $com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$impl() {
        return $com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$this$;
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Callable<? extends Result> foldd(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return $com$redhat$ceylon$compiler$java$test$issues$bug17xx$Bug1777$this$.foldd($reified$Result, initial);
    }
    protected final .ceylon.language.Iterable$impl<Element, .java.lang.Object> $ceylon$language$Iterable$this$;

    @.java.lang.Override
    public .ceylon.language.Iterable$impl<? extends Element, ? extends .java.lang.Object> $ceylon$language$Iterable$impl() {
        return $ceylon$language$Iterable$this$;
    }

    @.java.lang.Override
    public .ceylon.language.Iterable getPaired() {
        return (.ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends Element>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.getPaired();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getCycled() {
        return $ceylon$language$Iterable$this$.getCycled();
    }

    @.java.lang.Override
    public Element getLast() {
        return (Element)$ceylon$language$Iterable$this$.getLast();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element>, ? extends .java.lang.Object> getIndexed() {
        return $ceylon$language$Iterable$this$.getIndexed();
    }

    @.java.lang.Override
    public .java.lang.String toString() {
        return $ceylon$language$Iterable$this$.toString();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getCoalesced() {
        return $ceylon$language$Iterable$this$.getCoalesced();
    }

    @.java.lang.Override
    public boolean getEmpty() {
        return $ceylon$language$Iterable$this$.getEmpty();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getExceptLast() {
        return $ceylon$language$Iterable$this$.getExceptLast();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getRest() {
        return $ceylon$language$Iterable$this$.getRest();
    }

    @.java.lang.Override
    public Element getFirst() {
        return (Element)$ceylon$language$Iterable$this$.getFirst();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getDistinct() {
        return $ceylon$language$Iterable$this$.getDistinct();
    }

    @.java.lang.Override
    public long getSize() {
        return $ceylon$language$Iterable$this$.getSize();
    }

    @.java.lang.Override
    public boolean contains(final .java.lang.Object element) {
        return $ceylon$language$Iterable$this$.contains(element);
    }

    @.java.lang.Override
    public boolean longerThan(final long length) {
        return $ceylon$language$Iterable$this$.longerThan(length);
    }

    @.java.lang.Override
    public boolean shorterThan(final long length) {
        return $ceylon$language$Iterable$this$.shorterThan(length);
    }

    @.java.lang.Override
    public Element getFromFirst(final long index) {
        return $ceylon$language$Iterable$this$.getFromFirst(index);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> sequence() {
        return $ceylon$language$Iterable$this$.sequence();
    }

    @.java.lang.Override
    public .java.lang.Object indexes() {
        return $ceylon$language$Iterable$this$.indexes();
    }

    @.java.lang.Override
    public .java.lang.Object each(final .ceylon.language.Callable<? extends .java.lang.Object> step) {
        return $ceylon$language$Iterable$this$.each(step);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object> map(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.map($reified$Result, collecting);
    }

    @.java.lang.Override
    public <Result, OtherAbsent>.ceylon.language.Iterable flatMap(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends OtherAbsent>> collecting) {
        return (.ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.flatMap($reified$Result, $reified$OtherAbsent, collecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> filter(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.filter(selecting);
    }

    @.java.lang.Override
    public <Type>.ceylon.language.Iterable narrow(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Type) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.narrow($reified$Type);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Callable<? extends Result> fold(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return $ceylon$language$Iterable$this$.fold($reified$Result, initial);
    }

    @.java.lang.Override
    public <Result>.java.lang.Object reduce(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> accumulating) {
        return $ceylon$language$Iterable$this$.reduce($reified$Result, accumulating);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>> scan(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return $ceylon$language$Iterable$this$.scan($reified$Result, initial);
    }

    @.java.lang.Override
    public Element find(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.find(selecting);
    }

    @.java.lang.Override
    public Element findLast(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.findLast(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element> locate(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locate(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element> locateLast(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locateLast(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element>, ? extends .java.lang.Object> locations(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locations(selecting);
    }

    @.java.lang.Override
    public Element max(final .ceylon.language.Callable<? extends .ceylon.language.Comparison> comparing) {
        return (Element)$ceylon$language$Iterable$this$.max(comparing);
    }

    @.java.lang.Override
    public <Result, Args extends .ceylon.language.Sequential<? extends .java.lang.Object>>.ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>> spread(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Args, final .ceylon.language.Callable<? extends .ceylon.language.Callable<? extends Result>> method) {
        return $ceylon$language$Iterable$this$.spread($reified$Result, $reified$Args, method);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> sort(final .ceylon.language.Callable<? extends .ceylon.language.Comparison> comparing) {
        return $ceylon$language$Iterable$this$.sort(comparing);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Sequential<? extends Result> collect(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.collect($reified$Result, collecting);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> select(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.select(selecting);
    }

    @.java.lang.Override
    public long count(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.count(selecting);
    }

    @.java.lang.Override
    public boolean any(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.any(selecting);
    }

    @.java.lang.Override
    public boolean every(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.every(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> skip(final long skipping) {
        return $ceylon$language$Iterable$this$.skip(skipping);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> take(final long taking) {
        return $ceylon$language$Iterable$this$.take(taking);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> skipWhile(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> skipping) {
        return $ceylon$language$Iterable$this$.skipWhile(skipping);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> takeWhile(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> taking) {
        return $ceylon$language$Iterable$this$.takeWhile(taking);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> repeat(final long times) {
        return $ceylon$language$Iterable$this$.repeat(times);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> by(final long step) {
        return $ceylon$language$Iterable$this$.by(step);
    }

    @.java.lang.Override
    public <Default>.ceylon.language.Iterable defaultNullElements(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Default, final Default defaultValue) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.defaultNullElements($reified$Default, defaultValue);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends Element>, ? extends .java.lang.Object> partition(final long length) {
        return $ceylon$language$Iterable$this$.partition(length);
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable follow(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other head) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.follow($reified$Other, head);
    }

    @.java.lang.Override
    public <Other, OtherAbsent>.ceylon.language.Iterable chain(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Iterable<? extends Other, ? extends OtherAbsent> other) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.chain($reified$Other, $reified$OtherAbsent, other);
    }

    @.java.lang.Override
    public <Other, OtherAbsent>.ceylon.language.Iterable product(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Iterable<? extends Other, ? extends OtherAbsent> other) {
        return (.ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends .java.lang.Object>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.product($reified$Other, $reified$OtherAbsent, other);
    }

    @.java.lang.Override
    public final <Other>long interpose$step(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element) {
        return $ceylon$language$Iterable$this$.interpose$step($reified$Other, element);
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable interpose(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element) {
        return (
            let
            {
                long $ceylontmp$step$2 = interpose$step($reified$Other, element);
            }
            returning interpose$canonical$($reified$Other, element, $ceylontmp$step$2);
        );
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable interpose(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element, final long step) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.interpose($reified$Other, element, step);
    }

    private <Other>.ceylon.language.Iterable interpose$canonical$(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element, final long step) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.interpose($reified$Other, element, step);
    }

    @.java.lang.Override
    public final .ceylon.language.Map<? extends Element, ? extends .ceylon.language.Integer> frequencies() {
        return $ceylon$language$Iterable$this$.frequencies();
    }

    @.java.lang.Override
    public final <Result>.ceylon.language.Map<? extends Element, ? extends Result> tabulate(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.tabulate($reified$Result, collecting);
    }

    @.java.lang.Override
    public final <Group>.ceylon.language.Map<? extends Group, ? extends .ceylon.language.Sequence<? extends Element>> group(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Group, final .ceylon.language.Callable<? extends Group> grouping) {
        return $ceylon$language$Iterable$this$.group($reified$Group, grouping);
    }

    @.java.lang.Override
    public final <Group, Result>.ceylon.language.Map<? extends Group, ? extends Result> summarize(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Group, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Group> grouping, final .ceylon.language.Callable<? extends Result> accumulating) {
        return $ceylon$language$Iterable$this$.summarize($reified$Group, $reified$Result, grouping, accumulating);
    }
    protected final .ceylon.language.Category$impl<.java.lang.Object> $ceylon$language$Category$this$;

    @.java.lang.Override
    public .ceylon.language.Category$impl<? super .java.lang.Object> $ceylon$language$Category$impl() {
        return $ceylon$language$Category$this$;
    }

    @.java.lang.Override
    public boolean containsEvery(final .ceylon.language.Iterable<? extends .java.lang.Object, ? extends .java.lang.Object> elements) {
        return $ceylon$language$Category$this$.containsEvery(elements);
    }

    @.java.lang.Override
    public boolean containsAny(final .ceylon.language.Iterable<? extends .java.lang.Object, ? extends .java.lang.Object> elements) {
        return $ceylon$language$Category$this$.containsAny(elements);
    }

    @.java.lang.Override
    public .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $getType$() {
        return .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777_Impl.class, $reified$Element);
    }
}
public abstract class Bug1777_2<Element> implements .com.redhat.ceylon.compiler.java.runtime.model.ReifiedType, .ceylon.language.Iterable<Element, .java.lang.Object>, .java.io.Serializable {

    public Bug1777_2(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element) {
        this.$reified$Element = $reified$Element;
        this.$ceylon$language$Iterable$this$ = new .ceylon.language.Iterable$impl($reified$Element, .ceylon.language.Null.$TypeDescriptor$, this);
        this.$ceylon$language$Category$this$ = new .ceylon.language.Category$impl<.java.lang.Object>(.ceylon.language.Object.$TypeDescriptor$, this);
    }
    private final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Element;
    protected final .ceylon.language.Iterable$impl<Element, .java.lang.Object> $ceylon$language$Iterable$this$;

    @.java.lang.Override
    public .ceylon.language.Iterable$impl<? extends Element, ? extends .java.lang.Object> $ceylon$language$Iterable$impl() {
        return $ceylon$language$Iterable$this$;
    }

    @.java.lang.Override
    public .ceylon.language.Iterable getPaired() {
        return (.ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends Element>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.getPaired();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getCycled() {
        return $ceylon$language$Iterable$this$.getCycled();
    }

    @.java.lang.Override
    public Element getLast() {
        return (Element)$ceylon$language$Iterable$this$.getLast();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element>, ? extends .java.lang.Object> getIndexed() {
        return $ceylon$language$Iterable$this$.getIndexed();
    }

    @.java.lang.Override
    public .java.lang.String toString() {
        return $ceylon$language$Iterable$this$.toString();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getCoalesced() {
        return $ceylon$language$Iterable$this$.getCoalesced();
    }

    @.java.lang.Override
    public boolean getEmpty() {
        return $ceylon$language$Iterable$this$.getEmpty();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getExceptLast() {
        return $ceylon$language$Iterable$this$.getExceptLast();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getRest() {
        return $ceylon$language$Iterable$this$.getRest();
    }

    @.java.lang.Override
    public Element getFirst() {
        return (Element)$ceylon$language$Iterable$this$.getFirst();
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> getDistinct() {
        return $ceylon$language$Iterable$this$.getDistinct();
    }

    @.java.lang.Override
    public long getSize() {
        return $ceylon$language$Iterable$this$.getSize();
    }

    @.java.lang.Override
    public boolean contains(final .java.lang.Object element) {
        return $ceylon$language$Iterable$this$.contains(element);
    }

    @.java.lang.Override
    public boolean longerThan(final long length) {
        return $ceylon$language$Iterable$this$.longerThan(length);
    }

    @.java.lang.Override
    public boolean shorterThan(final long length) {
        return $ceylon$language$Iterable$this$.shorterThan(length);
    }

    @.java.lang.Override
    public Element getFromFirst(final long index) {
        return $ceylon$language$Iterable$this$.getFromFirst(index);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> sequence() {
        return $ceylon$language$Iterable$this$.sequence();
    }

    @.java.lang.Override
    public .java.lang.Object indexes() {
        return $ceylon$language$Iterable$this$.indexes();
    }

    @.java.lang.Override
    public .java.lang.Object each(final .ceylon.language.Callable<? extends .java.lang.Object> step) {
        return $ceylon$language$Iterable$this$.each(step);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object> map(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.map($reified$Result, collecting);
    }

    @.java.lang.Override
    public <Result, OtherAbsent>.ceylon.language.Iterable flatMap(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends OtherAbsent>> collecting) {
        return (.ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.flatMap($reified$Result, $reified$OtherAbsent, collecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> filter(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.filter(selecting);
    }

    @.java.lang.Override
    public <Type>.ceylon.language.Iterable narrow(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Type) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.narrow($reified$Type);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Callable<? extends Result> fold(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return $ceylon$language$Iterable$this$.fold($reified$Result, initial);
    }

    @.java.lang.Override
    public <Result>.java.lang.Object reduce(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> accumulating) {
        return $ceylon$language$Iterable$this$.reduce($reified$Result, accumulating);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>> scan(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return $ceylon$language$Iterable$this$.scan($reified$Result, initial);
    }

    @.java.lang.Override
    public Element find(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.find(selecting);
    }

    @.java.lang.Override
    public Element findLast(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.findLast(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element> locate(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locate(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element> locateLast(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locateLast(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Entry<? extends .ceylon.language.Integer, ? extends Element>, ? extends .java.lang.Object> locations(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.locations(selecting);
    }

    @.java.lang.Override
    public Element max(final .ceylon.language.Callable<? extends .ceylon.language.Comparison> comparing) {
        return (Element)$ceylon$language$Iterable$this$.max(comparing);
    }

    @.java.lang.Override
    public <Result, Args extends .ceylon.language.Sequential<? extends .java.lang.Object>>.ceylon.language.Callable<? extends .ceylon.language.Iterable<? extends Result, ? extends .java.lang.Object>> spread(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Args, final .ceylon.language.Callable<? extends .ceylon.language.Callable<? extends Result>> method) {
        return $ceylon$language$Iterable$this$.spread($reified$Result, $reified$Args, method);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> sort(final .ceylon.language.Callable<? extends .ceylon.language.Comparison> comparing) {
        return $ceylon$language$Iterable$this$.sort(comparing);
    }

    @.java.lang.Override
    public <Result>.ceylon.language.Sequential<? extends Result> collect(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.collect($reified$Result, collecting);
    }

    @.java.lang.Override
    public .ceylon.language.Sequential<? extends Element> select(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.select(selecting);
    }

    @.java.lang.Override
    public long count(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.count(selecting);
    }

    @.java.lang.Override
    public boolean any(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.any(selecting);
    }

    @.java.lang.Override
    public boolean every(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> selecting) {
        return $ceylon$language$Iterable$this$.every(selecting);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> skip(final long skipping) {
        return $ceylon$language$Iterable$this$.skip(skipping);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> take(final long taking) {
        return $ceylon$language$Iterable$this$.take(taking);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> skipWhile(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> skipping) {
        return $ceylon$language$Iterable$this$.skipWhile(skipping);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> takeWhile(final .ceylon.language.Callable<? extends .ceylon.language.Boolean> taking) {
        return $ceylon$language$Iterable$this$.takeWhile(taking);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> repeat(final long times) {
        return $ceylon$language$Iterable$this$.repeat(times);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends Element, ? extends .java.lang.Object> by(final long step) {
        return $ceylon$language$Iterable$this$.by(step);
    }

    @.java.lang.Override
    public <Default>.ceylon.language.Iterable defaultNullElements(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Default, final Default defaultValue) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.defaultNullElements($reified$Default, defaultValue);
    }

    @.java.lang.Override
    public .ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends Element>, ? extends .java.lang.Object> partition(final long length) {
        return $ceylon$language$Iterable$this$.partition(length);
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable follow(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other head) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.follow($reified$Other, head);
    }

    @.java.lang.Override
    public <Other, OtherAbsent>.ceylon.language.Iterable chain(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Iterable<? extends Other, ? extends OtherAbsent> other) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.chain($reified$Other, $reified$OtherAbsent, other);
    }

    @.java.lang.Override
    public <Other, OtherAbsent>.ceylon.language.Iterable product(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$OtherAbsent, final .ceylon.language.Iterable<? extends Other, ? extends OtherAbsent> other) {
        return (.ceylon.language.Iterable<? extends .ceylon.language.Sequence<? extends .java.lang.Object>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)$ceylon$language$Iterable$this$.product($reified$Other, $reified$OtherAbsent, other);
    }

    @.java.lang.Override
    public final <Other>long interpose$step(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element) {
        return $ceylon$language$Iterable$this$.interpose$step($reified$Other, element);
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable interpose(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element) {
        return (
            let
            {
                long $ceylontmp$step$3 = interpose$step($reified$Other, element);
            }
            returning interpose$canonical$($reified$Other, element, $ceylontmp$step$3);
        );
    }

    @.java.lang.Override
    public <Other>.ceylon.language.Iterable interpose(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element, final long step) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.interpose($reified$Other, element, step);
    }

    private <Other>.ceylon.language.Iterable interpose$canonical$(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Other, final Other element, final long step) {
        return (.ceylon.language.Iterable)$ceylon$language$Iterable$this$.interpose($reified$Other, element, step);
    }

    @.java.lang.Override
    public final .ceylon.language.Map<? extends Element, ? extends .ceylon.language.Integer> frequencies() {
        return $ceylon$language$Iterable$this$.frequencies();
    }

    @.java.lang.Override
    public final <Result>.ceylon.language.Map<? extends Element, ? extends Result> tabulate(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Result> collecting) {
        return $ceylon$language$Iterable$this$.tabulate($reified$Result, collecting);
    }

    @.java.lang.Override
    public final <Group>.ceylon.language.Map<? extends Group, ? extends .ceylon.language.Sequence<? extends Element>> group(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Group, final .ceylon.language.Callable<? extends Group> grouping) {
        return $ceylon$language$Iterable$this$.group($reified$Group, grouping);
    }

    @.java.lang.Override
    public final <Group, Result>.ceylon.language.Map<? extends Group, ? extends Result> summarize(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Group, final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final .ceylon.language.Callable<? extends Group> grouping, final .ceylon.language.Callable<? extends Result> accumulating) {
        return $ceylon$language$Iterable$this$.summarize($reified$Group, $reified$Result, grouping, accumulating);
    }
    protected final .ceylon.language.Category$impl<.java.lang.Object> $ceylon$language$Category$this$;

    @.java.lang.Override
    public .ceylon.language.Category$impl<? super .java.lang.Object> $ceylon$language$Category$impl() {
        return $ceylon$language$Category$this$;
    }

    @.java.lang.Override
    public boolean containsEvery(final .ceylon.language.Iterable<? extends .java.lang.Object, ? extends .java.lang.Object> elements) {
        return $ceylon$language$Category$this$.containsEvery(elements);
    }

    @.java.lang.Override
    public boolean containsAny(final .ceylon.language.Iterable<? extends .java.lang.Object, ? extends .java.lang.Object> elements) {
        return $ceylon$language$Category$this$.containsAny(elements);
    }

    public <Result>.ceylon.language.Callable<? extends Result> foldd(final .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $reified$Result, final Result initial) {
        return new .com.redhat.ceylon.compiler.java.language.AbstractCallable<Result>($reified$Result, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Callable.class, $reified$Result, .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, $reified$Result, $reified$Element))), "Result(Result(Result, Element))", (short)-1){

            @.java.lang.Override
            public Result $call$(final .java.lang.Object $param$0) {
                final .ceylon.language.Callable<? extends Result> accumulating = (.ceylon.language.Callable<? extends Result>)(.ceylon.language.Callable)$param$0;
                Result partial = initial;
                .java.lang.Object elem$4;
                .ceylon.language.Iterator<? extends Element> elem$iterator$$5 = .com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777_2<Element>.this.iterator();
                loop_1: while (!((elem$4 = elem$iterator$$5.next()) instanceof .ceylon.language.Finished)) {
                    final Element elem = (Element)elem$4;
                    partial = accumulating.$call$((.java.lang.Object)partial, elem);
                }
                return partial;
            }
        };
    }

    @.java.lang.Override
    public .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor $getType$() {
        return .com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.com.redhat.ceylon.compiler.java.test.issues.bug17xx.Bug1777_2.class, $reified$Element);
    }
}


/*
 * Copyright (c) 2003-2014 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include  <veriuser.h>
#include  <vpi_user.h>
#include  "priv.h"
#include  <assert.h>

static PLI_INT32 delay_callback(struct t_cb_data*cb)
{
      (void)cb; /* Parameter is not used. */
      vpi_printf("XXXX delay_callback called.\n");
      return 0;
}

int tf_isetdelay(PLI_INT32 delay, void*ss)
{
      vpiHandle sys = (vpiHandle)ss;
      int unit = vpi_get(vpiTimeUnit, sys);
      int prec = vpi_get(vpiTimePrecision, 0);

      struct t_cb_data cb;
      struct t_vpi_time ct;

      if (pli_trace) {
	    fprintf(pli_trace, "%s: tf_isetdelay(%d, ...)"
		    " <unit=%d, prec=%d>;\n",
		    vpi_get_str(vpiName, sys), (int)delay, unit, prec);
      }

	/* Convert the delay from the UNITS of the specified
	   task/function to the precision of the simulation. */
      assert(unit >= prec);

      while (unit > prec) {
	    PLI_INT32 tmp = delay * 10;
	    assert(tmp > delay);
	    delay = tmp;
	    unit -= 1;
      }

	/* Create a VPI callback to schedule the delay. */
      ct.type = vpiSimTime;
      ct.high = 0;
      ct.low  = delay;

      cb.reason = cbAfterDelay;
      cb.cb_rtn = delay_callback;
      cb.obj = 0;
      cb.time = &ct;
      cb.value = 0;
      cb.user_data = 0;
      vpi_register_cb(&cb);

      return 0;
}

int tf_setdelay(PLI_INT32 delay)
{
      return tf_isetdelay(delay, tf_getinstance());
}


#ifndef UTIL_H
#define UTIL_H

#include <stdlib.h>

void shuffle(int *, size_t);

#endif


/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the LICENSE file in
 * the root directory of this source tree.
 *
 * @flow
 * @format
 */

import * as React from 'react';

import nullthrows from 'nullthrows';

import type {ScrollbarIndicatorMark} from './main';

const MIN_PIXEL_HEIGHT = 4;

type MarkStyle = {
  width: number,
  offset: number,
  color: string,
};
type Props = {
  marks: Set<ScrollbarIndicatorMark>,
  screenRowForBufferRow(row: number): number,
  screenLineCount: number,
  markStyle: MarkStyle,
  height: number,
  width: number,
  editorIsVisible: boolean,
};

export default class ScrollBar extends React.PureComponent<Props> {
  _canvas: ?HTMLCanvasElement;
  _context: CanvasRenderingContext2D;

  componentDidMount() {
    const canvas = nullthrows(this._canvas);
    this._context = canvas.getContext('2d');
    this._drawToCanvas();
  }

  componentDidUpdate() {
    if (!this.props.editorIsVisible) {
      // Don't bother painting the canvas if it's not visible.
      return;
    }
    this._drawToCanvas();
  }

  _drawToCanvas() {
    const {width, height} = this._context.canvas;
    this._context.clearRect(0, 0, width, height);
    const {
      markStyle,
      screenRowForBufferRow,
      screenLineCount,
      marks,
    } = this.props;

    this._context.fillStyle = markStyle.color;
    marks.forEach(mark => {
      const screenStart = screenRowForBufferRow(mark.start);
      const screenEnd =
        // Often the mark is just one line. In that case, avoid the additional
        // call to `sceeenRowForBufferRow`
        mark.end === mark.start ? screenStart : screenRowForBufferRow(mark.end);

      const lineHeight = screenEnd - screenStart;
      const rangeHeight = Math.max(
        MIN_PIXEL_HEIGHT,
        Math.round(height * (lineHeight / screenLineCount)),
      );
      // Draw single lines as lines rather than ranges.
      const markPixelHeight = lineHeight === 1 ? MIN_PIXEL_HEIGHT : rangeHeight;
      const positionPercent = screenStart / screenLineCount;
      const pixelPosition = Math.floor(height * positionPercent);
      this._context.fillRect(
        markStyle.offset,
        pixelPosition,
        markStyle.width,
        markPixelHeight,
      );
    });
  }

  render(): React.Node {
    return (
      <canvas
        ref={node => (this._canvas = node)}
        height={this.props.height}
        width={this.props.width}
      />
    );
  }
}


// this is a test case to test whether rabit can recover model when
// facing an exception
#include <rabit.h>
#include <rabit/utils.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace rabit;

// dummy model
class Model : public rabit::Serializable {
 public:
  // iterations
  std::vector<float> data;
  // load from stream
  virtual void Load(rabit::Stream *fi) {
    fi->Read(&data);
  }
  /*! \brief save the model to the stream */
  virtual void Save(rabit::Stream *fo) const {
    fo->Write(data);
  }
  virtual void InitModel(size_t n, float v) {
    data.clear();
    data.resize(n, v);
  }
};

inline void TestMax(Model *model, Model *local, int ntrial, int iter) {
  int rank = rabit::GetRank();
  int nproc = rabit::GetWorldSize();
  const int z = iter + 111;
  std::vector<float> ndata(model->data.size());
  rabit::Allreduce<op::Max>(&ndata[0], ndata.size(),
                            [&]() {
                              // use lambda expression to prepare the data
                              for (size_t i = 0; i < ndata.size(); ++i) {
                                ndata[i] = (i * (rank+1)) % z  + local->data[i];
                              }
                            });

  for (size_t i = 0; i < ndata.size(); ++i) {
    float rmax = (i * 1) % z + model->data[i];
    for (int r = 0; r < nproc; ++r) {
      rmax = std::max(rmax, (float)((i * (r+1)) % z) + model->data[i] + r);
    }
    utils::Check(rmax == ndata[i], "[%d] TestMax check failure", rank);
  }
  model->data = ndata;
  local->data = ndata;
  for (size_t i = 0; i < ndata.size(); ++i) {
    local->data[i] = ndata[i] + rank;
  }
}

inline void TestSum(Model *model, Model *local, int ntrial, int iter) {
  int rank = rabit::GetRank();
  int nproc = rabit::GetWorldSize();
  const int z = 131 + iter;

  std::vector<float> ndata(model->data.size());
  for (size_t i = 0; i < ndata.size(); ++i) {
    ndata[i] = (i * (rank+1)) % z + local->data[i];
  }
  Allreduce<op::Sum>(&ndata[0], ndata.size());

  for (size_t i = 0; i < ndata.size(); ++i) {
    float rsum = 0.0f;
    for (int r = 0; r < nproc; ++r) {
      rsum += (float)((i * (r+1)) % z) + model->data[i] + r;
    }
    utils::Check(fabsf(rsum - ndata[i]) < 1e-5 ,
                 "[%d] TestSum check failure, local=%g, allreduce=%g", rank, rsum, ndata[i]);
  }
  model->data = ndata;
  for (size_t i = 0; i < ndata.size(); ++i) {
    local->data[i] = ndata[i] + rank;
  }
}

inline void TestBcast(size_t n, int root, int ntrial, int iter) {
  int rank = rabit::GetRank();
  std::string s; s.resize(n);
  for (size_t i = 0; i < n; ++i) {
    s[i] = char(i % 126 + 1);
  }
  std::string res;
  if (root == rank) {
    res = s;
    rabit::Broadcast(&res, root);
  } else {
    rabit::Broadcast(&res, root);
  }
  utils::Check(res == s, "[%d] TestBcast fail", rank);
}

int main(int argc, char *argv[]) {
  if (argc < 3) {
    printf("Usage: <ndata>\n");
    return 0;
  }
  int n = atoi(argv[1]);
  rabit::Init(argc, argv);
  int rank = rabit::GetRank();
  int nproc = rabit::GetWorldSize();
  std::string name = rabit::GetProcessorName();
  Model model, local;
  srand(0);
  int ntrial = 0;
  for (int i = 1; i < argc; ++i) {
    int n;
    if (sscanf(argv[i], "repeat=%d", &n) == 1) ntrial = n;
  }
  int iter = rabit::LoadCheckPoint(&model, &local);
  if (iter == 0) {
    model.InitModel(n, 1.0f);
    local.InitModel(n, 1.0f + rank);
    printf("[%d] reload-trail=%d, init iter=%d\n", rank, ntrial, iter);
  } else {
    printf("[%d] reload-trail=%d, init iter=%d\n", rank, ntrial, iter);
  }
  for (int r = iter; r < 3; ++r) {
    TestMax(&model, &local, ntrial, r);
    printf("[%d] !!!TestMax pass, iter=%d\n",  rank, r);
    int step = std::max(nproc / 3, 1);
    for (int i = 0; i < nproc; i += step) {
      TestBcast(n, i, ntrial, r);
    }
    printf("[%d] !!!TestBcast pass, iter=%d\n", rank, r);
    TestSum(&model, &local, ntrial, r);
    printf("[%d] !!!TestSum pass, iter=%d\n", rank, r);
    rabit::CheckPoint(&model, &local);
    printf("[%d] !!!CheckPont pass, iter=%d\n", rank, r);
  }
  rabit::Finalize();
  return 0;
}


#! /bin/bash
# del_html
# delete all html tags
# usage: del_html [filename]
file=$1
sed 's/<[^>]*>//g' $file #去掉所有html标签

sed '/<html>/,/<\/html>/!d' $file | sed '1d;$d'#截取<html>和</html>之间的内容


/**
 * @file
 * Transmission Control Protocol, outgoing traffic
 *
 * The output functions of TCP.
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

#include "lwip/opt.h"

#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */

#include "lwip/tcp.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/sys.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/inet.h"
#include "lwip/inet_chksum.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"

#include <string.h>

/* Forward declarations.*/
static void tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb);

static struct tcp_hdr *
tcp_output_set_header(struct tcp_pcb *pcb, struct pbuf *p, int optlen,
                      u32_t seqno_be /* already in network byte order */)
{
  struct tcp_hdr *tcphdr = p->payload;
  tcphdr->src = htons(pcb->local_port);
  tcphdr->dest = htons(pcb->remote_port);
  tcphdr->seqno = seqno_be;
  tcphdr->ackno = htonl(pcb->rcv_nxt);
  TCPH_FLAGS_SET(tcphdr, TCP_ACK);
  tcphdr->wnd = htons(pcb->rcv_ann_wnd);
  tcphdr->urgp = 0;
  TCPH_HDRLEN_SET(tcphdr, (5 + optlen / 4));
  tcphdr->chksum = 0;

  /* If we're sending a packet, update the announced right window edge */
  pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd;

  return tcphdr;
}

/**
 * Called by tcp_close() to send a segment including flags but not data.
 *
 * @param pcb the tcp_pcb over which to send a segment
 * @param flags the flags to set in the segment header
 * @return ERR_OK if sent, another err_t otherwise
 */
err_t
tcp_send_ctrl(struct tcp_pcb *pcb, u8_t flags)
{
  /* no data, no length, flags, copy=1, no optdata */
  return tcp_enqueue(pcb, NULL, 0, flags, TCP_WRITE_FLAG_COPY, 0);
}

/**
 * Write data for sending (but does not send it immediately).
 *
 * It waits in the expectation of more data being sent soon (as
 * it can send them more efficiently by combining them together).
 * To prompt the system to send data now, call tcp_output() after
 * calling tcp_write().
 *
 * @param pcb Protocol control block of the TCP connection to enqueue data for.
 * @param data pointer to the data to send
 * @param len length (in bytes) of the data to send
 * @param apiflags combination of following flags :
 * - TCP_WRITE_FLAG_COPY (0x01) data will be copied into memory belonging to the stack
 * - TCP_WRITE_FLAG_MORE (0x02) for TCP connection, PSH flag will be set on last segment sent,
 * @return ERR_OK if enqueued, another err_t on error
 *
 * @see tcp_write()
 */
err_t
tcp_write(struct tcp_pcb *pcb, const void *data, u16_t len, u8_t apiflags)
{
  LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_write(pcb=%p, data=%p, len=%"U16_F", apiflags=%"U16_F")\n", (void *)pcb,
    data, len, (u16_t)apiflags));
  /* connection is in valid state for data transmission? */
  if (pcb->state == ESTABLISHED ||
     pcb->state == CLOSE_WAIT ||
     pcb->state == SYN_SENT ||
     pcb->state == SYN_RCVD) {
    if (len > 0) {
#if LWIP_TCP_TIMESTAMPS
      return tcp_enqueue(pcb, (void *)data, len, 0, apiflags,
                         pcb->flags & TF_TIMESTAMP ? TF_SEG_OPTS_TS : 0);
#else
      return tcp_enqueue(pcb, (void *)data, len, 0, apiflags, 0);
#endif
    }
    return ERR_OK;
  } else {
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_STATE | 3, ("tcp_write() called in invalid state\n"));
    return ERR_CONN;
  }
}

/**
 * Enqueue data and/or TCP options for transmission
 *
 * Called by tcp_connect(), tcp_listen_input(), tcp_send_ctrl() and tcp_write().
 *
 * @param pcb Protocol control block for the TCP connection to enqueue data for.
 * @param arg Pointer to the data to be enqueued for sending.
 * @param len Data length in bytes
 * @param flags tcp header flags to set in the outgoing segment
 * @param apiflags combination of following flags :
 * - TCP_WRITE_FLAG_COPY (0x01) data will be copied into memory belonging to the stack
 * - TCP_WRITE_FLAG_MORE (0x02) for TCP connection, PSH flag will be set on last segment sent,
 * @param optflags options to include in segment later on (see definition of struct tcp_seg)
 */
err_t
tcp_enqueue(struct tcp_pcb *pcb, void *arg, u16_t len,
            u8_t flags, u8_t apiflags, u8_t optflags)
{
  struct pbuf *p;
  struct tcp_seg *seg, *useg, *queue;
  u32_t seqno;
  u16_t left, seglen;
  void *ptr;
  u16_t queuelen;
  u8_t optlen;

  LWIP_DEBUGF(TCP_OUTPUT_DEBUG,
              ("tcp_enqueue(pcb=%p, arg=%p, len=%"U16_F", flags=%"X16_F", apiflags=%"U16_F")\n",
               (void *)pcb, arg, len, (u16_t)flags, (u16_t)apiflags));
  LWIP_ERROR("tcp_enqueue: packet needs payload, options, or SYN/FIN (programmer violates API)",
             ((len != 0) || (optflags != 0) || ((flags & (TCP_SYN | TCP_FIN)) != 0)),
             return ERR_ARG;);
  LWIP_ERROR("tcp_enqueue: len != 0 || arg == NULL (programmer violates API)",
             ((len != 0) || (arg == NULL)), return ERR_ARG;);

  /* fail on too much data */
  if (len > pcb->snd_buf) {
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_enqueue: too much data (len=%"U16_F" > snd_buf=%"U16_F")\n", len, pcb->snd_buf));
    pcb->flags |= TF_NAGLEMEMERR;
    return ERR_MEM;
  }
  left = len;
  ptr = arg;

  optlen = LWIP_TCP_OPT_LENGTH(optflags);

  /* seqno will be the sequence number of the first segment enqueued
   * by the call to this function. */
  seqno = pcb->snd_lbb;

  LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue: queuelen: %"U16_F"\n", (u16_t)pcb->snd_queuelen));

  /* If total number of pbufs on the unsent/unacked queues exceeds the
   * configured maximum, return an error */
  queuelen = pcb->snd_queuelen;
  /* check for configured max queuelen and possible overflow */
  if ((queuelen >= TCP_SND_QUEUELEN) || (queuelen > TCP_SNDQUEUELEN_OVERFLOW)) {
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 3, ("tcp_enqueue: too long queue %"U16_F" (max %"U16_F")\n", queuelen, TCP_SND_QUEUELEN));
    TCP_STATS_INC(tcp.memerr);
    pcb->flags |= TF_NAGLEMEMERR;
    return ERR_MEM;
  }
  if (queuelen != 0) {
    LWIP_ASSERT("tcp_enqueue: pbufs on queue => at least one queue non-empty",
      pcb->unacked != NULL || pcb->unsent != NULL);
  } else {
    LWIP_ASSERT("tcp_enqueue: no pbufs on queue => both queues empty",
      pcb->unacked == NULL && pcb->unsent == NULL);
  }

  /* First, break up the data into segments and tuck them together in
   * the local "queue" variable. */
  useg = queue = seg = NULL;
  seglen = 0;
  while (queue == NULL || left > 0) {
    /* The segment length (including options) should be at most the MSS */
    seglen = left > (pcb->mss - optlen) ? (pcb->mss - optlen) : left;

    /* Allocate memory for tcp_seg, and fill in fields. */
    seg = memp_malloc(MEMP_TCP_SEG);
    if (seg == NULL) {
      LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2,
                  ("tcp_enqueue: could not allocate memory for tcp_seg\n"));
      goto memerr;
    }
    seg->next = NULL;
    seg->p = NULL;

    /* first segment of to-be-queued data? */
    if (queue == NULL) {
      queue = seg;
    }
    /* subsequent segments of to-be-queued data */
    else {
      /* Attach the segment to the end of the queued segments */
      LWIP_ASSERT("useg != NULL", useg != NULL);
      useg->next = seg;
    }
    /* remember last segment of to-be-queued data for next iteration */
    useg = seg;

    /* If copy is set, memory should be allocated
     * and data copied into pbuf, otherwise data comes from
     * ROM or other static memory, and need not be copied.  */
    if (apiflags & TCP_WRITE_FLAG_COPY) {
      if ((seg->p = pbuf_alloc(PBUF_TRANSPORT, seglen + optlen, PBUF_RAM)) == NULL) {
        LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2,
                    ("tcp_enqueue : could not allocate memory for pbuf copy size %"U16_F"\n", seglen));
        goto memerr;
      }
      LWIP_ASSERT("check that first pbuf can hold the complete seglen",
                  (seg->p->len >= seglen + optlen));
      queuelen += pbuf_clen(seg->p);
      if (arg != NULL) {
        MEMCPY((char *)seg->p->payload + optlen, ptr, seglen);
      }
      seg->dataptr = seg->p->payload;
    }
    /* do not copy data */
    else {
      /* First, allocate a pbuf for the headers. */
      if ((seg->p = pbuf_alloc(PBUF_TRANSPORT, optlen, PBUF_RAM)) == NULL) {
        LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2,
                    ("tcp_enqueue: could not allocate memory for header pbuf\n"));
        goto memerr;
      }
      queuelen += pbuf_clen(seg->p);

      /* Second, allocate a pbuf for holding the data.
       * since the referenced data is available at least until it is sent out on the
       * link (as it has to be ACKed by the remote party) we can safely use PBUF_ROM
       * instead of PBUF_REF here.
       */
      if (left > 0) {
        if ((p = pbuf_alloc(PBUF_RAW, seglen, PBUF_ROM)) == NULL) {
          /* If allocation fails, we have to deallocate the header pbuf as well. */
          pbuf_free(seg->p);
          seg->p = NULL;
          LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2,
                      ("tcp_enqueue: could not allocate memory for zero-copy pbuf\n"));
          goto memerr;
        }
        ++queuelen;
        /* reference the non-volatile payload data */
        p->payload = ptr;
        seg->dataptr = ptr;

        /* Concatenate the headers and data pbufs together. */
        pbuf_cat(seg->p/*header*/, p/*data*/);
        p = NULL;
      }
    }

    /* Now that there are more segments queued, we check again if the
    length of the queue exceeds the configured maximum or overflows. */
    if ((queuelen > TCP_SND_QUEUELEN) || (queuelen > TCP_SNDQUEUELEN_OVERFLOW)) {
      LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_enqueue: queue too long %"U16_F" (%"U16_F")\n", queuelen, TCP_SND_QUEUELEN));
      goto memerr;
    }

    seg->len = seglen;

    /* build TCP header */
    if (pbuf_header(seg->p, TCP_HLEN)) {
      LWIP_DEBUGF(TCP_OUTPUT_DEBUG | 2, ("tcp_enqueue: no room for TCP header in pbuf.\n"));
      TCP_STATS_INC(tcp.err);
      goto memerr;
    }
    seg->tcphdr = seg->p->payload;
    seg->tcphdr->src = htons(pcb->local_port);
    seg->tcphdr->dest = htons(pcb->remote_port);
    seg->tcphdr->seqno = htonl(seqno);
    seg->tcphdr->urgp = 0;
    TCPH_FLAGS_SET(seg->tcphdr, flags);
    /* don't fill in tcphdr->ackno and tcphdr->wnd until later */

    seg->flags = optflags;

    /* Set the length of the header */
    TCPH_HDRLEN_SET(seg->tcphdr, (5 + optlen / 4));
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE, ("tcp_enqueue: queueing %"U32_F":%"U32_F" (0x%"X16_F")\n",
      ntohl(seg->tcphdr->seqno),
      ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg),
      (u16_t)flags));

    left -= seglen;
    seqno += seglen;
    ptr = (void *)((u8_t *)ptr + seglen);
  }

  /* Now that the data to be enqueued has been broken up into TCP
  segments in the queue variable, we add them to the end of the
  pcb->unsent queue. */
  if (pcb->unsent == NULL) {
    useg = NULL;
  }
  else {
    for (useg = pcb->unsent; useg->next != NULL; useg = useg->next);
  }
  /* { useg is last segment on the unsent queue, NULL if list is empty } */

  /* If there is room in the last pbuf on the unsent queue,
  chain the first pbuf on the queue together with that. */
  if (useg != NULL &&
    TCP_TCPLEN(useg) != 0 &&
    !(TCPH_FLAGS(useg->tcphdr) & (TCP_SYN | TCP_FIN)) &&
    !(flags & (TCP_SYN | TCP_FIN)) &&
    /* fit within max seg size */
    (useg->len + queue->len <= pcb->mss) &&
    /* only concatenate segments with the same options */
    (useg->flags == queue->flags)) {
    /* Remove TCP header from first segment of our to-be-queued list */
    if(pbuf_header(queue->p, -(TCP_HLEN + optlen))) {
      /* Can we cope with this failing?  Just assert for now */
      LWIP_ASSERT("pbuf_header failed\n", 0);
      TCP_STATS_INC(tcp.err);
      goto memerr;
    }
    if (queue->p->len == 0) {
      /* free the first (header-only) pbuf if it is now empty (contained only headers) */
      struct pbuf *old_q = queue->p;
      queue->p = queue->p->next;
      old_q->next = NULL;
      queuelen--;
      pbuf_free(old_q);
    }
    LWIP_ASSERT("zero-length pbuf", (queue->p != NULL) && (queue->p->len > 0));
    pbuf_cat(useg->p, queue->p);
    useg->len += queue->len;
    useg->next = queue->next;

    LWIP_DEBUGF(TCP_OUTPUT_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("tcp_enqueue: chaining segments, new len %"U16_F"\n", useg->len));
    if (seg == queue) {
      seg = useg;
      seglen = useg->len;
    }
    memp_free(MEMP_TCP_SEG, queue);
  }
  else {
    /* empty list */
    if (useg == NULL) {
      /* initialize list with this segment */
      pcb->unsent = queue;
    }
    /* enqueue segment */
    else {
      useg->next = queue;
    }
  }
  if ((flags & TCP_SYN) || (flags & TCP_FIN)) {
    ++len;
  }
  if (flags & TCP_FIN) {
    pcb->flags |= TF_FIN;
  }
  pcb->snd_lbb += len;

  pcb->snd_buf -= len;

  /* update number of segments on the queues */
  pcb->snd_queuelen = queuelen;
  LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_enqueue: %"S16_F" (after enqueued)\n", pcb->snd_queuelen));
  if (pcb->snd_queuelen != 0) {
    LWIP_ASSERT("tcp_enqueue: valid queue length",
      pcb->unacked != NULL || pcb->unsent != NULL);
  }

  /* Set the PSH flag in the last segment that we enqueued, but only
  if the segment has data (indicated by seglen > 0). */
  if (seg != NULL && seglen > 0 && seg->tcphdr != NULL && ((apiflags & TCP_WRITE_FLAG_MORE)==0)) {
    TCPH_SET_FLAG(seg->tcphdr, TCP_PSH);
  }

  return ERR_OK;
memerr:
  pcb->flags |= TF_NAGLEMEMERR;
  TCP_STATS_INC(tcp.memerr);

  if (queue != NULL) {
    tcp_segs_free(queue);
  }
  if (pcb->snd_queuelen != 0) {
    LWIP_ASSERT("tcp_enqueue: valid queue length", pcb->unacked != NULL ||
      pcb->unsent != NULL);
  }
  LWIP_DEBUGF(TCP_QLEN_DEBUG | LWIP_DBG_STATE, ("tcp_enqueue: %"S16_F" (with mem err)\n", pcb->snd_queuelen));
  return ERR_MEM;
}

#if LWIP_TCP_TIMESTAMPS
/* Build a timestamp option (12 bytes long) at the specified options pointer)
 *
 * @param pcb tcp_pcb
 * @param opts option pointer where to store the timestamp option
 */
static void
tcp_build_timestamp_option(struct tcp_pcb *pcb, u32_t *opts)
{
  /* Pad with two NOP options to make everything nicely aligned */
  opts[0] = htonl(0x0101080A);
  opts[1] = htonl(sys_now());
  opts[2] = htonl(pcb->ts_recent);
}
#endif

/**
 * Find out what we can send and send it
 *
 * @param pcb Protocol control block for the TCP connection to send data
 * @return ERR_OK if data has been sent or nothing to send
 *         another err_t on error
 */
err_t
tcp_output(struct tcp_pcb *pcb)
{
  struct pbuf *p;
  struct tcp_hdr *tcphdr;
  struct tcp_seg *seg, *useg;
  u32_t wnd, snd_nxt;
#if TCP_CWND_DEBUG
  s16_t i = 0;
#endif /* TCP_CWND_DEBUG */
  u8_t optlen = 0;

  /* First, check if we are invoked by the TCP input processing
     code. If so, we do not output anything. Instead, we rely on the
     input processing code to call us when input processing is done
     with. */
  if (tcp_input_pcb == pcb) {
    return ERR_OK;
  }

  wnd = LWIP_MIN(pcb->snd_wnd, pcb->cwnd);

  seg = pcb->unsent;

  /* useg should point to last segment on unacked queue */
  useg = pcb->unacked;
  if (useg != NULL) {
    for (; useg->next != NULL; useg = useg->next);
  }

  /* If the TF_ACK_NOW flag is set and no data will be sent (either
   * because the ->unsent queue is empty or because the window does
   * not allow it), construct an empty ACK segment and send it.
   *
   * If data is to be sent, we will just piggyback the ACK (see below).
   */
  if (pcb->flags & TF_ACK_NOW &&
     (seg == NULL ||
      ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > wnd)) {
#if LWIP_TCP_TIMESTAMPS
    if (pcb->flags & TF_TIMESTAMP)
      optlen = LWIP_TCP_OPT_LENGTH(TF_SEG_OPTS_TS);
#endif
    p = pbuf_alloc(PBUF_IP, TCP_HLEN + optlen, PBUF_RAM);
    if (p == NULL) {
      LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: (ACK) could not allocate pbuf\n"));
      return ERR_BUF;
    }
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG,
                ("tcp_output: sending ACK for %"U32_F"\n", pcb->rcv_nxt));
    /* remove ACK flags from the PCB, as we send an empty ACK now */
    pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);

    tcphdr = tcp_output_set_header(pcb, p, optlen, htonl(pcb->snd_nxt));

    /* NB. MSS option is only sent on SYNs, so ignore it here */
#if LWIP_TCP_TIMESTAMPS
    pcb->ts_lastacksent = pcb->rcv_nxt;

    if (pcb->flags & TF_TIMESTAMP)
      tcp_build_timestamp_option(pcb, (u32_t *)(tcphdr + 1));
#endif

#if CHECKSUM_GEN_TCP
    tcphdr->chksum = inet_chksum_pseudo(p, &(pcb->local_ip), &(pcb->remote_ip),
          IP_PROTO_TCP, p->tot_len);
#endif
#if LWIP_NETIF_HWADDRHINT
    ip_output_hinted(p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos,
        IP_PROTO_TCP, &(pcb->addr_hint));
#else /* LWIP_NETIF_HWADDRHINT*/
    ip_output(p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos,
        IP_PROTO_TCP);
#endif /* LWIP_NETIF_HWADDRHINT*/
    pbuf_free(p);

    return ERR_OK;
  }

#if TCP_OUTPUT_DEBUG
  if (seg == NULL) {
    LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output: nothing to send (%p)\n",
                                   (void*)pcb->unsent));
  }
#endif /* TCP_OUTPUT_DEBUG */
#if TCP_CWND_DEBUG
  if (seg == NULL) {
    LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"U16_F
                                 ", cwnd %"U16_F", wnd %"U32_F
                                 ", seg == NULL, ack %"U32_F"\n",
                                 pcb->snd_wnd, pcb->cwnd, wnd, pcb->lastack));
  } else {
    LWIP_DEBUGF(TCP_CWND_DEBUG,
                ("tcp_output: snd_wnd %"U16_F", cwnd %"U16_F", wnd %"U32_F
                 ", effwnd %"U32_F", seq %"U32_F", ack %"U32_F"\n",
                 pcb->snd_wnd, pcb->cwnd, wnd,
                 ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len,
                 ntohl(seg->tcphdr->seqno), pcb->lastack));
  }
#endif /* TCP_CWND_DEBUG */
  /* data available and window allows it to be sent? */
  while (seg != NULL &&
         ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len <= wnd) {
    LWIP_ASSERT("RST not expected here!",
                (TCPH_FLAGS(seg->tcphdr) & TCP_RST) == 0);
    /* Stop sending if the nagle algorithm would prevent it
     * Don't stop:
     * - if tcp_enqueue had a memory error before (prevent delayed ACK timeout) or
     * - if FIN was already enqueued for this PCB (SYN is always alone in a segment -
     *   either seg->next != NULL or pcb->unacked == NULL;
     *   RST is no sent using tcp_enqueue/tcp_output.
     */
    if((tcp_do_output_nagle(pcb) == 0) &&
      ((pcb->flags & (TF_NAGLEMEMERR | TF_FIN)) == 0)){
      break;
    }
#if TCP_CWND_DEBUG
    LWIP_DEBUGF(TCP_CWND_DEBUG, ("tcp_output: snd_wnd %"U16_F", cwnd %"U16_F", wnd %"U32_F", effwnd %"U32_F", seq %"U32_F", ack %"U32_F", i %"S16_F"\n",
                            pcb->snd_wnd, pcb->cwnd, wnd,
                            ntohl(seg->tcphdr->seqno) + seg->len -
                            pcb->lastack,
                            ntohl(seg->tcphdr->seqno), pcb->lastack, i));
    ++i;
#endif /* TCP_CWND_DEBUG */

    pcb->unsent = seg->next;

    if (pcb->state != SYN_SENT) {
      TCPH_SET_FLAG(seg->tcphdr, TCP_ACK);
      pcb->flags &= ~(TF_ACK_DELAY | TF_ACK_NOW);
    }

    tcp_output_segment(seg, pcb);
    snd_nxt = ntohl(seg->tcphdr->seqno) + TCP_TCPLEN(seg);
    if (TCP_SEQ_LT(pcb->snd_nxt, snd_nxt)) {
      pcb->snd_nxt = snd_nxt;
    }
    /* put segment on unacknowledged list if length > 0 */
    if (TCP_TCPLEN(seg) > 0) {
      seg->next = NULL;
      /* unacked list is empty? */
      if (pcb->unacked == NULL) {
        pcb->unacked = seg;
        useg = seg;
      /* unacked list is not empty? */
      } else {
        /* In the case of fast retransmit, the packet should not go to the tail
         * of the unacked queue, but rather somewhere before it. We need to check for
         * this case. -STJ Jul 27, 2004 */
        if (TCP_SEQ_LT(ntohl(seg->tcphdr->seqno), ntohl(useg->tcphdr->seqno))){
          /* add segment to before tail of unacked list, keeping the list sorted */
          struct tcp_seg **cur_seg = &(pcb->unacked);
          while (*cur_seg &&
            TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) {
              cur_seg = &((*cur_seg)->next );
          }
          seg->next = (*cur_seg);
          (*cur_seg) = seg;
        } else {
          /* add segment to tail of unacked list */
          useg->next = seg;
          useg = useg->next;
        }
      }
    /* do not queue empty segments on the unacked list */
    } else {
      tcp_seg_free(seg);
    }
    seg = pcb->unsent;
  }

  if (seg != NULL && pcb->persist_backoff == 0 &&
      ntohl(seg->tcphdr->seqno) - pcb->lastack + seg->len > pcb->snd_wnd) {
    /* prepare for persist timer */
    pcb->persist_cnt = 0;
    pcb->persist_backoff = 1;
  }

  pcb->flags &= ~TF_NAGLEMEMERR;
  return ERR_OK;
}

/**
 * Called by tcp_output() to actually send a TCP segment over IP.
 *
 * @param seg the tcp_seg to send
 * @param pcb the tcp_pcb for the TCP connection used to send the segment
 */
static void
tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb)
{
  u16_t len;
  struct netif *netif;
  u32_t *opts;

  /** @bug Exclude retransmitted segments from this count. */
  snmp_inc_tcpoutsegs();

  /* The TCP header has already been constructed, but the ackno and
   wnd fields remain. */
  seg->tcphdr->ackno = htonl(pcb->rcv_nxt);

  /* advertise our receive window size in this TCP segment */
  seg->tcphdr->wnd = htons(pcb->rcv_ann_wnd);

  pcb->rcv_ann_right_edge = pcb->rcv_nxt + pcb->rcv_ann_wnd;

  /* Add any requested options.  NB MSS option is only set on SYN
     packets, so ignore it here */
  opts = (u32_t *)(seg->tcphdr + 1);
  if (seg->flags & TF_SEG_OPTS_MSS) {
    TCP_BUILD_MSS_OPTION(*opts);
    opts += 1;
  }
#if LWIP_TCP_TIMESTAMPS
  pcb->ts_lastacksent = pcb->rcv_nxt;

  if (seg->flags & TF_SEG_OPTS_TS) {
    tcp_build_timestamp_option(pcb, opts);
    opts += 3;
  }
#endif

  /* If we don't have a local IP address, we get one by
     calling ip_route(). */
  if (ip_addr_isany(&(pcb->local_ip))) {
    netif = ip_route(&(pcb->remote_ip));
    if (netif == NULL) {
      return;
    }
    ip_addr_set(&(pcb->local_ip), &(netif->ip_addr));
  }

  /* Set retransmission timer running if it is not currently enabled */
  if(pcb->rtime == -1)
    pcb->rtime = 0;

  if (pcb->rttest == 0) {
    pcb->rttest = tcp_ticks;
    pcb->rtseq = ntohl(seg->tcphdr->seqno);

    LWIP_DEBUGF(TCP_RTO_DEBUG, ("tcp_output_segment: rtseq %"U32_F"\n", pcb->rtseq));
  }
  LWIP_DEBUGF(TCP_OUTPUT_DEBUG, ("tcp_output_segment: %"U32_F":%"U32_F"\n",
          htonl(seg->tcphdr->seqno), htonl(seg->tcphdr->seqno) +
          seg->len));

  len = (u16_t)((u8_t *)seg->tcphdr - (u8_t *)seg->p->payload);

  seg->p->len -= len;
  seg->p->tot_len -= len;

  seg->p->payload = seg->tcphdr;

  seg->tcphdr->chksum = 0;
#if CHECKSUM_GEN_TCP
  seg->tcphdr->chksum = inet_chksum_pseudo(seg->p,
             &(pcb->local_ip),
             &(pcb->remote_ip),
             IP_PROTO_TCP, seg->p->tot_len);
#endif
  TCP_STATS_INC(tcp.xmit);

#if LWIP_NETIF_HWADDRHINT
  ip_output_hinted(seg->p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos,
      IP_PROTO_TCP, &(pcb->addr_hint));
#else /* LWIP_NETIF_HWADDRHINT*/
  ip_output(seg->p, &(pcb->local_ip), &(pcb->remote_ip), pcb->ttl, pcb->tos,
      IP_PROTO_TCP);
#endif /* LWIP_NETIF_HWADDRHINT*/
}

/**
 * Send a TCP RESET packet (empty segment with RST flag set) either to
 * abort a connection or to show that there is no matching local connection
 * for a received segment.
 *
 * Called by tcp_abort() (to abort a local connection), tcp_input() (if no
 * matching local pcb was found), tcp_listen_input() (if incoming segment
 * has ACK flag set) and tcp_process() (received segment in the wrong state)
 *
 * Since a RST segment is in most cases not sent for an active connection,
 * tcp_rst() has a number of arguments that are taken from a tcp_pcb for
 * most other segment output functions.
 *
 * @param seqno the sequence number to use for the outgoing segment
 * @param ackno the acknowledge number to use for the outgoing segment
 * @param local_ip the local IP address to send the segment from
 * @param remote_ip the remote IP address to send the segment to
 * @param local_port the local TCP port to send the segment from
 * @param remote_port the remote TCP port to send the segment to
 */
void
tcp_rst(u32_t seqno, u32_t ackno,
  struct ip_addr *local_ip, struct ip_addr *remote_ip,
  u16_t local_port, u16_t remote_port)
{
  struct pbuf *p;
  struct tcp_hdr *tcphdr;
  p = pbuf_alloc(PBUF_IP, TCP_HLEN, PBUF_RAM);
  if (p == NULL) {
      LWIP_DEBUGF(TCP_DEBUG, ("tcp_rst: could not allocate memory for pbuf\n"));
      return;
  }
  LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
              (p->len >= sizeof(struct tcp_hdr)));

  tcphdr = p->payload;
  tcphdr->src = htons(local_port);
  tcphdr->dest = htons(remote_port);
  tcphdr->seqno = htonl(seqno);
  tcphdr->ackno = htonl(ackno);
  TCPH_FLAGS_SET(tcphdr, TCP_RST | TCP_ACK);
  tcphdr->wnd = htons(TCP_WND);
  tcphdr->urgp = 0;
  TCPH_HDRLEN_SET(tcphdr, 5);

  tcphdr->chksum = 0;
#if CHECKSUM_GEN_TCP
  tcphdr->chksum = inet_chksum_pseudo(p, local_ip, remote_ip,
              IP_PROTO_TCP, p->tot_len);
#endif
  TCP_STATS_INC(tcp.xmit);
  snmp_inc_tcpoutrsts();
   /* Send output with hardcoded TTL since we have no access to the pcb */
  ip_output(p, local_ip, remote_ip, TCP_TTL, 0, IP_PROTO_TCP);
  pbuf_free(p);
  LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_rst: seqno %"U32_F" ackno %"U32_F".\n", seqno, ackno));
}

/**
 * Requeue all unacked segments for retransmission
 *
 * Called by tcp_slowtmr() for slow retransmission.
 *
 * @param pcb the tcp_pcb for which to re-enqueue all unacked segments
 */
void
tcp_rexmit_rto(struct tcp_pcb *pcb)
{
  struct tcp_seg *seg;

  if (pcb->unacked == NULL) {
    return;
  }

  /* Move all unacked segments to the head of the unsent queue */
  for (seg = pcb->unacked; seg->next != NULL; seg = seg->next);
  /* concatenate unsent queue after unacked queue */
  seg->next = pcb->unsent;
  /* unsent queue is the concatenated queue (of unacked, unsent) */
  pcb->unsent = pcb->unacked;
  /* unacked queue is now empty */
  pcb->unacked = NULL;

  /* increment number of retransmissions */
  ++pcb->nrtx;

  /* Don't take any RTT measurements after retransmitting. */
  pcb->rttest = 0;

  /* Do the actual retransmission */
  tcp_output(pcb);
}

/**
 * Requeue the first unacked segment for retransmission
 *
 * Called by tcp_receive() for fast retramsmit.
 *
 * @param pcb the tcp_pcb for which to retransmit the first unacked segment
 */
void
tcp_rexmit(struct tcp_pcb *pcb)
{
  struct tcp_seg *seg;
  struct tcp_seg **cur_seg;

  if (pcb->unacked == NULL) {
    return;
  }

  /* Move the first unacked segment to the unsent queue */
  /* Keep the unsent queue sorted. */
  seg = pcb->unacked;
  pcb->unacked = seg->next;

  cur_seg = &(pcb->unsent);
  while (*cur_seg &&
    TCP_SEQ_LT(ntohl((*cur_seg)->tcphdr->seqno), ntohl(seg->tcphdr->seqno))) {
      cur_seg = &((*cur_seg)->next );
  }
  seg->next = *cur_seg;
  *cur_seg = seg;

  ++pcb->nrtx;

  /* Don't take any rtt measurements after retransmitting. */
  pcb->rttest = 0;

  /* Do the actual retransmission. */
  snmp_inc_tcpretranssegs();
  tcp_output(pcb);
}

/**
 * Send keepalive packets to keep a connection active although
 * no data is sent over it.
 *
 * Called by tcp_slowtmr()
 *
 * @param pcb the tcp_pcb for which to send a keepalive packet
 */
void
tcp_keepalive(struct tcp_pcb *pcb)
{
  struct pbuf *p;
  struct tcp_hdr *tcphdr;

  LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: sending KEEPALIVE probe to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
                          ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
                          ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip)));

  LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: tcp_ticks %"U32_F"   pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n",
                          tcp_ticks, pcb->tmr, pcb->keep_cnt_sent));

  p = pbuf_alloc(PBUF_IP, TCP_HLEN, PBUF_RAM);

  if(p == NULL) {
    LWIP_DEBUGF(TCP_DEBUG,
                ("tcp_keepalive: could not allocate memory for pbuf\n"));
    return;
  }
  LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
              (p->len >= sizeof(struct tcp_hdr)));

  tcphdr = tcp_output_set_header(pcb, p, 0, htonl(pcb->snd_nxt - 1));

#if CHECKSUM_GEN_TCP
  tcphdr->chksum = inet_chksum_pseudo(p, &pcb->local_ip, &pcb->remote_ip,
                                      IP_PROTO_TCP, p->tot_len);
#endif
  TCP_STATS_INC(tcp.xmit);

  /* Send output to IP */
#if LWIP_NETIF_HWADDRHINT
  ip_output_hinted(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP,
    &(pcb->addr_hint));
#else /* LWIP_NETIF_HWADDRHINT*/
  ip_output(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP);
#endif /* LWIP_NETIF_HWADDRHINT*/

  pbuf_free(p);

  LWIP_DEBUGF(TCP_DEBUG, ("tcp_keepalive: seqno %"U32_F" ackno %"U32_F".\n",
                          pcb->snd_nxt - 1, pcb->rcv_nxt));
}

/**
 * Send persist timer zero-window probes to keep a connection active
 * when a window update is lost.
 *
 * Called by tcp_slowtmr()
 *
 * @param pcb the tcp_pcb for which to send a zero-window probe packet
 */
void
tcp_zero_window_probe(struct tcp_pcb *pcb)
{
  struct pbuf *p;
  struct tcp_hdr *tcphdr;
  struct tcp_seg *seg;

  LWIP_DEBUGF(TCP_DEBUG,
              ("tcp_zero_window_probe: sending ZERO WINDOW probe to %"
               U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
               ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
               ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip)));

  LWIP_DEBUGF(TCP_DEBUG,
              ("tcp_zero_window_probe: tcp_ticks %"U32_F
               "   pcb->tmr %"U32_F" pcb->keep_cnt_sent %"U16_F"\n",
               tcp_ticks, pcb->tmr, pcb->keep_cnt_sent));

  seg = pcb->unacked;

  if(seg == NULL)
    seg = pcb->unsent;

  if(seg == NULL)
    return;

  p = pbuf_alloc(PBUF_IP, TCP_HLEN + 1, PBUF_RAM);

  if(p == NULL) {
    LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: no memory for pbuf\n"));
    return;
  }
  LWIP_ASSERT("check that first pbuf can hold struct tcp_hdr",
              (p->len >= sizeof(struct tcp_hdr)));

  tcphdr = tcp_output_set_header(pcb, p, 0, seg->tcphdr->seqno);

  /* Copy in one byte from the head of the unacked queue */
  *((char *)p->payload + sizeof(struct tcp_hdr)) = *(char *)seg->dataptr;

#if CHECKSUM_GEN_TCP
  tcphdr->chksum = inet_chksum_pseudo(p, &pcb->local_ip, &pcb->remote_ip,
                                      IP_PROTO_TCP, p->tot_len);
#endif
  TCP_STATS_INC(tcp.xmit);

  /* Send output to IP */
#if LWIP_NETIF_HWADDRHINT
  ip_output_hinted(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP,
    &(pcb->addr_hint));
#else /* LWIP_NETIF_HWADDRHINT*/
  ip_output(p, &pcb->local_ip, &pcb->remote_ip, pcb->ttl, 0, IP_PROTO_TCP);
#endif /* LWIP_NETIF_HWADDRHINT*/

  pbuf_free(p);

  LWIP_DEBUGF(TCP_DEBUG, ("tcp_zero_window_probe: seqno %"U32_F
                          " ackno %"U32_F".\n",
                          pcb->snd_nxt - 1, pcb->rcv_nxt));
}
#endif /* LWIP_TCP */


var server = require('./server')
  , events = require('events')
  , stream = require('stream')
  , assert = require('assert')
  , request = require('../main.js')
  ;

var s = server.createServer();
var expectedBody = "waited";
var remainingTests = 5;

s.listen(s.port, function () {
  // Request that waits for 200ms
  s.on('/timeout', function (req, resp) {
    setTimeout(function(){
      resp.writeHead(200, {'content-type':'text/plain'})
      resp.write(expectedBody)
      resp.end()
    }, 200);
  });

  // Scenario that should timeout
  var shouldTimeout = {
    url: s.url + "/timeout",
    timeout:100
  }

  request(shouldTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  // Scenario that shouldn't timeout
  var shouldntTimeout = {
    url: s.url + "/timeout",
    timeout:300
  }

  request(shouldntTimeout, function (err, resp, body) {
    assert.equal(err, null);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with no timeout set, so shouldn't timeout
  var noTimeout = {
    url: s.url + "/timeout"
  }

  request(noTimeout, function (err, resp, body) {
    assert.equal(err);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with a negative timeout value, should be treated a zero or the minimum delay
  var negativeTimeout = {
    url: s.url + "/timeout",
    timeout:-1000
  }

  request(negativeTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  // Scenario with a float timeout value, should be rounded by setTimeout anyway
  var floatTimeout = {
    url: s.url + "/timeout",
    timeout: 100.76
  }

  request(floatTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  function checkDone() {
    if(--remainingTests == 0) {
      s.close();
      console.log("All tests passed.");
    }
  }
})


/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1

import (
	"fmt"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Describes a certificate signing request
type CertificateSigningRequest struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// The certificate request itself and any additional information.
	// +optional
	Spec CertificateSigningRequestSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`

	// Derived information about the request.
	// +optional
	Status CertificateSigningRequestStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

// This information is immutable after the request is created. Only the Request
// and Usages fields can be set on creation, other fields are derived by
// Kubernetes and cannot be modified by users.
type CertificateSigningRequestSpec struct {
	// Base64-encoded PKCS#10 CSR data
	Request []byte `json:"request" protobuf:"bytes,1,opt,name=request"`

	// allowedUsages specifies a set of usage contexts the key will be
	// valid for.
	// See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3
	//      https://tools.ietf.org/html/rfc5280#section-4.2.1.12
	Usages []KeyUsage `json:"usages,omitempty" protobuf:"bytes,5,opt,name=usages"`

	// Information about the requesting user.
	// See user.Info interface for details.
	// +optional
	Username string `json:"username,omitempty" protobuf:"bytes,2,opt,name=username"`
	// UID information about the requesting user.
	// See user.Info interface for details.
	// +optional
	UID string `json:"uid,omitempty" protobuf:"bytes,3,opt,name=uid"`
	// Group information about the requesting user.
	// See user.Info interface for details.
	// +optional
	Groups []string `json:"groups,omitempty" protobuf:"bytes,4,rep,name=groups"`
	// Extra information about the requesting user.
	// See user.Info interface for details.
	// +optional
	Extra map[string]ExtraValue `json:"extra,omitempty" protobuf:"bytes,6,rep,name=extra"`
}

// ExtraValue masks the value so protobuf can generate
// +protobuf.nullable=true
// +protobuf.options.(gogoproto.goproto_stringer)=false
type ExtraValue []string

func (t ExtraValue) String() string {
	return fmt.Sprintf("%v", []string(t))
}

type CertificateSigningRequestStatus struct {
	// Conditions applied to the request, such as approval or denial.
	// +optional
	Conditions []CertificateSigningRequestCondition `json:"conditions,omitempty" protobuf:"bytes,1,rep,name=conditions"`

	// If request was approved, the controller will place the issued certificate here.
	// +optional
	Certificate []byte `json:"certificate,omitempty" protobuf:"bytes,2,opt,name=certificate"`
}

type RequestConditionType string

// These are the possible conditions for a certificate request.
const (
	CertificateApproved RequestConditionType = "Approved"
	CertificateDenied   RequestConditionType = "Denied"
)

type CertificateSigningRequestCondition struct {
	// request approval state, currently Approved or Denied.
	Type RequestConditionType `json:"type" protobuf:"bytes,1,opt,name=type,casttype=RequestConditionType"`
	// brief reason for the request state
	// +optional
	Reason string `json:"reason,omitempty" protobuf:"bytes,2,opt,name=reason"`
	// human readable message with details about the request state
	// +optional
	Message string `json:"message,omitempty" protobuf:"bytes,3,opt,name=message"`
	// timestamp for the last update to this condition
	// +optional
	LastUpdateTime metav1.Time `json:"lastUpdateTime,omitempty" protobuf:"bytes,4,opt,name=lastUpdateTime"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

type CertificateSigningRequestList struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	Items []CertificateSigningRequest `json:"items" protobuf:"bytes,2,rep,name=items"`
}

// KeyUsages specifies valid usage contexts for keys.
// See: https://tools.ietf.org/html/rfc5280#section-4.2.1.3
//      https://tools.ietf.org/html/rfc5280#section-4.2.1.12
type KeyUsage string

const (
	UsageSigning            KeyUsage = "signing"
	UsageDigitalSignature   KeyUsage = "digital signature"
	UsageContentCommittment KeyUsage = "content commitment"
	UsageKeyEncipherment    KeyUsage = "key encipherment"
	UsageKeyAgreement       KeyUsage = "key agreement"
	UsageDataEncipherment   KeyUsage = "data encipherment"
	UsageCertSign           KeyUsage = "cert sign"
	UsageCRLSign            KeyUsage = "crl sign"
	UsageEncipherOnly       KeyUsage = "encipher only"
	UsageDecipherOnly       KeyUsage = "decipher only"
	UsageAny                KeyUsage = "any"
	UsageServerAuth         KeyUsage = "server auth"
	UsageClientAuth         KeyUsage = "client auth"
	UsageCodeSigning        KeyUsage = "code signing"
	UsageEmailProtection    KeyUsage = "email protection"
	UsageSMIME              KeyUsage = "s/mime"
	UsageIPsecEndSystem     KeyUsage = "ipsec end system"
	UsageIPsecTunnel        KeyUsage = "ipsec tunnel"
	UsageIPsecUser          KeyUsage = "ipsec user"
	UsageTimestamping       KeyUsage = "timestamping"
	UsageOCSPSigning        KeyUsage = "ocsp signing"
	UsageMicrosoftSGC       KeyUsage = "microsoft sgc"
	UsageNetscapSGC         KeyUsage = "netscape sgc"
)


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using NuGet.Services.Messaging.Email;
using System;
using System.Net.Mail;

namespace NuGetGallery.AccountDeleter
{
    public class DisposableEmailBuilder : IEmailBuilder
    {
        protected static string USERNAME_PLACEHOLDER = "{username}";

        private readonly IEmailBuilder _parentEmailBuilder;
        private readonly IEmailRecipients _emailRecipients;
        private readonly string _username;

        public DisposableEmailBuilder(IEmailBuilder parentBuilder, IEmailRecipients emailRecipients, string username)
        {
            _parentEmailBuilder = parentBuilder ?? throw new ArgumentNullException(nameof(parentBuilder));
            _emailRecipients = emailRecipients ?? throw new ArgumentNullException(nameof(emailRecipients));
            _username = username;
        }

        public MailAddress Sender
        {
            get
            {
                return _parentEmailBuilder.Sender;
            }
        }

        public string GetBody(EmailFormat format)
        {
            // run through a replacer
            return _parentEmailBuilder.GetBody(format).Replace(USERNAME_PLACEHOLDER, _username);
        }

        public IEmailRecipients GetRecipients()
        {
            return _emailRecipients;
        }

        public string GetSubject()
        {
            // run through a replacer
            return _parentEmailBuilder.GetSubject().Replace(USERNAME_PLACEHOLDER, _username);
        }
    }
}


"""
Scraping jobs given job title and location from indeed website
"""
from __future__ import annotations

from typing import Generator

import requests
from bs4 import BeautifulSoup

url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l="

def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]:
    soup = BeautifulSoup(requests.get(url + location).content, "html.parser")
    # This attribute finds out all the specifics listed in a job
    for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}):
        job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip()
        company_name = job.find("span", {"class": "company"}).text.strip()
        yield job_title, company_name

if __name__ == "__main__":
    for i, job in enumerate(fetch_jobs("Bangalore"), 1):
        print(f"Job {i:>2} is {job[0]} at {job[1]}")


# Test the LinearSystem component.

import unittest
import numpy as np

from openmdao.api import Group, Problem, LinearSystem, IndepVarComp, ScipyGMRES
from openmdao.test.util import assert_rel_error

class TestLinearSystem(unittest.TestCase):

    def test_linear_system(self):
        root = Group()

        lingrp = root.add('lingrp', Group(), promotes=['*'])
        lingrp.add('lin', LinearSystem(3))
        lingrp.ln_solver = ScipyGMRES()

        x = np.array([1, 2, -3])
        A = np.array([[ 5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]])
        b = A.dot(x)

        root.add('p1', IndepVarComp('A', A))
        root.add('p2', IndepVarComp('b', b))
        root.connect('p1.A', 'lin.A')
        root.connect('p2.b', 'lin.b')

        prob = Problem(root)
        prob.setup(check=False)
        prob.run()

        # Make sure it gets the right answer
        assert_rel_error(self, prob['lin.x'], x, .0001)
        assert_rel_error(self, np.linalg.norm(prob.root.resids.vec), 0.0, 1e-10)

        # Compare against calculated derivs
        Ainv = np.linalg.inv(A)
        dx_dA = np.outer(Ainv, -x).reshape(3, 9)
        dx_db = Ainv

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='rev', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='fd', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

    def test_linear_system_solve_linear(self):
        root = Group()

        lingrp = root.add('lingrp', Group(), promotes=['*'])
        lingrp.add('lin', LinearSystem(3))

        x = np.array([1, 2, -3])
        A = np.array([[ 5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]])
        b = A.dot(x)

        root.add('p1', IndepVarComp('A', A))
        root.add('p2', IndepVarComp('b', b))
        root.connect('p1.A', 'lin.A')
        root.connect('p2.b', 'lin.b')

        prob = Problem(root)
        prob.setup(check=False)
        prob.run()

        # Make sure it gets the right answer
        assert_rel_error(self, prob['lin.x'], x, .0001)
        assert_rel_error(self, np.linalg.norm(prob.root.resids.vec), 0.0, 1e-10)

        # Compare against calculated derivs
        Ainv = np.linalg.inv(A)
        dx_dA = np.outer(Ainv, -x).reshape(3, 9)
        dx_db = Ainv

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='rev', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'], mode='fd', return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

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


# package key

`import "github.com/vivint/rothko/draw/key"`

package key provides a way to draw a heatmap key

## Usage

#### func  Draw

```go
func Draw(canvas *draw.RGB, opts Options) (out *draw.RGB)
```
Draw draws a key using values from Options on to the provided canvas, allocating
an output canvas if the input is not large enough.

#### type Options

```go
type Options struct {
	// Colors is the slice of colors to map the column data on to.
	Colors []draw.Color

	// Height is how tall the key will be.
	Height int

	// Width is how wide the key will be.
	Width int
}
```

Options are the things you can specify to control the rendering of a key.