text:
package org.tensorflow.op.generator;

import static org.tensorflow.op.generator.GeneratorUtils.javaizeMemberName;
import static org.tensorflow.op.generator.GeneratorUtils.parseDocumentation;

import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ArrayTypeName;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeSpec.Builder;
import com.squareup.javapoet.TypeVariableName;
import com.squareup.javapoet.WildcardTypeName;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import javax.lang.model.element.Modifier;
import org.tensorflow.Names;
import org.tensorflow.proto.framework.ApiDef;
import org.tensorflow.proto.framework.ApiDef.Endpoint;
import org.tensorflow.proto.framework.ApiDef.Visibility;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.proto.framework.OpDef;
import org.tensorflow.proto.framework.OpDef.ArgDef;
import org.tensorflow.proto.framework.OpDef.AttrDef;

/** A generator to generate a op class */
final class ClassGenerator {

  /** Return true if we can generate the operation class for {@code op}. */
  static boolean canGenerateOp(OpDef op, ApiDef apiDef) {
    return apiDef.getVisibility() != Visibility.SKIP
        && !op.getName()
            .startsWith("_"); // TODO do I want this?  Some interesting ops like _XlaCompile
  }

  enum RenderMode {
    DEFAULT,
    LIST_OPERAND,
    OPERAND;
  }

  private static final String OP_NAME_FIELD = "OP_NAME";
  private static final String INPUTS_CLASS_NAME = "Inputs";

  /** The in-progress class builder for the top level op class. */
  private final TypeSpec.Builder builder;

  /** The op to build. */
  private final OpDef op;

  /** The api definition for the current op. */
  private final ApiDef apiDef;

  /** A type resolver for the current op. */
  private final TypeResolver resolver;

  /** The full package of the class. */
  private final String fullPackage;

  /** The base package for this op generation run. */
  private final String basePackage;

  /** The group of this op. */
  private final String group;

  /** The class name for this op. */
  private final String className;

  /** The endpoint being generated in this class. */
  private final Endpoint endpoint;

  private final StatefulPair statefulPair;
  private final boolean isStateSelector;
  private final boolean isStateSubclass;

  /**
   * The generated options class, or null if it doesn't have one or {@link #buildOptionsClass()} has
   * not been ran.
   */
  private TypeSpec optionsClass = null;

  /** What type of op this is. */
  private RenderMode mode = RenderMode.DEFAULT;

  /** The required attributes of this op. */
  private final List<AttrDef> requiredAttributes = new ArrayList<>();

  /** The optional attributes of this op. */
  private final List<AttrDef> optionalAttributes = new ArrayList<>();

  /** The class's type parameters, initialized in {@link #buildClass()}. */
  private final Set<TypeVariableName> typeParams = new LinkedHashSet<>();

  /** The api defs for the arguments. */
  private final Map<ArgDef, ApiDef.Arg> argApis = new HashMap<>();

  /** The api defs for the attributes. */
  private final Map<AttrDef, ApiDef.Attr> attrApis = new HashMap<>();

  ClassGenerator(
      Builder builder,
      OpDef op,
      ApiDef apiDef,
      String basePackage,
      String fullPackage,
      String group,
      String className,
      Endpoint endpoint,
      StatefulPair statefulPair) {

    this.builder = builder;
    this.op = op;
    this.apiDef = apiDef;
    this.resolver = new TypeResolver(op);
    this.basePackage = basePackage;
    this.fullPackage = fullPackage;
    this.group = group;
    this.className = className;
    this.endpoint = endpoint;
    this.statefulPair = statefulPair;
    this.isStateSelector = statefulPair != null && className.equals(statefulPair.selectorClassName);
    this.isStateSubclass = statefulPair != null && !isStateSelector;

    op.getAttrList()
        .forEach(
            attr -> {
              if (attr.hasDefaultValue() && !attr.getType().contains("type")) {
                optionalAttributes.add(attr);
              } else {
                requiredAttributes.add(attr);
              }
            });

    for (AttrDef attr : op.getAttrList()) {
      ApiDef.Attr api =
          apiDef.getAttrList().stream()
              .filter(x -> x.getName().equals(attr.getName()))
              .findFirst()
              .get();
      attrApis.put(attr, api);
    }

    for (ArgDef arg : op.getInputArgList()) {
      ApiDef.Arg api =
          apiDef.getInArgList().stream()
              .filter(x -> x.getName().equals(arg.getName()))
              .findFirst()
              .get();
      argApis.put(arg, api);
    }
    for (ArgDef arg : op.getOutputArgList()) {
      ApiDef.Arg api =
          apiDef.getOutArgList().stream()
              .filter(x -> x.getName().equals(arg.getName()))
              .findFirst()
              .get();
      argApis.put(arg, api);
    }
  }

  /** Get the Java variable name for an argument. */
  private String getJavaName(ArgDef arg) {
    String name = arg.getName();
    String rename = argApis.get(arg).getRenameTo();
    if (!rename.isEmpty()) {
      return javaizeMemberName(rename);
    } else {
      return javaizeMemberName(name);
    }
  }

  /** Get the Java variable name for an attribute. */
  private String getJavaName(AttrDef arg) {
    String name = arg.getName();
    String rename = attrApis.get(arg).getRenameTo();
    if (!rename.isEmpty()) {
      return javaizeMemberName(rename);
    } else {
      return javaizeMemberName(name);
    }
  }

  /** Get the fully qualified name of the class being generated. */
  private String fullClassName() {
    return fullPackage + "." + className;
  }

  private ClassName className() {
    return ClassName.get(fullPackage, className);
  }

  private ClassName inputsClassName() {
    return ClassName.get(fullPackage, className, INPUTS_CLASS_NAME);
  }

  private TypeName maybeParameterize(
      ClassName baseType, Collection<? extends TypeName> parameters) {
    if (parameters.isEmpty()) {
      return baseType;
    } else {
      return ParameterizedTypeName.get(baseType, parameters.toArray(new TypeName[0]));
    }
  }

