text:
package com.google.javascript.jscomp;

import com.google.common.base.CaseFormat;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.GlobalNamespace.Name;
import com.google.javascript.jscomp.GlobalNamespace.Ref;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.parsing.parser.util.format.SimpleFormat;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Rewrites "Polymer({})" calls into a form that is suitable for type checking and dead code
 * elimination. Also ensures proper format and types.
 *
 * <p>Only works with Polymer version: 0.8
 *
 * @author jlklein@google.com (Jeremy Klein)
 */
final class PolymerPass extends AbstractPostOrderCallback implements HotSwapCompilerPass {

  // TODO(jlklein): Switch back to an error when everyone is upgraded to Polymer 1.0
  static final DiagnosticType POLYMER_DESCRIPTOR_NOT_VALID = DiagnosticType.warning(
      "JSC_POLYMER_DESCRIPTOR_NOT_VALID",
      "The argument to Polymer() is not an obj lit (perhaps because this is a pre-Polymer-1.0 "
      + "call). Ignoring this call.");

  static final DiagnosticType POLYMER_INVALID_DECLARATION = DiagnosticType.error(
      "JSC_POLYMER_INVALID_DECLARAION", "A Polymer() declaration cannot use 'let' or 'const'.");

  // Errors
  static final DiagnosticType POLYMER_MISSING_IS = DiagnosticType.error("JSC_POLYMER_MISSING_IS",
      "The class descriptor must include an 'is' property.");

  static final DiagnosticType POLYMER_UNEXPECTED_PARAMS = DiagnosticType.error(
      "JSC_POLYMER_UNEXPECTED_PARAMS", "The class definition has too many arguments.");

  static final DiagnosticType POLYMER_MISSING_EXTERNS = DiagnosticType.error(
      "JSC_POLYMER_MISSING_EXTERNS", "Missing Polymer externs.");

  static final DiagnosticType POLYMER_INVALID_PROPERTY = DiagnosticType.error(
      "JSC_POLYMER_INVALID_PROPERTY", "Polymer property has an invalid or missing type.");

  static final DiagnosticType POLYMER_INVALID_BEHAVIOR_ARRAY = DiagnosticType.error(
      "JSC_POLYMER_INVALID_BEHAVIOR_ARRAY", "The behaviors property must be an array literal.");

  static final DiagnosticType POLYMER_UNQUALIFIED_BEHAVIOR = DiagnosticType.error(
      "JSC_POLYMER_UNQUALIFIED_BEHAVIOR",
      "Behaviors must be global, fully qualified names which are declared as object literals or "
      + "array literals of other valid Behaviors.");

  static final DiagnosticType POLYMER_UNANNOTATED_BEHAVIOR = DiagnosticType.error(
      "JSC_POLYMER_UNANNOTATED_BEHAVIOR",
      "Behavior declarations must be annotated with @polymerBehavior.");

  static final DiagnosticType POLYMER_SHORTHAND_NOT_SUPPORTED = DiagnosticType.error(
      "JSC_POLYMER_SHORTHAND_NOT_SUPPORTED",
      "Shorthand assignment in object literal is not allowed in "
      + "Polymer call arguments");

  static final String VIRTUAL_FILE = "<PolymerPass.java>";

  private final AbstractCompiler compiler;
  private Node polymerElementExterns;
  private Set<String> nativeExternsAdded;
  private final Map<String, String> tagNameMap;
  private List<Node> polymerElementProps;
  private final ImmutableSet<String> behaviorNamesNotToCopy;
  private GlobalNamespace globalNames;

  public PolymerPass(AbstractCompiler compiler) {
    this.compiler = compiler;
    tagNameMap = TagNameToType.getMap();
    polymerElementProps = new ArrayList<>();
    nativeExternsAdded = new HashSet<>();
    behaviorNamesNotToCopy = ImmutableSet.of(
        "created", "attached", "detached", "attributeChanged", "configure", "ready",
        "properties", "listeners", "observers", "hostAttributes");
  }

  @Override
  public void process(Node externs, Node root) {
    FindPolymerExterns externsCallback = new FindPolymerExterns();
    NodeTraversal.traverseEs6(compiler, externs, externsCallback);
    polymerElementExterns = externsCallback.polymerElementExterns;
    polymerElementProps = externsCallback.getpolymerElementProps();

    if (polymerElementExterns == null) {
      compiler.report(JSError.make(externs, POLYMER_MISSING_EXTERNS));
      return;
    }

    globalNames = new GlobalNamespace(compiler, externs, root);

    hotSwapScript(root, null);
  }

  /**
   * Finds the externs for the PolymerElement base class and all of its properties.
   */
  private static class FindPolymerExterns extends AbstractPostOrderCallback {
    private Node polymerElementExterns;
    private ImmutableList.Builder<Node> polymerElementProps;
    private static final String POLYMER_ELEMENT_NAME = "PolymerElement";

    public FindPolymerExterns() {
      polymerElementProps = ImmutableList.builder();
    }

    @Override
    public void visit(NodeTraversal t, Node n, Node parent) {
      if (isPolymerElementExterns(n)) {
        polymerElementExterns = n;
      } else if (isPolymerElementPropExpr(n)) {
        polymerElementProps.add(n);
      }
    }

    /**
     * @return Whether the node is the declaration of PolymerElement.
     */
    private boolean isPolymerElementExterns(Node value) {
      return value != null && value.isVar()
          && value.getFirstChild().matchesQualifiedName(POLYMER_ELEMENT_NAME);
    }

    /**
     * @return Whether the node is an expression result of an assignment to a property of
     * PolymerElement.
     */
    private boolean isPolymerElementPropExpr(Node value) {
      return value != null && value.isExprResult()
          && value.getFirstChild().getFirstChild().isGetProp()
          && NodeUtil.getRootOfQualifiedName(
              value.getFirstChild().getFirstChild()).matchesQualifiedName(POLYMER_ELEMENT_NAME);
    }

    public List<Node> getpolymerElementProps() {
      return polymerElementProps.build();
    }
  }

  /**
   * For every Polymer Behavior, strip property type annotations and add suppress checktypes on
   * functions.
   */
  private static class SuppressBehaviors extends AbstractPostOrderCallback {
    private final AbstractCompiler compiler;

    public SuppressBehaviors(AbstractCompiler compiler) {
      this.compiler = compiler;
    }

    @Override
    public void visit(NodeTraversal t, Node n, Node parent) {
      if (isBehavior(n)) {
        if (!n.isVar() && !n.isAssign()) {
          compiler.report(JSError.make(n, POLYMER_UNQUALIFIED_BEHAVIOR));
          return;
        }

        // Add @nocollapse.
        JSDocInfoBuilder newDocs = JSDocInfoBuilder.maybeCopyFrom(n.getJSDocInfo());
        newDocs.recordNoCollapse();
        n.setJSDocInfo(newDocs.build());

        Node behaviorValue = n.getChildAtIndex(1);
        if (n.isVar()) {
          behaviorValue = n.getFirstChild().getFirstChild();
        }
        suppressBehavior(behaviorValue);
      }
    }

    /**
     * @return Whether the node is the declaration of a Behavior.
     */
    private boolean isBehavior(Node value) {
      return value.getJSDocInfo() != null && value.getJSDocInfo().isPolymerBehavior();
    }

    /**
     * Strip property type annotations and add suppress checkTypes and globalThis on functions.
     */
    private void suppressBehavior(Node behaviorValue) {
      if (behaviorValue == null) {
        compiler.report(JSError.make(behaviorValue, POLYMER_UNQUALIFIED_BEHAVIOR));
        return;
      }

      if (behaviorValue.isArrayLit()) {
        for (Node child : behaviorValue.children()) {
          suppressBehavior(child);
        }
      } else if (behaviorValue.isObjectLit()) {
        stripPropertyTypes(behaviorValue);
        addBehaviorSuppressions(behaviorValue);
      }
    }

    private void stripPropertyTypes(Node behaviorValue) {
      List<MemberDefinition> properties = extractProperties(behaviorValue);
      for (MemberDefinition property : properties) {
        property.name.removeProp(Node.JSDOC_INFO_PROP);
      }
    }

    private void suppressDefaultValues(Node behaviorValue) {
      for (MemberDefinition property : extractProperties(behaviorValue)) {
        if (!property.value.isObjectLit()) {
          continue;
        }

        Node defaultValue = NodeUtil.getFirstPropMatchingKey(property.value, "value");
        if (defaultValue == null || !defaultValue.isFunction()) {
          continue;
        }
        Node defaultValueKey = defaultValue.getParent();
        JSDocInfoBuilder suppressDoc =
            JSDocInfoBuilder.maybeCopyFrom(defaultValueKey.getJSDocInfo());
        suppressDoc.addSuppression("checkTypes");
        suppressDoc.addSuppression("globalThis");
        defaultValueKey.setJSDocInfo(suppressDoc.build());
      }
    }

    private void addBehaviorSuppressions(Node behaviorValue) {
      for (Node keyNode : behaviorValue.children()) {
        if (keyNode.getFirstChild().isFunction()) {
          keyNode.removeProp(Node.JSDOC_INFO_PROP);
          JSDocInfoBuilder suppressDoc = new JSDocInfoBuilder(true);
          suppressDoc.addSuppression("checkTypes");
          suppressDoc.addSuppression("globalThis");
          keyNode.setJSDocInfo(suppressDoc.build());
        }
      }
      suppressDefaultValues(behaviorValue);
    }
  }

  @Override
  public void hotSwapScript(Node scriptRoot, Node originalRoot) {
    NodeTraversal.traverseEs6(compiler, scriptRoot, this);
    SuppressBehaviors suppressBehaviorsCallback = new SuppressBehaviors(compiler);
    NodeTraversal.traverseEs6(compiler, scriptRoot, suppressBehaviorsCallback);
  }

  @Override
  public void visit(NodeTraversal t, Node n, Node parent) {
    if (isPolymerCall(n)) {
      rewriteClassDefinition(n, parent, t);
    }
  }

