text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/run/v2/traffic_target.proto

package com.google.cloud.run.v2;

/**
 *
 *
 *

 * Represents the observed state of a single `TrafficTarget` entry.
 *

 *
 * Protobuf type {@code google.cloud.run.v2.TrafficTargetStatus}
 */
public final class TrafficTargetStatus extends com.google.protobuf.GeneratedMessageV3
    implements
    // @@protoc_insertion_point(message_implements:google.cloud.run.v2.TrafficTargetStatus)
    TrafficTargetStatusOrBuilder {
  private static final long serialVersionUID = 0L;
  // Use TrafficTargetStatus.newBuilder() to construct.
  private TrafficTargetStatus(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }

  private TrafficTargetStatus() {
    type_ = 0;
    revision_ = "";
    tag_ = "";
    uri_ = "";
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
    return new TrafficTargetStatus();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
    return this.unknownFields;
  }

  private TrafficTargetStatus(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    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;
          case 8:
            {
              int rawValue = input.readEnum();

              type_ = rawValue;
              break;
            }
          case 18:
            {
              java.lang.String s = input.readStringRequireUtf8();

              revision_ = s;
              break;
            }
          case 24:
            {
              percent_ = input.readInt32();
              break;
            }
          case 34:
            {
              java.lang.String s = input.readStringRequireUtf8();

              tag_ = s;
              break;
            }
          case 42:
            {
              java.lang.String s = input.readStringRequireUtf8();

              uri_ = s;
              break;
            }
          default:
            {
              if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              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 com.google.cloud.run.v2.TrafficTargetProto
        .internal_static_google_cloud_run_v2_TrafficTargetStatus_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.run.v2.TrafficTargetProto
        .internal_static_google_cloud_run_v2_TrafficTargetStatus_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.run.v2.TrafficTargetStatus.class,
            com.google.cloud.run.v2.TrafficTargetStatus.Builder.class);
  }

  public static final int TYPE_FIELD_NUMBER = 1;
  private int type_;
  /**
   *
   *
   *

   * The allocation type for this traffic target.
   *

   *
   * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
   *
   * @return The enum numeric value on the wire for type.
   */
  @java.lang.Override
  public int getTypeValue() {
    return type_;
  }
  /**
   *
   *
   *

   * The allocation type for this traffic target.
   *

   *
   * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
   *
   * @return The type.
   */
  @java.lang.Override
  public com.google.cloud.run.v2.TrafficTargetAllocationType getType() {
    @SuppressWarnings("deprecation")
    com.google.cloud.run.v2.TrafficTargetAllocationType result =
        com.google.cloud.run.v2.TrafficTargetAllocationType.valueOf(type_);
    return result == null
        ? com.google.cloud.run.v2.TrafficTargetAllocationType.UNRECOGNIZED
        : result;
  }

  public static final int REVISION_FIELD_NUMBER = 2;
  private volatile java.lang.Object revision_;
  /**
   *
   *
   *

   * Revision to which this traffic is sent.
   *

   *
   * string revision = 2 [(.google.api.resource_reference) = { ... }
   *
   * @return The revision.
   */
  @java.lang.Override
  public java.lang.String getRevision() {
    java.lang.Object ref = revision_;
    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();
      revision_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * Revision to which this traffic is sent.
   *

   *
   * string revision = 2 [(.google.api.resource_reference) = { ... }
   *
   * @return The bytes for revision.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getRevisionBytes() {
    java.lang.Object ref = revision_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      revision_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int PERCENT_FIELD_NUMBER = 3;
  private int percent_;
  /**
   *
   *
   *

   * Specifies percent of the traffic to this Revision.
   *

   *
   * int32 percent = 3;
   *
   * @return The percent.
   */
  @java.lang.Override
  public int getPercent() {
    return percent_;
  }

  public static final int TAG_FIELD_NUMBER = 4;
  private volatile java.lang.Object tag_;
  /**
   *
   *
   *

   * Indicates the string used in the URI to exclusively reference this target.
   *

   *
   * string tag = 4;
   *
   * @return The tag.
   */
  @java.lang.Override
  public java.lang.String getTag() {
    java.lang.Object ref = tag_;
    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();
      tag_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * Indicates the string used in the URI to exclusively reference this target.
   *

   *
   * string tag = 4;
   *
   * @return The bytes for tag.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getTagBytes() {
    java.lang.Object ref = tag_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      tag_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int URI_FIELD_NUMBER = 5;
  private volatile java.lang.Object uri_;
  /**
   *
   *
   *

   * Displays the target URI.
   *

   *
   * string uri = 5;
   *
   * @return The uri.
   */
  @java.lang.Override
  public java.lang.String getUri() {
    java.lang.Object ref = uri_;
    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();
      uri_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * Displays the target URI.
   *

   *
   * string uri = 5;
   *
   * @return The bytes for uri.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getUriBytes() {
    java.lang.Object ref = uri_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      uri_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;

  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
    if (type_
        != com.google.cloud.run.v2.TrafficTargetAllocationType
            .TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED
            .getNumber()) {
      output.writeEnum(1, type_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(revision_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 2, revision_);
    }
    if (percent_ != 0) {
      output.writeInt32(3, percent_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tag_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 4, tag_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 5, uri_);
    }
    unknownFields.writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (type_
        != com.google.cloud.run.v2.TrafficTargetAllocationType
            .TRAFFIC_TARGET_ALLOCATION_TYPE_UNSPECIFIED
            .getNumber()) {
      size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, type_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(revision_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, revision_);
    }
    if (percent_ != 0) {
      size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, percent_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tag_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, tag_);
    }
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, uri_);
    }
    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 com.google.cloud.run.v2.TrafficTargetStatus)) {
      return super.equals(obj);
    }
    com.google.cloud.run.v2.TrafficTargetStatus other =
        (com.google.cloud.run.v2.TrafficTargetStatus) obj;

    if (type_ != other.type_) return false;
    if (!getRevision().equals(other.getRevision())) return false;
    if (getPercent() != other.getPercent()) return false;
    if (!getTag().equals(other.getTag())) return false;
    if (!getUri().equals(other.getUri())) return false;
    if (!unknownFields.equals(other.unknownFields)) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + TYPE_FIELD_NUMBER;
    hash = (53 * hash) + type_;
    hash = (37 * hash) + REVISION_FIELD_NUMBER;
    hash = (53 * hash) + getRevision().hashCode();
    hash = (37 * hash) + PERCENT_FIELD_NUMBER;
    hash = (53 * hash) + getPercent();
    hash = (37 * hash) + TAG_FIELD_NUMBER;
    hash = (53 * hash) + getTag().hashCode();
    hash = (37 * hash) + URI_FIELD_NUMBER;
    hash = (53 * hash) + getUri().hashCode();
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus 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 com.google.cloud.run.v2.TrafficTargetStatus parseDelimitedFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus 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 com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      com.google.protobuf.CodedInputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() {
    return newBuilder();
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(com.google.cloud.run.v2.TrafficTargetStatus prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  @java.lang.Override
  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;
  }
  /**
   *
   *
   *

   * Represents the observed state of a single `TrafficTarget` entry.
   *

   *
   * Protobuf type {@code google.cloud.run.v2.TrafficTargetStatus}
   */
  public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
      implements
      // @@protoc_insertion_point(builder_implements:google.cloud.run.v2.TrafficTargetStatus)
      com.google.cloud.run.v2.TrafficTargetStatusOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
      return com.google.cloud.run.v2.TrafficTargetProto
          .internal_static_google_cloud_run_v2_TrafficTargetStatus_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.cloud.run.v2.TrafficTargetProto
          .internal_static_google_cloud_run_v2_TrafficTargetStatus_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.cloud.run.v2.TrafficTargetStatus.class,
              com.google.cloud.run.v2.TrafficTargetStatus.Builder.class);
    }

    // Construct using com.google.cloud.run.v2.TrafficTargetStatus.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }

    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
    }

    @java.lang.Override
    public Builder clear() {
      super.clear();
      type_ = 0;

      revision_ = "";

      percent_ = 0;

      tag_ = "";

      uri_ = "";

      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
      return com.google.cloud.run.v2.TrafficTargetProto
          .internal_static_google_cloud_run_v2_TrafficTargetStatus_descriptor;
    }

    @java.lang.Override
    public com.google.cloud.run.v2.TrafficTargetStatus getDefaultInstanceForType() {
      return com.google.cloud.run.v2.TrafficTargetStatus.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.cloud.run.v2.TrafficTargetStatus build() {
      com.google.cloud.run.v2.TrafficTargetStatus result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.cloud.run.v2.TrafficTargetStatus buildPartial() {
      com.google.cloud.run.v2.TrafficTargetStatus result =
          new com.google.cloud.run.v2.TrafficTargetStatus(this);
      result.type_ = type_;
      result.revision_ = revision_;
      result.percent_ = percent_;
      result.tag_ = tag_;
      result.uri_ = uri_;
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return super.clone();
    }

    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.setField(field, value);
    }

    @java.lang.Override
    public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }

    @java.lang.Override
    public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }

    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
      return super.setRepeatedField(field, index, value);
    }

    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.addRepeatedField(field, value);
    }

    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.cloud.run.v2.TrafficTargetStatus) {
        return mergeFrom((com.google.cloud.run.v2.TrafficTargetStatus) other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.cloud.run.v2.TrafficTargetStatus other) {
      if (other == com.google.cloud.run.v2.TrafficTargetStatus.getDefaultInstance()) return this;
      if (other.type_ != 0) {
        setTypeValue(other.getTypeValue());
      }
      if (!other.getRevision().isEmpty()) {
        revision_ = other.revision_;
        onChanged();
      }
      if (other.getPercent() != 0) {
        setPercent(other.getPercent());
      }
      if (!other.getTag().isEmpty()) {
        tag_ = other.tag_;
        onChanged();
      }
      if (!other.getUri().isEmpty()) {
        uri_ = other.uri_;
        onChanged();
      }
      this.mergeUnknownFields(other.unknownFields);
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      com.google.cloud.run.v2.TrafficTargetStatus parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (com.google.cloud.run.v2.TrafficTargetStatus) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private int type_ = 0;
    /**
     *
     *
     *

     * The allocation type for this traffic target.
     *

     *
     * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
     *
     * @return The enum numeric value on the wire for type.
     */
    @java.lang.Override
    public int getTypeValue() {
      return type_;
    }
    /**
     *
     *
     *

     * The allocation type for this traffic target.
     *

     *
     * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
     *
     * @param value The enum numeric value on the wire for type to set.
     * @return This builder for chaining.
     */
    public Builder setTypeValue(int value) {

      type_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * The allocation type for this traffic target.
     *

     *
     * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
     *
     * @return The type.
     */
    @java.lang.Override
    public com.google.cloud.run.v2.TrafficTargetAllocationType getType() {
      @SuppressWarnings("deprecation")
      com.google.cloud.run.v2.TrafficTargetAllocationType result =
          com.google.cloud.run.v2.TrafficTargetAllocationType.valueOf(type_);
      return result == null
          ? com.google.cloud.run.v2.TrafficTargetAllocationType.UNRECOGNIZED
          : result;
    }
    /**
     *
     *
     *

     * The allocation type for this traffic target.
     *

     *
     * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
     *
     * @param value The type to set.
     * @return This builder for chaining.
     */
    public Builder setType(com.google.cloud.run.v2.TrafficTargetAllocationType value) {
      if (value == null) {
        throw new NullPointerException();
      }

      type_ = value.getNumber();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * The allocation type for this traffic target.
     *

     *
     * .google.cloud.run.v2.TrafficTargetAllocationType type = 1;
     *
     * @return This builder for chaining.
     */
    public Builder clearType() {

      type_ = 0;
      onChanged();
      return this;
    }

    private java.lang.Object revision_ = "";
    /**
     *
     *
     *

     * Revision to which this traffic is sent.
     *

     *
     * string revision = 2 [(.google.api.resource_reference) = { ... }
     *
     * @return The revision.
     */
    public java.lang.String getRevision() {
      java.lang.Object ref = revision_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        revision_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * Revision to which this traffic is sent.
     *

     *
     * string revision = 2 [(.google.api.resource_reference) = { ... }
     *
     * @return The bytes for revision.
     */
    public com.google.protobuf.ByteString getRevisionBytes() {
      java.lang.Object ref = revision_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        revision_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * Revision to which this traffic is sent.
     *

     *
     * string revision = 2 [(.google.api.resource_reference) = { ... }
     *
     * @param value The revision to set.
     * @return This builder for chaining.
     */
    public Builder setRevision(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

      revision_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Revision to which this traffic is sent.
     *

     *
     * string revision = 2 [(.google.api.resource_reference) = { ... }
     *
     * @return This builder for chaining.
     */
    public Builder clearRevision() {

      revision_ = getDefaultInstance().getRevision();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Revision to which this traffic is sent.
     *

     *
     * string revision = 2 [(.google.api.resource_reference) = { ... }
     *
     * @param value The bytes for revision to set.
     * @return This builder for chaining.
     */
    public Builder setRevisionBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

      revision_ = value;
      onChanged();
      return this;
    }

    private int percent_;
    /**
     *
     *
     *

     * Specifies percent of the traffic to this Revision.
     *

     *
     * int32 percent = 3;
     *
     * @return The percent.
     */
    @java.lang.Override
    public int getPercent() {
      return percent_;
    }
    /**
     *
     *
     *

     * Specifies percent of the traffic to this Revision.
     *

     *
     * int32 percent = 3;
     *
     * @param value The percent to set.
     * @return This builder for chaining.
     */
    public Builder setPercent(int value) {

      percent_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Specifies percent of the traffic to this Revision.
     *

     *
     * int32 percent = 3;
     *
     * @return This builder for chaining.
     */
    public Builder clearPercent() {

      percent_ = 0;
      onChanged();
      return this;
    }

    private java.lang.Object tag_ = "";
    /**
     *
     *
     *

     * Indicates the string used in the URI to exclusively reference this target.
     *

     *
     * string tag = 4;
     *
     * @return The tag.
     */
    public java.lang.String getTag() {
      java.lang.Object ref = tag_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        tag_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * Indicates the string used in the URI to exclusively reference this target.
     *

     *
     * string tag = 4;
     *
     * @return The bytes for tag.
     */
    public com.google.protobuf.ByteString getTagBytes() {
      java.lang.Object ref = tag_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        tag_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * Indicates the string used in the URI to exclusively reference this target.
     *

     *
     * string tag = 4;
     *
     * @param value The tag to set.
     * @return This builder for chaining.
     */
    public Builder setTag(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

      tag_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Indicates the string used in the URI to exclusively reference this target.
     *

     *
     * string tag = 4;
     *
     * @return This builder for chaining.
     */
    public Builder clearTag() {

      tag_ = getDefaultInstance().getTag();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Indicates the string used in the URI to exclusively reference this target.
     *

     *
     * string tag = 4;
     *
     * @param value The bytes for tag to set.
     * @return This builder for chaining.
     */
    public Builder setTagBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

      tag_ = value;
      onChanged();
      return this;
    }

    private java.lang.Object uri_ = "";
    /**
     *
     *
     *

     * Displays the target URI.
     *

     *
     * string uri = 5;
     *
     * @return The uri.
     */
    public java.lang.String getUri() {
      java.lang.Object ref = uri_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        uri_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * Displays the target URI.
     *

     *
     * string uri = 5;
     *
     * @return The bytes for uri.
     */
    public com.google.protobuf.ByteString getUriBytes() {
      java.lang.Object ref = uri_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        uri_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * Displays the target URI.
     *

     *
     * string uri = 5;
     *
     * @param value The uri to set.
     * @return This builder for chaining.
     */
    public Builder setUri(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

      uri_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Displays the target URI.
     *

     *
     * string uri = 5;
     *
     * @return This builder for chaining.
     */
    public Builder clearUri() {

      uri_ = getDefaultInstance().getUri();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Displays the target URI.
     *

     *
     * string uri = 5;
     *
     * @param value The bytes for uri to set.
     * @return This builder for chaining.
     */
    public Builder setUriBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

      uri_ = value;
      onChanged();
      return this;
    }

    @java.lang.Override
    public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

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

    // @@protoc_insertion_point(builder_scope:google.cloud.run.v2.TrafficTargetStatus)
  }

  // @@protoc_insertion_point(class_scope:google.cloud.run.v2.TrafficTargetStatus)
  private static final com.google.cloud.run.v2.TrafficTargetStatus DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new com.google.cloud.run.v2.TrafficTargetStatus();
  }

  public static com.google.cloud.run.v2.TrafficTargetStatus getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

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

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

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

  @java.lang.Override
  public com.google.cloud.run.v2.TrafficTargetStatus getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.WebHooks;

namespace CustomReceiver.WebHooks
{
    public class CustomWebHookHandler : WebHookHandler
    {
        public CustomWebHookHandler()
        {
            this.Receiver = CustomWebHookReceiver.ReceiverName;
        }

        public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
        {
            // Get data from WebHook
            CustomNotifications data = context.GetDataOrDefault<CustomNotifications>();

            // Get data from each notification in this WebHook
            foreach (IDictionary<string, object> notification in data.Notifications)
            {
                // Process data
            }

            return Task.FromResult(true);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.workcraft.plugins.mpsat_verification.tasks;

import org.workcraft.plugins.mpsat_verification.presets.VerificationMode;
import org.workcraft.plugins.mpsat_verification.presets.VerificationParameters;
import org.workcraft.plugins.pcomp.tasks.PcompOutput;
import org.workcraft.tasks.ExportOutput;
import org.workcraft.tasks.Result;
import org.workcraft.workspace.WorkspaceEntry;

public class VerificationChainResultHandlingMonitor extends AbstractChainResultHandlingMonitor<VerificationChainOutput> {

    public VerificationChainResultHandlingMonitor(WorkspaceEntry we) {
        super(we);
    }

    @Override
    public Boolean handleSuccess(Result<? extends VerificationChainOutput> chainResult) {
        VerificationChainOutput chainOutput = chainResult.getPayload();

        Result<? extends ExportOutput> exportResult = (chainOutput == null) ? null : chainOutput.getExportResult();
        ExportOutput exportOutput = (exportResult == null) ? null : exportResult.getPayload();

        Result<? extends PcompOutput> pcompResult = (chainOutput == null) ? null : chainOutput.getPcompResult();
        PcompOutput pcompOutput = (pcompResult == null) ? null : pcompResult.getPayload();

        Result<? extends MpsatOutput> mpsatResult = (chainOutput == null) ? null : chainOutput.getMpsatResult();
        MpsatOutput mpsatOutput = (mpsatResult == null) ? null : mpsatResult.getPayload();

        VerificationParameters verificationParameters = (chainOutput == null) ? null : chainOutput.getVerificationParameters();

        String message = (chainOutput == null) ? null : chainOutput.getMessage();

        return new VerificationOutputInterpreter(getWorkspaceEntry(), exportOutput, pcompOutput,
                mpsatOutput, verificationParameters, message, isInteractive()).interpret();
    }

    @Override
    public boolean isConsistencyCheckMode(VerificationChainOutput chainOutput) {
        VerificationParameters verificationParameters = chainOutput.getVerificationParameters();
        return (verificationParameters != null)
                && (verificationParameters.getMode() == VerificationMode.STG_REACHABILITY_CONSISTENCY);
    }

    @Override
    public boolean canProcessSolution() {
        return true;
    }

    @Override
    public Result<? extends MpsatOutput> getFailedMpsatResult(VerificationChainOutput chainOutput) {
        Result<? extends MpsatOutput> mpsatResult = (chainOutput == null) ? null : chainOutput.getMpsatResult();
        if ((mpsatResult != null) && (mpsatResult.isFailure())) {
            return mpsatResult;
        }
        return null;
    }

}


text:
using System;
#if UNIVERSAL
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
#else
using System.Windows;
using System.Windows.Media;
#endif

namespace Newport
{
  public class CountToVisibilityConverter : BaseConverter
  {
    public bool Invert { get; set; }

    protected override object OnConvert(object value)
    {
      var booleanValue = ((int)value > 0);
      if (Invert)
      {
        booleanValue = !booleanValue;
      }
      return booleanValue ? Visibility.Visible : Visibility.Collapsed;
    }

    protected override object OnConvertBack(object value)
    {
      throw new NotImplementedException();
    }
  }
}


text:
package mcjty.rftools.blocks.teleporter;

import mcjty.lib.base.StyleConfig;
import mcjty.lib.container.EmptyContainer;
import mcjty.lib.gui.GenericGuiContainer;
import mcjty.lib.tileentity.GenericEnergyStorageTileEntity;
import mcjty.lib.gui.Window;
import mcjty.lib.gui.layout.HorizontalAlignment;
import mcjty.lib.gui.layout.HorizontalLayout;
import mcjty.lib.gui.layout.VerticalLayout;
import mcjty.lib.gui.widgets.Button;
import mcjty.lib.gui.widgets.*;
import mcjty.lib.gui.widgets.Label;
import mcjty.lib.gui.widgets.Panel;
import mcjty.lib.gui.widgets.TextField;
import mcjty.lib.typed.TypedMap;
import mcjty.rftools.RFTools;
import mcjty.rftools.setup.GuiProxy;
import mcjty.rftools.network.PacketGetPlayers;
import mcjty.rftools.network.RFToolsMessages;
import org.lwjgl.input.Keyboard;

import java.awt.*;
import java.util.*;
import java.util.List;

import static mcjty.rftools.blocks.teleporter.MatterTransmitterTileEntity.PARAM_PLAYER;

public class GuiMatterTransmitter extends GenericGuiContainer<MatterTransmitterTileEntity> {
    public static final int MATTER_WIDTH = 180;
    public static final int MATTER_HEIGHT = 160;
    public static final String ACCESS_PRIVATE = "Private";
    public static final String ACCESS_PUBLIC = "Public";

    private EnergyBar energyBar;
    private ChoiceLabel privateSetting;
    private WidgetList allowedPlayers;
    private Button addButton;
    private Button delButton;
    private TextField nameField;

    // A copy of the players we're currently showing.
    private List<String> players = null;
    private int listDirty = 0;

    private static Set<String> fromServer_allowedPlayers = new HashSet<>();
    public static void storeAllowedPlayersForClient(List<String> players) {
        fromServer_allowedPlayers = new HashSet<>(players);
    }

    public GuiMatterTransmitter(MatterTransmitterTileEntity transmitterTileEntity, EmptyContainer container) {
        super(RFTools.instance, RFToolsMessages.INSTANCE, transmitterTileEntity, container, GuiProxy.GUI_MANUAL_MAIN, "tptransmitter");
        GenericEnergyStorageTileEntity.setCurrentRF(transmitterTileEntity.getStoredPower());

        xSize = MATTER_WIDTH;
        ySize = MATTER_HEIGHT;
    }

    @Override
    public boolean doesGuiPauseGame() {
        return false;
    }

    @Override
    public void initGui() {
        super.initGui();

        long maxEnergyStored = tileEntity.getCapacity();
        energyBar = new EnergyBar(mc, this).setFilledRectThickness(1).setHorizontal().setDesiredHeight(12).setDesiredWidth(80).setMaxValue(maxEnergyStored).setShowText(false);
        energyBar.setValue(GenericEnergyStorageTileEntity.getCurrentRF());

        TextField textField = new TextField(mc, this)
                .setName("name")
                .setTooltips("Use this name to", "identify this transmitter", "in the dialer");
        Panel namePanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(new Label(mc, this).setText("Name:")).addChild(textField).setDesiredHeight(16);

        privateSetting = new ChoiceLabel(mc, this)
                .setName("private")
                .addChoices(ACCESS_PUBLIC, ACCESS_PRIVATE).setDesiredHeight(14).setDesiredWidth(60).
            setChoiceTooltip(ACCESS_PUBLIC, "Everyone can access this transmitter", "and change the dialing destination").
            setChoiceTooltip(ACCESS_PRIVATE, "Only people in the access list below", "can access this transmitter");
        ToggleButton beamToggle = new ToggleButton(mc, this)
                .setName("beam")
                .setText("Hide").setCheckMarker(true).setDesiredHeight(14).setDesiredWidth(49).setTooltips("Hide the teleportation beam");
        Panel privatePanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(new Label(mc, this).setText("Access:")).addChild(privateSetting).addChild(beamToggle).setDesiredHeight(16);

        allowedPlayers = new WidgetList(mc, this).setName("allowedplayers");
        Slider allowedPlayerSlider = new Slider(mc, this).setDesiredWidth(10).setVertical().setScrollableName("allowedplayers");
        Panel allowedPlayersPanel = new Panel(mc, this).setLayout(new HorizontalLayout().setHorizontalMargin(3).setSpacing(1)).addChild(allowedPlayers).addChild(allowedPlayerSlider)
                .setFilledBackground(0xff9e9e9e);

        nameField = new TextField(mc, this);
        addButton = new Button(mc, this).setChannel("addplayer").setText("Add").setDesiredHeight(13).setDesiredWidth(34).setTooltips("Add a player to the access list");
        delButton = new Button(mc, this).setChannel("delplayer").setText("Del").setDesiredHeight(13).setDesiredWidth(34).setTooltips("Remove the selected player", "from the access list");
        Panel buttonPanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(nameField).addChild(addButton).addChild(delButton).setDesiredHeight(16);

        Panel toplevel = new Panel(mc, this).setFilledRectThickness(2).setLayout(new VerticalLayout().setHorizontalMargin(3).setVerticalMargin(3).setSpacing(1)).
                addChildren(energyBar, namePanel, privatePanel, allowedPlayersPanel, buttonPanel);
        toplevel.setBounds(new Rectangle(guiLeft, guiTop, MATTER_WIDTH, MATTER_HEIGHT));
        window = new Window(this, toplevel);
        Keyboard.enableRepeatEvents(true);

        listDirty = 0;
        requestPlayers();
        tileEntity.requestRfFromServer(RFTools.MODID);

        window.bind(RFToolsMessages.INSTANCE, "name", tileEntity, MatterTransmitterTileEntity.VALUE_NAME.getName());
        window.bind(RFToolsMessages.INSTANCE, "private", tileEntity, MatterTransmitterTileEntity.VALUE_PRIVATE.getName());
        window.bind(RFToolsMessages.INSTANCE, "beam", tileEntity, MatterTransmitterTileEntity.VALUE_BEAM.getName());
        window.event("addplayer", (source, params) -> addPlayer());
        window.event("delplayer", (source, params) -> delPlayer());
    }

    private void addPlayer() {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterTransmitterTileEntity.CMD_ADDPLAYER,
                TypedMap.builder()
                        .put(PARAM_PLAYER, nameField.getText())
                        .build());
        listDirty = 0;
    }

    private void delPlayer() {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterTransmitterTileEntity.CMD_DELPLAYER,
                TypedMap.builder()
                        .put(PARAM_PLAYER, nameField.getText())
                        .build());
        listDirty = 0;
    }

    private void requestPlayers() {
        RFToolsMessages.INSTANCE.sendToServer(new PacketGetPlayers(tileEntity.getPos(), MatterTransmitterTileEntity.CMD_GETPLAYERS, MatterTransmitterTileEntity.CLIENTCMD_GETPLAYERS));
    }

    private void populatePlayers() {
        List<String> newPlayers = new ArrayList<>(fromServer_allowedPlayers);
        Collections.sort(newPlayers);
        if (newPlayers.equals(players)) {
            return;
        }

        players = new ArrayList<>(newPlayers);
        allowedPlayers.removeChildren();
        for (String player : players) {
            allowedPlayers.addChild(new Label(mc, this).setColor(StyleConfig.colorTextInListNormal).setText(player).setHorizontalAlignment(HorizontalAlignment.ALIGN_LEFT));
        }
    }

    private void requestListsIfNeeded() {
        listDirty--;
        if (listDirty <= 0) {
            requestPlayers();
            listDirty = 20;
        }
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) {
        requestListsIfNeeded();
        populatePlayers();
        enableButtons();

        drawWindow();
        long currentRF = GenericEnergyStorageTileEntity.getCurrentRF();
        energyBar.setValue(currentRF);
        tileEntity.requestRfFromServer(RFTools.MODID);
    }

    private void enableButtons() {
        boolean isPrivate = ACCESS_PRIVATE.equals(privateSetting.getCurrentChoice());
        allowedPlayers.setEnabled(isPrivate);
        nameField.setEnabled(isPrivate);

        int isPlayerSelected = allowedPlayers.getSelected();
        delButton.setEnabled(isPrivate && (isPlayerSelected != -1));
        String name = nameField.getText();
        addButton.setEnabled(isPrivate && name != null && !name.isEmpty());
    }
}


text:
<?php

// autoload_classmap.php generated by Composer

$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);

return array(
    'BaseFacebook' => $baseDir . '/vendor/facebook/php-sdk/src/base_facebook.php',
    'Facebook' => $baseDir . '/vendor/facebook/php-sdk/src/facebook.php',
    'FacebookApiException' => $baseDir . '/vendor/facebook/php-sdk/src/base_facebook.php',
    'OAuthConsumer' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthDataStore' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthException' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthRequest' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthServer' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthSignatureMethod' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthSignatureMethod_HMAC_SHA1' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthSignatureMethod_PLAINTEXT' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthSignatureMethod_RSA_SHA1' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthToken' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'OAuthUtil' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/OAuth.php',
    'TwitterOAuth' => $baseDir . '/vendor/kertz/twitteroauth/twitteroauth/twitteroauth.php',
);


text:
import {MapvDataSet} from '../../../../src/mapboxgl/overlay/mapv/MapvDataSet'

describe('mapboxgl_MapvDataSet', () => {
    it('getPoint', () => {
        var point = [106.540545, 29.531714];
        var mapvDataSets = MapvDataSet;
        var dataset = mapvDataSets.getPoint(point);
        expect(dataset).not.toBeNull();
        expect(dataset._data.length).toEqual(1);
        var data = dataset._data[0];
        expect(data.geometry.type).toEqual("Point");
        expect(data.geometry.coordinates.length).toEqual(2);
        expect(data.geometry.coordinates[0]).toEqual(106.540545);
        expect(data.geometry.coordinates[1]).toEqual(29.531714);
        data = null;
    });

    it('getPoints', () => {
        var points = [{
            "geometry": {
                "type": "Point",
                "coordinates": [106.63530472117604, 29.492206977571094]
            }
        }, {
            "geometry": {
                "type": "Point",
                "coordinates": [106.63530472117604, 29.492206977571094]
            }
        }];
        var mapvDataSets = MapvDataSet;
        var dataset = mapvDataSets.getPoints(points);
        expect(dataset).not.toBeNull();
        expect(dataset._data.length).toEqual(2);
        expect(dataset._data[0].geometry.type).toEqual('Point');
        expect(dataset._data[0].geometry.coordinates.length).toEqual(2);
        expect(dataset._data[0].geometry.coordinates[0]).toEqual(106.63530472117604);
        expect(dataset._data[0].geometry.coordinates[1]).toEqual(29.492206977571094);
        expect(dataset._data[1].geometry.type).toEqual('Point');
        expect(dataset._data[1].geometry.coordinates.length).toEqual(2);
        expect(dataset._data[1].geometry.coordinates[0]).toEqual(106.63530472117604);
        expect(dataset._data[1].geometry.coordinates[1]).toEqual(29.492206977571094);
    });

    it('getCurveLines', () => {
        var startPoint = [10, 20];
        var linePoints = [{
            "geometry": {
                "type": "Point",
                "coordinates": [100, 30]
            }
        }, {
            "geometry": {
                "type": "Point",
                "coordinates": [101, 29]
            }
        }];
        var mapvDataSets = MapvDataSet;
        var dataset = mapvDataSets.getCurveLines(startPoint, linePoints);
        expect(dataset).not.toBeNull();
        expect(dataset._data.length).toEqual(2);
        for (var i = 0; i < dataset._data.length; i++) {
            expect(dataset._data[i].geometry.type).toEqual("LineString");
            expect(dataset._data[i].geometry.coordinates.length).toEqual(41);
            var coordinates = dataset._data[i].geometry.coordinates;
            for (var j = 0; j < coordinates.length; j++) {
                expect(coordinates[j].length).toEqual(2);
            }
        }
    });

    it('getCurveDynamicPoints', () => {
        var point = [10, 20];
        var endPoints = [{
            "geometry": {
                "type": "Point",
                "coordinates": [100, 30]
            }
        }, {
            "geometry": {
                "type": "Point",
                "coordinates": [101, 29]
            }
        }];
        var mapvDataSets = MapvDataSet;
        var dataset = mapvDataSets.getCurveDynamicPoints(point, endPoints);
        expect(dataset).not.toBeNull();
        expect(dataset._data.length).toBeGreaterThan(0);
        for (var i = 0; i < dataset._data.length; i++) {
            expect(dataset._data[i].time).toBeGreaterThanOrEqual(0);
            expect(dataset._data[i].geometry.type).toEqual("Point");
            expect(dataset._data[i].geometry.coordinates.length).toEqual(2);
        }

    })
});


text:
package org.apache.phoenix.filter;

import org.apache.hadoop.hbase.util.Bytes;

import org.apache.phoenix.expression.Expression;

/**
 *
 * SingleKeyValueComparisonFilter that needs to compare both the column family and
 * column qualifier parts of the key value to disambiguate with another similarly
 * named column qualifier in a different column family.
 *
 *
 * @since 0.1
 */
public class SingleCFCQKeyValueComparisonFilter extends SingleKeyValueComparisonFilter {
    public SingleCFCQKeyValueComparisonFilter() {
    }

    public SingleCFCQKeyValueComparisonFilter(Expression expression) {
        super(expression);
    }

    @Override
    protected final int compare(byte[] cfBuf, int cfOffset, int cfLength, byte[] cqBuf, int cqOffset, int cqLength) {
        int c = Bytes.compareTo(cf, 0, cf.length, cfBuf, cfOffset, cfLength);
        if (c != 0) return c;
        return Bytes.compareTo(cq, 0, cq.length, cqBuf, cqOffset, cqLength);
    }

}


text:
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:bk2k="http://typo3.org/ns/BK2K/BootstrapPackage/ViewHelpers" data-namespace-typo3-fluid="true">
<picture>
    <f:for each="{variants}" key="name" as="variant">
        <f:variable name="breakpoint">{variant.breakpoint as integer}</f:variable>
        <f:variable name="width">{variant.width as integer}</f:variable>
        <f:variable name="height" value="" />
        <f:if condition="{width}">
            <f:if condition="{variant.aspectRatio}">
                <f:variable name="aspectRatio">{variant.aspectRatio as float}</f:variable>
                <f:variable name="height">{width / aspectRatio}</f:variable>
                <f:variable name="height">{height as integer}</f:variable>
            </f:if>
            <f:variable name="mediaQuery">{f:if(condition: breakpoint, then: 'media="(min-width: {breakpoint}px)"')}</f:variable>
            <f:if condition="{variant.sizes}">
                <f:variable name="srcset" value="" />
                <f:for each="{variant.sizes}" key="sizeKey" as="sizeConfig" iteration="iteration">
                    <f:variable name="sizeWidth">{sizeConfig.multiplier as float}</f:variable>
                    <f:variable name="sizeWidth">{sizeWidth * width}</f:variable>
                    <f:variable name="sizeHeight" value="" />
                    <f:if condition="{height}">
                        <f:then>
                            <f:variable name="sizeHeight">{sizeConfig.multiplier as float}</f:variable>
                            <f:variable name="sizeHeight">{sizeHeight * height}</f:variable>
                            <f:variable name="sizeUrl">{f:uri.image(image: file, cropVariant: name, width: '{sizeWidth}c', height: '{sizeHeight}c')}</f:variable>
                        </f:then>
                        <f:else>
                            <f:variable name="sizeUrl">{f:uri.image(image: file, cropVariant: name, maxWidth: sizeWidth)}</f:variable>
                        </f:else>
                    </f:if>
                    <f:variable name="srcset">{srcset}{sizeUrl} {sizeKey}{f:if(condition: iteration.isLast, else: ',')}</f:variable>
                </f:for>
            </f:if>
            <source data-variant="{name}" {f:if(condition: sizeHeight, then: 'data-width="{width}" data-height="{sizeHeight}"', else: 'data-maxwidth="{width}"')} {mediaQuery->f:format.raw()} srcset="{srcset}">
        </f:if>
    </f:for>
    <f:variable name="defaultWidth" value="{variants.default.width}" />
    <f:variable name="defaultAspectRatio" value="{variants.default.aspectRatio}" />
    <f:if condition="{defaultAspectRatio}">
        <f:variable name="aspectRatio">{defaultAspectRatio as float}</f:variable>
        <f:variable name="defaultHeight">{defaultWidth / aspectRatio}</f:variable>
        <f:variable name="defaultHeight">{defaultHeight as integer}c</f:variable>
    </f:if>
    <f:if condition="{defaultHeight}">
        <f:then>
            <f:variable name="src" value="{f:uri.image(image: file, cropVariant: 'default', width: defaultWidth, height: defaultHeight)}" />
        </f:then>
        <f:else>
            <f:variable name="src" value="{f:uri.image(image: file, cropVariant: 'default', width: defaultWidth)}" />
        </f:else>
    </f:if>
    <f:variable name="finalWidth" value="{bk2k:data.imageInfo(src: src, property: 'width')}" />
    <f:variable name="finalHeight" value="{bk2k:data.imageInfo(src: src, property: 'height')}" />
    <img loading="lazy" src="{src}" width="{finalWidth}" height="{finalHeight}" intrinsicsize="{finalWidth}x{finalHeight}" title="{file.properties.title}" alt="{file.properties.alternative}">
</picture>
</html>


text:
class AddRateToClients < ActiveRecord::Migration
  def change
    add_column :clients, :rate_cents, :integer, after: :name
  end
end


text: affdex::Path validatePath(affdex::Path path, const std::string& env_variable = "");


text:
package org.apache.druid.sql.calcite.schema;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.inject.Inject;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.AbstractSchema;
import org.apache.druid.client.ServerView;
import org.apache.druid.client.TimelineServerView;
import org.apache.druid.guice.ManageLifecycle;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Yielder;
import org.apache.druid.java.util.common.guava.Yielders;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.query.GlobalTableDataSource;
import org.apache.druid.query.TableDataSource;
import org.apache.druid.query.metadata.metadata.AllColumnIncluderator;
import org.apache.druid.query.metadata.metadata.ColumnAnalysis;
import org.apache.druid.query.metadata.metadata.SegmentAnalysis;
import org.apache.druid.query.metadata.metadata.SegmentMetadataQuery;
import org.apache.druid.query.spec.MultipleSpecificSegmentSpec;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.join.JoinableFactory;
import org.apache.druid.server.QueryLifecycleFactory;
import org.apache.druid.server.SegmentManager;
import org.apache.druid.server.coordination.DruidServerMetadata;
import org.apache.druid.server.coordination.ServerType;
import org.apache.druid.server.security.Access;
import org.apache.druid.server.security.AuthenticationResult;
import org.apache.druid.server.security.Escalator;
import org.apache.druid.sql.calcite.planner.PlannerConfig;
import org.apache.druid.sql.calcite.table.DruidTable;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;

import java.io.IOException;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@ManageLifecycle
public class DruidSchema extends AbstractSchema
{
  // Newest segments first, so they override older ones.
  private static final Comparator<SegmentId> SEGMENT_ORDER = Comparator
      .comparing((SegmentId segmentId) -> segmentId.getInterval().getStart())
      .reversed()
      .thenComparing(Function.identity());

  private static final EmittingLogger log = new EmittingLogger(DruidSchema.class);
  private static final int MAX_SEGMENTS_PER_QUERY = 15000;
  private static final long DEFAULT_NUM_ROWS = 0;

  private final QueryLifecycleFactory queryLifecycleFactory;
  private final PlannerConfig config;
  private final SegmentManager segmentManager;
  private final JoinableFactory joinableFactory;
  private final ExecutorService cacheExec;
  private final ConcurrentMap<String, DruidTable> tables;

  // For awaitInitialization.
  private final CountDownLatch initialized = new CountDownLatch(1);

  // Protects access to segmentSignatures, mutableSegments, segmentsNeedingRefresh, lastRefresh, isServerViewInitialized, segmentMetadata
  private final Object lock = new Object();

  // DataSource -> Segment -> AvailableSegmentMetadata(contains RowSignature) for that segment.
  // Use TreeMap for segments so they are merged in deterministic order, from older to newer.
  @GuardedBy("lock")
  private final Map<String, TreeMap<SegmentId, AvailableSegmentMetadata>> segmentMetadataInfo = new HashMap<>();
  private int totalSegments = 0;

  // All mutable segments.
  @GuardedBy("lock")
  private final Set<SegmentId> mutableSegments = new TreeSet<>(SEGMENT_ORDER);

  // All dataSources that need tables regenerated.
  @GuardedBy("lock")
  private final Set<String> dataSourcesNeedingRebuild = new HashSet<>();

  // All segments that need to be refreshed.
  @GuardedBy("lock")
  private final TreeSet<SegmentId> segmentsNeedingRefresh = new TreeSet<>(SEGMENT_ORDER);

  // Escalator, so we can attach an authentication result to queries we generate.
  private final Escalator escalator;

  @GuardedBy("lock")
  private boolean refreshImmediately = false;
  @GuardedBy("lock")
  private long lastRefresh = 0L;
  @GuardedBy("lock")
  private long lastFailure = 0L;
  @GuardedBy("lock")
  private boolean isServerViewInitialized = false;

  @Inject
  public DruidSchema(
      final QueryLifecycleFactory queryLifecycleFactory,
      final TimelineServerView serverView,
      final SegmentManager segmentManager,
      final JoinableFactory joinableFactory,
      final PlannerConfig config,
      final Escalator escalator
  )
  {
    this.queryLifecycleFactory = Preconditions.checkNotNull(queryLifecycleFactory, "queryLifecycleFactory");
    Preconditions.checkNotNull(serverView, "serverView");
    this.segmentManager = segmentManager;
    this.joinableFactory = joinableFactory;
    this.config = Preconditions.checkNotNull(config, "config");
    this.cacheExec = Execs.singleThreaded("DruidSchema-Cache-%d");
    this.tables = new ConcurrentHashMap<>();
    this.escalator = escalator;

    serverView.registerTimelineCallback(
        Execs.directExecutor(),
        new TimelineServerView.TimelineCallback()
        {
          @Override
          public ServerView.CallbackAction timelineInitialized()
          {
            synchronized (lock) {
              isServerViewInitialized = true;
              lock.notifyAll();
            }

            return ServerView.CallbackAction.CONTINUE;
          }

          @Override
          public ServerView.CallbackAction segmentAdded(final DruidServerMetadata server, final DataSegment segment)
          {
            addSegment(server, segment);
            return ServerView.CallbackAction.CONTINUE;
          }

          @Override
          public ServerView.CallbackAction segmentRemoved(final DataSegment segment)
          {
            removeSegment(segment);
            return ServerView.CallbackAction.CONTINUE;
          }

          @Override
          public ServerView.CallbackAction serverSegmentRemoved(
              final DruidServerMetadata server,
              final DataSegment segment
          )
          {
            removeServerSegment(server, segment);
            return ServerView.CallbackAction.CONTINUE;
          }
        }
    );
  }

  @LifecycleStart
  public void start() throws InterruptedException
  {
    cacheExec.submit(
        () -> {
          try {
            while (!Thread.currentThread().isInterrupted()) {
              final Set<SegmentId> segmentsToRefresh = new TreeSet<>();
              final Set<String> dataSourcesToRebuild = new TreeSet<>();

              try {
                synchronized (lock) {
                  final long nextRefreshNoFuzz = DateTimes
                      .utc(lastRefresh)
                      .plus(config.getMetadataRefreshPeriod())
                      .getMillis();

                  // Fuzz a bit to spread load out when we have multiple brokers.
                  final long nextRefresh = nextRefreshNoFuzz + (long) ((nextRefreshNoFuzz - lastRefresh) * 0.10);

                  while (true) {
                    // Do not refresh if it's too soon after a failure (to avoid rapid cycles of failure).
                    final boolean wasRecentFailure = DateTimes.utc(lastFailure)
                                                              .plus(config.getMetadataRefreshPeriod())
                                                              .isAfterNow();

                    if (isServerViewInitialized &&
                        !wasRecentFailure &&
                        (!segmentsNeedingRefresh.isEmpty() || !dataSourcesNeedingRebuild.isEmpty()) &&
                        (refreshImmediately || nextRefresh < System.currentTimeMillis())) {
                      // We need to do a refresh. Break out of the waiting loop.
                      break;
                    }

                    // lastFailure != 0L means exceptions happened before and there're some refresh work was not completed.
                    // so that even ServerView is initialized, we can't let broker complete initialization.
                    if (isServerViewInitialized && lastFailure == 0L) {
                      // Server view is initialized, but we don't need to do a refresh. Could happen if there are
                      // no segments in the system yet. Just mark us as initialized, then.
                      initialized.countDown();
                    }

                    // Wait some more, we'll wake up when it might be time to do another refresh.
                    lock.wait(Math.max(1, nextRefresh - System.currentTimeMillis()));
                  }

                  segmentsToRefresh.addAll(segmentsNeedingRefresh);
                  segmentsNeedingRefresh.clear();

                  // Mutable segments need a refresh every period, since new columns could be added dynamically.
                  segmentsNeedingRefresh.addAll(mutableSegments);

                  lastFailure = 0L;
                  lastRefresh = System.currentTimeMillis();
                  refreshImmediately = false;
                }

                // Refresh the segments.
                final Set<SegmentId> refreshed = refreshSegments(segmentsToRefresh);

                synchronized (lock) {
                  // Add missing segments back to the refresh list.
                  segmentsNeedingRefresh.addAll(Sets.difference(segmentsToRefresh, refreshed));

                  // Compute the list of dataSources to rebuild tables for.
                  dataSourcesToRebuild.addAll(dataSourcesNeedingRebuild);
                  refreshed.forEach(segment -> dataSourcesToRebuild.add(segment.getDataSource()));
                  dataSourcesNeedingRebuild.clear();

                  lock.notifyAll();
                }

                // Rebuild the dataSources.
                for (String dataSource : dataSourcesToRebuild) {
                  final DruidTable druidTable = buildDruidTable(dataSource);
                  final DruidTable oldTable = tables.put(dataSource, druidTable);
                  final String description = druidTable.getDataSource().isGlobal() ? "global dataSource" : "dataSource";
                  if (oldTable == null || !oldTable.getRowSignature().equals(druidTable.getRowSignature())) {
                    log.info("%s [%s] has new signature: %s.", description, dataSource, druidTable.getRowSignature());
                  } else {
                    log.debug("%s [%s] signature is unchanged.", description, dataSource);
                  }
                }

                initialized.countDown();
              }
              catch (InterruptedException e) {
                // Fall through.
                throw e;
              }
              catch (Exception e) {
                log.warn(e, "Metadata refresh failed, trying again soon.");

                synchronized (lock) {
                  // Add our segments and dataSources back to their refresh and rebuild lists.
                  segmentsNeedingRefresh.addAll(segmentsToRefresh);
                  dataSourcesNeedingRebuild.addAll(dataSourcesToRebuild);
                  lastFailure = System.currentTimeMillis();
                  lock.notifyAll();
                }
              }
            }
          }
          catch (InterruptedException e) {
            // Just exit.
          }
          catch (Throwable e) {
            // Throwables that fall out to here (not caught by an inner try/catch) are potentially gnarly, like
            // OOMEs. Anyway, let's just emit an alert and stop refreshing metadata.
            log.makeAlert(e, "Metadata refresh failed permanently").emit();
            throw e;
          }
          finally {
            log.info("Metadata refresh stopped.");
          }
        }
    );

    if (config.isAwaitInitializationOnStart()) {
      final long startNanos = System.nanoTime();
      log.debug("%s waiting for initialization.", getClass().getSimpleName());
      awaitInitialization();
      log.info("%s initialized in [%,d] ms.", getClass().getSimpleName(), (System.nanoTime() - startNanos) / 1000000);
    }
  }

  @LifecycleStop
  public void stop()
  {
    cacheExec.shutdownNow();
  }

  public void awaitInitialization() throws InterruptedException
  {
    initialized.await();
  }

  @Override
  protected Map<String, Table> getTableMap()
  {
    return ImmutableMap.copyOf(tables);
  }

  @VisibleForTesting
  void addSegment(final DruidServerMetadata server, final DataSegment segment)
  {
    synchronized (lock) {
      // someday we could hypothetically remove broker special casing, whenever BrokerServerView supports tracking
      // broker served segments in the timeline, to ensure that removeSegment the event is triggered accurately
      if (server.getType().equals(ServerType.BROKER)) {
        // a segment on a broker means a broadcast datasource, skip metadata because we'll also see this segment on the
        // historical, however mark the datasource for refresh because it needs to be globalized
        dataSourcesNeedingRebuild.add(segment.getDataSource());
      } else {
        final Map<SegmentId, AvailableSegmentMetadata> knownSegments = segmentMetadataInfo.get(segment.getDataSource());
        AvailableSegmentMetadata segmentMetadata = knownSegments != null ? knownSegments.get(segment.getId()) : null;
        if (segmentMetadata == null) {
          // segmentReplicatable is used to determine if segments are served by historical or realtime servers
          long isRealtime = server.isSegmentReplicationTarget() ? 0 : 1;
          segmentMetadata = AvailableSegmentMetadata.builder(
              segment,
              isRealtime,
              ImmutableSet.of(server),
              null,
              DEFAULT_NUM_ROWS
          ).build();
          // Unknown segment.
          setAvailableSegmentMetadata(segment.getId(), segmentMetadata);
          segmentsNeedingRefresh.add(segment.getId());
          if (!server.isSegmentReplicationTarget()) {
            log.debug("Added new mutable segment[%s].", segment.getId());
            mutableSegments.add(segment.getId());
          } else {
            log.debug("Added new immutable segment[%s].", segment.getId());
          }
        } else {
          final Set<DruidServerMetadata> segmentServers = segmentMetadata.getReplicas();
          final ImmutableSet<DruidServerMetadata> servers = new ImmutableSet.Builder<DruidServerMetadata>()
              .addAll(segmentServers)
              .add(server)
              .build();
          final AvailableSegmentMetadata metadataWithNumReplicas = AvailableSegmentMetadata
              .from(segmentMetadata)
              .withReplicas(servers)
              .withRealtime(recomputeIsRealtime(servers))
              .build();
          knownSegments.put(segment.getId(), metadataWithNumReplicas);
          if (server.isSegmentReplicationTarget()) {
            // If a segment shows up on a replicatable (historical) server at any point, then it must be immutable,
            // even if it's also available on non-replicatable (realtime) servers.
            mutableSegments.remove(segment.getId());
            log.debug("Segment[%s] has become immutable.", segment.getId());
          }
        }
      }
      if (!tables.containsKey(segment.getDataSource())) {
        refreshImmediately = true;
      }

      lock.notifyAll();
    }
  }

  @VisibleForTesting
  void removeSegment(final DataSegment segment)
  {
    synchronized (lock) {
      log.debug("Segment[%s] is gone.", segment.getId());

      segmentsNeedingRefresh.remove(segment.getId());
      mutableSegments.remove(segment.getId());

      final Map<SegmentId, AvailableSegmentMetadata> dataSourceSegments =
          segmentMetadataInfo.get(segment.getDataSource());
      if (dataSourceSegments.remove(segment.getId()) != null) {
        totalSegments--;
      }

      if (dataSourceSegments.isEmpty()) {
        segmentMetadataInfo.remove(segment.getDataSource());
        tables.remove(segment.getDataSource());
        log.info("dataSource[%s] no longer exists, all metadata removed.", segment.getDataSource());
      } else {
        dataSourcesNeedingRebuild.add(segment.getDataSource());
      }

      lock.notifyAll();
    }
  }

  @VisibleForTesting
  void removeServerSegment(final DruidServerMetadata server, final DataSegment segment)
  {
    synchronized (lock) {
      log.debug("Segment[%s] is gone from server[%s]", segment.getId(), server.getName());
      final Map<SegmentId, AvailableSegmentMetadata> knownSegments = segmentMetadataInfo.get(segment.getDataSource());

      // someday we could hypothetically remove broker special casing, whenever BrokerServerView supports tracking
      // broker served segments in the timeline, to ensure that removeSegment the event is triggered accurately
      if (server.getType().equals(ServerType.BROKER)) {
        // for brokers, if the segment drops from all historicals before the broker this could be null.
        if (knownSegments != null && !knownSegments.isEmpty()) {
          // a segment on a broker means a broadcast datasource, skip metadata because we'll also see this segment on the
          // historical, however mark the datasource for refresh because it might no longer be broadcast or something
          dataSourcesNeedingRebuild.add(segment.getDataSource());
        }
      } else {
        final AvailableSegmentMetadata segmentMetadata = knownSegments.get(segment.getId());
        final Set<DruidServerMetadata> segmentServers = segmentMetadata.getReplicas();
        final ImmutableSet<DruidServerMetadata> servers = FluentIterable
            .from(segmentServers)
            .filter(Predicates.not(Predicates.equalTo(server)))
            .toSet();

        final AvailableSegmentMetadata metadataWithNumReplicas = AvailableSegmentMetadata
            .from(segmentMetadata)
            .withReplicas(servers)
            .withRealtime(recomputeIsRealtime(servers))
            .build();
        knownSegments.put(segment.getId(), metadataWithNumReplicas);
      }
      lock.notifyAll();
    }
  }

  /**
   * Attempt to refresh "segmentSignatures" for a set of segments. Returns the set of segments actually refreshed,
   * which may be a subset of the asked-for set.
   */
  @VisibleForTesting
  Set<SegmentId> refreshSegments(final Set<SegmentId> segments) throws IOException
  {
    final Set<SegmentId> retVal = new HashSet<>();

    // Organize segments by dataSource.
    final Map<String, TreeSet<SegmentId>> segmentMap = new TreeMap<>();

    for (SegmentId segmentId : segments) {
      segmentMap.computeIfAbsent(segmentId.getDataSource(), x -> new TreeSet<>(SEGMENT_ORDER))
                .add(segmentId);
    }

    for (Map.Entry<String, TreeSet<SegmentId>> entry : segmentMap.entrySet()) {
      final String dataSource = entry.getKey();
      retVal.addAll(refreshSegmentsForDataSource(dataSource, entry.getValue()));
    }

    return retVal;
  }

  private long recomputeIsRealtime(ImmutableSet<DruidServerMetadata> servers)
  {
    final Optional<DruidServerMetadata> historicalServer = servers
        .stream()
        .filter(metadata -> metadata.getType().equals(ServerType.HISTORICAL))
        .findAny();

    // if there is any historical server in the replicas, isRealtime flag should be unset
    final long isRealtime = historicalServer.isPresent() ? 0 : 1;
    return isRealtime;
  }

  /**
   * Attempt to refresh "segmentSignatures" for a set of segments for a particular dataSource. Returns the set of
   * segments actually refreshed, which may be a subset of the asked-for set.
   */
  private Set<SegmentId> refreshSegmentsForDataSource(final String dataSource, final Set<SegmentId> segments)
      throws IOException
  {
    if (!segments.stream().allMatch(segmentId -> segmentId.getDataSource().equals(dataSource))) {
      // Sanity check. We definitely expect this to pass.
      throw new ISE("'segments' must all match 'dataSource'!");
    }

    log.debug("Refreshing metadata for dataSource[%s].", dataSource);

    final long startTime = System.currentTimeMillis();

    // Segment id string -> SegmentId object.
    final Map<String, SegmentId> segmentIdMap = Maps.uniqueIndex(segments, SegmentId::toString);

    final Set<SegmentId> retVal = new HashSet<>();
    final Sequence<SegmentAnalysis> sequence = runSegmentMetadataQuery(
        queryLifecycleFactory,
        Iterables.limit(segments, MAX_SEGMENTS_PER_QUERY),
        escalator.createEscalatedAuthenticationResult()
    );

    Yielder<SegmentAnalysis> yielder = Yielders.each(sequence);

    try {
      while (!yielder.isDone()) {
        final SegmentAnalysis analysis = yielder.get();
        final SegmentId segmentId = segmentIdMap.get(analysis.getId());

        if (segmentId == null) {
          log.warn("Got analysis for segment[%s] we didn't ask for, ignoring.", analysis.getId());
        } else {
          synchronized (lock) {
            final RowSignature rowSignature = analysisToRowSignature(analysis);
            log.debug("Segment[%s] has signature[%s].", segmentId, rowSignature);
            final Map<SegmentId, AvailableSegmentMetadata> dataSourceSegments = segmentMetadataInfo.get(dataSource);
            if (dataSourceSegments == null) {
              // Datasource may have been removed or become unavailable while this refresh was ongoing.
              log.warn(
                  "No segment map found with datasource[%s], skipping refresh of segment[%s]",
                  dataSource,
                  segmentId
              );
            } else {
              final AvailableSegmentMetadata segmentMetadata = dataSourceSegments.get(segmentId);
              if (segmentMetadata == null) {
                log.warn("No segment[%s] found, skipping refresh", segmentId);
              } else {
                final AvailableSegmentMetadata updatedSegmentMetadata = AvailableSegmentMetadata
                    .from(segmentMetadata)
                    .withRowSignature(rowSignature)
                    .withNumRows(analysis.getNumRows())
                    .build();
                dataSourceSegments.put(segmentId, updatedSegmentMetadata);
                setAvailableSegmentMetadata(segmentId, updatedSegmentMetadata);
                retVal.add(segmentId);
              }
            }
          }
        }

        yielder = yielder.next(null);
      }
    }
    finally {
      yielder.close();
    }

    log.debug(
        "Refreshed metadata for dataSource[%s] in %,d ms (%d segments queried, %d segments left).",
        dataSource,
        System.currentTimeMillis() - startTime,
        retVal.size(),
        segments.size() - retVal.size()
    );

    return retVal;
  }

  @VisibleForTesting
  void setAvailableSegmentMetadata(final SegmentId segmentId, final AvailableSegmentMetadata availableSegmentMetadata)
  {
    synchronized (lock) {
      TreeMap<SegmentId, AvailableSegmentMetadata> dataSourceSegments = segmentMetadataInfo.computeIfAbsent(
          segmentId.getDataSource(),
          x -> new TreeMap<>(SEGMENT_ORDER)
      );
      if (dataSourceSegments.put(segmentId, availableSegmentMetadata) == null) {
        totalSegments++;
      }
    }
  }

  protected DruidTable buildDruidTable(final String dataSource)
  {
    synchronized (lock) {
      final Map<SegmentId, AvailableSegmentMetadata> segmentMap = segmentMetadataInfo.get(dataSource);
      final Map<String, ValueType> columnTypes = new TreeMap<>();

      if (segmentMap != null) {
        for (AvailableSegmentMetadata availableSegmentMetadata : segmentMap.values()) {
          final RowSignature rowSignature = availableSegmentMetadata.getRowSignature();
          if (rowSignature != null) {
            for (String column : rowSignature.getColumnNames()) {
              // Newer column types should override older ones.
              final ValueType columnType =
                  rowSignature.getColumnType(column)
                              .orElseThrow(() -> new ISE("Encountered null type for column[%s]", column));

              columnTypes.putIfAbsent(column, columnType);
            }
          }
        }
      }

      final RowSignature.Builder builder = RowSignature.builder();
      columnTypes.forEach(builder::add);

      final TableDataSource tableDataSource;

      // to be a GlobalTableDataSource instead of a TableDataSource, it must appear on all servers (inferred by existing
      // in the segment cache, which in this case belongs to the broker meaning only broadcast segments live here)
      // to be joinable, it must be possibly joinable according to the factory. we only consider broadcast datasources
      // at this time, and isGlobal is currently strongly coupled with joinable, so only make a global table datasource
      // if also joinable
      final GlobalTableDataSource maybeGlobal = new GlobalTableDataSource(dataSource);
      final boolean isJoinable = joinableFactory.isDirectlyJoinable(maybeGlobal);
      final boolean isBroadcast = segmentManager.getDataSourceNames().contains(dataSource);
      if (isBroadcast && isJoinable) {
        tableDataSource = maybeGlobal;
      } else {
        tableDataSource = new TableDataSource(dataSource);
      }
      return new DruidTable(tableDataSource, builder.build(), isJoinable, isBroadcast);
    }
  }

  private static Sequence<SegmentAnalysis> runSegmentMetadataQuery(
      final QueryLifecycleFactory queryLifecycleFactory,
      final Iterable<SegmentId> segments,
      final AuthenticationResult authenticationResult
  )
  {
    // Sanity check: getOnlyElement of a set, to ensure all segments have the same dataSource.
    final String dataSource = Iterables.getOnlyElement(
        StreamSupport.stream(segments.spliterator(), false)
                     .map(SegmentId::getDataSource).collect(Collectors.toSet())
    );

    final MultipleSpecificSegmentSpec querySegmentSpec = new MultipleSpecificSegmentSpec(
        StreamSupport.stream(segments.spliterator(), false)
                     .map(SegmentId::toDescriptor).collect(Collectors.toList())
    );

    final SegmentMetadataQuery segmentMetadataQuery = new SegmentMetadataQuery(
        new TableDataSource(dataSource),
        querySegmentSpec,
        new AllColumnIncluderator(),
        false,
        ImmutableMap.of(),
        EnumSet.noneOf(SegmentMetadataQuery.AnalysisType.class),
        false,
        false
    );

    return queryLifecycleFactory.factorize().runSimple(segmentMetadataQuery, authenticationResult, Access.OK);
  }

  private static RowSignature analysisToRowSignature(final SegmentAnalysis analysis)
  {
    final RowSignature.Builder rowSignatureBuilder = RowSignature.builder();
    for (Map.Entry<String, ColumnAnalysis> entry : analysis.getColumns().entrySet()) {
      if (entry.getValue().isError()) {
        // Skip columns with analysis errors.
        continue;
      }

      ValueType valueType;
      try {
        valueType = ValueType.valueOf(StringUtils.toUpperCase(entry.getValue().getType()));
      }
      catch (IllegalArgumentException e) {
        // Assume unrecognized types are some flavor of COMPLEX. This throws away information about exactly
        // what kind of complex column it is, which we may want to preserve some day.
        valueType = ValueType.COMPLEX;
      }

      rowSignatureBuilder.add(entry.getKey(), valueType);
    }
    return rowSignatureBuilder.build();
  }

  Map<SegmentId, AvailableSegmentMetadata> getSegmentMetadataSnapshot()
  {
    synchronized (lock) {
      final Map<SegmentId, AvailableSegmentMetadata> segmentMetadata = Maps.newHashMapWithExpectedSize(
          segmentMetadataInfo.values().stream().mapToInt(v -> v.size()).sum());
      for (TreeMap<SegmentId, AvailableSegmentMetadata> val : segmentMetadataInfo.values()) {
        segmentMetadata.putAll(val);
      }
      return segmentMetadata;
    }
  }

  int getTotalSegments()
  {
    return totalSegments;
  }
}


text:
package org.jamppa.component.utils;

import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.PacketError.Condition;
import org.xmpp.packet.PacketError.Type;

public class XMPPUtils {

	/**
	 * Logs the error and returns an IQ error response
	 *
	 * @param iq
	 * @param errorMessage
	 * @param logger
	 * @return
	 */
	public static IQ error(IQ iq, String errorMessage, Logger logger) {
		logger.error(errorMessage);
		return error(iq, errorMessage);
	}

	/**
	 * Logs the error and returns an IQ error response
	 *
	 * @param iq
	 * @param errorMessage
	 * @param logger
	 * @return
	 */
	public static IQ error(IQ iq, String errorMessage) {
		return XMPPUtils.createErrorResponse(iq, errorMessage,
				Condition.bad_request, Type.modify);
	}

	/**
	 * @param iq
	 * @param errorMessage
	 * @param logger
	 * @return
	 */
	public static IQ error(IQ iq, String errorMessage, Exception e, Logger logger) {
		logger.error(errorMessage, e);
		return XMPPUtils.createErrorResponse(iq, errorMessage,
				Condition.bad_request, Type.modify);
	}

	/**
	 * Logs the RSM page not found error and returns an IQ error response
	 *
	 * @param iq
	 * @param errorMessage
	 * @param logger
	 * @return
	 */
	public static IQ errorRSM(IQ iq, Logger logger) {
		String rsmMessage = "RSM: Page Not Found";
		logger.error(rsmMessage + " " + iq);
		return XMPPUtils.createErrorResponse(iq, rsmMessage,
				Condition.item_not_found, Type.cancel);
	}

	/**
	 * Creates an error response for a given IQ request.
	 *
	 * @param request
	 * @param message
	 * @param condition
	 * @param type
	 * @return
	 */
	public static IQ createErrorResponse(final IQ request, final String message,
			Condition condition, Type type) {
		final IQ result = request.createCopy();
		result.setID(request.getID());
		result.setFrom(request.getTo());
		result.setTo(request.getFrom());

		PacketError e = new PacketError(condition, type);
		if(message != null) {
			e.setText(message);
		}
		result.setError(e);

		return result;
	}

	public static void addInfo(String message, Element queryElement) {
		Element messageEl = queryElement.addElement("info");
		messageEl.setText(message);
	}
}


text:
import includes from 'array-includes';

//Source modules
import util from './utilities';
import requireValidationMessages from './require-validations-messages';
import message from './validations-messages';

const requireErrorMap = {
  forceOverwrite: 'invalidValidForceMsg',
  hideMessages: 'invalidHideMessageMsg',
  template: 'noTemplateMsg',
  output: 'noOutputDirMsg'
};

const optionsValidator = () => {};

const validOptionsChoices = ['forceOverwrite', 'hideMessages'];

const validateOptions = Object.assign(optionsValidator.prototype, {
  forceOverwrite: (params) => {
    return util.isBoolean(params.forceOverwrite);
  },
  hideMessages: (params) => {
    return util.isBoolean(params.hideMessages);
  },
  message: (validationResult) => {

    const requireErrors = [];
    const validationEntries = validationResult.error || validationResult;

    validationEntries.forEach((error) => {
      const requireErrorMsg = requireValidationMessages[requireErrorMap[error]];
      requireErrors.push(requireErrorMsg);
      message.error(requireErrorMsg);
    });

    return requireErrors;
  },
  validateInputOutput: (template, output) => {
    const validatedResult = [];
    if (typeof template === 'undefined') {
      validatedResult.push('template');
    }
    if (typeof output === 'undefined') {
      validatedResult.push('output');
    }
    return validatedResult;
  },
  validateOptions: (params) => {
    const optionTypes = [];
    let validatedResult = {};

    //Go through all the option keys that are present in the 'validateOptions' object
    Object.keys(params.options).forEach((key) => {
      if (typeof validateOptions[key] !== 'undefined' &&
        includes(validOptionsChoices, key)) {
        const validatedResults = validateOptions[key](params.options);

        //'False' means the option fails validation and will need to be logged
        if (!validatedResults) {

          if (optionTypes.length === 0) {
            validatedResult = { error: optionTypes };
          }

          validatedResult.error.push(key);
        }
      }
    });

    return validatedResult;
  }
});

export default validateOptions;


text:
package com.google.common.io;

import com.google.common.testing.GcFinalization;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

/**
 * Unit tests for {@link FileBackedOutputStream}.
 *
 * @author Chris Nokleberg
 */
@AndroidIncompatible // Android forbids much filesystem access. Maybe we could make it work?
public class FileBackedOutputStreamTest extends IoTestCase {

  public void testThreshold() throws Exception {
    testThreshold(0, 100, true, false);
    testThreshold(10, 100, true, false);
    testThreshold(100, 100, true, false);
    testThreshold(1000, 100, true, false);
    testThreshold(0, 100, false, false);
    testThreshold(10, 100, false, false);
    testThreshold(100, 100, false, false);
    testThreshold(1000, 100, false, false);
  }

  private void testThreshold(
      int fileThreshold, int dataSize, boolean singleByte, boolean resetOnFinalize)
      throws IOException {
    byte[] data = newPreFilledByteArray(dataSize);
    FileBackedOutputStream out = new FileBackedOutputStream(fileThreshold, resetOnFinalize);
    ByteSource source = out.asByteSource();
    int chunk1 = Math.min(dataSize, fileThreshold);
    int chunk2 = dataSize - chunk1;

    // Write just enough to not trip the threshold
    if (chunk1 > 0) {
      write(out, data, 0, chunk1, singleByte);
      assertTrue(ByteSource.wrap(data).slice(0, chunk1).contentEquals(source));
    }
    File file = out.getFile();
    assertNull(file);

    // Write data to go over the threshold
    if (chunk2 > 0) {
      write(out, data, chunk1, chunk2, singleByte);
      file = out.getFile();
      assertEquals(dataSize, file.length());
      assertTrue(file.exists());
    }
    out.close();

    // Check that source returns the right data
    assertTrue(Arrays.equals(data, source.read()));

    // Make sure that reset deleted the file
    out.reset();
    if (file != null) {
      assertFalse(file.exists());
    }
  }

  public void testFinalizeDeletesFile() throws Exception {
    byte[] data = newPreFilledByteArray(100);
    FileBackedOutputStream out = new FileBackedOutputStream(0, true);

    write(out, data, 0, 100, true);
    final File file = out.getFile();
    assertEquals(100, file.length());
    assertTrue(file.exists());
    out.close();

    // Make sure that finalize deletes the file
    out = null;

    // times out and throws RuntimeException on failure
    GcFinalization.awaitDone(
        new GcFinalization.FinalizationPredicate() {
          @Override
          public boolean isDone() {
            return !file.exists();
          }
        });
  }

  public void testThreshold_resetOnFinalize() throws Exception {
    testThreshold(0, 100, true, true);
    testThreshold(10, 100, true, true);
    testThreshold(100, 100, true, true);
    testThreshold(1000, 100, true, true);
    testThreshold(0, 100, false, true);
    testThreshold(10, 100, false, true);
    testThreshold(100, 100, false, true);
    testThreshold(1000, 100, false, true);
  }

  private static void write(OutputStream out, byte[] b, int off, int len, boolean singleByte)
      throws IOException {
    if (singleByte) {
      for (int i = off; i < off + len; i++) {
        out.write(b[i]);
      }
    } else {
      out.write(b, off, len);
    }
    out.flush(); // for coverage
  }

  // TODO(chrisn): only works if we ensure we have crossed file threshold

  public void testWriteErrorAfterClose() throws Exception {
    byte[] data = newPreFilledByteArray(100);
    FileBackedOutputStream out = new FileBackedOutputStream(50);
    ByteSource source = out.asByteSource();

    out.write(data);
    assertTrue(Arrays.equals(data, source.read()));

    out.close();
    try {
      out.write(42);
      fail("expected exception");
    } catch (IOException expected) {
    }

    // Verify that write had no effect
    assertTrue(Arrays.equals(data, source.read()));
    out.reset();
  }

  public void testReset() throws Exception {
    byte[] data = newPreFilledByteArray(100);
    FileBackedOutputStream out = new FileBackedOutputStream(Integer.MAX_VALUE);
    ByteSource source = out.asByteSource();

    out.write(data);
    assertTrue(Arrays.equals(data, source.read()));

    out.reset();
    assertTrue(Arrays.equals(new byte[0], source.read()));

    out.write(data);
    assertTrue(Arrays.equals(data, source.read()));

    out.close();
  }
}


text:
package com.messners.ajf.data.converters;

import java.math.BigInteger;

import com.messners.ajf.data.ConversionException;
import com.messners.ajf.data.Converter;

/**
 * Default {@link Converter} implementation to convert a value object
 * into a java.math.BigInteger instance.
 *
 * @author  Greg Messner <greg@messners.com>
 */
public final class BigIntegerConverter implements Converter<BigInteger> {

	private BigInteger defaultValue;
	private boolean returnDefault;

	/**
	 *
Create a {@link Converter} to convert to and from
	 * java.math.BigInteger.

	 *
	 * Instances created with this constructor will throw a
	 * ConversionException if an error occurs during conversion.
	 */
	public BigIntegerConverter () {

		this.defaultValue  = null;
		this.returnDefault = false;
	}

	/**
	 * Create a {@link Converter} to convert to and from
	 * java.math.BigInteger. This constructor sets up
	 * this converter to return the provided default value if the
	 * value provided to the convert() method is null
	 * or an exception occurs during conversion.
	 *
	 * @param  defaultValue  the BigInteger instance to use as the default value
	 */
	public BigIntegerConverter (BigInteger defaultValue) {

		this.defaultValue = defaultValue;
		this.returnDefault = true;
	}

	/**
	 * Create a {@link Converter} to convert to and from
	 * java.math.BigInteger. This constructor sets up
	 * this converter to return the provided default value if the
	 * value provided to the convert() method is null
	 * or an exception occurs during conversion.
	 *
	 * @param  defaultValue  the int value to use as the default value
	 */
	public BigIntegerConverter (int defaultValue) {

		this.defaultValue = BigInteger.valueOf(defaultValue);
		this.returnDefault = true;
	}

	/**
	 * Convert the provided object into an object of the specified type.
	 *
	 * @param value the value to be converted
	 * @exception ConversionException if an error occurs during conversion
	 */
	public BigInteger convert (Object value) throws ConversionException {

		if (value == null) {

			if (returnDefault) {
				return (defaultValue);
			} else {
				throw new ConversionException(new NullPointerException());
			}
		}

		if (value instanceof BigInteger) {
			return (BigInteger) (value);
		}

		try {

			if (value instanceof String) {
				return (new BigInteger((String)value));
			} else {
				return (new BigInteger(value.toString()));
			}

		} catch (Exception e) {

			if (returnDefault) {
				return (defaultValue);
			} else {
				throw new ConversionException(e);
			}
		}
	}

	/**
	 * Convert the passed value to a String.
	 *
	 * @param  value the Object to convert to a String
	 * @return the converted String
	 * @throws ConversionException if value is not the proper type
	 */
	public String toString (Object value) throws ConversionException {
		return (convert(value).toString());
	}
}