  /** Build the class. */
  void buildClass() {
    builder.addModifiers(Modifier.PUBLIC);
    if (!isStateSelector) {
      builder.addModifiers(Modifier.FINAL);
      addInputsMetadataAnnotation();
    }

    if (isStateSubclass) {
      builder.addSuperinterface(ClassName.get(fullPackage, statefulPair.selectorClassName));
    }

    // add class javadocs
    String summary = parseDocumentation(apiDef.getSummary());
    if (!summary.isEmpty()) {
      builder.addJavadoc("$L", summary + "\n");
    } else {
      builder.addJavadoc("The $L operation\n", apiDef.getGraphOpName());
    }
    String desc = parseDocumentation(apiDef.getDescription());
    if (!desc.isEmpty()) {
      builder.addJavadoc("$L", desc + "\n");
    }

    if (isStateSelector) {
      builder.addJavadoc("\n<p>");
      builder.addJavadoc(
          "Selects between {@link "
              + statefulPair.statefulClassName
              + "} and {@link "
              + statefulPair.statelessClassName
              + "} based on the statefulness of the function arguments.");
    }

    // add superinterface and set mode
    if (op.getOutputArgCount() == 1) {
      ArgDef output = op.getOutputArg(0);
      ResolvedType rType = resolver.typeOf(output);
      TypeName type = rType.unwrapArg();
      boolean iterable = rType.iterable;
      TypeName operandTypeParam = type instanceof WildcardTypeName ? Names.TType : type;
      TypeName operandType = ParameterizedTypeName.get(Names.Operand, operandTypeParam);

      if (iterable) {
        mode = RenderMode.LIST_OPERAND;
        if (!isStateSubclass) {
          builder.addSuperinterface(
              ParameterizedTypeName.get(ClassName.get(Iterable.class), operandType));
        }
      } else {
        mode = RenderMode.OPERAND;
        if (!isStateSubclass) {
          builder.addSuperinterface(operandType);
        }
      }
    }

    // add and store type variables
    Set<String> seenGenerics = new HashSet<>();
    for (ArgDef output : op.getOutputArgList()) {
      ResolvedType type = resolver.typeOf(output);
      for (TypeVariableName typeVar : type.findGenerics()) {
        if (seenGenerics.add(typeVar.name)) {
          typeParams.add(typeVar);
          builder.addTypeVariable(typeVar);
          builder.addJavadoc(
              "\n@param <$L> data type for {@code $L} output\n", typeVar.name, output.getName());
        }
      }
    }

    // add deprecated if necessary
    if (endpoint.getDeprecated()) {
      builder.addAnnotation(Deprecated.class);
      Endpoint first = apiDef.getEndpoint(0);
      String explanation;
      if (!first.getDeprecated()) {
        explanation = "use {@link " + basePackage + "." + first.getName() + "} instead";
      } else {
        explanation = op.getDeprecation().getExplanation();
      }
      builder.addJavadoc("\n@deprecated $L", explanation);
    }

    // add the Operator annotation
    if (apiDef.getVisibility() != Visibility.HIDDEN) {
      AnnotationSpec.Builder annotation = AnnotationSpec.builder(Names.Operator);
      if (!group.equals("core")) {
        annotation.addMember("group", "$S", group);
      }
      builder.addAnnotation(annotation.build());
    }

    if (!optionalAttributes.isEmpty() && !isStateSubclass) {
      buildOptionsClass();
    }

    buildFactoryMethods();
    buildGettersAndSetters();
    if (mode != RenderMode.DEFAULT) {
      buildInterfaceImpl();
    }

    if (!isStateSelector) { // add op name field
      builder.addField(
          FieldSpec.builder(
                  TypeResolver.STRING,
                  OP_NAME_FIELD,
                  Modifier.PUBLIC,
                  Modifier.STATIC,
                  Modifier.FINAL)
              .addJavadoc("$L", "The name of this op, as known by TensorFlow core engine")
              .initializer("$S", op.getName())
              .build());

      // add output fields
      if (op.getOutputArgCount() > 0) {
        for (ArgDef output : op.getOutputArgList()) {
          builder.addField(
              resolver.typeOf(output).listIfIterable().javaType,
              getJavaName(output),
              Modifier.PRIVATE);
        }
      }

      buildConstructor();
      buildInputsClass();
      builder.superclass(Names.RawOp);
    }
  }

  /** Add a nested class for Options */
  private void buildOptionsClass() {

    if (optionalAttributes.isEmpty()) {
      return;
    }

    TypeSpec.Builder optionsBuilder =
        TypeSpec.classBuilder("Options").addModifiers(Modifier.PUBLIC, Modifier.STATIC);
    optionsBuilder.addJavadoc("$L", "Optional attributes for {@link " + fullClassName() + "}");

    ClassName optionsClassName = ClassName.get(fullPackage, className, "Options");

    for (AttrDef attr : optionalAttributes) {
      ResolvedType type = resolver.typeOf(attr);

      String name = getJavaName(attr);

      ApiDef.Attr apiAttr = attrApis.get(attr);

      String description =
          apiAttr.getDescription().isEmpty()
              ? String.format("the %s option", name)
              : apiAttr.getDescription();

      // add the setter method, adding one with varargs and one with List if the attribute is
      // iterable
      if (type.iterable) {
        optionsBuilder.addMethod(
            MethodSpec.methodBuilder(name)
                .returns(optionsClassName)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(type.classIfGeneric().listIfIterable().javaType, name)
                .addJavadoc("Sets the $L option.\n", name)
                .addJavadoc("\n@param $L $L", name, parseDocumentation(description))
                .addJavadoc("\n@return this Options instance.")
                .addCode("this.$L = $L;\nreturn this;\n", name, name)
                .build());

        optionsBuilder.addMethod(
            MethodSpec.methodBuilder(name)
                .returns(optionsClassName)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(type.classIfGeneric().arrayIfIterable().javaType, name)
                .addJavadoc("Sets the $L option.\n", name)
                .addJavadoc("\n@param $L $L", name, parseDocumentation(description))
                .addJavadoc("\n@return this Options instance.")
                .addCode("this.$L = $T.asList($L);\nreturn this;\n", name, Arrays.class, name)
                .varargs()
                .build());

      } else {
        optionsBuilder.addMethod(
            MethodSpec.methodBuilder(name)
                .returns(optionsClassName)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(type.classIfGeneric().javaType, name)
                .addJavadoc("Sets the $L option.\n", name)
                .addJavadoc("\n@param $L $L", name, parseDocumentation(description))
                .addJavadoc("\n@return this Options instance.")
                .addCode("this.$L = $L;\nreturn this;\n", name, name)
                .build());
      }

      FieldSpec.Builder field =
          FieldSpec.builder(type.classIfGeneric().listIfIterable().javaType, name);
      if (!isStateSelector) {
        field.addModifiers(Modifier.PRIVATE);
      }

      // add the field
      optionsBuilder.addField(field.build());
    }

    // add a private constructor
    optionsBuilder.addMethod(
        MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build());

    optionsClass = optionsBuilder.build();
    builder.addType(optionsClass);
  }

  /**
   * Write statements to set an attribute in an OperationBuilder. Meant to be used in {@link
   * #buildFactoryMethods()}
   *
   * @param body the body to write to
   * @param attr the attribute to set
   * @param type the type of the attribute, or null to get it ourselves
   * @param optional whether the attribute is optional
   */
  private void writeSetAttr(
      CodeBlock.Builder body, AttrDef attr, ResolvedType type, boolean optional) {
    String varName = optional ? "opts." + getJavaName(attr) : getJavaName(attr);
    if (type == null) {
      type = resolver.typeOf(attr);
    }

    if (type.jniType.equals(ClassName.get(DataType.class))) {
      body.addStatement(
          "opBuilder.setAttr($S, $T.$L($L))",
          attr.getName(),
          Names.Operands,
          type.iterable ? "toDataTypes" : "toDataType",
          varName);
    } else {
      if (type.iterable) {
        String arrayName = javaizeMemberName(attr.getName()) + "Array";
        body.addStatement(
            "$T[] $L = new $T[$L.size()]", type.jniType, arrayName, type.jniType, varName);

        body.beginControlFlow("for (int i = 0 ; i < $L.length ; i++)", arrayName);

        body.addStatement("$L[i] = $L.get(i)", arrayName, varName);

        body.endControlFlow();

        body.addStatement("opBuilder.setAttr($S, $L)", attr.getName(), arrayName);
      } else {
        body.addStatement("opBuilder.setAttr($S, $L)", attr.getName(), varName);
      }
    }
  }