  private void rewriteClassDefinition(Node n, Node parent, NodeTraversal t) {
    if (parent.getParent().isConst() || parent.getParent().isLet()) {
      compiler.report(JSError.make(n, POLYMER_INVALID_DECLARATION));
      return;
    }
    ClassDefinition def = extractClassDefinition(n);
    if (def != null) {
      if (NodeUtil.isNameDeclaration(parent.getParent()) || parent.isAssign()) {
        rewritePolymerClass(parent.getParent(), def, t);
      } else {
        rewritePolymerClass(parent, def, t);
      }
    }
  }

  private static class MemberDefinition {
    final JSDocInfo info;
    final Node name;
    final Node value;

    MemberDefinition(JSDocInfo info, Node name, Node value) {
      this.info = info;
      this.name = name;
      this.value = value;
    }
  }

  private static final class BehaviorDefinition {
    final List<MemberDefinition> props;
    final List<MemberDefinition> functionsToCopy;
    final List<MemberDefinition> nonPropertyMembersToCopy;
    final boolean isGlobalDeclaration;

    BehaviorDefinition(
        List<MemberDefinition> props, List<MemberDefinition> functionsToCopy,
        List<MemberDefinition> nonPropertyMembersToCopy, boolean isGlobalDeclaration) {
      this.props = props;
      this.functionsToCopy = functionsToCopy;
      this.nonPropertyMembersToCopy = nonPropertyMembersToCopy;
      this.isGlobalDeclaration = isGlobalDeclaration;
    }
  }

  private static final class ClassDefinition {
    /** The target node (LHS) for the Polymer element definition. */
    final Node target;

    /** The object literal passed to the call to the Polymer() function. */
    final Node descriptor;

    /** The constructor function for the element. */
    final MemberDefinition constructor;

    /** The name of the native HTML element which this element extends. */
    final String nativeBaseElement;

    /** Properties declared in the Polymer "properties" block. */
    final List<MemberDefinition> props;

    /** Flattened list of behavior definitions used by this element. */
    final List<BehaviorDefinition> behaviors;

    ClassDefinition(Node target, Node descriptor, JSDocInfo classInfo, MemberDefinition constructor,
        String nativeBaseElement, List<MemberDefinition> props,
        List<BehaviorDefinition> behaviors) {
      this.target = target;
      Preconditions.checkState(descriptor.isObjectLit());
      this.descriptor = descriptor;
      this.constructor = constructor;
      this.nativeBaseElement = nativeBaseElement;
      this.props = props;
      this.behaviors = behaviors;
    }
  }

  /**
   * Validates the class definition and if valid, destructively extracts the class definition from
   * the AST.
   */
  private ClassDefinition extractClassDefinition(Node callNode) {
    Node descriptor = NodeUtil.getArgumentForCallOrNew(callNode, 0);
    if (descriptor == null || !descriptor.isObjectLit()) {
      // report bad class definition
      compiler.report(JSError.make(callNode, POLYMER_DESCRIPTOR_NOT_VALID));
      return null;
    }

    int paramCount = callNode.getChildCount() - 1;
    if (paramCount != 1) {
      compiler.report(JSError.make(callNode, POLYMER_UNEXPECTED_PARAMS));
      return null;
    }

    Node elName = NodeUtil.getFirstPropMatchingKey(descriptor, "is");
    if (elName == null) {
      compiler.report(JSError.make(callNode, POLYMER_MISSING_IS));
      return null;
    }

    String elNameString = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, elName.getString());
    elNameString += "Element";

    Node target;
    if (NodeUtil.isNameDeclaration(callNode.getParent().getParent())) {
      target = IR.name(callNode.getParent().getString());
    } else if (callNode.getParent().isAssign()) {
      target = callNode.getParent().getFirstChild().cloneTree();
    } else {
      target = IR.name(elNameString);
    }

    target.useSourceInfoIfMissingFrom(callNode);
    JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(target);

    JSDocInfo ctorInfo = null;
    Node constructor = NodeUtil.getFirstPropMatchingKey(descriptor, "factoryImpl");
    if (constructor == null) {
      constructor = IR.function(IR.name(""), IR.paramList(), IR.block());
      constructor.useSourceInfoFromForTree(callNode);
    } else {
      ctorInfo = NodeUtil.getBestJSDocInfo(constructor);
    }

    Node baseClass = NodeUtil.getFirstPropMatchingKey(descriptor, "extends");
    String nativeBaseElement = baseClass == null ? null : baseClass.getString();

    Node behaviorArray = NodeUtil.getFirstPropMatchingKey(descriptor, "behaviors");
    List<BehaviorDefinition> behaviors = extractBehaviors(behaviorArray);
    List<MemberDefinition> allProperties = new LinkedList<>();
    for (BehaviorDefinition behavior : behaviors) {
      overwriteMembersIfPresent(allProperties, behavior.props);
    }
    overwriteMembersIfPresent(allProperties, extractProperties(descriptor));

