text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: grpc/common.proto

package alluxio.grpc;

/**
 *

 **
 * Information about blocks.
 *

 *
 * Protobuf type {@code alluxio.grpc.BlockLocation}
 */
public  final class BlockLocation extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:alluxio.grpc.BlockLocation)
    BlockLocationOrBuilder {
private static final long serialVersionUID = 0L;
  // Use BlockLocation.newBuilder() to construct.
  private BlockLocation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private BlockLocation() {
    workerId_ = 0L;
    tierAlias_ = "";
    mediumType_ = "";
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return this.unknownFields;
  }
  private BlockLocation(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    int mutable_bitField0_ = 0;
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          default: {
            if (!parseUnknownField(
                input, unknownFields, extensionRegistry, tag)) {
              done = true;
            }
            break;
          }
          case 8: {
            bitField0_ |= 0x00000001;
            workerId_ = input.readInt64();
            break;
          }
          case 18: {
            alluxio.grpc.WorkerNetAddress.Builder subBuilder = null;
            if (((bitField0_ & 0x00000002) == 0x00000002)) {
              subBuilder = workerAddress_.toBuilder();
            }
            workerAddress_ = input.readMessage(alluxio.grpc.WorkerNetAddress.PARSER, extensionRegistry);
            if (subBuilder != null) {
              subBuilder.mergeFrom(workerAddress_);
              workerAddress_ = subBuilder.buildPartial();
            }
            bitField0_ |= 0x00000002;
            break;
          }
          case 26: {
            com.google.protobuf.ByteString bs = input.readBytes();
            bitField0_ |= 0x00000004;
            tierAlias_ = bs;
            break;
          }
          case 34: {
            com.google.protobuf.ByteString bs = input.readBytes();
            bitField0_ |= 0x00000008;
            mediumType_ = bs;
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(
          e).setUnfinishedMessage(this);
    } finally {
      this.unknownFields = unknownFields.build();
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return alluxio.grpc.CommonProto.internal_static_alluxio_grpc_BlockLocation_descriptor;
  }

  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return alluxio.grpc.CommonProto.internal_static_alluxio_grpc_BlockLocation_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            alluxio.grpc.BlockLocation.class, alluxio.grpc.BlockLocation.Builder.class);
  }

  private int bitField0_;
  public static final int WORKERID_FIELD_NUMBER = 1;
  private long workerId_;
  /**
   * optional int64 workerId = 1;
   */
  public boolean hasWorkerId() {
    return ((bitField0_ & 0x00000001) == 0x00000001);
  }
  /**
   * optional int64 workerId = 1;
   */
  public long getWorkerId() {
    return workerId_;
  }

  public static final int WORKERADDRESS_FIELD_NUMBER = 2;
  private alluxio.grpc.WorkerNetAddress workerAddress_;
  /**
   * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
   */
  public boolean hasWorkerAddress() {
    return ((bitField0_ & 0x00000002) == 0x00000002);
  }
  /**
   * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
   */
  public alluxio.grpc.WorkerNetAddress getWorkerAddress() {
    return workerAddress_ == null ? alluxio.grpc.WorkerNetAddress.getDefaultInstance() : workerAddress_;
  }
  /**
   * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
   */
  public alluxio.grpc.WorkerNetAddressOrBuilder getWorkerAddressOrBuilder() {
    return workerAddress_ == null ? alluxio.grpc.WorkerNetAddress.getDefaultInstance() : workerAddress_;
  }

  public static final int TIERALIAS_FIELD_NUMBER = 3;
  private volatile java.lang.Object tierAlias_;
  /**
   * optional string tierAlias = 3;
   */
  public boolean hasTierAlias() {
    return ((bitField0_ & 0x00000004) == 0x00000004);
  }
  /**
   * optional string tierAlias = 3;
   */
  public java.lang.String getTierAlias() {
    java.lang.Object ref = tierAlias_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        tierAlias_ = s;
      }
      return s;
    }
  }
  /**
   * optional string tierAlias = 3;
   */
  public com.google.protobuf.ByteString
      getTierAliasBytes() {
    java.lang.Object ref = tierAlias_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      tierAlias_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int MEDIUMTYPE_FIELD_NUMBER = 4;
  private volatile java.lang.Object mediumType_;
  /**
   * optional string mediumType = 4;
   */
  public boolean hasMediumType() {
    return ((bitField0_ & 0x00000008) == 0x00000008);
  }
  /**
   * optional string mediumType = 4;
   */
  public java.lang.String getMediumType() {
    java.lang.Object ref = mediumType_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        mediumType_ = s;
      }
      return s;
    }
  }
  /**
   * optional string mediumType = 4;
   */
  public com.google.protobuf.ByteString
      getMediumTypeBytes() {
    java.lang.Object ref = mediumType_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      mediumType_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      output.writeInt64(1, workerId_);
    }
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      output.writeMessage(2, getWorkerAddress());
    }
    if (((bitField0_ & 0x00000004) == 0x00000004)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 3, tierAlias_);
    }
    if (((bitField0_ & 0x00000008) == 0x00000008)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 4, mediumType_);
    }
    unknownFields.writeTo(output);
  }

  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (((bitField0_ & 0x00000001) == 0x00000001)) {
      size += com.google.protobuf.CodedOutputStream
        .computeInt64Size(1, workerId_);
    }
    if (((bitField0_ & 0x00000002) == 0x00000002)) {
      size += com.google.protobuf.CodedOutputStream
        .computeMessageSize(2, getWorkerAddress());
    }
    if (((bitField0_ & 0x00000004) == 0x00000004)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, tierAlias_);
    }
    if (((bitField0_ & 0x00000008) == 0x00000008)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, mediumType_);
    }
    size += unknownFields.getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof alluxio.grpc.BlockLocation)) {
      return super.equals(obj);
    }
    alluxio.grpc.BlockLocation other = (alluxio.grpc.BlockLocation) obj;

    boolean result = true;
    result = result && (hasWorkerId() == other.hasWorkerId());
    if (hasWorkerId()) {
      result = result && (getWorkerId()
          == other.getWorkerId());
    }
    result = result && (hasWorkerAddress() == other.hasWorkerAddress());
    if (hasWorkerAddress()) {
      result = result && getWorkerAddress()
          .equals(other.getWorkerAddress());
    }
    result = result && (hasTierAlias() == other.hasTierAlias());
    if (hasTierAlias()) {
      result = result && getTierAlias()
          .equals(other.getTierAlias());
    }
    result = result && (hasMediumType() == other.hasMediumType());
    if (hasMediumType()) {
      result = result && getMediumType()
          .equals(other.getMediumType());
    }
    result = result && unknownFields.equals(other.unknownFields);
    return result;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    if (hasWorkerId()) {
      hash = (37 * hash) + WORKERID_FIELD_NUMBER;
      hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
          getWorkerId());
    }
    if (hasWorkerAddress()) {
      hash = (37 * hash) + WORKERADDRESS_FIELD_NUMBER;
      hash = (53 * hash) + getWorkerAddress().hashCode();
    }
    if (hasTierAlias()) {
      hash = (37 * hash) + TIERALIAS_FIELD_NUMBER;
      hash = (53 * hash) + getTierAlias().hashCode();
    }
    if (hasMediumType()) {
      hash = (37 * hash) + MEDIUMTYPE_FIELD_NUMBER;
      hash = (53 * hash) + getMediumType().hashCode();
    }
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static alluxio.grpc.BlockLocation parseFrom(
      java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      java.nio.ByteBuffer data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static alluxio.grpc.BlockLocation parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static alluxio.grpc.BlockLocation parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static alluxio.grpc.BlockLocation parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static alluxio.grpc.BlockLocation parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static alluxio.grpc.BlockLocation parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(alluxio.grpc.BlockLocation prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   **
   * Information about blocks.
   *

   *
   * Protobuf type {@code alluxio.grpc.BlockLocation}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:alluxio.grpc.BlockLocation)
      alluxio.grpc.BlockLocationOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return alluxio.grpc.CommonProto.internal_static_alluxio_grpc_BlockLocation_descriptor;
    }

    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return alluxio.grpc.CommonProto.internal_static_alluxio_grpc_BlockLocation_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              alluxio.grpc.BlockLocation.class, alluxio.grpc.BlockLocation.Builder.class);
    }

    // Construct using alluxio.grpc.BlockLocation.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(
        com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessageV3
              .alwaysUseFieldBuilders) {
        getWorkerAddressFieldBuilder();
      }
    }
    public Builder clear() {
      super.clear();
      workerId_ = 0L;
      bitField0_ = (bitField0_ & ~0x00000001);
      if (workerAddressBuilder_ == null) {
        workerAddress_ = null;
      } else {
        workerAddressBuilder_.clear();
      }
      bitField0_ = (bitField0_ & ~0x00000002);
      tierAlias_ = "";
      bitField0_ = (bitField0_ & ~0x00000004);
      mediumType_ = "";
      bitField0_ = (bitField0_ & ~0x00000008);
      return this;
    }

    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return alluxio.grpc.CommonProto.internal_static_alluxio_grpc_BlockLocation_descriptor;
    }

    public alluxio.grpc.BlockLocation getDefaultInstanceForType() {
      return alluxio.grpc.BlockLocation.getDefaultInstance();
    }

    public alluxio.grpc.BlockLocation build() {
      alluxio.grpc.BlockLocation result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    public alluxio.grpc.BlockLocation buildPartial() {
      alluxio.grpc.BlockLocation result = new alluxio.grpc.BlockLocation(this);
      int from_bitField0_ = bitField0_;
      int to_bitField0_ = 0;
      if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
        to_bitField0_ |= 0x00000001;
      }
      result.workerId_ = workerId_;
      if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
        to_bitField0_ |= 0x00000002;
      }
      if (workerAddressBuilder_ == null) {
        result.workerAddress_ = workerAddress_;
      } else {
        result.workerAddress_ = workerAddressBuilder_.build();
      }
      if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
        to_bitField0_ |= 0x00000004;
      }
      result.tierAlias_ = tierAlias_;
      if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
        to_bitField0_ |= 0x00000008;
      }
      result.mediumType_ = mediumType_;
      result.bitField0_ = to_bitField0_;
      onBuilt();
      return result;
    }

    public Builder clone() {
      return (Builder) super.clone();
    }
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return (Builder) super.setField(field, value);
    }
    public Builder clearField(
        com.google.protobuf.Descriptors.FieldDescriptor field) {
      return (Builder) super.clearField(field);
    }
    public Builder clearOneof(
        com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return (Builder) super.clearOneof(oneof);
    }
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        int index, java.lang.Object value) {
      return (Builder) super.setRepeatedField(field, index, value);
    }
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        java.lang.Object value) {
      return (Builder) super.addRepeatedField(field, value);
    }
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof alluxio.grpc.BlockLocation) {
        return mergeFrom((alluxio.grpc.BlockLocation)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(alluxio.grpc.BlockLocation other) {
      if (other == alluxio.grpc.BlockLocation.getDefaultInstance()) return this;
      if (other.hasWorkerId()) {
        setWorkerId(other.getWorkerId());
      }
      if (other.hasWorkerAddress()) {
        mergeWorkerAddress(other.getWorkerAddress());
      }
      if (other.hasTierAlias()) {
        bitField0_ |= 0x00000004;
        tierAlias_ = other.tierAlias_;
        onChanged();
      }
      if (other.hasMediumType()) {
        bitField0_ |= 0x00000008;
        mediumType_ = other.mediumType_;
        onChanged();
      }
      this.mergeUnknownFields(other.unknownFields);
      onChanged();
      return this;
    }

    public final boolean isInitialized() {
      return true;
    }

    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      alluxio.grpc.BlockLocation parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (alluxio.grpc.BlockLocation) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }
    private int bitField0_;

    private long workerId_ ;
    /**
     * optional int64 workerId = 1;
     */
    public boolean hasWorkerId() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    /**
     * optional int64 workerId = 1;
     */
    public long getWorkerId() {
      return workerId_;
    }
    /**
     * optional int64 workerId = 1;
     */
    public Builder setWorkerId(long value) {
      bitField0_ |= 0x00000001;
      workerId_ = value;
      onChanged();
      return this;
    }
    /**
     * optional int64 workerId = 1;
     */
    public Builder clearWorkerId() {
      bitField0_ = (bitField0_ & ~0x00000001);
      workerId_ = 0L;
      onChanged();
      return this;
    }

    private alluxio.grpc.WorkerNetAddress workerAddress_ = null;
    private com.google.protobuf.SingleFieldBuilderV3<
        alluxio.grpc.WorkerNetAddress, alluxio.grpc.WorkerNetAddress.Builder, alluxio.grpc.WorkerNetAddressOrBuilder> workerAddressBuilder_;
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public boolean hasWorkerAddress() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public alluxio.grpc.WorkerNetAddress getWorkerAddress() {
      if (workerAddressBuilder_ == null) {
        return workerAddress_ == null ? alluxio.grpc.WorkerNetAddress.getDefaultInstance() : workerAddress_;
      } else {
        return workerAddressBuilder_.getMessage();
      }
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public Builder setWorkerAddress(alluxio.grpc.WorkerNetAddress value) {
      if (workerAddressBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        workerAddress_ = value;
        onChanged();
      } else {
        workerAddressBuilder_.setMessage(value);
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public Builder setWorkerAddress(
        alluxio.grpc.WorkerNetAddress.Builder builderForValue) {
      if (workerAddressBuilder_ == null) {
        workerAddress_ = builderForValue.build();
        onChanged();
      } else {
        workerAddressBuilder_.setMessage(builderForValue.build());
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public Builder mergeWorkerAddress(alluxio.grpc.WorkerNetAddress value) {
      if (workerAddressBuilder_ == null) {
        if (((bitField0_ & 0x00000002) == 0x00000002) &&
            workerAddress_ != null &&
            workerAddress_ != alluxio.grpc.WorkerNetAddress.getDefaultInstance()) {
          workerAddress_ =
            alluxio.grpc.WorkerNetAddress.newBuilder(workerAddress_).mergeFrom(value).buildPartial();
        } else {
          workerAddress_ = value;
        }
        onChanged();
      } else {
        workerAddressBuilder_.mergeFrom(value);
      }
      bitField0_ |= 0x00000002;
      return this;
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public Builder clearWorkerAddress() {
      if (workerAddressBuilder_ == null) {
        workerAddress_ = null;
        onChanged();
      } else {
        workerAddressBuilder_.clear();
      }
      bitField0_ = (bitField0_ & ~0x00000002);
      return this;
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public alluxio.grpc.WorkerNetAddress.Builder getWorkerAddressBuilder() {
      bitField0_ |= 0x00000002;
      onChanged();
      return getWorkerAddressFieldBuilder().getBuilder();
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    public alluxio.grpc.WorkerNetAddressOrBuilder getWorkerAddressOrBuilder() {
      if (workerAddressBuilder_ != null) {
        return workerAddressBuilder_.getMessageOrBuilder();
      } else {
        return workerAddress_ == null ?
            alluxio.grpc.WorkerNetAddress.getDefaultInstance() : workerAddress_;
      }
    }
    /**
     * optional .alluxio.grpc.WorkerNetAddress workerAddress = 2;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
        alluxio.grpc.WorkerNetAddress, alluxio.grpc.WorkerNetAddress.Builder, alluxio.grpc.WorkerNetAddressOrBuilder>
        getWorkerAddressFieldBuilder() {
      if (workerAddressBuilder_ == null) {
        workerAddressBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
            alluxio.grpc.WorkerNetAddress, alluxio.grpc.WorkerNetAddress.Builder, alluxio.grpc.WorkerNetAddressOrBuilder>(
                getWorkerAddress(),
                getParentForChildren(),
                isClean());
        workerAddress_ = null;
      }
      return workerAddressBuilder_;
    }

    private java.lang.Object tierAlias_ = "";
    /**
     * optional string tierAlias = 3;
     */
    public boolean hasTierAlias() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    /**
     * optional string tierAlias = 3;
     */
    public java.lang.String getTierAlias() {
      java.lang.Object ref = tierAlias_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          tierAlias_ = s;
        }
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string tierAlias = 3;
     */
    public com.google.protobuf.ByteString
        getTierAliasBytes() {
      java.lang.Object ref = tierAlias_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        tierAlias_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string tierAlias = 3;
     */
    public Builder setTierAlias(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
      tierAlias_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string tierAlias = 3;
     */
    public Builder clearTierAlias() {
      bitField0_ = (bitField0_ & ~0x00000004);
      tierAlias_ = getDefaultInstance().getTierAlias();
      onChanged();
      return this;
    }
    /**
     * optional string tierAlias = 3;
     */
    public Builder setTierAliasBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
      tierAlias_ = value;
      onChanged();
      return this;
    }

    private java.lang.Object mediumType_ = "";
    /**
     * optional string mediumType = 4;
     */
    public boolean hasMediumType() {
      return ((bitField0_ & 0x00000008) == 0x00000008);
    }
    /**
     * optional string mediumType = 4;
     */
    public java.lang.String getMediumType() {
      java.lang.Object ref = mediumType_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          mediumType_ = s;
        }
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string mediumType = 4;
     */
    public com.google.protobuf.ByteString
        getMediumTypeBytes() {
      java.lang.Object ref = mediumType_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        mediumType_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string mediumType = 4;
     */
    public Builder setMediumType(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000008;
      mediumType_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string mediumType = 4;
     */
    public Builder clearMediumType() {
      bitField0_ = (bitField0_ & ~0x00000008);
      mediumType_ = getDefaultInstance().getMediumType();
      onChanged();
      return this;
    }
    /**
     * optional string mediumType = 4;
     */
    public Builder setMediumTypeBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000008;
      mediumType_ = value;
      onChanged();
      return this;
    }
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:alluxio.grpc.BlockLocation)
  }

  // @@protoc_insertion_point(class_scope:alluxio.grpc.BlockLocation)
  private static final alluxio.grpc.BlockLocation DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new alluxio.grpc.BlockLocation();
  }

  public static alluxio.grpc.BlockLocation getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  @java.lang.Deprecated public static final com.google.protobuf.Parser<BlockLocation>
      PARSER = new com.google.protobuf.AbstractParser<BlockLocation>() {
    public BlockLocation parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return new BlockLocation(input, extensionRegistry);
    }
  };

  public static com.google.protobuf.Parser<BlockLocation> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<BlockLocation> getParserForType() {
    return PARSER;
  }

  public alluxio.grpc.BlockLocation getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


text:
class Course::Settings::Component < SimpleDelegator
  include ActiveModel::Validations

  # Update settings with the hash attributes
  #
  # @param [Hash] attributes The hash for the new settings
  def update(attributes)
    attributes.each { |k, v| public_send("#{k}=", v) }
    valid?
  end

  # TODO: Remove once all setting forms have been ported to React
  def persisted?
    true
  end

  private

  def settings
    @settings ||= current_course.settings(key)
  end
end

redpajama_set_name: RedPajamaGithub


text:
### Nothing

Let's make another scratch repo, right up through the `git add```
```bash
cd /tmp
rm -rf scratch
git init scratch
cd $_
touch README
git add .
git commit -m'initial'
tree .git/objects
```

(The command `git init <directoryname>` is a shorthand
that both makes the directory and does the `git init` inside it)

Wait.
You have a computer.
Space is cheap.
Be generous!
Make half a dozen scratch repos.

```bash
cd
for i in {1..6}; do
  git init scratch.$i
  pushd scratch.$i
  cp /dev/null $LOGNAME
  git add $LOGNAME
  popd
done
ls -l scratch.$i/$LOGNAME
```

Empty files, every one.
What's in the objects directory for all of them?

```bash
for i in {1..6}; do
  tree $LOGNAME.$i/.git/objects
done
```

They all have the same thing. That must be git's "empty file."

```bash
cmp {/tmp/scratch,*.1}/.git/objects/e6/9*
```

They're the same as the `e6/9de29...91` under `/tmp/scratch```,
which was made out of a file called `README` instead of your login name,
so it must not contain the filename.

You're working on a different machine, in a different home directory, at a different time, and have a different login name.
You've made empty files three different ways (```> filename```, `touch filename```, and `cp /dev/null filename```),
but you got `e6/9de29` every time, just like I did. That object must just *be* an empty file:
no history of how it was created, no machine name, no username, no filesystem location, no datestamp, no extra stuff, no nothin'. Right?

```bash
cat /tmp/scratch/.git/objects/e6/9*
```

Wrong. Oh well.

(If you have a more modern shell,
you can use its **globstar** option
to save yourself some typing.

```bash
shopt -s globstar # set the globstar option
cat /tmp/scratch/**/9* # or maybe even cat /tmp/**/9*
```

)

It looks like garbage because it *does* add a couple of pieces of metadata, the filesize and the object type (which we'll get to in a minute), and it's zlib-compressed.

To show the contents, **`git`** gives us a tool: **git**'s Swiss-army knife, `git cat-file```.

```bash
cd /tmp/scratch
git cat-file -s e69de29 # show the object's size
git cat-file -t e69de29 # show the object's type
git cat-file -p e69de29 # pretty-print the object's contents
```

Pause here, add a couple of non-empty files to one of your scratch repos, and use `git cat-file` to look at the objects you added.

And what happens if you try to add a few more *empty* files, by other names?

Notice that though the object is in `.git/objects/e6/9de29...91```,
**`git`** is letting us name the object with the directory name, `e6```, stuck on to the first few characters of the filename, `9de```.

By the time you're done, I predict you'll recognize `e69de` as "the empty file."

For now, though, let's move on to do a commit, and use `git cat-file` and
[look at those other two objects.](https://github.com/jsh/git-internals/blob/new-course/repos/two-new-object-types.md)


text:
import fs = require('fs');

export class Configuration {
  public readonly appDataPath: string;
  public readonly cachePath: string;
  public readonly cacheStateFilename: string;
  public readonly lockFilename: string;
  public readonly pidFilename: string;
  public readonly configFilename: string;
  public readonly ngrokBinPath: string;

  /* Configuration values - set in config.json by TIKE */

  public readonly port: number;

  /* ngrok Configuration */

  public readonly useNgrok: boolean;
  public readonly ngrokControlPort: number;
  public readonly ngrokToken: string;
  public readonly ngrokRegion: string;
  public readonly ngrokVisible: boolean;

  public ngrokEndpoint: string = '';

  constructor() {

    this.appDataPath = (process.env.APPDATA ||
      (process.platform == 'darwin' ? process.env.HOME + '/Library/Preferences' : process.env.HOME + "/.local/share")) +
      '/Keyman/Keyman Developer/Server/';
    this.cachePath = this.appDataPath + 'cache/';
    this.cacheStateFilename = this.appDataPath + 'cache.json';
    this.lockFilename = this.appDataPath + 'lock.json';
    this.pidFilename = this.appDataPath + 'pid.json';
    this.configFilename = this.appDataPath + 'config.json';

    fs.mkdirSync(this.cachePath, { recursive: true});

    let cfg = null;
    if(fs.existsSync(this.configFilename)) {
      const data = fs.readFileSync(this.configFilename, 'utf-8');
      cfg = JSON.parse(data);
    }

    this.port = cfg?.port ?? 8008;

    // ngrok configuration
    this.useNgrok = cfg?.useNgrok ?? false;
    this.ngrokBinPath = this.appDataPath + 'bin/';
    this.ngrokControlPort = cfg?.ngrokControlPort ?? 8009;
    this.ngrokToken = cfg?.ngrokToken ?? '';
    this.ngrokRegion = cfg?.ngrokRegion ?? '';
    this.ngrokVisible = cfg?.ngrokVisible ?? false;
  }
};

export const configuration = new Configuration();


text:
using System;
using System.Windows.Forms;
using Open.WinKeyboardHook;
using ModifierKeys = System.Windows.Input.ModifierKeys;

namespace WinCap.ShortcutKeys
{
    /// <summary>
    /// ショートカットキーを検出する機能を提供します。
    /// ([modifier key(s)] + [key] style)
    /// </summary>
    public class ShortcutKeyDetector
    {
        /// <summary>
        /// 押下した修飾キー
        /// </summary>
        private ModifierKeys pressedModifierKeys = ModifierKeys.None;

        /// <summary>
        /// キーボード監視
        /// </summary>
        private readonly IKeyboardInterceptor interceptor = new KeyboardInterceptor();

        /// <summary>
        /// 開始状態
        /// </summary>
        private bool started;

        /// <summary>
        /// 停止状態
        /// </summary>
        private bool suspended;

        /// <summary>
        /// 停止状態
        /// </summary>
        public bool IsSuspended => this.suspended;

        /// <summary>
        /// ショートカットキー検出イベント
        /// </summary>
        public event EventHandler<ShortcutKeyPressedEventArgs> Pressed;

        /// <summary>
        /// コンストラクタ
        /// </summary>
        public ShortcutKeyDetector()
        {
            this.interceptor.KeyDown += this.InterceptorOnKeyDown;
            this.interceptor.KeyUp += this.InterceptorOnKeyUp;
        }

        /// <summary>
        /// ショートカットの監視を開始します。
        /// </summary>
        public void Start()
        {
            if (!this.started)
            {
                this.interceptor.StartCapturing();
                this.started = true;
            }

            this.suspended = false;
        }

        /// <summary>
        /// ショートカットの監視を停止します。
        /// </summary>
        public void Stop()
        {
            this.suspended = true;
            this.pressedModifierKeys = ModifierKeys.None;
        }

        /// <summary>
        /// キーダウン割り込みイベント
        /// </summary>
        /// <param name="sender">イベント発生元オブジェクト</param>
        /// <param name="args">イベント引数</param>
        private void InterceptorOnKeyDown(object sender, KeyEventArgs args)
        {
            if (this.suspended) { return; }

            if (args.KeyCode.IsModifyKey())
            {
                this.pressedModifierKeys |= args.KeyCode.GetModifierKeys();
            }
            else
            {
                var pressedEventArgs = new ShortcutKeyPressedEventArgs(args.KeyCode.ToKey(), this.pressedModifierKeys);
                this.Pressed?.Invoke(this, pressedEventArgs);
                if (pressedEventArgs.Handled)
                {
                    args.SuppressKeyPress = true;
                }
            }
        }

        /// <summary>
        /// キーアップ割り込みイベント
        /// </summary>
        /// <param name="sender">イベント発生元オブジェクト</param>
        /// <param name="args">イベント引数</param>
        private void InterceptorOnKeyUp(object sender, KeyEventArgs args)
        {
            if (this.suspended) { return; }

            if (args.KeyCode.IsModifyKey())
            {
                this.pressedModifierKeys ^= args.KeyCode.GetModifierKeys();
            }
        }
    }
}


text:
DROP PUBLIC SYNONYM ARRAY_REPORTER_CH
/

--
-- ARRAY_REPORTER_CH  (Synonym)
--
--  Dependencies:
--   ARRAY_REPORTER_CH (Table)
--
CREATE PUBLIC SYNONYM ARRAY_REPORTER_CH FOR ARRAY_REPORTER_CH
/


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 67(3): 570 (1975)

#### Original name
Ciboria rufescens Kanouse

### Remarks
null


text:
/**
 * @fileoverview added by tsickle
 * Generated from: test_files/file_comment/other_fileoverview_comments.ts
 * @modName {some_mod}
 */
goog.module('test_files.file_comment.other_fileoverview_comments');
var module = module || { id: 'test_files/file_comment/other_fileoverview_comments.ts' };
goog.require('tslib');
// @modName also belongs in a fileoverview comment, so must be merged.
console.log('hello');


text:
"""Create an environment.$ARCH file, as used by ninja.

This is enabled by using -G ninja_use_custom_environment_files.

The file format is simply a set of environment variables in which to run things
in. Use this to set the PATH to e.g. VC binaries, platform_sdk binaries, etc.
"""

import optparse
import os
import StringIO

NUL = chr(0)

def DoMain(argv):
  """This is the entry point that's called when pymod_do_main is used in gyp.

  Args:
    argv: list of arguments as defined in the .gyp file.

  Returns:
    Command to run (which replaces the 'action' in the gyp target).
  """
  parser = optparse.OptionParser()
  parser.add_option('--environment_file_dir')
  parser.add_option('--possible_configurations')
  parser.add_option('--windows_path_dirs_x86')
  parser.add_option('--windows_path_dirs_x64')
  # Some tools, such as rc.exe, expect to find "windows.h". Since rc.exe is
  # launched by gyp-win-tool (a wrapper for some common windows build tools), we
  # don't have access to its command line arguments. Instead we set the INCLUDE
  # environment variable (globally) so it can find windows.h.
  parser.add_option('--windows_include_dirs')
  options, _ = parser.parse_args(argv)

  environment_file_dir = options.environment_file_dir
  possible_configurations = options.possible_configurations.split(' ')
  windows_path_dirs_x86 = options.windows_path_dirs_x86.split(' ')
  windows_path_dirs_x64 = options.windows_path_dirs_x64.split(' ')
  windows_includes = options.windows_include_dirs.split()

  include_env = os.environ.get('INCLUDE')
  lib_env = os.environ.get('LIB')

  # LIB is needed for VS2015, which uses a few files from the Windows 10 SDK
  # even when targeting the Windows 8.1 SDK.
  default_env = {
      'SYSTEMROOT': os.environ.get('SYSTEMROOT').split(os.pathsep),
      'TEMP': os.environ.get('TEMP').split(os.pathsep),
      'TMP': os.environ.get('TMP').split(os.pathsep),
      'PATH': os.environ.get('PATH').split(os.pathsep),
      'INCLUDE': (include_env.split(os.pathsep) if include_env else []) +
                 windows_includes,
      'LIB': lib_env.split(os.pathsep) if lib_env else [],

      # This value is needed by some tools, such as the multiprocessing module.
      'NUMBER_OF_PROCESSORS': os.environ.get('NUMBER_OF_PROCESSORS', '1'),
  }

  env_x86 = default_env.copy()
  env_x64 = default_env.copy()

  # Make the specified paths ahead of the default paths.
  env_x86['PATH'] = windows_path_dirs_x86 + env_x86['PATH']
  env_x64['PATH'] = windows_path_dirs_x64 + env_x64['PATH']

  for conf in possible_configurations:
    for env, env_file_name in [(env_x86, 'environment.x86'),
                               (env_x64, 'environment.x64')]:
      env_file = os.path.join(environment_file_dir, conf, env_file_name)
      # The directories might not exist yet, since this action is running as the
      # very first target in the build process.
      if not os.path.isdir(os.path.dirname(env_file)):
        os.makedirs(os.path.dirname(env_file))

      # It saves a lot of build time if we don't overwrite this file if it has
      # not been modified.
      existing_contents = None
      if os.path.isfile(env_file):
        with open(env_file, 'rb') as f:
          existing_contents = f.read()

      sio = StringIO.StringIO()
      for k, v in env.items():
        if isinstance(v, list):
          # Assume they are paths.
          sio.write('='.join([k, os.pathsep.join(v)]))
        else:
          # Assume it's just a value.
          sio.write('='.join((k, v)))
        sio.write(NUL)

      # Yes, this last NUL is necessary. See gyp's win-tool.py:_GetEnv() for
      # details.
      sio.write(NUL)

      if sio.getvalue() != existing_contents:
        with open(env_file, 'wb') as f:
          f.write(sio.getvalue())

  # This script is used in an 'action' block. The output from this command will
  # replace the contents of the action block, so we must return some dummy thing
  # to execute. The actual work is already done above, so this is just to make
  # gyp happy.
  #
  # REM is a command in windows that does nothing.
  return 'rem'


text:
from os.path import dirname, exists, isdir, join, relpath

from django.conf import settings
import django.core.management.commands.loaddata
from django.core.files.storage import default_storage
import django.core.serializers
from django.db.models import get_apps, get_models, signals
from django.db.models.fields.files import FileField
from django.utils._os import upath

# For Python < 3.3
file_not_found_error = getattr(__builtins__,'FileNotFoundError', IOError)

def models_with_filefields():
    for app in get_apps():
        modelclasses = get_models(app)
        for modelclass in modelclasses:
            if any(isinstance(field, FileField) for field in modelclass._meta.fields):
                yield modelclass

class Command(django.core.management.commands.loaddata.Command):

    def load_images_for_signal(self, sender, **kwargs):
        instance = kwargs['instance']
        for field in sender._meta.fields:
            if not isinstance(field, FileField):
                continue
            path = getattr(instance, field.attname)
            if path is None or not path.name:
                continue
            for fixture_path in self.fixture_media_paths:
                filepath = join(fixture_path, path.name)
                try:
                    with open(filepath, 'rb') as f:
                        default_storage.save(path.name, f)
                except file_not_found_error:
                    self.stderr.write("Expected file at {} doesn't exist, skipping".format(filepath))
                    continue

    def handle(self, *fixture_labels, **options):
        # Hook up pre_save events for all the apps' models that have FileFields.
        for modelclass in models_with_filefields():
            signals.pre_save.connect(self.load_images_for_signal, sender=modelclass)

        fixture_paths = self.find_fixture_paths()
        fixture_paths = (join(path, 'media') for path in fixture_paths)
        fixture_paths = [path for path in fixture_paths if isdir(path)]
        self.fixture_media_paths = fixture_paths

        return super(Command, self).handle(*fixture_labels, **options)

    def find_fixture_paths(self):
        """Return the full paths to all possible fixture directories."""
        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(upath(path))
            else:
                # It's a models.py module
                app_module_paths.append(upath(app.__file__))

        app_fixtures = [join(dirname(path), 'fixtures') for path in app_module_paths]

        return app_fixtures + list(settings.FIXTURE_DIRS)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Vincetoxicum melanthum Decne.

### Remarks
null


text:
struct gre_protocol {
	int  (*handler)(struct sk_buff *skb);
	void (*err_handler)(struct sk_buff *skb, u32 info);
};

int gre_add_protocol(const struct gre_protocol *proto, u8 version);
int gre_del_protocol(const struct gre_protocol *proto, u8 version);

#endif


text:
DrQA
---

A pytorch implementation of the ACL 2017 paper [Reading Wikipedia to Answer Open-Domain Questions](http://www-cs.stanford.edu/people/danqi/papers/acl2017.pdf) (DrQA). The code is based on [Runqi](https://hitvoice.github.io/about/)'s implementation (https://github.com/hitvoice/DrQA).

## Requirements
- python >=3.5
- numpy
- pandas
- msgpack
- spacy 1.x

## Quick Start
### Setup
- make sure python 3 and pip is installed.
- install [pytorch](http://pytorch.org/) matched with your OS, python and cuda versions.
- install the remaining requirements via `pip install -r requirements.txt`
- download the [SQuAD](https://rajpurkar.github.io/SQuAD-explorer/) datafile, GloVe word vectors and Spacy English language models using `bash download.sh`.

### Train

```bash
# prepare the data
python prepro.py

# make sure CUDA lib path and SRU can be found. if not, try:
export LD_LIBRARY_PATH=/usr/local/cuda/lib64
export PYTHONPATH=/path_to_sru_repo/sru/

# train for 100 epoches with batchsize 32
python train.py -e 100 -bs 32
```

## Results
||EM|Time used in RNN|Total time/epoch|
|---|---|---|---|
|LSTM (original paper)|69.5|~316s|~431s|
|SRU (v1, 6 layer)|**~71.1**|**~100s**|**~201s**|
|SRU (this version, 6 layer)|**~71.4**|**~100s**|**~201s**|

Tested on GeForce GTX 1070.

### Credits
Author of the Document Reader model: [Danqi Chen](https://github.com/danqi).

Author of the original Pytorch implementation: [Runqi Yang](https://hitvoice.github.io/about/).

Most of the pytorch model code is borrowed from [Facebook/ParlAI](https://github.com/facebookresearch/ParlAI/) under a BSD-3 license.


text:
  iFlow © 2017 Universidad de los Andes.
  iFlow


text:
package net.tokensmith.hello.controller;

import net.tokensmith.otter.controller.entity.StatusCode;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import suite.IntegrationTestSuite;
import suite.ServletContainerTest;

import java.net.URI;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@Category(ServletContainerTest.class)
public class HelloResourceTest {
    private static URI BASE_URI;

    @BeforeClass
    public static void beforeClass() {
        BASE_URI = IntegrationTestSuite.getServletContainerURI();
    }

    @Test
    public void getShouldReturn200() throws Exception {

        String helloURI = BASE_URI.toString() + "hello";

        ListenableFuture<Response> f = IntegrationTestSuite.getHttpClient()
                .prepareGet(helloURI)
                .addHeader("Content-Type", "text/html")
                .execute();

        Response response = f.get();

        String errorMsg = "Attempted GET " + helloURI;
        assertThat(errorMsg, response.getStatusCode(), is(StatusCode.OK.getCode()));

        // make sure jsp was executed.
        assertThat(response.getResponseBody().contains("<div id=\"hello\">Hello World</>"), is(true));

    }

    @Test
    public void getWhenNoContentTypeShouldReturn200() throws Exception {

        String helloURI = BASE_URI.toString() + "hello";

        ListenableFuture<Response> f = IntegrationTestSuite.getHttpClient()
                .prepareGet(helloURI)
                .execute();

        Response response = f.get();

        String errorMsg = "Attempted GET " + helloURI;
        assertThat(errorMsg, response.getStatusCode(), is(StatusCode.OK.getCode()));
    }

}


text:
using content::WebContents;

namespace guest_view {

namespace {

using WebContentsGuestViewMap = std::map<const WebContents*, GuestViewBase*>;
base::LazyInstance<WebContentsGuestViewMap>::Leaky g_webcontents_guestview_map =
    LAZY_INSTANCE_INITIALIZER;

}  // namespace

SetSizeParams::SetSizeParams() = default;
SetSizeParams::~SetSizeParams() = default;

// TODO(832879): It would be better to have proper ownership semantics than
// manually destroying guests and their WebContents.
//
// This observer ensures that the GuestViewBase destroys itself when its
// embedder goes away. It also tracks when the embedder's fullscreen is
// toggled so the guest can change itself accordingly.
class GuestViewBase::OwnerContentsObserver : public WebContentsObserver {
 public:
  OwnerContentsObserver(GuestViewBase* guest,
                        WebContents* embedder_web_contents)
      : WebContentsObserver(embedder_web_contents),
        is_fullscreen_(false),
        destroyed_(false),
        guest_(guest) {}

  OwnerContentsObserver(const OwnerContentsObserver&) = delete;
  OwnerContentsObserver& operator=(const OwnerContentsObserver&) = delete;

  ~OwnerContentsObserver() override = default;

  // WebContentsObserver implementation.
  void WebContentsDestroyed() override {
    // If the embedder is destroyed then destroy the guest.
    Destroy();
  }

  void DidFinishNavigation(
      content::NavigationHandle* navigation_handle) override {
    // TODO(1206312, 1205920): It is incorrect to assume that a navigation will
    // destroy the embedder.
    // If the embedder navigates to a different page then destroy the guest.
    if (!navigation_handle->IsInMainFrame() ||
        !navigation_handle->HasCommitted() ||
        navigation_handle->IsSameDocument()) {
      return;
    }

    Destroy();
  }

  void PrimaryMainFrameRenderProcessGone(
      base::TerminationStatus status) override {
    if (destroyed_)
      return;
    // If the embedder process is destroyed, then destroy the guest.
    Destroy();
  }

  void DidToggleFullscreenModeForTab(bool entered_fullscreen,
                                     bool will_cause_resize) override {
    if (destroyed_)
      return;

    is_fullscreen_ = entered_fullscreen;
    guest_->EmbedderFullscreenToggled(is_fullscreen_);
  }

  void PrimaryMainFrameWasResized(bool width_changed) override {
    if (destroyed_ || !web_contents()->GetDelegate())
      return;

    bool current_fullscreen =
        web_contents()->GetDelegate()->IsFullscreenForTabOrPending(
            web_contents());
    if (is_fullscreen_ && !current_fullscreen) {
      is_fullscreen_ = false;
      guest_->EmbedderFullscreenToggled(is_fullscreen_);
    }
  }

  void DidUpdateAudioMutingState(bool muted) override {
    if (destroyed_)
      return;

    guest_->web_contents()->SetAudioMuted(muted);
  }

  void RenderFrameDeleted(content::RenderFrameHost* rfh) override {
    guest_->OnRenderFrameHostDeleted(rfh->GetProcess()->GetID(),
                                     rfh->GetRoutingID());
  }

 private:
  bool is_fullscreen_;
  bool destroyed_;
  raw_ptr<GuestViewBase> guest_;

  void Destroy() {
    if (destroyed_)
      return;
    destroyed_ = true;

    // The outer WebContents have ownership of attached OOPIF-based guests, so
    // we are not responsible for their deletion.
    bool also_delete = guest_->web_contents() ?
        !guest_->web_contents()->GetOuterWebContents() : false;
    guest_->Destroy(also_delete);
  }
};

// This observer ensures that the GuestViewBase destroys itself if its opener
// WebContents goes away before the GuestViewBase is attached.
class GuestViewBase::OpenerLifetimeObserver : public WebContentsObserver {
 public:
  explicit OpenerLifetimeObserver(GuestViewBase* guest)
      : WebContentsObserver(guest->GetOpener()->web_contents()),
        guest_(guest) {}

  OpenerLifetimeObserver(const OpenerLifetimeObserver&) = delete;
  OpenerLifetimeObserver& operator=(const OpenerLifetimeObserver&) = delete;

  ~OpenerLifetimeObserver() override = default;

  // WebContentsObserver implementation.
  void WebContentsDestroyed() override {
    if (guest_->attached())
      return;

    // If the opener is destroyed then destroy the guest.
    guest_->Destroy(true);
  }

 private:
  raw_ptr<GuestViewBase> guest_;
};

GuestViewBase::GuestViewBase(WebContents* owner_web_contents)
    : owner_web_contents_(owner_web_contents),
      browser_context_(owner_web_contents->GetBrowserContext()),
      guest_instance_id_(GetGuestViewManager()->GetNextInstanceID()),
      view_instance_id_(kInstanceIDNone),
      element_instance_id_(kInstanceIDNone),
      attach_in_progress_(false),
      initialized_(false),
      is_being_destroyed_(false),
      guest_host_(nullptr),
      auto_size_enabled_(false),
      is_full_page_plugin_(false) {
  SetOwnerHost();
}

GuestViewBase::~GuestViewBase() {
  // NOTE(andre@vivaldi.com) : This is only set in Vivaldi. See
  // BrowserPluginGuestDelegate::delegate_to_browser_plugin_.
  if (delegate_to_browser_plugin_) {
    delegate_to_browser_plugin_->set_delegate(nullptr);
  }

  // Make sure destroy is called so the guestview manager is updated.
  // This can happen when the guest is automatically deleted via webcontents
  // being destroyed when attached to a widget. (I.e. an AppWindow.)
  //
  // TODO(igor@vivaldi.com): Do we still need this? And if we do, then
  // investigate if calling Destroy really does what we want. The method calls
  // virtual WillDestroy so WebViewGuest::WillDestroy() will not run when called
  // from the destructor. So perhaps move this to ~WebViewGuest.
  if (web_contents())
    Destroy(true);
}

void GuestViewBase::Init(const base::DictionaryValue& create_params,
                         WebContentsCreatedCallback callback) {
  if (initialized_)
    return;
  initialized_ = true;

  if (!GetGuestViewManager()->IsGuestAvailableToContext(this)) {
    // The derived class did not create a WebContents so this class serves no
    // purpose. Let's self-destruct.
    delete this;
    std::move(callback).Run(nullptr);
    return;
  }

  std::unique_ptr<base::DictionaryValue> params(create_params.DeepCopy());
  CreateWebContents(create_params,
                    base::BindOnce(&GuestViewBase::CompleteInit,
                                   weak_ptr_factory_.GetWeakPtr(),
                                   std::move(params), std::move(callback)));
}

void GuestViewBase::InitWithWebContents(
    const base::DictionaryValue& create_params,
    WebContents* guest_web_contents) {
  DCHECK(guest_web_contents);

  // Create a ZoomController to allow the guest's contents to be zoomed.
  // Do this before adding the GuestView as a WebContents Observer so that
  // the GuestView and its derived classes can re-configure the ZoomController
  // after the latter has handled WebContentsObserver events (observers are
  // notified of events in the same order they are added as observers). For
  // example, GuestViewBase may wish to put its guest into isolated zoom mode
  // in DidFinishNavigation, but since ZoomController always resets to default
  // zoom mode on this event, GuestViewBase would need to do so after
  // ZoomController::DidFinishNavigation has completed.
  zoom::ZoomController::CreateForWebContents(guest_web_contents);

#if BUILDFLAG(ENABLE_EXTENSIONS)
  AttachWebContentsObservers(guest_web_contents);
#endif

  // At this point, we have just created the guest WebContents, we need to add
  // an observer to the owner WebContents. This observer will be responsible
  // for destroying the guest WebContents if the owner goes away.
  owner_contents_observer_ =
      std::make_unique<OwnerContentsObserver>(this, owner_web_contents_);

  WebContentsObserver::Observe(guest_web_contents);

  // NOTE(david@vivaldi.com): In Vivaldi we need to use the
  // DevtoolsConnectorItem as a proxy delegate.
  if (vivaldi::IsVivaldiRunning())
    guest_web_contents->SetDelegate(GetDevToolsConnector());
  else
  guest_web_contents->SetDelegate(this);
  g_webcontents_guestview_map.Get().insert(
      std::make_pair(guest_web_contents, this));
  GetGuestViewManager()->AddGuest(guest_instance_id_, guest_web_contents);

  // Populate the view instance ID if we have it on creation.
  create_params.GetInteger(kParameterInstanceId, &view_instance_id_);

  SetUpSizing(create_params);

  // Observe guest zoom changes.
  auto* zoom_controller = zoom::ZoomController::FromWebContents(web_contents());
  zoom_controller->AddObserver(this);

  // Give the derived class an opportunity to perform additional initialization.
  DidInitialize(create_params);
}

void GuestViewBase::DispatchOnResizeEvent(const gfx::Size& old_size,
                                          const gfx::Size& new_size) {
  if (new_size == old_size)
    return;

  // Dispatch the onResize event.
  auto args = std::make_unique<base::DictionaryValue>();
  args->SetInteger(kOldWidth, old_size.width());
  args->SetInteger(kOldHeight, old_size.height());
  args->SetInteger(kNewWidth, new_size.width());
  args->SetInteger(kNewHeight, new_size.height());
  DispatchEventToGuestProxy(
      std::make_unique<GuestViewEvent>(kEventResize, std::move(args)));
}

gfx::Size GuestViewBase::GetDefaultSize() const {
  // Setting default size other than viewport makes detached/backgrounded pages
  // to be drawn with a small size when first shown. We do not want this in
  // Vivaldi.
  if (!vivaldi::IsVivaldiRunning() && !is_full_page_plugin())
    return gfx::Size(kDefaultWidth, kDefaultHeight);

  // Full page plugins default to the size of the owner's viewport.
  return owner_web_contents()
      ->GetRenderWidgetHostView()
      ->GetVisibleViewportSize();
}

void GuestViewBase::SetSize(const SetSizeParams& params) {
  bool enable_auto_size =
      params.enable_auto_size ? *params.enable_auto_size : auto_size_enabled_;
  gfx::Size min_size = params.min_size ? *params.min_size : min_auto_size_;
  gfx::Size max_size = params.max_size ? *params.max_size : max_auto_size_;

  if (params.normal_size)
    normal_size_ = *params.normal_size;

  min_auto_size_ = min_size;
  min_auto_size_.SetToMin(max_size);
  max_auto_size_ = max_size;
  max_auto_size_.SetToMax(min_size);

  enable_auto_size &= !min_auto_size_.IsEmpty() && !max_auto_size_.IsEmpty() &&
                      IsAutoSizeSupported();

  content::RenderWidgetHostView* rwhv =
      web_contents()->GetRenderWidgetHostView();
  if (enable_auto_size) {
    // Autosize is being enabled.
    if (rwhv)
      rwhv->EnableAutoResize(min_auto_size_, max_auto_size_);
    normal_size_.SetSize(0, 0);
  } else {
    // Autosize is being disabled.
    // Use default width/height if missing from partially defined normal size.
    if (normal_size_.width() && !normal_size_.height())
      normal_size_.set_height(GetDefaultSize().height());
    if (!normal_size_.width() && normal_size_.height())
      normal_size_.set_width(GetDefaultSize().width());

    gfx::Size new_size;
    if (!normal_size_.IsEmpty()) {
      new_size = normal_size_;
    } else if (!guest_size_.IsEmpty()) {
      new_size = guest_size_;
    } else {
      new_size = GetDefaultSize();
    }

    bool changed_due_to_auto_resize = false;
    if (auto_size_enabled_) {
      // Autosize was previously enabled.
      if (rwhv)
        rwhv->DisableAutoResize(new_size);
      changed_due_to_auto_resize = true;
    } else {
      // Autosize was already disabled. The RenderWidgetHostView is responsible
      // for the GuestView's size.
    }

    UpdateGuestSize(new_size, changed_due_to_auto_resize);
  }

  auto_size_enabled_ = enable_auto_size;
}

// static
void GuestViewBase::CleanUp(content::BrowserContext* browser_context,
                            int embedder_process_id,
                            int view_instance_id) {
  // TODO(paulmeyer): Add in any general GuestView cleanup work here.
}

// static
GuestViewBase* GuestViewBase::FromWebContents(const WebContents* web_contents) {
  WebContentsGuestViewMap* guest_map = g_webcontents_guestview_map.Pointer();
  auto it = guest_map->find(web_contents);
  return it == guest_map->end() ? nullptr : it->second;
}

// static
GuestViewBase* GuestViewBase::From(int owner_process_id,
                                   int guest_instance_id) {
  auto* host = content::RenderProcessHost::FromID(owner_process_id);
  if (!host)
    return nullptr;

  WebContents* guest_web_contents =
      GuestViewManager::FromBrowserContext(host->GetBrowserContext())
          ->GetGuestByInstanceIDSafely(guest_instance_id, owner_process_id);
  if (!guest_web_contents)
    return nullptr;

  return GuestViewBase::FromWebContents(guest_web_contents);
}

// static
WebContents* GuestViewBase::GetTopLevelWebContents(WebContents* web_contents) {
  while (GuestViewBase* guest = FromWebContents(web_contents))
    web_contents = guest->owner_web_contents();
  return web_contents;
}

// static
bool GuestViewBase::IsGuest(WebContents* web_contents) {
  return !!GuestViewBase::FromWebContents(web_contents);
}

bool GuestViewBase::IsAutoSizeSupported() const {
  return false;
}

bool GuestViewBase::IsPreferredSizeModeEnabled() const {
  return false;
}

bool GuestViewBase::ZoomPropagatesFromEmbedderToGuest() const {
  return true;
}

GuestViewManager* GuestViewBase::GetGuestViewManager() {
  return GuestViewManager::FromBrowserContext(browser_context());
}

WebContents* GuestViewBase::CreateNewGuestWindow(
    const WebContents::CreateParams& create_params) {
  if( !owner_web_contents())
    return nullptr;

  return GetGuestViewManager()->CreateGuestWithWebContentsParams(
      GetViewType(), owner_web_contents(), create_params);
}

void GuestViewBase::OnRenderFrameHostDeleted(int process_id, int routing_id) {}

void GuestViewBase::DidAttach() {
  DCHECK(attach_in_progress_);
  // Clear this flag here, as functions called below may check attached().
  attach_in_progress_ = false;

  opener_lifetime_observer_.reset();

  SetUpSizing(*attach_params());

  // NOTE(andre@vivaldi.com) : We can set muting on a tab, which is a guest. So
  // we cannot do the default behaviour of copying the parents mute-state. Check
  // bail if the owner is our app-window. The guest should have the same muting
  if (!extensions::VivaldiAppHelper::FromWebContents(owner_web_contents())){
  // state as the owner.
  web_contents()->SetAudioMuted(owner_web_contents()->IsAudioMuted());
  } // if the owner is the Vivaldi app-window.

  // Give the derived class an opportunity to perform some actions.
  DidAttachToEmbedder();

  SendQueuedEvents();
}

WebContents* GuestViewBase::GetOwnerWebContents() {
  return owner_web_contents_;
}

const GURL& GuestViewBase::GetOwnerSiteURL() const {
  return owner_web_contents()->GetMainFrame()->GetSiteInstance()->GetSiteURL();
}

bool GuestViewBase::ShouldDestroyOnDetach() const {
  return false;
}

void GuestViewBase::Destroy(bool also_delete) {
  if (is_being_destroyed_)
    return;

  is_being_destroyed_ = true;

  // It is important to clear owner_web_contents_ after the call to
  // StopTrackingEmbedderZoomLevel(), but before the rest of
  // the statements in this function.
  StopTrackingEmbedderZoomLevel();
  owner_web_contents_ = nullptr;

  DCHECK(web_contents());

  // Give the derived class an opportunity to perform some cleanup.
  WillDestroy();

  // Invalidate weak pointers now so that bound callbacks cannot be called late
  // into destruction. We must call this after WillDestroy because derived types
  // may wish to access their openers.
  weak_ptr_factory_.InvalidateWeakPtrs();

  // Give the content module an opportunity to perform some cleanup.
  if (guest_host_) {
    // clang-format off
  guest_host_->WillDestroy();
    // clang-format on
  }
  guest_host_ = nullptr;

  g_webcontents_guestview_map.Get().erase(web_contents());
  GetGuestViewManager()->RemoveGuest(guest_instance_id_);
  pending_events_.clear();

  if (vivaldi::IsVivaldiRunning() && web_contents()) {
    if (VivaldiTabCheck::IsOwnedByTabStripOrDevTools(web_contents())) {
      web_contents()->SetDelegate(nullptr);
      content::WebContentsObserver::Observe(nullptr);
      return;
    }
    // NOTE(jarle@vivaldi): Check if the WebContent object is already being
    // destroyed. We can get a callback from the WebContentsImpl destructor
    // through GuestViewBase::OwnerContentsObserver. This fixes VB-8381.
    //
    // NOTE(igor@vivaldi.com): This check is probably not applicable. The
    // IsOwnedByTabStripOrDevTools check should reliably skip externally owned
    // WebContents and GuestViewBase::WebContentsDestroyed() calls
    // Destroy(false). But there could still be a code path that destroys the
    // view from another WebContentsDestroyed callback before Destroy(false) was
    // called. As we patched the destructor to call Destroy(true) we need to
    // check for that possibility.
    if (web_contents()->IsBeingDestroyed())
      return;
  }

  if (also_delete)
    delete web_contents();
}

void GuestViewBase::SetAttachParams(const base::DictionaryValue& params) {
  attach_params_.reset(params.DeepCopy());
  attach_params_->GetInteger(kParameterInstanceId, &view_instance_id_);
}

void GuestViewBase::SetOpener(GuestViewBase* guest) {
  if (guest) {
    opener_ = guest->weak_ptr_factory_.GetWeakPtr();
    if (!attached()) {
      opener_lifetime_observer_ =
          std::make_unique<OpenerLifetimeObserver>(this);
    }
  } else {
    opener_ = base::WeakPtr<GuestViewBase>();
    opener_lifetime_observer_.reset();
  }
}

void GuestViewBase::SetGuestHost(content::GuestHost* guest_host) {
  guest_host_ = guest_host;
}

void GuestViewBase::WillAttach(WebContents* embedder_web_contents,
                               int element_instance_id,
                               bool is_full_page_plugin,
                               base::OnceClosure completion_callback) {
  WillAttach(embedder_web_contents, nullptr, element_instance_id,
             is_full_page_plugin, std::move(completion_callback));
}

void GuestViewBase::WillAttach(WebContents* embedder_web_contents,
                               content::RenderFrameHost* outer_contents_frame,
                               int element_instance_id,
                               bool is_full_page_plugin,
                               base::OnceClosure completion_callback) {
  // Stop tracking the old embedder's zoom level.
  if (owner_web_contents())
    StopTrackingEmbedderZoomLevel();

  if (owner_web_contents_ != embedder_web_contents) {
    DCHECK_EQ(owner_contents_observer_->web_contents(), owner_web_contents_);
    owner_web_contents_ = embedder_web_contents;
    owner_contents_observer_ =
        std::make_unique<OwnerContentsObserver>(this, embedder_web_contents);
    SetOwnerHost();
  }

  // Start tracking the new embedder's zoom level.
  StartTrackingEmbedderZoomLevel();
  attach_in_progress_ = true;
  element_instance_id_ = element_instance_id;
  is_full_page_plugin_ = is_full_page_plugin;

  WillAttachToEmbedder();

  web_contents()->ResumeLoadingCreatedWebContents();

  owner_web_contents_->AttachInnerWebContents(
      base::WrapUnique<WebContents>(web_contents()), outer_contents_frame,
      is_full_page_plugin);
  // TODO(ekaramad): MimeHandlerViewGuest might not need this ACK
  // (https://crbug.com/659750).
  // We don't ACK until after AttachToOuterWebContentsFrame, so that
  // |outer_contents_frame| gets swapped before the AttachIframeGuest callback
  // is run. We also need to send the ACK before queued events are sent in
  // DidAttach.
  embedder_web_contents->GetMainFrame()->Send(
      new GuestViewMsg_AttachToEmbedderFrame_ACK(element_instance_id));

  // Completing attachment will resume suspended resource loads and then send
  // queued events.
  SignalWhenReady(std::move(completion_callback));
}

void GuestViewBase::SignalWhenReady(base::OnceClosure callback) {
  // The default behavior is to call the |callback| immediately. Derived classes
  // can implement an alternative signal for readiness.
  std::move(callback).Run();
}

int GuestViewBase::LogicalPixelsToPhysicalPixels(double logical_pixels) const {
  DCHECK(logical_pixels >= 0);
  double zoom_factor = GetEmbedderZoomFactor();
  return lround(logical_pixels * zoom_factor);
}

double GuestViewBase::PhysicalPixelsToLogicalPixels(int physical_pixels) const {
  DCHECK(physical_pixels >= 0);
  double zoom_factor = GetEmbedderZoomFactor();
  return physical_pixels / zoom_factor;
}

void GuestViewBase::DidStopLoading() {
  content::RenderViewHost* rvh =
      web_contents()->GetMainFrame()->GetRenderViewHost();

  if (IsPreferredSizeModeEnabled())
    rvh->EnablePreferredSizeMode();
  GuestViewDidStopLoading();
}

void GuestViewBase::RenderViewReady() {
  GuestReady();
}

void GuestViewBase::WebContentsDestroyed() {
  Destroy(false);

  // Let the derived class know that its WebContents is in the process of
  // being destroyed. web_contents() is still valid at this point.
  // TODO(fsamuel): This allows for reentrant code into WebContents during
  // destruction. This could potentially lead to bugs. Perhaps we should get rid
  // of this?
  GuestDestroyed();

  // Self-destruct.
  delete this;
}

void GuestViewBase::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  // TODO(https://crbug.com/1218946): With MPArch there may be multiple main
  // frames. This caller was converted automatically to the primary main frame
  // to preserve its semantics. Follow up to confirm correctness.
  if (!navigation_handle->IsInPrimaryMainFrame() ||
      !navigation_handle->HasCommitted())
    return;

  if (attached() && ZoomPropagatesFromEmbedderToGuest())
    SetGuestZoomLevelToMatchEmbedder();
}

void GuestViewBase::ActivateContents(WebContents* web_contents) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return;

  embedder_web_contents()->GetDelegate()->ActivateContents(
      embedder_web_contents());
}

void GuestViewBase::ContentsMouseEvent(WebContents* source,
                                       bool motion,
                                       bool exited) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return;

  embedder_web_contents()->GetDelegate()->ContentsMouseEvent(
      embedder_web_contents(), motion, exited);
}

void GuestViewBase::ContentsZoomChange(bool zoom_in) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return;
  embedder_web_contents()->GetDelegate()->ContentsZoomChange(zoom_in);
}

bool GuestViewBase::HandleKeyboardEvent(
    WebContents* source,
    const content::NativeWebKeyboardEvent& event) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return false;

  // Send the keyboard events back to the embedder to reprocess them.
  return embedder_web_contents()->GetDelegate()->HandleKeyboardEvent(
      embedder_web_contents(), event);
}

void GuestViewBase::LoadingStateChanged(WebContents* source,
                                        bool should_show_loading_ui) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return;

  embedder_web_contents()->GetDelegate()->LoadingStateChanged(
      embedder_web_contents(), should_show_loading_ui);
}

void GuestViewBase::ResizeDueToAutoResize(WebContents* web_contents,
                                          const gfx::Size& new_size) {
  UpdateGuestSize(new_size, auto_size_enabled_);
}

void GuestViewBase::RunFileChooser(
    content::RenderFrameHost* render_frame_host,
    scoped_refptr<content::FileSelectListener> listener,
    const blink::mojom::FileChooserParams& params) {
  if (!attached() || !embedder_web_contents()->GetDelegate()) {
    listener->FileSelectionCanceled();
    return;
  }

  embedder_web_contents()->GetDelegate()->RunFileChooser(
      render_frame_host, std::move(listener), params);
}

bool GuestViewBase::ShouldFocusPageAfterCrash() {
  // Focus is managed elsewhere.
  return false;
}

bool GuestViewBase::PreHandleGestureEvent(WebContents* source,
                                          const blink::WebGestureEvent& event) {
  if (vivaldi::IsVivaldiRunning()) {
    // NOTE(espen@vivaldi.com): We need pinch events in guests. DCHECK below
    // is not correct for us.
    return false;
  }
  // Pinch events which cause a scale change should not be routed to a guest.
  // We still allow synthetic wheel events for touchpad pinch to go to the page.
  DCHECK(!blink::WebInputEvent::IsPinchGestureEventType(event.GetType()) ||
         (event.SourceDevice() == blink::WebGestureDevice::kTouchpad &&
          event.NeedsWheelEvent()));
  return false;
}

void GuestViewBase::UpdatePreferredSize(WebContents* target_web_contents,
                                        const gfx::Size& pref_size) {
  // In theory it's not necessary to check IsPreferredSizeModeEnabled() because
  // there will only be events if it was enabled in the first place. However,
  // something else may have turned on preferred size mode, so double check.
  DCHECK_EQ(web_contents(), target_web_contents);
  if (IsPreferredSizeModeEnabled()) {
    OnPreferredSizeChanged(pref_size);
  }
}

content::WebContents* GuestViewBase::GetResponsibleWebContents(
    content::WebContents* source) {
  return owner_web_contents();
}

void GuestViewBase::UpdateTargetURL(WebContents* source, const GURL& url) {
  if (!attached() || !embedder_web_contents()->GetDelegate())
    return;

  embedder_web_contents()->GetDelegate()->UpdateTargetURL(
      embedder_web_contents(), url);
}

bool GuestViewBase::ShouldResumeRequestsForCreatedWindow() {
  // Delay so that the embedder page has a chance to call APIs such as
  // webRequest in time to be applied to the initial navigation in the new guest
  // contents. We resume during WillAttach.
  return false;
}

content::RenderWidgetHost* GuestViewBase::GetOwnerRenderWidgetHost() {
  // We assume guests live inside an owner RenderFrame but the RenderFrame may
  // not be cross-process. In case a type of guest should be allowed to be
  // embedded in a cross-process frame, this method should be overrode for that
  // specific guest type. For all other guests, the owner RenderWidgetHost is
  // that of the owner WebContents.
  auto* owner = GetOwnerWebContents();
  if (owner && owner->GetRenderWidgetHostView())
    return owner->GetRenderWidgetHostView()->GetRenderWidgetHost();
  return nullptr;
}

content::SiteInstance* GuestViewBase::GetOwnerSiteInstance() {
  // We assume guests live inside an owner RenderFrame but the RenderFrame may
  // not be cross-process. In case a type of guest should be allowed to be
  // embedded in a cross-process frame, this method should be overrode for that
  // specific guest type. For all other guests, the owner site instance can be
  // from the owner WebContents.
  if (auto* owner_contents = GetOwnerWebContents())
    return owner_contents->GetSiteInstance();
  return nullptr;
}

void GuestViewBase::AttachToOuterWebContentsFrame(
    content::RenderFrameHost* embedder_frame,
    int32_t element_instance_id,
    bool is_full_page_plugin) {
  auto completion_callback =
      base::BindOnce(&GuestViewBase::DidAttach, weak_ptr_factory_.GetWeakPtr());
  WillAttach(WebContents::FromRenderFrameHost(embedder_frame), embedder_frame,
             element_instance_id, is_full_page_plugin,
             std::move(completion_callback));
}

void GuestViewBase::OnZoomChanged(
    const zoom::ZoomController::ZoomChangedEventData& data) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  // NOTE(arnar@vivaldi.com): Do not update guest zoom level if embedder
  // is Vivaldi app. (UI Zoom)
  if (embedder_web_contents()) {
    auto *vivaldi_app_helper =
        extensions::VivaldiAppHelper::FromWebContents(embedder_web_contents());
    if (vivaldi_app_helper) {
      return;
    }
  }
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

  if (data.web_contents == embedder_web_contents()) {
    // The embedder's zoom level has changed.
    auto* guest_zoom_controller =
        zoom::ZoomController::FromWebContents(web_contents());
    if (blink::PageZoomValuesEqual(data.new_zoom_level,
                                   guest_zoom_controller->GetZoomLevel())) {
      return;
    }
    // When the embedder's zoom level doesn't match the guest's, then update the
    // guest's zoom level to match.
    guest_zoom_controller->SetZoomLevel(data.new_zoom_level);
    return;
  }

  if (data.web_contents == web_contents()) {
    // The guest's zoom level has changed.
    GuestZoomChanged(data.old_zoom_level, data.new_zoom_level);
  }
}

void GuestViewBase::DispatchEventToGuestProxy(
    std::unique_ptr<GuestViewEvent> event) {
  event->Dispatch(this, guest_instance_id_);
}

void GuestViewBase::DispatchEventToView(std::unique_ptr<GuestViewEvent> event) {
  if (attached() && pending_events_.empty()) {
    event->Dispatch(this, view_instance_id_);
    return;
  }
  pending_events_.push_back(std::move(event));
}

void GuestViewBase::SendQueuedEvents() {
  if (!attached())
    return;
  while (!pending_events_.empty()) {
    std::unique_ptr<GuestViewEvent> event_ptr =
        std::move(pending_events_.front());
    pending_events_.pop_front();
    event_ptr->Dispatch(this, view_instance_id_);
  }
}

void GuestViewBase::CompleteInit(
    std::unique_ptr<base::DictionaryValue> create_params,
    WebContentsCreatedCallback callback,
    WebContents* guest_web_contents) {
  if (!guest_web_contents) {
    // The derived class did not create a WebContents so this class serves no
    // purpose. Let's self-destruct.
    delete this;
    std::move(callback).Run(nullptr);
    return;
  }

  // web_contents() will not be set in some cases (like when we avctivate an
  // non-loaded pdf-tab). We can deal with an unset delegate_to_browser_plugin_.
  if (vivaldi::IsVivaldiRunning() && guest_web_contents) {
    delegate_to_browser_plugin_ =
      static_cast<content::WebContentsImpl*>(guest_web_contents)
      ->GetBrowserPluginGuest();
  }

  InitWithWebContents(*create_params, guest_web_contents);
  std::move(callback).Run(guest_web_contents);
}

double GuestViewBase::GetEmbedderZoomFactor() const {
  if (!embedder_web_contents())
    return 1.0;

  return blink::PageZoomLevelToZoomFactor(
      zoom::ZoomController::GetZoomLevelForWebContents(
          embedder_web_contents()));
}

void GuestViewBase::SetUpSizing(const base::DictionaryValue& params) {
  // Read the autosize parameters passed in from the embedder.
  absl::optional<bool> auto_size_enabled_opt =
      params.FindBoolKey(kAttributeAutoSize);
  bool auto_size_enabled = auto_size_enabled_opt.value_or(auto_size_enabled_);

  int max_height = max_auto_size_.height();
  int max_width = max_auto_size_.width();
  params.GetInteger(kAttributeMaxHeight, &max_height);
  params.GetInteger(kAttributeMaxWidth, &max_width);

  int min_height = min_auto_size_.height();
  int min_width = min_auto_size_.width();
  params.GetInteger(kAttributeMinHeight, &min_height);
  params.GetInteger(kAttributeMinWidth, &min_width);

  double element_height = params.FindDoublePath(kElementHeight).value_or(0.0);
  double element_width = params.FindDoublePath(kElementWidth).value_or(0.0);

  // Set the normal size to the element size so that the guestview will fit
  // the element initially if autosize is disabled.
  int normal_height = normal_size_.height();
  int normal_width = normal_size_.width();
  // If the element size was provided in logical units (versus physical), then
  // it will be converted to physical units.
  absl::optional<bool> element_size_is_logical_opt =
      params.FindBoolKey(kElementSizeIsLogical);
  bool element_size_is_logical = element_size_is_logical_opt.value_or(false);
  if (element_size_is_logical) {
    // Convert the element size from logical pixels to physical pixels.
    normal_height = LogicalPixelsToPhysicalPixels(element_height);
    normal_width = LogicalPixelsToPhysicalPixels(element_width);
  } else {
    normal_height = lround(element_height);
    normal_width = lround(element_width);
  }

  SetSizeParams set_size_params;
  set_size_params.enable_auto_size = std::make_unique<bool>(auto_size_enabled);
  set_size_params.min_size = std::make_unique<gfx::Size>(min_width, min_height);
  set_size_params.max_size = std::make_unique<gfx::Size>(max_width, max_height);
  set_size_params.normal_size =
      std::make_unique<gfx::Size>(normal_width, normal_height);

  // Call SetSize to apply all the appropriate validation and clipping of
  // values.
  SetSize(set_size_params);
}

void GuestViewBase::SetGuestZoomLevelToMatchEmbedder() {
  auto* embedder_zoom_controller =
      zoom::ZoomController::FromWebContents(owner_web_contents());
  if (!embedder_zoom_controller)
    return;

#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (embedder_web_contents()) {
    auto *vivaldi_app_helper =
      extensions::VivaldiAppHelper::FromWebContents(owner_web_contents());
    if (vivaldi_app_helper) {
      // NOTE(arnar@vivaldi.com): Do not set Guest zoom level to match level of
      // embedder if embedder is Vivaldi app (UI Zoom)
      return;
    }
  }
#endif // BUILDFLAG(ENABLE_EXTENSIONS)

  zoom::ZoomController::FromWebContents(web_contents())
      ->SetZoomLevel(embedder_zoom_controller->GetZoomLevel());
}

void GuestViewBase::StartTrackingEmbedderZoomLevel() {
  if (!ZoomPropagatesFromEmbedderToGuest())
    return;

  auto* embedder_zoom_controller =
      zoom::ZoomController::FromWebContents(owner_web_contents());
  // Chrome Apps do not have a ZoomController.
  if (!embedder_zoom_controller)
    return;
  // Listen to the embedder's zoom changes.
  embedder_zoom_controller->AddObserver(this);

  // Set the guest's initial zoom level to be equal to the embedder's.
  SetGuestZoomLevelToMatchEmbedder();
}

void GuestViewBase::StopTrackingEmbedderZoomLevel() {
  // TODO(wjmaclean): Remove the observer any time the GuestWebView transitions
  // from propagating to not-propagating the zoom from the embedder.

  auto* embedder_zoom_controller =
      zoom::ZoomController::FromWebContents(owner_web_contents());
  // Chrome Apps do not have a ZoomController.
  if (!embedder_zoom_controller)
    return;

  // It is safe to remove an observer that was never registed.
  embedder_zoom_controller->RemoveObserver(this);
}

void GuestViewBase::UpdateGuestSize(const gfx::Size& new_size,
                                    bool due_to_auto_resize) {
  if (due_to_auto_resize)
    GuestSizeChangedDueToAutoSize(guest_size_, new_size);
  DispatchOnResizeEvent(guest_size_, new_size);
  guest_size_ = new_size;
}

void GuestViewBase::SetOwnerHost() {
  auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
  owner_host_ = manager->IsOwnedByExtension(this)
                    ? owner_web_contents()->GetLastCommittedURL().host()
                    : std::string();
}

bool GuestViewBase::CanBeEmbeddedInsideCrossProcessFrames() {
  return false;
}

}  // namespace guest_view


text:
// @flow

/* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/no-noninteractive-tabindex: 0 */

import React from "react";

import Markdown from "@nteract/markdown";

import { Outputs, PromptBuffer, Input } from "./";

type Props = {
  source: string,
  focusEditor: () => void,
  unfocusEditor: () => void,
  focusAbove: () => void,
  focusBelow: () => void,
  cellFocused: boolean,
  editorFocused: boolean,
  children: React$Element<*>
};

type State = {
  view: boolean
};

const noop = function() {};

// TODO: Consider whether this component is really something like two components:
//
//       * a behavioral component that tracks focus (possibly already covered elsewhere)
//       * the actual markdown previewer
//
//       Since I'm really unsure and don't want to write a silly abstraction that
//       only I (@rgbkrk) understand, I'll wait for others to reflect on this
//       within the code base (or leave it alone, which is totally cool too). :)

export default class MarkdownCell extends React.Component<any, State> {
  rendered: ?HTMLElement;

  static defaultProps = {
    cellFocused: false,
    editorFocused: false,
    focusAbove: noop,
    focusBelow: noop,
    focusEditor: noop,
    unfocusEditor: noop,
    source: ""
  };

  constructor(props: Props): void {
    super(props);
    this.state = {
      view: true
    };
    (this: any).openEditor = this.openEditor.bind(this);
    (this: any).editorKeyDown = this.editorKeyDown.bind(this);
    (this: any).renderedKeyDown = this.renderedKeyDown.bind(this);
    (this: any).closeEditor = this.closeEditor.bind(this);
  }

  componentDidMount(): void {
    this.updateFocus();
  }

  componentWillReceiveProps(nextProps: Props): void {
    this.setState({
      view: !nextProps.editorFocused
    });
  }

  componentDidUpdate(): void {
    this.updateFocus();
  }

  updateFocus(): void {
    if (
      this.rendered &&
      this.state &&
      this.state.view &&
      this.props.cellFocused
    ) {
      this.rendered.focus();
      if (this.props.editorFocused) {
        this.openEditor();
      }
    }
  }

  /**
   * Handles when a keydown event occurs on the unrendered MD cell
   */
  editorKeyDown(e: SyntheticKeyboardEvent<*>): void {
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      this.closeEditor();
    }
  }

  closeEditor(): void {
    this.setState({ view: true });
    this.props.unfocusEditor();
  }

  openEditor(): void {
    this.setState({ view: false });
    this.props.focusEditor();
  }

  /**
   * Handles when a keydown event occurs on the rendered MD cell
   */
  renderedKeyDown(e: SyntheticKeyboardEvent<*>) {
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      if (this.state.view) {
        return;
      }
      // This likely isn't even possible, as we _should_ be in view mode
      this.closeEditor();
      return;
    }

    switch (e.key) {
      case "Enter":
        this.openEditor();
        e.preventDefault();
        return;
      case "ArrowUp":
        this.props.focusAbove();
        break;
      case "ArrowDown":
        this.props.focusBelow();
        break;
      default:
    }
    return;
  }

  render(): ?React$Element<any> {
    const source = this.props.source;

    return this.state && this.state.view ? (
      <div
        onDoubleClick={this.openEditor}
        onKeyDown={this.renderedKeyDown}
        ref={rendered => {
          this.rendered = rendered;
        }}
        tabIndex={this.props.cellFocused ? 0 : null}
        style={{
          outline: "none"
        }}
      >
        <Outputs>
          <Markdown
            source={
              source
                ? source
                : "*Empty markdown cell, double click me to add content.*"
            }
          />
        </Outputs>
      </div>
    ) : (
      <div onKeyDown={this.editorKeyDown}>
        <Input>
          <PromptBuffer />
          {/* The editor */}
          {this.props.children}
        </Input>
        <Outputs hidden={source === ""}>
          <Markdown
            source={
              source
                ? source
                : "*Empty markdown cell, double click me to add content.*"
            }
          />
        </Outputs>
      </div>
    );
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

   	<base href="/">

    <title>Shop Homepage</title>

    <link href="public/assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css">

    <link href="public/assets/css/shop-homepage.css" rel="stylesheet">

    <link href="public/assets/css/style.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Shopping App

                <form class="navbar-form navbar-right" id="formLogin" ng-submit="main.doLogin()">

                       <input type="text" class="form-control" id="userName" placeholder="username" ng-model="main.loginData.username">
                       <input type="password" class="form-control" id="password" placeholder="password" ng-model="main.loginData.password">

                   <button type="submit" id="btnLogin" class="btn btn-default">Login</button>
                   Register
                </form>

                 {{main.user.username}}
                  <form  class="navbar-form navbar-right" id="formLogin" ng-submit="main.doLogout()">
                    <button type="submit" id="btnLogin" class="btn btn-default">Logout</button>
                  </form>

There was an error with your Username/Password combination. Please try again.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
package sample.actuator;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for /health with {@code endpoints.health.sensitive=false}.
 *
 * @author Phillip Webb
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
		"endpoints.health.sensitive=false" })
@DirtiesContext
public class NonSensitiveHealthTests {

	@Autowired
	private TestRestTemplate restTemplate;

	@Test
	public void testSecureHealth() throws Exception {
		ResponseEntity<String> entity = this.restTemplate.getForEntity("/health",
				String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
		assertThat(entity.getBody()).doesNotContain("\"hello\":1");
	}

}


text:
package org.arakhne.afc.inputoutput.filetype;

import javax.activation.MimeType;

/** This class defines a set of informations that could distinguish
 * a file content from another one. It is also known as Magic Number
 * on several operating systems.
 *
 *
This magic number supports XML files and permits to
 * test the system and user Identifiers extracted from the XML
 * content.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 14.0
 */
public class DTDBasedXMLMagicNumber extends XMLMagicNumber {

	private final String systemId;

	private final String publicId;

	/**
	 * @param mimeType is the MIME type associated to this magic number.
	 * @param systemId is the DTD system ID associated to this magic number.
	 * @param publicId is the DTD system ID associated to this magic number.
	 */
	public DTDBasedXMLMagicNumber(MimeType mimeType, String systemId, String publicId) {
		super(mimeType, null);
		this.systemId = systemId;
		this.publicId = publicId;
	}

	/**
	 * @param mimeType is the MIME type associated to this magic number.
	 * @param formatVersion is the version of the supported format.
	 * @param systemId is the DTD system ID associated to this magic number.
	 * @param publicId is the DTD system ID associated to this magic number.
	 */
	public DTDBasedXMLMagicNumber(MimeType mimeType, String formatVersion, String systemId, String publicId) {
		super(mimeType, null, formatVersion);
		this.systemId = systemId;
		this.publicId = publicId;
	}

	/** Replies if the specified stream contains data
	 * that corresponds to this magic number.
	 *
	 * @param schemaId is the ID of the XSL schema associated to this magic number.
	 * @param schemaVersion is the ID of the XSL schema associated to this magic number.
	 * @param systemId is the DTD system ID associated to this magic number.
	 * @param publicId is the DTD system ID associated to this magic number.
	 * @return true if this magic number is corresponding to the given
	 *     XML document, otherwise false
	 */
	@Override
	protected boolean isContentType(String schemaId, String schemaVersion, String systemId, String publicId) {
		return (this.publicId != null && this.publicId.equalsIgnoreCase(publicId))
				|| (this.systemId != null && this.systemId.equalsIgnoreCase(systemId));
	}

}