  /** Add the {@code create} factory methods. */
  private void buildFactoryMethods() {
    MethodSpec.Builder factoryBuilder =
        MethodSpec.methodBuilder("create").addModifiers(Modifier.PUBLIC, Modifier.STATIC);

    // the main creator will inherit any class type params
    TypeName returnType = ClassName.get(fullPackage, className);
    if (!typeParams.isEmpty()) {
      returnType =
          ParameterizedTypeName.get((ClassName) returnType, typeParams.toArray(new TypeName[0]));
    }
    factoryBuilder.returns(returnType);

    AnnotationSpec.Builder endpointAnnotation =
        AnnotationSpec.builder(Names.Endpoint).addMember("describeByClass", "true");

    String methodName = GeneratorUtils.getOpMethodName(className);

    if (methodName != null) {
      endpointAnnotation.addMember("name", "$S", methodName);
    }

    factoryBuilder.addAnnotation(endpointAnnotation.build());

    factoryBuilder.addJavadoc(
        "Factory method to create a class wrapping a new $L operation.\n", op.getName());

    // we're going to build the body as add arguments
    CodeBlock.Builder body = CodeBlock.builder();

    Map<String, CodeBlock> paramTags = new LinkedHashMap<>();

    factoryBuilder.addParameter(ParameterSpec.builder(Names.Scope, "scope").build());
    paramTags.put("scope", CodeBlock.of("current scope"));

    Set<TypeVariableName> typeVars = new LinkedHashSet<>(typeParams);

    body.addStatement(
        "$T opBuilder = scope.opBuilder($L, $S)", Names.OperationBuilder, OP_NAME_FIELD, className);

    List<String> functionArgs = new ArrayList<>();
    List<String> iterableFunctionArgs = new ArrayList<>();

    // add the inputs as parameters, and add them to the op builder
    for (ArgDef input : op.getInputArgList()) {
      ApiDef.Arg argDef = argApis.get(input);
      ResolvedType type = resolver.typeOf(input);
      String name = getJavaName(input);

      if (type.javaType.equals(Names.ConcreteFunction)) {
        if (type.iterable) {
          iterableFunctionArgs.add(name);
        } else {
          functionArgs.add(name);
        }
      }

      ParameterSpec.Builder param = ParameterSpec.builder(type.iterableIfIterable().javaType, name);
      String description =
          argDef.getDescription().isEmpty()
              ? String.format("The %s value", name)
              : argDef.getDescription();
      paramTags.put(name, CodeBlock.of("$L", parseDocumentation(description)));
      factoryBuilder.addParameter(param.build());

      typeVars.addAll(type.findGenerics());

      if (type.iterable) {
        body.addStatement("opBuilder.addInputList($T.asOutputs($L))", Names.Operands, name);
      } else {
        body.addStatement("opBuilder.addInput($L.asOutput())", name);
      }
    }

    // add the required attribute params, and build the default type maps for use in the secondary
    // factory
    Map<AttrDef, TypeName> defaultTypes = new HashMap<>();
    Map<String, TypeName> defaultTypeVars = new HashMap<>();
    for (AttrDef attr : requiredAttributes) {
      if (resolver.partOfInput(attr.getName())) {
        continue;
      }

      ResolvedType type = resolver.typeOf(attr);
      ApiDef.Attr apiAttr = attrApis.get(attr);
      String javaName = getJavaName(attr);

      if (type.javaType.equals(Names.ConcreteFunction)) {
        if (type.iterable) {
          iterableFunctionArgs.add(javaName);
        } else {
          functionArgs.add(javaName);
        }
      }

      ParameterSpec.Builder builder =
          ParameterSpec.builder(type.classIfGeneric().listIfIterable().javaType, getJavaName(attr));

      String description =
          apiAttr.getDescription().isEmpty()
              ? String.format("The value of the %s attribute", javaName)
              : apiAttr.getDescription();
      paramTags.put(javaName, CodeBlock.of("$L", parseDocumentation(description)));

      typeVars.addAll(type.findGenerics());

      factoryBuilder.addParameter(builder.build());

      // we only add defaults for type variable arguments
      if (attr.hasDefaultValue() && type.shouldWrapInClass()) {
        TypeName defaultType = TypeResolver.forDataType(attr.getDefaultValue().getType());
        if (!(defaultType instanceof WildcardTypeName) && defaultType != Names.TType) {
          defaultTypes.put(attr, defaultType);
          defaultTypeVars.put(((TypeVariableName) type.javaType).name, defaultType);
        }
      }

      writeSetAttr(body, attr, type, false);
    }

    // TODO optional function attrs (there currently aren't any)

    // add optional attributes
    if (optionsClass != null || (isStateSubclass && statefulPair.hasOptionalAttrs())) {

      ClassName optionsClassName;
      if (isStateSubclass) {
        optionsClassName = ClassName.get(fullPackage, statefulPair.selectorClassName, "Options");
      } else {
        optionsClassName = ClassName.get(fullPackage, className, "Options");
      }

      factoryBuilder.addParameter(
          ParameterSpec.builder(ArrayTypeName.of(optionsClassName), "options").build());
      paramTags.put("options", CodeBlock.of("$L", "carries optional attribute values"));
      factoryBuilder.varargs();

      body.beginControlFlow("if (options != null)");

      body.beginControlFlow("for ($T opts : options)", optionsClassName);
      for (AttrDef attr : optionalAttributes) {
        String name = getJavaName(attr);
        body.beginControlFlow("if (opts.$L != null)", name);

        writeSetAttr(body, attr, null, true);

        body.endControlFlow();
      }
      body.endControlFlow();

      body.endControlFlow();
    }

    body.addStatement(
        "return new $L(opBuilder.build())", typeParams.isEmpty() ? className : (className + "<>"));

    if (isStateSelector) {
      body.clear();

      body.addStatement("boolean isStateful = false");
      functionArgs.forEach(
          arg -> {
            body.beginControlFlow("if ($L.isStateful())", arg)
                .addStatement("isStateful = true")
                .endControlFlow();
          });
      iterableFunctionArgs.forEach(
          arg -> {
            body.beginControlFlow("if ($L.stream().anyMatch(x -> x.isStateful()))", arg)
                .addStatement("isStateful = true")
                .endControlFlow();
          });

      StringJoiner argList = new StringJoiner(", ");
      factoryBuilder.parameters.forEach(x -> argList.add(x.name));

      body.beginControlFlow("if (isStateful)")
          .addStatement(
              "return $T.create($L)",
              ClassName.get(fullPackage, statefulPair.statefulClassName),
              argList.toString())
          .nextControlFlow("else")
          .addStatement(
              "return $T.create($L)",
              ClassName.get(fullPackage, statefulPair.statelessClassName),
              argList.toString())
          .endControlFlow();
    }
    factoryBuilder.addCode(body.build());

    paramTags.forEach(
        (param, doc) -> {
          String description = doc.toString();
          if (description.isEmpty() || description.equals("\n")) {
            factoryBuilder.addJavadoc("\n@param $L the $L property", param, param);
          } else {
            factoryBuilder.addJavadoc("\n@param $L $L", param, doc);
          }
        });
    for (TypeVariableName typeVar : typeVars) {
      factoryBuilder.addJavadoc(
          "\n@param <"
              + typeVar.name
              + "> data type for {@code "
              + op.getName()
              + "} output and operands");
    }

    factoryBuilder.addTypeVariables(typeVars);
    factoryBuilder.addJavadoc("\n@return a new instance of $L\n", className);
    MethodSpec method = factoryBuilder.build();
    builder.addMethod(method);

    if (!defaultTypes.isEmpty()) {
      buildSecondaryFactory(defaultTypes, defaultTypeVars, method, paramTags);
    }
  }