    ClassDefinition def = new ClassDefinition(target, descriptor, classInfo,
        new MemberDefinition(ctorInfo, null, constructor), nativeBaseElement, allProperties,
        behaviors);
    return def;
  }

  /**
   * Appends a list of new MemberDefinitions to the end of a list and removes any previous
   * MemberDefinition in the list which has the same name as the new member.
   */
  private static void overwriteMembersIfPresent(
      List<MemberDefinition> list, List<MemberDefinition> newMembers) {
    for (MemberDefinition newMember : newMembers) {
      for (MemberDefinition member : list) {
        if (member.name.getString().equals(newMember.name.getString())) {
          list.remove(member);
          break;
        }
      }
      list.add(newMember);
    }
  }

  /**
   * Extracts all Behaviors from an array recursively. The array must be an array
   * literal whose value is known at compile-time. Entries in the array can be
   * object literals or array literals (of other behaviors). Behavior names must be
   * global, fully qualified names.
   * @see https://github.com/Polymer/polymer/blob/0.8-preview/PRIMER.md#behaviors
   * @return A list of all {@code BehaviorDefinitions} in the array.
   */
  private List<BehaviorDefinition> extractBehaviors(Node behaviorArray) {
    if (behaviorArray == null) {
      return ImmutableList.of();
    }

    if (!behaviorArray.isArrayLit()) {
      compiler.report(JSError.make(behaviorArray, POLYMER_INVALID_BEHAVIOR_ARRAY));
      return ImmutableList.of();
    }

    ImmutableList.Builder<BehaviorDefinition> behaviors = ImmutableList.builder();
    for (Node behaviorName : behaviorArray.children()) {
      if (behaviorName.isObjectLit()) {
        this.switchDollarSignPropsToBrackets(behaviorName);
        this.quoteListenerAndHostAttributeKeys(behaviorName);
        behaviors.add(new BehaviorDefinition(
            extractProperties(behaviorName), getBehaviorFunctionsToCopy(behaviorName),
            getNonPropertyMembersToCopy(behaviorName), !NodeUtil.isInFunction(behaviorName)));
        continue;
      }

      Name behaviorGlobalName = globalNames.getSlot(behaviorName.getQualifiedName());
      boolean isGlobalDeclaration = true;
      if (behaviorGlobalName == null) {
        compiler.report(JSError.make(behaviorName, POLYMER_UNQUALIFIED_BEHAVIOR));
        continue;
      }

      Ref behaviorDeclaration = behaviorGlobalName.getDeclaration();

      // Use any set as a backup declaration, even if it's local.
      if (behaviorDeclaration == null) {
        List<Ref> behaviorRefs = behaviorGlobalName.getRefs();
        for (Ref ref : behaviorRefs) {
          if (ref.isSet()) {
            isGlobalDeclaration = false;
            behaviorDeclaration = ref;
            break;
          }
        }
      }

      if (behaviorDeclaration == null) {
        compiler.report(JSError.make(behaviorName, POLYMER_UNQUALIFIED_BEHAVIOR));
        continue;
      }

      Node behaviorDeclarationNode = behaviorDeclaration.getNode();
      JSDocInfo behaviorInfo = NodeUtil.getBestJSDocInfo(behaviorDeclarationNode);
      if (behaviorInfo == null || !behaviorInfo.isPolymerBehavior()) {
        compiler.report(JSError.make(behaviorDeclarationNode, POLYMER_UNANNOTATED_BEHAVIOR));
      }

      Node behaviorValue = NodeUtil.getRValueOfLValue(behaviorDeclarationNode);

      if (behaviorValue == null) {
        compiler.report(JSError.make(behaviorName, POLYMER_UNQUALIFIED_BEHAVIOR));
      } else if (behaviorValue.isArrayLit()) {
        // Individual behaviors can also be arrays of behaviors. Parse them recursively.
        behaviors.addAll(extractBehaviors(behaviorValue));
      } else if (behaviorValue.isObjectLit()) {
        this.switchDollarSignPropsToBrackets(behaviorValue);
        this.quoteListenerAndHostAttributeKeys(behaviorValue);
        behaviors.add(new BehaviorDefinition(
            extractProperties(behaviorValue), getBehaviorFunctionsToCopy(behaviorValue),
            getNonPropertyMembersToCopy(behaviorValue), isGlobalDeclaration));
      } else {
        compiler.report(JSError.make(behaviorName, POLYMER_UNQUALIFIED_BEHAVIOR));
      }
    }

    return behaviors.build();
  }

  /**
   * @return A list of functions from a behavior which should be copied to the element prototype.
   */
  private List<MemberDefinition> getBehaviorFunctionsToCopy(Node behaviorObjLit) {
    Preconditions.checkState(behaviorObjLit.isObjectLit());
    ImmutableList.Builder<MemberDefinition> functionsToCopy = ImmutableList.builder();

    for (Node keyNode : behaviorObjLit.children()) {
      if ((keyNode.isStringKey() && keyNode.getFirstChild().isFunction()
          || keyNode.isMemberFunctionDef())
          && !behaviorNamesNotToCopy.contains(keyNode.getString())) {
        functionsToCopy.add(new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode,
          keyNode.getFirstChild()));
      }
    }

    return functionsToCopy.build();
  }

  /**
   * @return A list of MemberDefinitions in a behavior which are not in the properties block, but
   *     should still be copied to the element prototype.
   */
  private List<MemberDefinition> getNonPropertyMembersToCopy(Node behaviorObjLit) {
    Preconditions.checkState(behaviorObjLit.isObjectLit());
    ImmutableList.Builder<MemberDefinition> membersToCopy = ImmutableList.builder();

    for (Node keyNode : behaviorObjLit.children()) {
      if (keyNode.isGetterDef() || (keyNode.isStringKey() && !keyNode.getFirstChild().isFunction()
          && !behaviorNamesNotToCopy.contains(keyNode.getString()))) {
        membersToCopy.add(new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode,
          keyNode.getFirstChild()));
      }
    }

    return membersToCopy.build();
  }

  private static List<MemberDefinition> extractProperties(Node descriptor) {
    Node properties = NodeUtil.getFirstPropMatchingKey(descriptor, "properties");
    if (properties == null) {
      return ImmutableList.of();
    }

    ImmutableList.Builder<MemberDefinition> members = ImmutableList.builder();
    for (Node keyNode : properties.children()) {
      members.add(new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode,
          keyNode.getFirstChild()));
    }
    return members.build();
  }

  private void rewritePolymerClass(Node exprRoot, final ClassDefinition cls, NodeTraversal t) {
    // Add {@code @lends} to the object literal.
    Node call = exprRoot.getFirstChild();
    if (call.isAssign()) {
      call = call.getChildAtIndex(1);
    } else if (call.isName()) {
      call = call.getFirstChild();
    }

    Node objLit = cls.descriptor;
    if (hasShorthandAssignment(objLit)){
      compiler.report(JSError.make(objLit, POLYMER_SHORTHAND_NOT_SUPPORTED));
      return;
    }

    JSDocInfoBuilder objLitDoc = new JSDocInfoBuilder(true);
    objLitDoc.recordLends(cls.target.getQualifiedName() + ".prototype");
    objLit.setJSDocInfo(objLitDoc.build());

    this.addTypesToFunctions(objLit, cls.target.getQualifiedName());
    this.switchDollarSignPropsToBrackets(objLit);
    this.quoteListenerAndHostAttributeKeys(objLit);

    // For simplicity add everything into a block, before adding it to the AST.
    Node block = IR.block();

    if (cls.nativeBaseElement != null) {
      this.appendPolymerElementExterns(cls);
    }
    JSDocInfoBuilder constructorDoc = this.getConstructorDoc(cls);

    // Remove the original constructor JS docs from the objlit.
    Node ctorKey = cls.constructor.value.getParent();
    if (ctorKey != null) {
      ctorKey.removeProp(Node.JSDOC_INFO_PROP);
    }

    if (cls.target.isGetProp()) {
      // foo.bar = Polymer({...});
      Node assign = IR.assign(
          cls.target.cloneTree(),
          cls.constructor.value.cloneTree());
      assign.setJSDocInfo(constructorDoc.build());
      Node exprResult = IR.exprResult(assign);
      block.addChildToBack(exprResult);
    } else {
      // var foo = Polymer({...}); OR Polymer({...});
      Node var = IR.var(cls.target.cloneTree(), cls.constructor.value.cloneTree());
      var.setJSDocInfo(constructorDoc.build());
      block.addChildToBack(var);
    }

    appendPropertiesToBlock(cls, block, cls.target.getQualifiedName() + ".prototype.");
    appendBehaviorMembersToBlock(cls, block);
    List<MemberDefinition> readOnlyProps = parseReadOnlyProperties(cls, block);
    addInterfaceExterns(cls, readOnlyProps);
    removePropertyDocs(objLit);

    block.useSourceInfoIfMissingFromForTree(exprRoot);
    Node stmts = block.removeChildren();
    Node parent = exprRoot.getParent();

    // If the call to Polymer() is not in the global scope and the assignment target is not
    // namespaced (which likely means it's exported to the global scope), put the type declaration
    // into the global scope at the start of the current script.
    //
    // This avoids unknown type warnings which are a result of the compiler's poor understanding of
    // types declared inside IIFEs or any non-global scope. We should revisit this decision after
    // moving to the new type inference system which should be able to infer these types better.
    if (!t.getScope().isGlobal() && !cls.target.isGetProp()) {
      Node scriptNode = NodeUtil.getEnclosingScript(exprRoot);
      scriptNode.addChildrenToFront(stmts);
    } else {
      Node beforeRoot = parent.getChildBefore(exprRoot);
      if (beforeRoot == null) {
        parent.addChildrenToFront(stmts);
      } else {
        parent.addChildrenAfter(stmts, beforeRoot);
      }
    }

    if (exprRoot.isVar()) {
      Node assignExpr = varToAssign(exprRoot);
      parent.replaceChild(exprRoot, assignExpr);
    }

    compiler.reportCodeChange();
  }

  /**
   * Add an @this annotation to all functions in the objLit.
   */
  private void addTypesToFunctions(Node objLit, String thisType) {
    Preconditions.checkState(objLit.isObjectLit());
    for (Node keyNode : objLit.children()) {
      Node value = keyNode.getLastChild();
      if (value != null && value.isFunction()) {
        JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(keyNode.getJSDocInfo());
        fnDoc.recordThisType(new JSTypeExpression(
            new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
        keyNode.setJSDocInfo(fnDoc.build());
      }
    }

    // Add @this and @return to default property values.
    for (MemberDefinition property : extractProperties(objLit)) {
      if (!property.value.isObjectLit()) {
        continue;
      }
      if (hasShorthandAssignment(property.value)){
        compiler.report(JSError.make(property.value, POLYMER_SHORTHAND_NOT_SUPPORTED));
        return;
      }

      Node defaultValue = NodeUtil.getFirstPropMatchingKey(property.value, "value");
      if (defaultValue == null || !defaultValue.isFunction()) {
        continue;
      }
      Node defaultValueKey = defaultValue.getParent();
      JSDocInfoBuilder fnDoc = JSDocInfoBuilder.maybeCopyFrom(defaultValueKey.getJSDocInfo());
      fnDoc.recordThisType(new JSTypeExpression(
          new Node(Token.BANG, IR.string(thisType)), VIRTUAL_FILE));
      fnDoc.recordReturnType(getTypeFromProperty(property));
      defaultValueKey.setJSDocInfo(fnDoc.build());
    }
  }

  /**
   * Switches all "this.$.foo" to "this.$['foo']".
   */
  private void switchDollarSignPropsToBrackets(Node objLit) {
    Preconditions.checkState(objLit.isObjectLit());
    for (Node keyNode : objLit.children()) {
      Node value = keyNode.getFirstChild();
      if (value != null && value.isFunction()) {
        NodeUtil.visitPostOrder(
            value.getLastChild(),
            new NodeUtil.Visitor() {
              @Override
              public void visit(Node n) {
                if (n.isString() && n.getString().equals("$") && n.getParent().isGetProp()
                    && n.getParent().getParent().isGetProp()) {
                  Node dollarChildProp = n.getParent().getParent();
                  dollarChildProp.setType(Token.GETELEM);
                  compiler.reportCodeChange();
                }
              }
            },
            Predicates.<Node>alwaysTrue());
      }
    }
  }

  /**
   * Makes sure that the keys for listeners and hostAttributes blocks are quoted to avoid renaming.
   */
  private void quoteListenerAndHostAttributeKeys(Node objLit) {
    Preconditions.checkState(objLit.isObjectLit());
    for (Node keyNode : objLit.children()) {
      if (keyNode.isComputedProp()) {
        continue;
      }
      if (!keyNode.getString().equals("listeners")
          && !keyNode.getString().equals("hostAttributes")) {
        continue;
      }
      for (Node keyToQuote : keyNode.getFirstChild().children()) {
        keyToQuote.setQuotedString();
      }
    }
  }

  /**
   * Appends all properties in the ClassDefinition to the prototype of the custom element.
   */
  private void appendPropertiesToBlock(final ClassDefinition cls, Node block, String basePath) {
    for (MemberDefinition prop : cls.props) {
      Node propertyNode = IR.exprResult(
          NodeUtil.newQName(compiler, basePath + prop.name.getString()));
      JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(prop.info);

      JSTypeExpression propType = getTypeFromProperty(prop);
      if (propType == null) {
        return;
      }
      info.recordType(propType);
      propertyNode.getFirstChild().setJSDocInfo(info.build());

      block.addChildToBack(propertyNode);
    }
  }

  /**
   * Remove all JSDocs from properties of a class definition
   */
  private void removePropertyDocs(final Node objLit) {
    for (MemberDefinition prop : extractProperties(objLit)) {
      prop.name.removeProp(Node.JSDOC_INFO_PROP);
    }
  }

  /**
   * Appends all required behavior functions and non-property members to the given block.
   */
  private void appendBehaviorMembersToBlock(final ClassDefinition cls, Node block) {
    String qualifiedPath = cls.target.getQualifiedName() + ".prototype.";
    Map<String, Node> nameToExprResult = new HashMap<>();
    for (BehaviorDefinition behavior : cls.behaviors) {
      for (MemberDefinition behaviorFunction : behavior.functionsToCopy) {
        String fnName = behaviorFunction.name.getString();
        // Don't copy functions already defined by the element itself.
        if (NodeUtil.getFirstPropMatchingKey(cls.descriptor, fnName) != null) {
          continue;
        }

        // Avoid copying over the same function twice. The last definition always wins.
        if (nameToExprResult.containsKey(fnName)) {
          block.removeChild(nameToExprResult.get(fnName));
        }

        Node fnValue = behaviorFunction.value.cloneTree();
        Node exprResult = IR.exprResult(
            IR.assign(NodeUtil.newQName(compiler, qualifiedPath + fnName), fnValue));
        JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorFunction.info);

        // Behaviors whose declarations are not in the global scope may contain references to
        // symbols which do not exist in the element's scope. Only copy a function stub. See
        if (!behavior.isGlobalDeclaration) {
          NodeUtil.getFunctionBody(fnValue).removeChildren();
        }

        exprResult.getFirstChild().setJSDocInfo(info.build());
        block.addChildToBack(exprResult);
        nameToExprResult.put(fnName, exprResult);
      }

      // Copy other members.
      for (MemberDefinition behaviorProp : behavior.nonPropertyMembersToCopy) {
        String propName = behaviorProp.name.getString();
        if (nameToExprResult.containsKey(propName)) {
          block.removeChild(nameToExprResult.get(propName));
        }

        Node exprResult = IR.exprResult(NodeUtil.newQName(compiler, qualifiedPath + propName));
        JSDocInfoBuilder info = JSDocInfoBuilder.maybeCopyFrom(behaviorProp.info);

        if (behaviorProp.name.isGetterDef()) {
          info = new JSDocInfoBuilder(true);
          if (behaviorProp.info != null && behaviorProp.info.getReturnType() != null) {
            info.recordType(behaviorProp.info.getReturnType());
          }
        }

        exprResult.getFirstChild().setJSDocInfo(info.build());
        block.addChildToBack(exprResult);
        nameToExprResult.put(propName, exprResult);
      }
    }
  }

  /**
   * Generates the _set* setters for readonly properties and appends them to the given block.
   * @return A List of all readonly properties.
   */
  private List<MemberDefinition> parseReadOnlyProperties(final ClassDefinition cls, Node block) {
    String qualifiedPath = cls.target.getQualifiedName() + ".prototype.";
    ImmutableList.Builder<MemberDefinition> readOnlyProps = ImmutableList.builder();

    for (MemberDefinition prop : cls.props) {
      // Generate the setter for readOnly properties.
      if (prop.value.isObjectLit()) {
        Node readOnlyValue = NodeUtil.getFirstPropMatchingKey(prop.value, "readOnly");
        if (readOnlyValue != null && readOnlyValue.isTrue()) {
          block.addChildToBack(makeReadOnlySetter(prop.name.getString(), qualifiedPath));
          readOnlyProps.add(prop);
        }
      }
    }

    return readOnlyProps.build();
  }

  /**
   * Gets the JSTypeExpression for a given property using its "type" key.
   * @see https://github.com/Polymer/polymer/blob/0.8-preview/PRIMER.md#configuring-properties
   */
  private JSTypeExpression getTypeFromProperty(MemberDefinition property) {
    if (property.info != null && property.info.hasType()) {
      return property.info.getType();
    }

    String typeString = "";
    if (property.value.isObjectLit()) {
      Node typeValue = NodeUtil.getFirstPropMatchingKey(property.value, "type");
      if (typeValue == null || !typeValue.isName()) {
        compiler.report(JSError.make(property.name, POLYMER_INVALID_PROPERTY));
        return null;
      }
      typeString = typeValue.getString();
    } else if (property.value.isName()) {
      typeString = property.value.getString();
    }

    Node typeNode = null;
    switch (typeString) {
      case "Boolean":
      case "String":
      case "Number":
        typeNode = IR.string(typeString.toLowerCase());
        break;
      case "Array":
      case "Function":
      case "Object":
      case "Date":
        typeNode = new Node(Token.BANG, IR.string(typeString));
        break;
      default:
        compiler.report(JSError.make(property.name, POLYMER_INVALID_PROPERTY));
        return null;
    }

    return new JSTypeExpression(typeNode, VIRTUAL_FILE);
  }

  /**
   * Adds the generated setter for a readonly property.
   * @see https://www.polymer-project.org/0.8/docs/devguide/properties.html#read-only
   */
  private Node makeReadOnlySetter(String propName, String qualifiedPath) {
    String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
    Node fnNode = IR.function(IR.name(""), IR.paramList(IR.name(propName)), IR.block());
    Node exprResNode = IR.exprResult(
        IR.assign(NodeUtil.newQName(compiler, qualifiedPath + setterName), fnNode));

    JSDocInfoBuilder info = new JSDocInfoBuilder(true);
    // This is overriding a generated function which was added to the interface in
    // {@code addInterfaceExterns}.
    info.recordOverride();
    exprResNode.getFirstChild().setJSDocInfo(info.build());

    return exprResNode;
  }

  /**
   * Duplicates the PolymerElement externs with a different element base class if needed.
   * For example, if the base class is HTMLInputElement, then a class PolymerInputElement will be
   * added. If the element does not extend a native HTML element, this method is a no-op.
   */
  private void appendPolymerElementExterns(final ClassDefinition cls) {
    if (!nativeExternsAdded.add(cls.nativeBaseElement)) {
      return;
    }

    Node block = IR.block();

    Node baseExterns = polymerElementExterns.cloneTree();
    String polymerElementType = getPolymerElementType(cls);
    baseExterns.getFirstChild().setString(polymerElementType);

    String elementType = tagNameMap.get(cls.nativeBaseElement);
    JSTypeExpression elementBaseType = new JSTypeExpression(
        new Node(Token.BANG, IR.string(elementType)), VIRTUAL_FILE);
    JSDocInfoBuilder baseDocs = JSDocInfoBuilder.copyFrom(baseExterns.getJSDocInfo());
    baseDocs.changeBaseType(elementBaseType);
    baseExterns.setJSDocInfo(baseDocs.build());
    block.addChildToBack(baseExterns);

    for (Node baseProp : polymerElementProps) {
      Node newProp = baseProp.cloneTree();
      Node newPropRootName = NodeUtil.getRootOfQualifiedName(
           newProp.getFirstChild().getFirstChild());
      newPropRootName.setString(polymerElementType);
      block.addChildToBack(newProp);
    }

    block.useSourceInfoIfMissingFromForTree(polymerElementExterns);

    Node parent = polymerElementExterns.getParent();
    Node stmts = block.removeChildren();
    parent.addChildrenAfter(stmts, polymerElementExterns);

    compiler.reportCodeChange();
  }

  /**
   * Adds an interface for the given ClassDefinition to externs. This allows generated setter
   * functions for read-only properties to avoid renaming altogether.
   * @see https://www.polymer-project.org/0.8/docs/devguide/properties.html#read-only
   */
  private void addInterfaceExterns(final ClassDefinition cls,
      List<MemberDefinition> readOnlyProps) {
    Node block = IR.block();

    String interfaceName = getInterfaceName(cls);
    Node fnNode = IR.function(IR.name(""), IR.paramList(), IR.block());
    Node varNode = IR.var(NodeUtil.newQName(compiler, interfaceName), fnNode);

    JSDocInfoBuilder info = new JSDocInfoBuilder(true);
    info.recordInterface();
    varNode.setJSDocInfo(info.build());
    block.addChildToBack(varNode);

    appendPropertiesToBlock(cls, block, interfaceName + ".prototype.");
    for (MemberDefinition prop : readOnlyProps) {
      // Add all _set* functions to avoid renaming.
      String propName = prop.name.getString();
      String setterName = "_set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
      Node setterExprNode = IR.exprResult(
          NodeUtil.newQName(compiler, interfaceName + ".prototype." + setterName));

      JSDocInfoBuilder setterInfo = new JSDocInfoBuilder(true);
      JSTypeExpression propType = getTypeFromProperty(prop);
      setterInfo.recordParameter(propName, propType);
      setterExprNode.getFirstChild().setJSDocInfo(setterInfo.build());

      block.addChildToBack(setterExprNode);
    }

    block.useSourceInfoIfMissingFromForTree(polymerElementExterns);

    Node parent = polymerElementExterns.getParent();
    Node stmts = block.removeChildren();
    parent.addChildrenToBack(stmts);

    compiler.reportCodeChange();
  }

  /**
   * @return The name of the generated extern interface which the element implements.
   */
  private String getInterfaceName(final ClassDefinition cls) {
    return "Polymer" + cls.target.getQualifiedName().replaceAll("\\.", "_") + "Interface";
  }

  /**
   * @return The proper constructor doc for the Polymer call.
   */
  private JSDocInfoBuilder getConstructorDoc(final ClassDefinition cls) {
    JSDocInfoBuilder constructorDoc = JSDocInfoBuilder.maybeCopyFrom(cls.constructor.info);
    constructorDoc.recordConstructor();

    JSTypeExpression baseType = new JSTypeExpression(
        new Node(Token.BANG, IR.string(getPolymerElementType(cls))), VIRTUAL_FILE);
    constructorDoc.recordBaseType(baseType);

    String interfaceName = getInterfaceName(cls);
    JSTypeExpression interfaceType = new JSTypeExpression(
        new Node(Token.BANG, IR.string(interfaceName)), VIRTUAL_FILE);
    constructorDoc.recordImplementedInterface(interfaceType);

    return constructorDoc;
  }

  /**
   * @return An assign replacing the equivalent var declaration.
   */
  private static Node varToAssign(Node var) {
    Node assign = IR.assign(
        IR.name(var.getFirstChild().getString()),
        var.getFirstChild().removeFirstChild());
    return IR.exprResult(assign).useSourceInfoFromForTree(var);
  }

  /**
   * @return The PolymerElement type string for a class definition.
   */
  private static String getPolymerElementType(final ClassDefinition cls) {
    return SimpleFormat.format("Polymer%sElement", cls.nativeBaseElement == null ? ""
        : CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, cls.nativeBaseElement));
  }

  /**
   * @return Whether the call represents a call to Polymer.
   */
  private static boolean isPolymerCall(Node value) {
    return value != null && value.isCall() && value.getFirstChild().matchesQualifiedName("Polymer");
  }

  private boolean hasShorthandAssignment (Node objLit){
    Preconditions.checkState(objLit.isObjectLit());
    for (Node property : objLit.children()){
      if (property.isStringKey() && !property.hasChildren()){
        return true;
      }
    }
    return false;
  }

}