  /** Add a secondary factory method with the provided default type maps */
  private void buildSecondaryFactory(
      Map<AttrDef, TypeName> defaultTypes,
      Map<String, TypeName> defaultTypeVars,
      MethodSpec mainFactory,
      Map<String, CodeBlock> paramTags) {
    MethodSpec.Builder factoryBuilder =
        MethodSpec.methodBuilder(mainFactory.name)
            .addModifiers(mainFactory.modifiers)
            .returns(
                ParameterizedTypeName.get(
                    ClassName.get(fullPackage, className),
                    typeParams.stream()
                        .map(x -> defaultTypeVars.getOrDefault(x.name, x))
                        .toArray(TypeName[]::new)));
    factoryBuilder.addAnnotations(mainFactory.annotations);

    factoryBuilder.addJavadoc(
        "Factory method to create a class wrapping a new $L operation, with the default output types.\n",
        op.getName());

    CodeBlock.Builder body = CodeBlock.builder();
    body.add("return create(");

    Set<TypeVariableName> typeVars = new LinkedHashSet<>();

    // we want to add all of the main factory's parameters except for those with defaults
    // we just pass them through
    boolean first = true;
    for (ParameterSpec param : mainFactory.parameters) {
      if (!first) {
        body.add(", ");
      }

      AttrDef attr =
          op.getAttrList().stream()
              .filter(x -> getJavaName(x).equals(param.name))
              .findFirst()
              .orElse(null);
      if (attr != null
          && resolver.typeOf(attr).shouldWrapInClass()
          && defaultTypes.containsKey(attr)) {
        body.add("$T.class", defaultTypes.get(attr));
      } else {
        factoryBuilder.addParameter(param);
        factoryBuilder.addJavadoc("\n@param $L $L", param.name, paramTags.get(param.name));
        typeVars.addAll(new ResolvedType(param.type).findGenerics());
        body.add("$L", param.name);
      }
      first = false;
    }

    body.add(");");

    for (TypeVariableName typeVar : typeVars) {
      factoryBuilder.addJavadoc(
          "\n@param <"
              + typeVar.name
              + "> data type for {@code "
              + op.getName()
              + "} output and operands");
    }

    factoryBuilder.addJavadoc(
        "\n@return a new instance of $L, with default output types", className);

    if (!isStateSelector) {
      factoryBuilder.addCode(body.build());
    }
    factoryBuilder.addTypeVariables(typeVars);

    builder.addMethod(factoryBuilder.build());
  }

  /**
   * Add getters for the outputs and setters/Options creators for the optional attributes.
   *
   * <p>Needs to be called after {@link #buildOptionsClass()}
   */
  private void buildGettersAndSetters() {
    if (optionsClass != null) {
      optionsClass.methodSpecs.stream()
          .filter(x -> !x.isConstructor())
          .forEach(
              method -> {
                String argName = method.parameters.get(0).name;
                builder.addMethod(
                    MethodSpec.methodBuilder(method.name)
                        .addParameter(method.parameters.get(0))
                        .addJavadoc(method.javadoc)
                        .returns(ClassName.get(fullPackage, className, "Options"))
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .addCode("return new Options().$L($L);", method.name, argName)
                        .varargs(method.varargs)
                        .build());
              });
    }

    for (ArgDef output : op.getOutputArgList()) {
      String name = getJavaName(output);
      ApiDef.Arg argDef = argApis.get(output);

      MethodSpec.Builder method =
          MethodSpec.methodBuilder(name)
              .addModifiers(Modifier.PUBLIC)
              .returns(resolver.typeOf(output).listIfIterable().javaType)
              .addJavadoc("Gets $L.\n", name)
              .addJavadoc("$L", parseDocumentation(argDef.getDescription()))
              .addJavadoc("\n@return $L.", name);

      if (isStateSelector) {
        method.addModifiers(Modifier.ABSTRACT);
      } else {
        if (isStateSubclass) {
          method.addAnnotation(Override.class);
        }
        method.addCode("return $L;", name);
      }

      builder.addMethod(method.build());
    }
  }

  /** Add interface implementation methods if this is a single output or list output op. */
  private void buildInterfaceImpl() {
    ArgDef output = op.getOutputArg(0);
    TypeName type = resolver.typeOf(output).unwrapArg();

    boolean uncheckedCast = type instanceof WildcardTypeName;
    TypeName outputTType = uncheckedCast ? Names.TType : type;

    if (mode == RenderMode.OPERAND) {
      TypeName outputType = ParameterizedTypeName.get(Names.Output, outputTType);
      MethodSpec.Builder asOutput =
          MethodSpec.methodBuilder("asOutput")
              .addModifiers(Modifier.PUBLIC)
              .returns(outputType)
              .addAnnotation(Override.class);

      if (isStateSelector) {
        asOutput.addModifiers(Modifier.ABSTRACT);
      } else {
        if (uncheckedCast) {
          asOutput.addAnnotation(
              AnnotationSpec.builder(SuppressWarnings.class)
                  .addMember("value", "$S", "unchecked")
                  .build());
          asOutput.addCode("return ($T) $L;", outputType, getJavaName(output));
        } else {
          asOutput.addCode("return $L;", getJavaName(output));
        }
      }

      builder.addMethod(asOutput.build());
    } else {
      TypeName operandType = ParameterizedTypeName.get(Names.Operand, outputTType);
      TypeName returnType = ParameterizedTypeName.get(ClassName.get(Iterator.class), operandType);

      MethodSpec.Builder iterator =
          MethodSpec.methodBuilder("iterator")
              .addModifiers(Modifier.PUBLIC)
              .returns(returnType)
              .addAnnotation(Override.class)
              .addAnnotation(
                  AnnotationSpec.builder(SuppressWarnings.class)
                      .addMember("value", "{$S, $S}", "rawtypes", "unchecked")
                      .build());

      if (isStateSelector) {
        iterator.addModifiers(Modifier.ABSTRACT);
      } else {
        iterator.addCode("return ($T) $L.iterator();", Iterator.class, getJavaName(output));
      }

      builder.addMethod(iterator.build());
    }
  }

  /** Add a constructor to get the outputs from an operation */
  private void buildConstructor() {
    MethodSpec.Builder ctor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);

    ctor.addParameter(Names.Operation, "operation");

    for (ArgDef output : op.getOutputArgList()) {
      ResolvedType type = resolver.typeOf(output);
      if (type.iterable || type.unwrapArg() instanceof WildcardTypeName) {
        ctor.addAnnotation(
            AnnotationSpec.builder(SuppressWarnings.class)
                .addMember("value", "$S", "unchecked")
                .build());
        break;
      }
    }
    CodeBlock.Builder body = CodeBlock.builder();
    body.addStatement("super(operation, $L)", OP_NAME_FIELD);

    if (op.getOutputArgCount() > 0) {
      body.addStatement("int outputIdx = 0");
      for (ArgDef output : op.getOutputArgList()) {
        ResolvedType type = resolver.typeOf(output);
        boolean iterable = type.iterable;
        if (iterable) {
          String lengthVar = getJavaName(output) + "Length";

          body.addStatement("int $L = operation.outputListLength($S)", lengthVar, output.getName());

          if (type.unwrapArg() instanceof WildcardTypeName) {
            body.addStatement(
                "$L = $T.asList(operation.outputList(outputIdx, $L))",
                getJavaName(output),
                Arrays.class,
                lengthVar);
          } else {
            body.addStatement(
                "$L = $T.asList(($T) operation.outputList(outputIdx, $L))",
                getJavaName(output),
                Arrays.class,
                ArrayTypeName.of(type.javaType),
                lengthVar);
          }
          body.addStatement("outputIdx += $L", lengthVar);

        } else {
          body.addStatement("$L = operation.output(outputIdx++)", getJavaName(output));
        }
      }
    }