text:
/**
 * Function converts attribute name "data-some-value" to "someValue".
 *
 * @param {string} name
 * @returns {string}
 */
export function attributeNameToProperty(name) {
    let result = name.replace(/^data-/i, '');
    return result.replace(/-(\w)/g, (match, letter) => letter.toUpperCase());
}

/**
 * Function converts dataset property name "someValue" to "data-some-value".
 *
 * @param {string} name
 * @returns {string}
 */
export function propertyNameToAttribute(name) {
    let result = name.replace(/([A-Z])/g, (match, letter) => '-' + letter.toLowerCase());
    return 'data-' + result;
}

redpajama_set_name: RedPajamaGithub


text:
package edu.hm.hafner.analysis.parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.Priority;
import edu.hm.hafner.analysis.RegexpLineParser;

/**
 * A parser for IBM xlC compiler warnings.
 *
 * @author Andrew Gvozdev
 */
public class XlcCompilerParser extends RegexpLineParser {
    private static final long serialVersionUID = 5490211629355204910L;

    private static final String XLC_WARNING_PATTERN = ANT_TASK + ".*((?:[A-Z]+|[0-9]+-)[0-9]+)* ?\\([USEWI]\\)\\s*("
            + ".*)$";
    private static final String XLC_WARNING_PATTERN_WITH_LINE = ANT_TASK + "\"?([^\"]*)\"?, line ([0-9]+)\\.[0-9]+:( "
            + "(?:[A-Z]+|[0-9]+-)[0-9]+)? \\(([USEWI])\\)\\s*(.*)$";
    private static final String XLC_WARNING_PATTERN_NO_LINE = ANT_TASK + "\\s*((?:[A-Z]+|[0-9]+-)[0-9]+)?:? ?\\("
            + "([USEWI])\\)( INFORMATION:)?\\s*(.*)$";
    private static final Pattern PATTERN_WITH_LINE = Pattern.compile(XLC_WARNING_PATTERN_WITH_LINE);
    private static final Pattern PATTERN_WITHOUT_LINE = Pattern.compile(XLC_WARNING_PATTERN_NO_LINE);