    ctor.addCode(body.build());
    builder.addMethod(ctor.build());
  }

  private Set<TypeVariableName> buildInputsClass() {
    TypeSpec.Builder inputsBuilder =
        TypeSpec.classBuilder(INPUTS_CLASS_NAME).addModifiers(Modifier.PUBLIC, Modifier.STATIC);
    MethodSpec.Builder ctor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
    ctor.addParameter(Names.GraphOperation, "op");

    StringJoiner attrNames = new StringJoiner(", ");

    Set<TypeVariableName> typeVars = new LinkedHashSet<>();
    CodeBlock.Builder fieldInits = CodeBlock.builder();

    fieldInits.addStatement("int inputIndex = 0");

    // add the inputs as parameters, and add them to the op builder
    for (ArgDef input : op.getInputArgList()) {
      ResolvedType type = resolver.typeOf(input);
      String name = getJavaName(input);
      ApiDef.Arg argDef = argApis.get(input);

      typeVars.addAll(type.findGenerics());

      TypeName javaType = type.iterableIfIterable().javaType;

      String description =
          argDef.getDescription().isEmpty()
              ? String.format("The %s input", name)
              : argDef.getDescription();

      inputsBuilder.addField(
          FieldSpec.builder(javaType, name, Modifier.PUBLIC, Modifier.FINAL)
              .addJavadoc("$L", parseDocumentation(description))
              .build());

      if (type.iterable) {
        String inputListLength = name + "Length";
        fieldInits.addStatement(
            "int $L = op.inputListLength($S)", inputListLength, input.getName());
        fieldInits.addStatement(
            "$L = $T.asList(($T) op.inputList(inputIndex, $L))",
            name,
            Names.Arrays,
            ArrayTypeName.of(type.javaType),
            inputListLength);
        fieldInits.addStatement("inputIndex += $L", inputListLength);
      } else {
        fieldInits.addStatement("$L = ($T) op.input(inputIndex++)", name, javaType);
      }
    }

    for (AttrDef attr : op.getAttrList()) {
      ResolvedType type = resolver.typeOf(attr);
      String name = getJavaName(attr);

      if (type.attributeType != null) {

        ApiDef.Attr apiAttr = attrApis.get(attr);

        String description =
            apiAttr.getDescription().isEmpty()
                ? String.format("The %s attribute", name)
                : apiAttr.getDescription();

        TypeName javaType = type.jniType;
        if (type.iterable) {
          javaType = ArrayTypeName.of(javaType);
        }

        attrNames.add(CodeBlock.of("$S", attr.getName()).toString());
        inputsBuilder.addField(
            FieldSpec.builder(javaType, name, Modifier.PUBLIC, Modifier.FINAL)
                .addJavadoc("$L", description)
                .build());
        fieldInits.addStatement(
            "$L = op.attributes().getAttr$L($S)",
            name,
            type.attributeType.getterName(type.iterable),
            attr.getName());
      }
    }

    List<TypeName> sharedTypeVars = new ArrayList<>();
    for (TypeVariableName onClass : this.builder.typeVariables) {
      if (typeVars.contains(onClass)) {
        sharedTypeVars.add(onClass);
      } else {
        sharedTypeVars.add(WildcardTypeName.subtypeOf(TypeName.OBJECT));
      }
    }

    TypeName outputClass = className();
    if (!this.builder.typeVariables.isEmpty()) {
      outputClass =
          ParameterizedTypeName.get(
              (ClassName) outputClass, sharedTypeVars.toArray(new TypeName[0]));
    }

    inputsBuilder.superclass(ParameterizedTypeName.get(Names.RawOpInputs, outputClass));

    CodeBlock.Builder body = CodeBlock.builder();
    body.addStatement(
        "super(new $L(op), op, $T.asList($L))",
        this.builder.typeVariables.isEmpty() ? className : className + "<>",
        Names.Arrays,
        attrNames.toString());

    body.add(fieldInits.build());
    ctor.addCode(body.build());

    inputsBuilder.addMethod(ctor.build());
    inputsBuilder.addTypeVariables(typeVars);
    addInputsMetadataAnnotation(inputsBuilder);
    this.builder.addType(inputsBuilder.build());
    return typeVars;
  }

  /** Adds the GeneratedOpMetadata annotation to the op class. */
  private void addInputsMetadataAnnotation() {
    builder.addAnnotation(
        AnnotationSpec.builder(Names.OpMetadata)
            .addMember("opType", "$L", className + ".OP_NAME")
            .addMember("inputsClass", "$T.class", inputsClassName())
            .build());
  }

  /** Adds the GeneratedOpInputsMetadata annotation to the op input class. */
  private void addInputsMetadataAnnotation(TypeSpec.Builder inputsBuilder) {
    inputsBuilder.addAnnotation(
        AnnotationSpec.builder(Names.OpInputsMetadata)
            .addMember("outputsClass", "$T.class", className())
            .build());
  }
}


text:
package io.reflectoring.dto;

import lombok.Builder;
import lombok.Data;
import lombok.ToString;

@Data
@Builder
@ToString
public class EmploymentDTO {
    private String designation;
    private long salary;
}

redpajama_set_name: RedPajamaGithub


text:
import Bacon from "baconjs"
import React from "react"

export default React.createClass({
  getInitialState() {
    return {}
  },
  tryDispose() {
    const {dispose} = this.state
    if (dispose) {
      dispose()
      this.replaceState({})
    }
  },
  trySubscribe(props) {
    this.tryDispose()
    const {children} = props
    if (children)
      this.setState(
        {dispose: (children instanceof Bacon.Observable ? children :
                   Bacon.combineTemplate(
                     children instanceof Array
                       ? React.DOM.div({...props, children})
                       : children)).onValue(DOM => this.setState({DOM}))})
  },
  componentWillReceiveProps(nextProps) {
    this.trySubscribe(nextProps)
  },
  componentWillMount() {
    this.trySubscribe(this.props)
    const {willMount} = this.props
    !willMount || willMount(this)
  },
  componentDidMount() {
    const {didMount} = this.props
    !didMount || didMount(this)
  },
  shouldComponentUpdate(nextProps, nextState) {
    return nextState.DOM !== this.state.DOM
  },
  componentWillUnmount() {
    this.tryDispose()
    const {willUnmount} = this.props
    !willUnmount || willUnmount(this)
  },
  render() {
    const {DOM} = this.state
    return (!DOM ? null :
            DOM instanceof Array ? React.DOM.div({...this.props, children: DOM}) :
            DOM)
  }
})


text:
package org.apache.velocity.context;

import java.util.List;
import org.apache.velocity.Template;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.context.InternalEventContext;
import org.apache.velocity.context.InternalHousekeepingContext;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.util.introspection.IntrospectionCacheData;

class InternalContextBase implements InternalEventContext, InternalHousekeepingContext
{
    public EventCartridge attachEventCartridge(EventCartridge p0){ return null; }
    public EventCartridge getEventCartridge(){ return null; }
    public IntrospectionCacheData icacheGet(Object p0){ return null; }
    public List<Template> getMacroLibraries(){ return null; }
    public Resource getCurrentResource(){ return null; }
    public String getCurrentMacroName(){ return null; }
    public String getCurrentTemplateName(){ return null; }
    public String[] getMacroNameStack(){ return null; }
    public String[] getTemplateNameStack(){ return null; }
    public int getCurrentMacroCallDepth(){ return 0; }
    public void icachePut(Object p0, IntrospectionCacheData p1){}
    public void popCurrentMacroName(){}
    public void popCurrentTemplateName(){}
    public void pushCurrentMacroName(String p0){}
    public void pushCurrentTemplateName(String p0){}
    public void setCurrentResource(Resource p0){}
    public void setMacroLibraries(List<Template> p0){}
}


text:
package com.app.tbd.ui.Module;

import com.app.tbd.AppModule;
import com.app.tbd.ui.Activity.Login.LoginFragment;
import com.app.tbd.ui.Activity.Profile.UserProfile.MyProfileFragment;
import com.app.tbd.ui.Presenter.LoginPresenter;
import com.app.tbd.ui.Presenter.ProfilePresenter;
import com.squareup.otto.Bus;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(
        injects = MyProfileFragment.class,
        addsTo = AppModule.class,
        complete = false
)
public class MyProfileModule {

    private final ProfilePresenter.MyProfileView loginView;

    public MyProfileModule(ProfilePresenter.MyProfileView loginView) {
        this.loginView = loginView;
    }

    @Provides
    @Singleton
    ProfilePresenter provideLoginPresenter(Bus bus) {
        return new ProfilePresenter(loginView, bus);
    }
}


text:
Calls to `Statement::fetchColumn()` with an invalid column index currently return `NULL`. In the future, such calls will result in a exception.

## Deprecated `Configuration::getFilterSchemaAssetsExpression()`, `::setFilterSchemaAssetsExpression()` and `AbstractSchemaManager::getFilterSchemaAssetsExpression()`.

Regular expression-based filters are hard to extend by combining together. Instead, you may use callback-based filers via `::getSchemaAssetsFilter()` and `::getSchemaAssetsFilter()`. Callbacks can use regular expressions internally.

## Deprecated `Doctrine\DBAL\Types\Type::getDefaultLength()`

This method was never used by DBAL internally. It is now deprecated and will be removed in DBAL 3.0.

## Deprecated `Doctrine\DBAL\Types\Type::__toString()`

Relying on string representation is discouraged and will be removed in DBAL 3.0.

## Deprecated `NULL` value of `$offset` in LIMIT queries

The `NULL` value of the `$offset` argument in `AbstractPlatform::(do)?ModifyLimitQuery()` methods is deprecated. If explicitly used in the method call, the absence of the offset should be indicated with a `0`.

## Deprecated dbal:import CLI command

The `dbal:import` CLI command has been deprecated since it only works with PDO-based drivers by relying on a non-documented behavior of the extension, and it's impossible to make it work with other drivers.
Please use other database client applications for import, e.g.:

 * For MySQL and MariaDB: `mysql [dbname] < data.sql`.
 * For PostgreSQL: `psql [dbname] < data.sql`.
 * For SQLite: `sqlite3 /path/to/file.db < data.sql`.

# Upgrade to 2.8

## Deprecated usage of DB-generated UUIDs

The format of DB-generated UUIDs is inconsistent across supported platforms and therefore is not portable. Some of the platforms produce UUIDv1, some produce UUIDv4, some produce the values which are not even UUID.

Unless UUIDs are used in stored procedures which DBAL doesn't support, there's no real benefit of DB-generated UUIDs comparing to the application-generated ones.