    /**
     * Creates a new instance of {@link XlcCompilerParser}.
     */
    public XlcCompilerParser() {
        super(XLC_WARNING_PATTERN);
    }

    private Priority toPriority(final String severity) {
        switch (severity.charAt(0)) {
            case 'U':
            case 'S':
            case 'E':
                return Priority.HIGH;
            case 'W':
                return Priority.NORMAL;
            case 'I':
                return Priority.LOW;
            default:
                return Priority.HIGH;
        }
    }

    @Override
    protected Issue createIssue(final Matcher matcher, final IssueBuilder builder) {
        String line = matcher.group(0);

        Matcher lineMatcher = PATTERN_WITH_LINE.matcher(line);
        if (lineMatcher.find()) {
            return builder.setFileName(lineMatcher.group(1))
                    .setLineStart(parseInt(lineMatcher.group(2)))
                    .setCategory(lineMatcher.group(3).trim())
                    .setMessage(lineMatcher.group(5))
                    .setPriority(toPriority(lineMatcher.group(4)))
                    .build();
        }

        return createIssueWithoutLine(builder, line);
    }

    private Issue createIssueWithoutLine(final IssueBuilder builder, final String line) {
        Matcher matcher = PATTERN_WITHOUT_LINE.matcher(line);
        if (matcher.find()) {
            return builder.setFileName("")
                    .setLineStart(0)
                    .setCategory(matcher.group(1).trim())
                    .setMessage(matcher.group(4))
                    .setPriority(toPriority(matcher.group(2)))
                    .build();
        }
        return FALSE_POSITIVE;
    }
}


text:
/**
* Author: CZ cz.theng@gmail.com
 */

// Package log is a wraper for log
package log

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"sync"
)

type devicer interface {
	Write(buf []byte) (n int, err error)
}

type device struct {
	fp  *os.File
	mtx sync.Mutex
}

type consoleDevice struct {
	device
}

func newConsoleDevice() (*consoleDevice, error) {
	cd := new(consoleDevice)
	cd.fp = os.Stdout
	return cd, nil
}

func (cd *consoleDevice) write(buf []byte) (n int, err error) {
	cd.mtx.Lock()
	defer cd.mtx.Unlock()
	n, err = cd.fp.Write(buf)
	return
}

type fileDevice struct {
	device
	fileName string
	fileSize uint64
	logLen   uint64
}

func newFileDevice(fileName string) (fd *fileDevice, err error) {
	fd = new(fileDevice)
	fd.fileName = fileName
	fd.fp, err = openFile(fd.fileName)
	return fd, err
}

func (fd *fileDevice) setFileSize(size uint64) {
	fd.fileSize = size
}

func (fd *fileDevice) SetFileName(fileName string) {
	fd.fileName = fileName
}

func (fd *fileDevice) Write(buf []byte) (n int, err error) {
	fd.mtx.Lock()
	defer fd.mtx.Unlock()
	bufLen := uint64(len(buf))
	if bufLen+fd.logLen <= fd.fileSize {
		n, err = fd.fp.Write(buf)
		fd.logLen += uint64(n)
		return
	}
	remainBuf := buf[fd.fileSize-fd.logLen:]
	/* for CoverAll 95%
	n, err = fd.fp.Write(buf[:fd.fileSize-fd.logLen])
	if err != nil {
		return
	}
	*/
	n, _ = fd.fp.Write(buf[:fd.fileSize-fd.logLen])
	fd.fp.Sync()
	fd.fp.Close()
	/* for CoverAll 95%
	fd.fp, err = openFile(fd.fileName)
	if err != nil {
		return
	}
	*/
	fd.fp, _ = openFile(fd.fileName)
	fd.logLen = 0
	/* for Covarall 95%
	n, err = fd.fp.Write(remainBuf)
	if err != nil {
		return
	}
	*/
	n, _ = fd.fp.Write(remainBuf)
	fd.logLen += uint64(n)
	return
}

func fileNotExist(filePath string) bool {
	_, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			return true
		}
		return false
	}
	return false
}

func openFile(fileName string) (fp *os.File, err error) {
	err = os.MkdirAll(filepath.Dir(fileName), os.ModePerm)
	if err != nil {
		return
	}
	logPath := fileName
	for i := 1; ; i++ {
		ret := fileNotExist(logPath)
		if ret {
			flag := os.O_WRONLY | os.O_CREATE | os.O_APPEND
			fp, err = os.OpenFile(logPath, flag, 0666)
			break
		} else {
			var buf bytes.Buffer
			buf.WriteString(fmt.Sprintf("%s.%d", fileName, i))
			logPath = buf.String()
		}
	}
	return
}


text:
use std::env;
use std::fs;
use std::path::PathBuf;

fn main() {
    let src = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
    let src_dll = src.join("../openvr/bin/win64/openvr_api.dll").canonicalize().unwrap();
    let mut dst = PathBuf::from(env::var_os("OUT_DIR").unwrap());
    dst.pop();
    dst.pop();
    dst.pop();
    let dst_dll = dst.join("openvr_api.dll");
    fs::copy(&src_dll, &dst_dll).expect("copy dll");
}


text:
package io.apiman.gateway.platforms.servlet.auth.tls;

import io.apiman.common.config.options.TLSOptions;
import io.apiman.gateway.engine.IApiConnection;
import io.apiman.gateway.engine.IApiConnectionResponse;
import io.apiman.gateway.engine.IApiConnector;
import io.apiman.gateway.engine.async.IAsyncResult;
import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.auth.RequiredAuthType;
import io.apiman.gateway.engine.beans.Api;
import io.apiman.gateway.engine.beans.ApiRequest;
import io.apiman.gateway.engine.beans.exceptions.ConnectorException;
import io.apiman.gateway.platforms.servlet.connectors.ConnectorConfigImpl;
import io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Tests various standard TLS scenarios, in which the client is *not* authenticated. Some of these include
 * authentication of the server certificate, whilst others are all trusting (devmode).
 *
 * @author Marc Savy <msavy@redhat.com>
 */
@SuppressWarnings("nls")
public class StandardTLSTest {