Use a PHP library (e.g. [ramsey/uuid](https://packagist.org/packages/ramsey/uuid)) to generate UUIDs on the application side.

## Deprecated usage of binary fields whose length exceeds the platform maximum

- The usage of binary fields whose length exceeds the maximum field size on a given platform is deprecated.
  Use binary fields of a size which fits all target platforms, or use blob explicitly instead.

## Removed dependency on doctrine/common

The dependency on doctrine/common package has been removed.
DBAL now depends on doctrine/cache and doctrine/event-manager instead.
If you are using any other component from doctrine/common package,
you will have to add an explicit dependency to your composer.json.

## Corrected exception thrown by ``Doctrine\DBAL\Platforms\SQLAnywhere16Platform::getAdvancedIndexOptionsSQL()``

This method now throws SPL ``UnexpectedValueException`` instead of accidentally throwing ``Doctrine\Common\Proxy\Exception\UnexpectedValueException``.

# Upgrade to 2.7

## Doctrine\DBAL\Platforms\AbstractPlatform::DATE_INTERVAL_UNIT_* constants deprecated

``Doctrine\DBAL\Platforms\AbstractPlatform::DATE_INTERVAL_UNIT_*`` constants were moved into ``Doctrine\DBAL\Platforms\DateIntervalUnit`` class without the ``DATE_INTERVAL_UNIT_`` prefix.

## Doctrine\DBAL\Platforms\AbstractPlatform::TRIM_* constants deprecated

``Doctrine\DBAL\Platforms\AbstractPlatform::TRIM_*`` constants were moved into ``Doctrine\DBAL\Platforms\TrimMode`` class without the ``TRIM_`` prefix.

## Doctrine\DBAL\Connection::TRANSACTION_* constants deprecated

``Doctrine\DBAL\Connection::TRANSACTION_*`` were moved into ``Doctrine\DBAL\TransactionIsolationLevel`` class without the ``TRANSACTION_`` prefix.

## DEPRECATION: direct usage of the PDO APIs in the DBAL API

1. When calling `Doctrine\DBAL\Driver\Statement` methods, instead of `PDO::PARAM_*` constants, `Doctrine\DBAL\ParameterType` constants should be used.
2. When calling `Doctrine\DBAL\Driver\ResultStatement` methods, instead of `PDO::FETCH_*` constants, `Doctrine\DBAL\FetchMode` constants should be used.
3. When configuring `Doctrine\DBAL\Portability\Connection`, instead of `PDO::CASE_*` constants, `Doctrine\DBAL\ColumnCase` constants should be used.
4. Usage of `PDO::PARAM_INPUT_OUTPUT` in `Doctrine\DBAL\Driver\Statement::bindValue()` is deprecated.
5. Usage of `PDO::FETCH_FUNC` in `Doctrine\DBAL\Driver\ResultStatement::fetch()` is deprecated.
6. Calls to `\PDOStatement` methods on a `\Doctrine\DBAL\Driver\PDOStatement` instance (e.g. `fetchObject()`) are deprecated.

# Upgrade to 2.6

## MINOR BC BREAK: `fetch()` and `fetchAll()` method signatures in `Doctrine\DBAL\Driver\ResultStatement`

1. ``Doctrine\DBAL\Driver\ResultStatement::fetch()`` now has 3 arguments instead of 1, respecting
``PDO::fetch()`` signature.

Before:

    Doctrine\DBAL\Driver\ResultStatement::fetch($fetchMode);

After:

    Doctrine\DBAL\Driver\ResultStatement::fetch($fetchMode, $cursorOrientation, $cursorOffset);

2. ``Doctrine\DBAL\Driver\ResultStatement::fetchAll()`` now has 3 arguments instead of 1, respecting
``PDO::fetchAll()`` signature.

Before:

    Doctrine\DBAL\Driver\ResultStatement::fetchAll($fetchMode);

After:

    Doctrine\DBAL\Driver\ResultStatement::fetch($fetchMode, $fetchArgument, $ctorArgs);

## MINOR BC BREAK: URL-style DSN with percentage sign in password

URL-style DSNs (e.g. ``mysql://foo@bar:localhost/db``) are now assumed to be percent-encoded
in order to allow certain special characters in usernames, paswords and database names. If
you are using a URL-style DSN and have a username, password or database name containing a
percentage sign, you need to update your DSN. If your password is, say, ``foo%foo``, it
should be encoded as ``foo%25foo``.

# Upgrade to 2.5.1

## MINOR BC BREAK: Doctrine\DBAL\Schema\Table

When adding indexes to ``Doctrine\DBAL\Schema\Table`` via ``addIndex()`` or ``addUniqueIndex()``,
duplicate indexes are not silently ignored/dropped anymore (based on semantics, not naming!).
Duplicate indexes are considered indexes that pass ``isFullfilledBy()`` or ``overrules()``
in ``Doctrine\DBAL\Schema\Index``.
This is required to make the index renaming feature introduced in 2.5.0 work properly and avoid
issues in the ORM schema tool / DBAL schema manager which pretends users from updating
their schemas and migrate to DBAL 2.5.*.
Additionally it offers more flexibility in declaring indexes for the user and potentially fixes
related issues in the ORM.
With this change, the responsibility to decide which index is a "duplicate" is completely deferred
to the user.
Please also note that adding foreign key constraints to a table via ``addForeignKeyConstraint()``,
``addUnnamedForeignKeyConstraint()`` or ``addNamedForeignKeyConstraint()`` now first checks if an
appropriate index is already present and avoids adding an additional auto-generated one eventually.

# Upgrade to 2.5

## BC BREAK: time type resets date fields to UNIX epoch

When mapping `time` type field to PHP's `DateTime` instance all unused date fields are
reset to UNIX epoch (i.e. 1970-01-01). This might break any logic which relies on comparing
`DateTime` instances with date fields set to the current date.

Use `!` format prefix (see http://php.net/manual/en/datetime.createfromformat.php) for parsing
time strings to prevent having different date fields when comparing user input and `DateTime`
instances as mapped by Doctrine.

## BC BREAK: Doctrine\DBAL\Schema\Table

The methods ``addIndex()`` and ``addUniqueIndex()`` in ``Doctrine\DBAL\Schema\Table``
have an additional, optional parameter. If you override these methods, you should
add this new parameter to the declaration of your overridden methods.

## BC BREAK: Doctrine\DBAL\Connection

The visibility of the property ``$_platform`` in ``Doctrine\DBAL\Connection``
was changed from protected to private. If you have subclassed ``Doctrine\DBAL\Connection``
in your application and accessed ``$_platform`` directly, you have to change the code
portions to use ``getDatabasePlatform()`` instead to retrieve the underlying database
platform.
The reason for this change is the new automatic platform version detection feature,
which lazily evaluates the appropriate platform class to use for the underlying database
server version at runtime.
Please also note, that calling ``getDatabasePlatform()`` now needs to establish a connection
in order to evaluate the appropriate platform class if ``Doctrine\DBAL\Connection`` is not
already connected. Under the following circumstances, it is not possible anymore to retrieve
the platform instance from the connection object without having to do a real connect:

1. ``Doctrine\DBAL\Connection`` was instantiated without the ``platform`` connection parameter.
2. ``Doctrine\DBAL\Connection`` was instantiated without the ``serverVersion`` connection parameter.
3. The underlying driver is "version aware" and can provide different platform instances
   for different versions.
4. The underlying driver connection is "version aware" and can provide the database server
   version without having to query for it.

If one of the above conditions is NOT met, there is no need for ``Doctrine\DBAL\Connection``
to do a connect when calling ``getDatabasePlatform()``.

## datetime Type uses date_create() as fallback

Before 2.5 the DateTime type always required a specific format, defined in
`$platform->getDateTimeFormatString()`, which could cause quite some troubles
on platforms that had various microtime precision formats. Starting with 2.5
whenever the parsing of a date fails with the predefined platform format,
the `date_create()` function will be used to parse the date.

This could cause some troubles when your date format is weird and not parsed
correctly by `date_create`, however since databases are rather strict on dates
there should be no problem.

## Support for pdo_ibm driver removed

The ``pdo_ibm`` driver is buggy and does not work well with Doctrine. Therefore it will no
longer be supported and has been removed from the ``Doctrine\DBAL\DriverManager`` drivers
map. It is highly encouraged to to use `ibm_db2` driver instead if you want to connect
to an IBM DB2 database as it is much more stable and secure.

If for some reason you have to utilize the ``pdo_ibm`` driver you can still use the `driverClass`
connection parameter to explicitly specify the ``Doctrine\DBAL\Driver\PDOIbm\Driver`` class.
However be aware that you are doing this at your own risk and it will not be guaranteed that
Doctrine will work as expected.

# Upgrade to 2.4

## Doctrine\DBAL\Schema\Constraint

If you have custom classes that implement the constraint interface, you have to implement
an additional method ``getQuotedColumns`` now. This method is used to build proper constraint
SQL for columns that need to be quoted, like keywords reserved by the specific platform used.
The method has to return the same values as ``getColumns`` only that those column names that
need quotation have to be returned quoted for the given platform.

# Upgrade to 2.3

## Oracle Session Init now sets Numeric Character

Before 2.3 the Oracle Session Init did not care about the numeric character of the Session.
This could lead to problems on non english locale systems that required a comma as a floating
point seperator in Oracle. Since 2.3, using the Oracle Session Init on connection start the
client session will be altered to set the numeric character to ".,":

    ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '.,'

See [DBAL-345](http://www.doctrine-project.org/jira/browse/DBAL-345) for more details.

## Doctrine\DBAL\Connection and Doctrine\DBAL\Statement

The query related methods including but not limited to executeQuery, exec, query, and executeUpdate
now wrap the driver exceptions such as PDOException with DBALException to add more debugging
information such as the executed SQL statement, and any bound parameters.

If you want to retrieve the driver specific exception, you can retrieve it by calling the
``getPrevious()`` method on DBALException.

Before:

    catch(\PDOException $ex) {
        // ...
    }

After:

    catch(\Doctrine\DBAL\DBALException $ex) {
        $pdoException = $ex->getPrevious();
        // ...
    }

## Doctrine\DBAL\Connection#setCharsetSQL() removed

This method only worked on MySQL and it is considered unsafe on MySQL to use SET NAMES UTF-8 instead
of setting the charset directly on connection already. Replace this behavior with the
connection charset option:

Before:

    $conn = DriverManager::getConnection(array(..));
    $conn->setCharset('UTF8');

After:

    $conn = DriverManager::getConnection(array('charset' => 'UTF8', ..));

## Doctrine\DBAL\Schema\Table#renameColumn() removed

Doctrine\DBAL\Schema\Table#renameColumn() was removed, because it drops and recreates
the column instead. There is no fix available, because a schema diff
cannot reliably detect if a column was renamed or one column was created
and another one dropped.

You should use explicit SQL ALTER TABLE statements to change columns names.

## Schema Filter paths

The Filter Schema assets expression is not wrapped in () anymore for the regexp automatically.

Before:

    $config->setFilterSchemaAssetsExpression('foo');

After:

    $config->setFilterSchemaAssetsExpression('(foo)');

## Creating MySQL Tables now defaults to UTF-8

If you are creating a new MySQL Table through the Doctrine API, charset/collate are
now set to 'utf8'/'utf8_unicode_ci' by default. Previously the MySQL server defaults were used.

# Upgrade to 2.2

## Doctrine\DBAL\Connection#insert and Doctrine\DBAL\Connection#update

Both methods now accept an optional last parameter $types with binding types of the values passed.
This can potentially break child classes that have overwritten one of these methods.

## Doctrine\DBAL\Connection#executeQuery

Doctrine\DBAL\Connection#executeQuery() got a new last parameter "QueryCacheProfile $qcp"

## Doctrine\DBAL\Driver\Statement split

The Driver statement was split into a ResultStatement and the normal statement extending from it.
This separates the configuration and the retrieval API from a statement.

## MsSql Platform/SchemaManager renamed

The MsSqlPlatform was renamed to SQLServerPlatform, the MsSqlSchemaManager was renamed
to SQLServerSchemaManager.

## Cleanup SQLServer Platform version mess

DBAL 2.1 and before were actually only compatible to SQL Server 2008, not earlier versions.
Still other parts of the platform did use old features instead of newly introduced datatypes
in SQL Server 2005. Starting with DBAL 2.2 you can pick the Doctrine abstraction exactly
matching your SQL Server version.

The PDO SqlSrv driver now uses the new `SQLServer2008Platform` as default platform.
This platform uses new features of SQL Server as of version 2008. This also includes a switch
in the used fields for "text" and "blob" field types to:

    "text" => "VARCHAR(MAX)"
    "blob" => "VARBINARY(MAX)"

Additionally `SQLServerPlatform` in DBAL 2.1 and before used "DATE", "TIME" and "DATETIME2" for dates.
This types are only available since version 2008 and the introduction of an explicit
SQLServer 2008 platform makes this dependency explicit.

An `SQLServer2005Platform` was also introduced to differentiate the features between
versions 2003, earlier and 2005.

With this change the `SQLServerPlatform` now throws an exception for using limit queries
with an offset, since SQLServer 2003 and lower do not support this feature.

To use the old SQL Server Platform, because you are using SQL Server 2003 and below use
the following configuration code:

    use Doctrine\DBAL\DriverManager;
    use Doctrine\DBAL\Platforms\SQLServerPlatform;
    use Doctrine\DBAL\Platforms\SQLServer2005Platform;

    // You are using SQL Server 2003 or earlier
    $conn = DriverManager::getConnection(array(
        'driver' => 'pdo_sqlsrv',
        'platform' => new SQLServerPlatform()
        // .. additional parameters
    ));

    // You are using SQL Server 2005
    $conn = DriverManager::getConnection(array(
        'driver' => 'pdo_sqlsrv',
        'platform' => new SQLServer2005Platform()
        // .. additional parameters
    ));

    // You are using SQL Server 2008
    $conn = DriverManager::getConnection(array(
        'driver' => 'pdo_sqlsrv',
        // 2008 is default platform
        // .. additional parameters
    ));


text:
FILE(REMOVE_RECURSE
  "msg_gen"
  "src/shm_led_x2xn/msg"
  "CMakeFiles/ROSBUILD_genmsg_cpp"
  "msg_gen/cpp/include/shm_led_x2xn/LEDX2XNCmd.h"
  "msg_gen/cpp/include/shm_led_x2xn/LEDX2XNRGB.h"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang)
  INCLUDE(CMakeFiles/ROSBUILD_genmsg_cpp.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
  <wicket:head>

  </wicket:head>
  <wicket:panel>

                <eventLabel wicket:id="successLabel"/>

                <input type="checkbox" wicket:id="successSelector" style="margin-top: 0px;margin-bottom: 0px;"/>

                <eventLabel wicket:id="failureLabel"/>

                <input type="checkbox" wicket:id="failureSelector" style="margin-top: 0px;margin-bottom: 0px;"/>

              [subcategory]

              <input type="checkbox" wicket:id="successCheck"/>

              <input type="checkbox" wicket:id="failureCheck"/>

  </wicket:panel>


text:
package com.rubyalliance.cims.courses.sp17.datastructures.lab6;

import java.util.Arrays;

/**
 * Created by fredf on 2/25/2017.
 */
public class QuickSort<T extends Comparable<? super T>> implements ISorting<T> {
    private T[] copyOfElements;

    @Override
    public T[] sort(T[] elements) {
        if (elements == null || elements.length == 0) {
            return elements;
        }
        this.copyOfElements = Arrays.copyOf(elements,elements.length);
        quicksort(0, elements.length - 1);
        return copyOfElements;
    }

    private void quicksort(int low, int high) {
        int i = low, j = high;
        T pivot = copyOfElements[low + (high - low) / 2];
        while (i <= j) {
            while (copyOfElements[i].compareTo(pivot) < 0) {
                i++;
            }
            while (copyOfElements[j].compareTo(pivot) > 0) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                i++;
                j--;
            }
        }
        if (low < j)
            quicksort(low, j);
        if (i < high)
            quicksort(i, high);
    }

    private void swap(int i, int j) {
        T temp = copyOfElements[i];
        copyOfElements[i] = copyOfElements[j];
        copyOfElements[j] = temp;
    }
}


text:
<item>
    <id>{{item.id}}</id>
    <name>{{item.name}}</name>
    <description>{{item.description}}</description>
</item>


text:
//
//  MHMovieSeries.h
//  CoreHound
//
//  Copyright (c) 2015 MediaHound. All rights reserved.
//

#import "MHMedia.h"

/**
 * An MHMovieSeries
 */
@interface MHMovieSeries : MHMedia

@end


text:
#import "CDAAbstractPdfReaderWithThumbsViewController.h"
#import "CDAPdfReaderUtils.h"

@interface CDAAbstractPdfReaderWithThumbsViewController ()<CDAPdfReaderDelegateProtocol>

@end

@implementation CDAAbstractPdfReaderWithThumbsViewController
@synthesize thumbsViewController = _thumbsViewController, pdfReaderController = _pdfReaderController, documentPath = _documentPath, orientationLayout = _orientationLayout, initialPageIndex = _initialPageIndex;

#pragma mark - life cycle
- (instancetype)init{
    if(!(self = [super init]))return nil;
    self.initialPageIndex = NSNotFound;
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    if(!(self = [super initWithCoder:aDecoder]))return nil;
    self.initialPageIndex = NSNotFound;
    return self;
}

#pragma mark - public
- (void)setThumbsViewController:(UIViewController<CDAPdfThumbsViewControllerProtocol> *)thumbsViewController{
    _thumbsViewController = thumbsViewController;
    _thumbsViewController.delegate = self;
}
- (void)setPdfReaderController:(UIViewController<CDAPdfReaderProtocol> *)pdfReaderController{
    _pdfReaderController = pdfReaderController;
    [_pdfReaderController setReaderDelegate:self];
}

#pragma mark - CDAThumbVCDelegate
- (void)thumbsVC:(id)thumbsVC didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.pdfReaderController.currentPageIndex = indexPath.row;
}
#pragma mark - CDAPdfReaderDelegateProtocol
- (void)CDAPdfReader:(UIViewController<CDAPdfReaderProtocol> *)pdfReader didChangeToPageIndex:(NSInteger)pageIndex{
    [self.thumbsViewController setCurrentPageIndex:pageIndex];
}

@end