    private Server server;
    private HttpConfiguration http_config;
    private Map<String, String> config = new HashMap<>();

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Before
    public void setupJetty() throws Exception {
        server = new Server();
        server.setStopAtShutdown(true);

        http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");

        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
        sslContextFactory.setTrustStorePassword("password");
        sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
        sslContextFactory.setKeyStorePassword("password");
        sslContextFactory.setKeyManagerPassword("password");
        // Use default trust store
        // No client auth
        sslContextFactory.setNeedClientAuth(false);
        sslContextFactory.setWantClientAuth(false);

        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());

        ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,"http/1.1"),
            new HttpConnectionFactory(https_config));
        sslConnector.setPort(8008);

        server.addConnector(sslConnector);
        // Thanks to Jetty getting started guide.
        server.setHandler(new AbstractHandler() {

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request,
                    HttpServletResponse response) throws IOException, ServletException {

                Enumeration<String> z = request.getAttributeNames();

                while (z.hasMoreElements()) {
                    String elem = z.nextElement();
                    System.out.println(elem + " - " + request.getAttribute(elem));
                }

                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getWriter().println("apiman");
            }
        });
        server.start();
    }

    @After
    public void destroyJetty() throws Exception {
        server.stop();
        server.destroy();
        config.clear();
    }

    ApiRequest request = new ApiRequest();
    Api api = new Api();
    {
        request.setApiKey("12345");
        request.setDestination("/");
        request.getHeaders().put("test", "it-worked");
        request.setTransportSecure(true);
        request.setRemoteAddr("https://localhost:8008/");
        request.setType("GET");

        api.setEndpoint("https://localhost:8008/");
        api.getEndpointProperties().put(RequiredAuthType.ENDPOINT_AUTHORIZATION_TYPE, "mtls");
    }

    /**
     * Scenario:
     *   - CA inherited trust
     *   - gateway trusts API via CA
     *   - API does not evaluate trust
     */
    @Test
    public void shouldSucceedWithValidTLS() {
        config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
        config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
        config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
        config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");

        HttpConnectorFactory factory = new HttpConnectorFactory(config);
        IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false, new ConnectorConfigImpl());
        IApiConnection connection = connector.connect(request,
                new IAsyncResultHandler<IApiConnectionResponse>() {

            @Override
            public void handle(IAsyncResult<IApiConnectionResponse> result) {
                if (result.isError())
                    throw new RuntimeException(result.getError());

                Assert.assertTrue(result.isSuccess());
            }
        });

        connection.end();
    }

    /**
     * Scenario:
     *   - CA is only in API trust store, missing from gateway trust store
     *   - Gateway does not trust API, as it does not trust CA
     *   - API trusts gateway via CA
     */
    @Test
    public void shouldFailWhenCANotTrusted() {
        // Keystore does not trust the root CA API is signed with.
        config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth/gateway_ts.jks"));
        config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
        config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
        config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");

        HttpConnectorFactory factory = new HttpConnectorFactory(config);
        IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false, new ConnectorConfigImpl());
        IApiConnection connection = connector.connect(request,
                new IAsyncResultHandler<IApiConnectionResponse>() {

         @Override
         public void handle(IAsyncResult<IApiConnectionResponse> result) {
             Assert.assertTrue(result.isError());
             System.out.println(result.getError());
             Assert.assertTrue(result.getError() instanceof ConnectorException);
         }
        });

        connection.end();
    }

    /**
     * Scenario:
     *   - Development mode TLS pass-through. Accepts anything.
     */
    @Test
    public void shouldAllowAllWhenDevMode() {
        config.put(TLSOptions.TLS_DEVMODE, "true");

        HttpConnectorFactory factory = new HttpConnectorFactory(config);
        IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false, new ConnectorConfigImpl());
        IApiConnection connection = connector.connect(request,
                new IAsyncResultHandler<IApiConnectionResponse>() {

         @Override
         public void handle(IAsyncResult<IApiConnectionResponse> result) {
             Assert.assertTrue(result.isSuccess());
         }
        });

        connection.end();
    }

    /**
     * Scenario:
     *   - No settings whatsoever.
     *   - Will fail, as defaults are relatively safe,
     *     and API certificate will not be recognised.
     */
    @Test
    public void shouldFailWithNoSettings() {
        HttpConnectorFactory factory = new HttpConnectorFactory(config);
        IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false, new ConnectorConfigImpl());
        IApiConnection connection = connector.connect(request,
                new IAsyncResultHandler<IApiConnectionResponse>() {

         @Override
         public void handle(IAsyncResult<IApiConnectionResponse> result) {
                 Assert.assertTrue(result.isError());
                 System.out.println(result.getError());
             }
        });

        connection.end();
    }

    private String getResourcePath(String res) {
        URL resource = StandardTLSTest.class.getResource(res);
        try {
            return Paths.get(resource.toURI()).toFile().getAbsolutePath();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
"""Mock almaden backend"""

from .fake_almaden import FakeAlmadenV2
from .fake_almaden import FakeAlmaden


text:
namespace Histacom2.OS.Win95.Win95Apps
{
    partial class GuessTheNumber
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.pictureBox1 = new Histacom2.Engine.UI.ClassicButton();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.pictureBox3 = new Histacom2.Engine.UI.ClassicButton();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(20, 10);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(224, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "I am thinking of a number between 1 and 100.";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(16, 36);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(40, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "Guess:";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(58, 33);
            this.textBox1.MaxLength = 3;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(33, 20);
            this.textBox1.TabIndex = 2;
            //
            // pictureBox1
            //
            this.pictureBox1.BackColor = System.Drawing.Color.Silver;
            this.pictureBox1.ForeColor = System.Drawing.Color.Black;
            this.pictureBox1.Location = new System.Drawing.Point(191, 30);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(55, 27);
            this.pictureBox1.TabIndex = 5;
            this.pictureBox1.Text = "Check";
            this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
            //
            // pictureBox2
            //
            this.pictureBox2.Location = new System.Drawing.Point(97, 31);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(88, 24);
            this.pictureBox2.TabIndex = 4;
            this.pictureBox2.TabStop = false;
            //
            // pictureBox3
            //
            this.pictureBox3.BackColor = System.Drawing.Color.Silver;
            this.pictureBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.pictureBox3.ForeColor = System.Drawing.Color.Black;
            this.pictureBox3.Location = new System.Drawing.Point(19, 62);
            this.pictureBox3.Name = "pictureBox3";
            this.pictureBox3.Size = new System.Drawing.Size(227, 23);
            this.pictureBox3.TabIndex = 0;
            this.pictureBox3.Text = "Restart";
            this.pictureBox3.Click += new System.EventHandler(this.pictureBox3_Click);
            //
            // GuessTheNumber
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Silver;
            this.Controls.Add(this.pictureBox3);
            this.Controls.Add(this.pictureBox2);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "GuessTheNumber";
            this.Size = new System.Drawing.Size(268, 100);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBox1;
        private Engine.UI.ClassicButton pictureBox1;
        private System.Windows.Forms.PictureBox pictureBox2;
        private Engine.UI.ClassicButton pictureBox3;
    }
}


text:
<?php
// classes/Google_OAuth2.class.php

/**
 * Authenticate with the Google servers using OAuth2
 * https://accounts.google.com/o/oauth2/auth
 *
 */
class Google_OAuth2 {

	const URL = 'https://accounts.google.com/o/oauth2/auth';
	public $authenticated = false;

	// these variables will be encoded into a GET query
	public $response_type = "code",
		$access_type,
		$client_id,
		$redirect_uri;
	public $scopes = array();

	/**
	 * add a URL OAuth2 scope to the scope list.
	 */
	public function addScope($scope) {
		$this->scopes[] = $scope;
	}

	/**
	 * make the OAuth2 login request.
	 * This is done by forwarding the user
	 * to a login screen
	 */
	public function authenticate() {
		$scope = implode(" ", $this->scopes);

		$query_params = array(
			'response_type' => $this->response_type,
			'access_type' => 'offline',
			'client_id' => $this->client_id,
			'redirect_uri' => $this->redirect_uri,
			'scope' => $scope
		);

		$forward_url = self::URL . '?' . http_build_query($query_params);

		header('Location: ' . $forward_url);
	}

}

?>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>vdelayxs</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="vdelayxq.html" title="vdelayxq" />
    <link rel="next" href="vdelayxw.html" title="vdelayxw" />

          vdelayxs

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          vdelayxs

vdelayxs —
      Un opcode de délai variable stéréo avec interpolation de grande qualité.

Description

      Un opcode de délai variable stéréo avec interpolation de grande qualité.

Syntaxe

aout1, aout2 vdelayxs ain1, ain2, adl, imd, iws [, ist]

Initialisation

      imd -- durée maximale du délai (en secondes).

      iws -- taille de la fenêtre d'interpolation (voir ci-dessous).

      ist (facultatif) -- l'initialisation est ignorée s'il est
      différent de zéro.

Exécution

      aout1, aout2 -- signaux audio en sortie.

      ain1, ain2 -- signaux audio en entrée.

      adl -- durée du délai en secondes.

      Cet opcode utilise une interpolation de grande qualité (et peu rapide), qui est
      bien plus précise que les interpolations linéaire et cubique couramment
      disponibles. Le paramètre iws fixe le nombre d'échantillons
      en entrée utilisés pour le calcul d'un échantillon en sortie (les valeurs
      permises sont des multiples entiers de 4 compris entre 4 et 1024) ; plus les
      valeurs sont élevées, meilleure est la qualité et plus lent le processus.

      Les opcodes multicanaux (par exemple vdelayxq) permettent
      de retarder 2 ou 4 variables à la fois (signaux stéréo ou quadro) ; c'est bien
      plus efficace que d'utiliser un opcode séparé pour chaque canal.

              Notes

La durée du délai est mesurée en secondes (à la différence
          de vdelay et de
          vdelay3), et doit
          être de taux-a.

Le délai minimum autorisé est de iws/2
          échantillons.

Il est permis d'utiliser les mêmes variables en entrée et
          en sortie dans ces opcodes.

Dans vdelayxw*, le changement de la
          durée du délai à des effets sur le volume de sortie :

a = 1 / (1 + dt)

 où a est le gain en sortie
          et dt est la valeur du changement du délai par seconde.

Ces opcodes sont plus adaptés à la version de Csound
          en double précision.

Exemples

      Voici un exemple de l'opcode vdelayxs. Il utilise le fichier
      vdelayxs.csd.

            Exemple 1024. Exemple de l'opcode vdelayxs.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac  ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if realtime audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o vdelayxs.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

instr 1

ims  =	.5						;maximum delay time in seconds
iws  =	1024						;window size
adl  =	.5						;delay time
asig1, asig2 diskin2 "kickroll.wav", 1, 0, 1		;loop stereo file kickroll.wav
a2   poscil .25, .1, 1					;make an LFO, 1 cycle per 2 seconds
adl  = a2 + ims/2      					;offset the LFO so that it is positive
aoutL, aoutR vdelayxs asig1, asig2, adl, ims, iws	;use the LFO to control delay time
     outs aoutL, aoutR

endin
</CsInstruments>
<CsScore>
f1 0 8192 10 1

i 1 0 10

e
</CsScore>
</CsoundSynthesizer>

Voir aussi

      vdelayx,
      vdelayxq,
      vdelayxw,
      vdelayxwq,
      vdelayxws

          Précédent

            Niveau supérieur

           Suivant

          vdelayxq

            Sommaire

           vdelayxw


text:
<?php

/* ConnectionAdminBundle:Settings:background.html.twig */
class __TwigTemplate_99289dc137f0f981d676ad3aa82509a0b2cdb66b955b688db01daa9d40c1af28 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("ConnectionAdminBundle::layout.html.twig");

        $this->blocks = array(
            'stylesheets' => array($this, 'block_stylesheets'),
            'content' => array($this, 'block_content'),
            'javascript' => array($this, 'block_javascript'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "ConnectionAdminBundle::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_stylesheets($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        $this->displayParentBlock("stylesheets", $context, $blocks);
        echo "
    <link rel=\"stylesheet\" href=\"";
        // line 5
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/connectionadmin/js/dropzone/css/dropzone.css"), "html", null, true);
        echo "\" type=\"text/css\" />
    <link rel=\"stylesheet\" href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/connectionadmin/css/background.css"), "html", null, true);
        echo "\" type=\"text/css\" />
";
    }

    // line 9
    public function block_content($context, array $blocks = array())
    {
        // line 10
        echo "

        <form action=\"";
        // line 11
        echo twig_escape_filter($this->env, $this->env->getExtension('oneup_uploader')->endpoint("admin"), "html", null, true);
        echo "\" class=\"dropzone dz-clickable\" id=\"admin_settings_background\">

Drop files here to upload

        </form>

        ";
        // line 16
        if ((array_key_exists("images", $context) && (!twig_test_empty((isset($context["images"]) ? $context["images"] : $this->getContext($context, "images")))))) {
            // line 17
            echo "            ";
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable((isset($context["images"]) ? $context["images"] : $this->getContext($context, "images")));
            foreach ($context['_seq'] as $context["_key"] => $context["image"]) {
                // line 18
                echo "
getAttribute($context["image"], "isDefault", array())) ? ("default") : (""));
                echo "\">
                    env, $this->getAttribute($context["image"], "path", array()), "html", null, true);
                echo "\" class=\"img-thumbnail\">

                            <button class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\">

                            </button>

                                    env, $this->env->getExtension('routing')->getPath("admin_settings_background_set", array("id" => $this->getAttribute($context["image"], "id", array()))), "html", null, true);
                echo "\">
                                        Set as default background

                                    env, $this->env->getExtension('routing')->getPath("admin_settings_background_delete", array("id" => $this->getAttribute($context["image"], "id", array()))), "html", null, true);
                echo "\">
                                        Delete

            ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['image'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 42
            echo "        ";
        }
        // line 43
        echo "

";
    }

    // line 46
    public function block_javascript($context, array $blocks = array())
    {
        // line 47
        echo "    ";
        $this->displayParentBlock("javascript", $context, $blocks);
        echo "

";
    }

    public function getTemplateName()
    {
        return "ConnectionAdminBundle:Settings:background.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  125 => 48,  120 => 47,  117 => 46,  112 => 43,  109 => 42,  94 => 33,  86 => 28,  74 => 19,  69 => 18,  64 => 17,  62 => 16,  54 => 11,  51 => 10,  48 => 9,  42 => 6,  38 => 5,  33 => 4,  30 => 3,);
    }
}


text:
.. networking-hp documentation master file, created by
   sphinx-quickstart on Thu Jun 18 04:59:21 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to networking-hp's documentation!
========================================================

Contents:

.. toctree::
   :maxdepth: 2

   readme
   installation
   usage
   contributing

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="refresh" content="0;URL='example'" />
</head>
<body></body>
</html>


text:
tar -xzvf libssh.tar.gz
cd master/obj
./build_make.sh -withstaticlib
make


text:
lado = int(input('Digite o valor correspondente ao lado de um quadrado:'))

perimetro = 4 * lado
area = lado ** 2

print('perímetro:', perimetro, '- área:', area)


text:
#import <Foundation/NSCoder.h>
#import <Foundation/NSPropertyList.h>
#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
#import <Foundation/NSGeometry.h>
#endif

@class NSArray<ObjectType>, NSMutableData, NSData, NSString;
@protocol NSKeyedArchiverDelegate, NSKeyedUnarchiverDelegate;

NS_ASSUME_NONNULL_BEGIN

FOUNDATION_EXPORT NSString * const NSInvalidArchiveOperationException;
FOUNDATION_EXPORT NSString * const NSInvalidUnarchiveOperationException;
// Archives created using the class method archivedRootDataWithObject used this key for the root object in the hierarchy of encoded objects. The NSKeyedUnarchiver class method unarchiveObjectWithData: will look for this root key as well. You can also use it as the key for the root object in your own archives.
FOUNDATION_EXPORT NSString * const NSKeyedArchiveRootObjectKey NS_AVAILABLE(10_9, 7_0);

@interface NSKeyedArchiver : NSCoder {
@private
    void *_stream;
    NSUInteger _flags;
    id _delegate;
    id _containers;
    id _objects;
    id _objRefMap;
    id _replacementMap;
    id _classNameMap;
    id _conditionals;
    id _classes;
    NSUInteger _genericKey;
    void *_cache;
    NSUInteger _cacheSize;
    NSUInteger _estimatedCount;
    void *_reserved2;
    id _visited;
    void *  __strong _reserved0;
}

+ (NSData *)archivedDataWithRootObject:(id)rootObject;
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;

- (instancetype)initForWritingWithMutableData:(NSMutableData *)data;

@property (nullable, assign) id <NSKeyedArchiverDelegate> delegate;

@property NSPropertyListFormat outputFormat;

- (void)finishEncoding;

+ (void)setClassName:(nullable NSString *)codedName forClass:(Class)cls;
- (void)setClassName:(nullable NSString *)codedName forClass:(Class)cls;
	// During encoding, the coder first checks with the coder's
	// own table, then if there was no mapping there, the class's.

+ (nullable NSString *)classNameForClass:(Class)cls;
- (nullable NSString *)classNameForClass:(Class)cls;

- (void)encodeObject:(nullable id)objv forKey:(NSString *)key;
- (void)encodeConditionalObject:(nullable id)objv forKey:(NSString *)key;
- (void)encodeBool:(BOOL)boolv forKey:(NSString *)key;
- (void)encodeInt:(int)intv forKey:(NSString *)key;	// native int
- (void)encodeInt32:(int32_t)intv forKey:(NSString *)key;
- (void)encodeInt64:(int64_t)intv forKey:(NSString *)key;
- (void)encodeFloat:(float)realv forKey:(NSString *)key;
- (void)encodeDouble:(double)realv forKey:(NSString *)key;
- (void)encodeBytes:(nullable const uint8_t *)bytesp length:(NSUInteger)lenv forKey:(NSString *)key;

// Enables secure coding support on this keyed archiver. You do not need to enable secure coding on the archiver to enable secure coding on the unarchiver. Enabling secure coding on the archiver is a way for you to be sure that all classes that are encoded conform with NSSecureCoding (it will throw an exception if a class which does not NSSecureCoding is archived). Note that the getter is on the superclass, NSCoder. See NSCoder for more information about secure coding.
@property (readwrite) BOOL requiresSecureCoding NS_AVAILABLE(10_8, 6_0);

@end

@interface NSKeyedUnarchiver : NSCoder {
@private
    id _delegate;
    uint32_t _flags;
    id _objRefMap;
    id _replacementMap;
    id _nameClassMap;
    id _tmpRefObjMap;
    id _refObjMap;
    int32_t _genericKey;
    id _data;
    void *_offsetData;
    id _containers;
    id _objects;
    const uint8_t *_bytes;
    uint64_t _len;
    id _helper;
    void *  __strong _reserved0;
}

+ (nullable id)unarchiveObjectWithData:(NSData *)data;
+ (nullable id)unarchiveTopLevelObjectWithData:(NSData *)data error:(NSError **)error NS_AVAILABLE(10_11, 9_0) NS_SWIFT_UNAVAILABLE("Use 'unarchiveTopLevelObjectWithData(_:) throws' instead");
+ (nullable id)unarchiveObjectWithFile:(NSString *)path;

- (instancetype)initForReadingWithData:(NSData *)data;

@property (nullable, assign) id <NSKeyedUnarchiverDelegate> delegate;

- (void)finishDecoding;

+ (void)setClass:(nullable Class)cls forClassName:(NSString *)codedName;
- (void)setClass:(nullable Class)cls forClassName:(NSString *)codedName;
	// During decoding, the coder first checks with the coder's
	// own table, then if there was no mapping there, the class's.

+ (nullable Class)classForClassName:(NSString *)codedName;
- (nullable Class)classForClassName:(NSString *)codedName;

- (BOOL)containsValueForKey:(NSString *)key;

- (nullable id)decodeObjectForKey:(NSString *)key;
- (BOOL)decodeBoolForKey:(NSString *)key;
- (int)decodeIntForKey:(NSString *)key;		// may raise a range exception
- (int32_t)decodeInt32ForKey:(NSString *)key;
- (int64_t)decodeInt64ForKey:(NSString *)key;
- (float)decodeFloatForKey:(NSString *)key;
- (double)decodeDoubleForKey:(NSString *)key;
- (nullable const uint8_t *)decodeBytesForKey:(NSString *)key returnedLength:(nullable NSUInteger *)lengthp NS_RETURNS_INNER_POINTER;	// returned bytes immutable, and they go away with the unarchiver, not the containing autorelease pool

// Enables secure coding support on this keyed unarchiver. When enabled, anarchiving a disallowed class throws an exception. Once enabled, attempting to set requiresSecureCoding to NO will throw an exception. This is to prevent classes from selectively turning secure coding off. This is designed to be set once at the top level and remain on. Note that the getter is on the superclass, NSCoder. See NSCoder for more information about secure coding.
@property (readwrite) BOOL requiresSecureCoding NS_AVAILABLE(10_8, 6_0);

@end

@protocol NSKeyedArchiverDelegate <NSObject>
@optional

// substitution
- (nullable id)archiver:(NSKeyedArchiver *)archiver willEncodeObject:(id)object;
	// Informs the delegate that the object is about to be encoded.  The delegate
	// either returns this object or can return a different object to be encoded
	// instead.  The delegate can also fiddle with the coder state.  If the delegate
	// returns nil, nil is encoded.  This method is called after the original object
        // may have replaced itself with replacementObjectForKeyedArchiver:.
        // This method is not called for an object once a replacement mapping has been
        // setup for that object (either explicitly, or because the object has previously
        // been encoded).  This is also not called when nil is about to be encoded.
        // This method is called whether or not the object is being encoded conditionally.

- (void)archiver:(NSKeyedArchiver *)archiver didEncodeObject:(nullable id)object;
	// Informs the delegate that the given object has been encoded.  The delegate
	// might restore some state it had fiddled previously, or use this to keep
	// track of the objects which are encoded.  The object may be nil.  Not called
	// for conditional objects until they are really encoded (if ever).

// notification
- (void)archiver:(NSKeyedArchiver *)archiver willReplaceObject:(nullable id)object withObject:(nullable id)newObject;
	// Informs the delegate that the newObject is being substituted for the
	// object. This is also called when the delegate itself is doing/has done
	// the substitution. The delegate may use this method if it is keeping track
	// of the encoded or decoded objects.

- (void)archiverWillFinish:(NSKeyedArchiver *)archiver;
	// Notifies the delegate that encoding is about to finish.

- (void)archiverDidFinish:(NSKeyedArchiver *)archiver;
	// Notifies the delegate that encoding has finished.

@end

@protocol NSKeyedUnarchiverDelegate <NSObject>
@optional

// error handling
- (nullable Class)unarchiver:(NSKeyedUnarchiver *)unarchiver cannotDecodeObjectOfClassName:(NSString *)name originalClasses:(NSArray<NSString *> *)classNames;
	// Informs the delegate that the named class is not available during decoding.
	// The delegate may, for example, load some code to introduce the class to the
	// runtime and return it, or substitute a different class object.  If the
	// delegate returns nil, unarchiving aborts with an exception.  The first class
        // name string in the array is the class of the encoded object, the second is
        // the immediate superclass, and so on.

// substitution
- (nullable id)unarchiver:(NSKeyedUnarchiver *)unarchiver didDecodeObject:(nullable id) NS_RELEASES_ARGUMENT object NS_RETURNS_RETAINED;
	// Informs the delegate that the object has been decoded.  The delegate
	// either returns this object or can return a different object to replace
	// the decoded one.  The object may be nil.  If the delegate returns nil,
        // the decoded value will be unchanged (that is, the original object will be
        // decoded). The delegate may use this to keep track of the decoded objects.

// notification
- (void)unarchiver:(NSKeyedUnarchiver *)unarchiver willReplaceObject:(id)object withObject:(id)newObject;
	// Informs the delegate that the newObject is being substituted for the
	// object. This is also called when the delegate itself is doing/has done
	// the substitution. The delegate may use this method if it is keeping track
	// of the encoded or decoded objects.

- (void)unarchiverWillFinish:(NSKeyedUnarchiver *)unarchiver;
	// Notifies the delegate that decoding is about to finish.

- (void)unarchiverDidFinish:(NSKeyedUnarchiver *)unarchiver;
	// Notifies the delegate that decoding has finished.

@end

@interface NSObject (NSKeyedArchiverObjectSubstitution)

@property (nullable, readonly) Class classForKeyedArchiver;
	// Implemented by classes to substitute a new class for instances during
	// encoding.  The object will be encoded as if it were a member of the
	// returned class.  The results of this method are overridden by the archiver
        // class and instance name<->class encoding tables.  If nil is returned,
        // the result of this method is ignored.  This method returns the result of
	// [self classForArchiver] by default, NOT -classForCoder as might be
	// expected.  This is a concession to source compatibility.

- (nullable id)replacementObjectForKeyedArchiver:(NSKeyedArchiver *)archiver;
	// Implemented by classes to substitute new instances for the receiving
	// instance during encoding.  The returned object will be encoded instead
	// of the receiver (if different).  This method is called only if no
	// replacement mapping for the object has been set up in the archiver yet
        // (for example, due to a previous call of replacementObjectForKeyedArchiver:
        // to that object).  This method returns the result of
	// [self replacementObjectForArchiver:nil] by default, NOT
	// -replacementObjectForCoder: as might be expected.  This is a concession
	// to source compatibility.

+ (NSArray<NSString *> *)classFallbacksForKeyedArchiver;

@end

@interface NSObject (NSKeyedUnarchiverObjectSubstitution)

+ (Class)classForKeyedUnarchiver;
	// Implemented by classes to substitute a new class during decoding.
        // Objects of the class will be decoded as members of the returned
        // class.  This method overrides the results of the unarchiver's class and
        // instance name<->class encoding tables.  Returns self by default.

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.archiva.scheduler.repository;

import org.apache.archiva.model.ArtifactReference;
import org.apache.archiva.scheduler.repository.model.RepositoryTask;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;

import java.util.Collection;

/**
 * ArchivaRepositoryScanningTaskExecutorPhase1Test
 *
 *
 */
@ContextConfiguration( locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context.xml" } )
public class ArchivaRepositoryScanningTaskExecutorPhase1Test
    extends AbstractArchivaRepositoryScanningTaskExecutorTest
{
    // Split of ArchivaRepositoryScanningTaskExecutorTest should be executed first
    // to avoid testConsumer in unknown state if member of Phase2 all ready executed
    @Test
    public void testExecutor()
        throws Exception
    {
        RepositoryTask repoTask = new RepositoryTask();

        repoTask.setRepositoryId( TEST_REPO_ID );

        taskExecutor.executeTask( repoTask );

        Collection<ArtifactReference> unprocessedResultList = testConsumer.getConsumed();

        assertNotNull( unprocessedResultList );
        assertEquals( "Incorrect number of unprocessed artifacts detected.", 8, unprocessedResultList.size() );

    }

}


text:
package com.github.retrofit2.app;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.EditText;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.ButterKnife;
import butterknife.InjectView;

import rx.Observable;
import rx.Subscription;
import rx.functions.*;
import rx.subjects.*;

import rx.android.app.*;
import rx.android.view.ViewObservable;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;

public class RxCardsFragment extends Fragment {
    @InjectView(R.id.list)
    RecyclerView listView;
    @InjectView(R.id.refresh)
    SwipeRefreshLayout refreshView;

    //Subject<View, View> viewSubject = PublishSubject.create();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_swipe, container, false);
        ButterKnife.inject(this, view);
        //viewSubject.onNext(view);

        listAdapter = ListRecyclerAdapter.create();
        listAdapter.createViewHolder(new Func2<ViewGroup, Integer, CardViewHolder>() {
            @Override
            public CardViewHolder call(ViewGroup parent, Integer position) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_card, parent, false);

                /*
                TypedValue typedValue = new TypedValue();
                parent.getContext().getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
                view.setBackgroundResource(typedValue.resourceId);
                */

                return new CardViewHolder(view);
            }
        });

        listView.setLayoutManager(new LinearLayoutManager(listView.getContext()));
        listView.setAdapter(listAdapter);

        refreshView.setOnRefreshListener(() -> {
            load();
        });

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            //if (refreshView == null) {
                //viewSubject.asObservable().subscribe(v -> load()); // FIXME onDestoryView unsubscribe subscription?
            //} else {
                load();
            //}
        }
    }

    public Subscription load() {
        if (refreshView != null) refreshView.setRefreshing(true);
        return AppObservable.bindFragment(RxCardsFragment.this, items).toList().subscribe(list -> {
            android.util.Log.d("RetroWeibo", "list: " + list);
            android.util.Log.d("RetroWeibo", "list.size(): " + list.size());
            listAdapter.getList().clear();
            listAdapter.getList().addAll(list);
            listAdapter.notifyDataSetChanged();
        }, e -> {}, () -> {
            refreshView.setRefreshing(false);
        });
    }

    private ListRecyclerAdapter<RxCard, CardViewHolder> listAdapter;
    Observable<RxCard> items;

    public RxCardsFragment items(Observable<RxCard> items) {
        this.items = items;

        return this;
    }

    public static RxCardsFragment create() {
        return new RxCardsFragment();
    }

    public static class CardViewHolder extends BindViewHolder<RxCard> {
        @InjectView(R.id.icon)
        ImageView icon;
        @InjectView(R.id.text1)
        TextView text1;
        @InjectView(R.id.message)
        TextView message;
        @InjectView(R.id.imageCard)
        CardView imageCard;
        @InjectView(R.id.image)
        ImageView image;
        @InjectView(R.id.comments)
        RecyclerView commentsView;
        @InjectView(R.id.likeCount)
        TextView likeCountView;
        @InjectView(R.id.like)
        ImageView likeView;
        @InjectView(R.id.comment)
        ImageView commentView;
        @InjectView(R.id.commentCount)
        TextView commentCountView;
        @InjectView(R.id.comment_avatar)
        ImageView commentAvatar;
        @InjectView(R.id.comment_edit)
        EditText commentEdit;
        @InjectView(R.id.send)
        ImageView sendView;

        ListRecyclerAdapter<String, CommentViewHolder> commentsAdapter;
        boolean liked;
        int likeCount;
        int commentCount;

        public CardViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);

            commentsAdapter = ListRecyclerAdapter.create();
            commentsAdapter.createViewHolder(new Func2<ViewGroup, Integer, CommentViewHolder>() {
                @Override
                public CommentViewHolder call(ViewGroup parent, Integer position) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment, parent, false);

                    return new CommentViewHolder(view);
                }
            });

            commentsView.setLayoutManager(new MeasuredLinearLayoutManager(commentsView.getContext()));
            commentsView.setAdapter(commentsAdapter);
        }

        @Override
        public void onBind(int position, RxCard item) {
            icon.setVisibility(View.GONE);
            ViewObservable.bindView(icon, item.icon).filter(url -> !android.text.TextUtils.isEmpty(url)).subscribe(url -> {
                icon.setVisibility(View.VISIBLE);
                Glide.with(itemView.getContext())
                    .load(url)
                    .fitCenter()
                    .into(icon);
            });

            itemView.setOnClickListener(v -> {}); // clear
            ViewObservable.bindView(text1, item.text1)
                .filter(name -> !android.text.TextUtils.isEmpty(name))
                .subscribe(name -> {
                    text1.setText(name);

                    itemView.setOnClickListener(v -> {
                        Context context = v.getContext();
                        Intent intent = new Intent(context, CheeseDetailActivity.class);

                        if (!android.text.TextUtils.isEmpty(name)) intent.putExtra(CheeseDetailActivity.EXTRA_NAME, name);

                        context.startActivity(intent);
                    });
                });

            ViewObservable.bindView(message, item.message)
                .filter(s -> !android.text.TextUtils.isEmpty(s))
                .subscribe(s -> message.setText(s));

            image.setVisibility(View.GONE);
            imageCard.setVisibility(View.GONE);
            ViewObservable.bindView(image, item.image).filter(url -> !android.text.TextUtils.isEmpty(url)).subscribe(url -> {
                image.setVisibility(View.VISIBLE);
                imageCard.setVisibility(View.VISIBLE);
                Glide.with(itemView.getContext())
                    .load(url)
                    .fitCenter()
                    .into(image);
            });

            likeCount = 0;
            likeCountView.setText("" + likeCount); // clear
            ViewObservable.bindView(likeCountView, item.likeCount).subscribe(i -> {
                likeCount = i;
                likeCountView.setText("" + likeCount);
            });

            commentCount = 0;
            commentCountView.setText("" + commentCount); // clear
            ViewObservable.bindView(commentCountView, item.commentCount).subscribe(i -> {
                commentCount = i;
                commentCountView.setText("" + commentCount);
            });

            liked = false;
            likeView.setOnClickListener(v -> {}); // clear
            Glide.with(itemView.getContext())
                .load(R.drawable.ic_thumb_up_outline)
                .fitCenter()
                .into(likeView);

            commentsView.setVisibility(View.GONE);
            commentsAdapter.getList().clear();
        }
    }

    public static class CommentViewHolder extends BindViewHolder<String> {
        @InjectView(R.id.icon)
        ImageView icon;
        @InjectView(R.id.text1)
        TextView text1;
        @InjectView(R.id.like)
        ImageView likeView;
        @InjectView(R.id.likes)
        TextView likes;

        public CommentViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);
        }

        boolean liked;
        int likeCount;

        @Override
        public void onBind(int position, String item) {
        }
    }
}