text:
app

.controller("IndexCtrl"
	, [       "$scope", "$mdBottomSheet", "$mdToast", "$translate", "localStorageService", "sysd", "Loading"
	, function($scope,   $mdBottomSheet,   $mdToast,   $translate,   localStorageService,   sysd,   Loading) {

	sysd.host = localStorageService.get("sysdhost") || "127.0.0.1";
	sysd.port = +localStorageService.get("sysdport") || 8;
	$scope.sysd = sysd;
	$scope.Loading = Loading;
	$scope.config = {
		host: sysd.host,
		port: sysd.port
	};
	$scope.apiReq = {
		method: "",
		path: ""
	};
	$scope.apiResData = "";

	$scope.showLangBottomSheet = function($event) {
		// show config view
		$scope.apiResData = "";

		$mdBottomSheet.show({
			templateUrl: "directives/langSelect.html",
			controller: "langSelectCtrl",
			targetEvent: $event
		}).then(function(clickedItem) {
			$translate.use(clickedItem.lang);
		});
	};

	$scope.api = function(path) {
		Loading.add("api");
		$scope.apiReq.method = "GET";
		$scope.apiReq.path = "/" + path;
		sysd.api.get[path]().then(function(data) {
			$scope.apiResData = JSON.stringify(data, undefined, 4);
		}, function() {
			$mdToast.show({
				template: "<md-toast>" +
					"
Execute API failed
" +
					"
" + path + "
" +
					"</md-toast>",
				hideDelay: 5000,
				position: "top left"
			});
		}).finally(function() {
			Loading.del("api");
		});
	};

	$scope.regapis = function() {
		Loading.add("regapis");
		sysd.regapis().then(function() {
			// success
		}, function(res) {
			if (sysd.host == "127.0.0.1" && sysd.port == 8) {
				return;
			}
			$mdToast.show({
				template: "<md-toast>" +
					"
Connect to sysd server failed
" +
					"
Please check configuration
" +
					"
" + sysd.host + ":" + sysd.port + "
" +
					"</md-toast>",
				hideDelay: 5000,
				position: "top left"
			});
		}).finally(function() {
			Loading.del("regapis");
		});
	};

	$scope.saveConfig = function() {
		sysd.host = $scope.config.host;
		sysd.port = $scope.config.port;
		localStorageService.set("sysdhost", sysd.host);
		localStorageService.set("sysdport", sysd.port);
		$scope.regapis();
	};

	$scope.resetConfig = function() {
		sysd.host = $scope.config.host = "127.0.0.1";
		sysd.port = $scope.config.port = 8;
		localStorageService.clearAll()
		$scope.regapis();
	};

	$scope.regapis();

}])

;


text:
#import "CCParticleSystem.h"

#define CC_MAX_PARTICLE_SIZE 64

/** CCParticleSystemPoint is a subclass of CCParticleSystem
 Attributes of a Particle System:
 * All the attributes of Particle System

 Features:
  * consumes small memory: uses 1 vertex (x,y) per particle, no need to assign tex coordinates
  * size can't be bigger than 64
  * the system can't be scaled since the particles are rendered using GL_POINT_SPRITE

 Limitations:
  * On 3rd gen iPhone devices and iPads, this node performs MUCH slower than CCParticleSystemQuad.
 */
@interface CCParticleSystemPoint : CCParticleSystem
{
	// Array of (x,y,size)
	ccPointSprite *vertices;
	// vertices buffer id
#if CC_USES_VBO
	GLuint	verticesID;
#endif
}
@end

redpajama_set_name: RedPajamaGithub


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

package com.google.cloud.dialogflow.v2;

/**
 *
 *
 *

 * The top-level message sent by the client to the
 * `StreamingDetectIntent` method.
 * Multiple request messages should be sent in order:
 * 1.  The first message must contain `session`, `query_input` plus optionally
 *     `query_params` and/or `single_utterance`. The message must not contain
 *     `input_audio`.
 * 2.  If `query_input` was set to a streaming input audio config,
 *     all subsequent messages must contain only `input_audio`.
 *     Otherwise, finish the request stream.
 *

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

  private StreamingDetectIntentRequest() {
    session_ = "";
    singleUtterance_ = false;
    inputAudio_ = com.google.protobuf.ByteString.EMPTY;
  }

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

  private StreamingDetectIntentRequest(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    if (extensionRegistry == null) {
      throw new java.lang.NullPointerException();
    }
    int mutable_bitField0_ = 0;
    com.google.protobuf.UnknownFieldSet.Builder unknownFields =
        com.google.protobuf.UnknownFieldSet.newBuilder();
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          case 10:
            {
              java.lang.String s = input.readStringRequireUtf8();

              session_ = s;
              break;
            }
          case 18:
            {
              com.google.cloud.dialogflow.v2.QueryParameters.Builder subBuilder = null;
              if (queryParams_ != null) {
                subBuilder = queryParams_.toBuilder();
              }
              queryParams_ =
                  input.readMessage(
                      com.google.cloud.dialogflow.v2.QueryParameters.parser(), extensionRegistry);
              if (subBuilder != null) {
                subBuilder.mergeFrom(queryParams_);
                queryParams_ = subBuilder.buildPartial();
              }

              break;
            }
          case 26:
            {
              com.google.cloud.dialogflow.v2.QueryInput.Builder subBuilder = null;
              if (queryInput_ != null) {
                subBuilder = queryInput_.toBuilder();
              }
              queryInput_ =
                  input.readMessage(
                      com.google.cloud.dialogflow.v2.QueryInput.parser(), extensionRegistry);
              if (subBuilder != null) {
                subBuilder.mergeFrom(queryInput_);
                queryInput_ = subBuilder.buildPartial();
              }

              break;
            }
          case 32:
            {
              singleUtterance_ = input.readBool();
              break;
            }
          case 50:
            {
              inputAudio_ = input.readBytes();
              break;
            }
          default:
            {
              if (!parseUnknownFieldProto3(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.dialogflow.v2.SessionProto
        .internal_static_google_cloud_dialogflow_v2_StreamingDetectIntentRequest_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.dialogflow.v2.SessionProto
        .internal_static_google_cloud_dialogflow_v2_StreamingDetectIntentRequest_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.class,
            com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.Builder.class);
  }

  public static final int SESSION_FIELD_NUMBER = 1;
  private volatile java.lang.Object session_;
  /**
   *
   *
   *

   * Required. The name of the session the query is sent to.
   * Format of the session name:
   * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
   * caller to choose an appropriate <Session ID>. It can be a random number or
   * some type of user identifier (preferably hashed). The length of the session
   * ID must not exceed 36 characters.
   *

   *
   * string session = 1;
   */
  public java.lang.String getSession() {
    java.lang.Object ref = session_;
    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();
      session_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * Required. The name of the session the query is sent to.
   * Format of the session name:
   * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
   * caller to choose an appropriate <Session ID>. It can be a random number or
   * some type of user identifier (preferably hashed). The length of the session
   * ID must not exceed 36 characters.
   *

   *
   * string session = 1;
   */
  public com.google.protobuf.ByteString getSessionBytes() {
    java.lang.Object ref = session_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      session_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int QUERY_PARAMS_FIELD_NUMBER = 2;
  private com.google.cloud.dialogflow.v2.QueryParameters queryParams_;
  /**
   *
   *
   *

   * Optional. The parameters of this query.
   *

   *
   * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
   */
  public boolean hasQueryParams() {
    return queryParams_ != null;
  }
  /**
   *
   *
   *

   * Optional. The parameters of this query.
   *

   *
   * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
   */
  public com.google.cloud.dialogflow.v2.QueryParameters getQueryParams() {
    return queryParams_ == null
        ? com.google.cloud.dialogflow.v2.QueryParameters.getDefaultInstance()
        : queryParams_;
  }
  /**
   *
   *
   *

   * Optional. The parameters of this query.
   *

   *
   * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
   */
  public com.google.cloud.dialogflow.v2.QueryParametersOrBuilder getQueryParamsOrBuilder() {
    return getQueryParams();
  }

  public static final int QUERY_INPUT_FIELD_NUMBER = 3;
  private com.google.cloud.dialogflow.v2.QueryInput queryInput_;
  /**
   *
   *
   *

   * Required. The input specification. It can be set to:
   * 1.  an audio config which instructs the speech recognizer how to process
   *     the speech audio,
   * 2.  a conversational query in the form of text, or
   * 3.  an event that specifies which intent to trigger.
   *

   *
   * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
   */
  public boolean hasQueryInput() {
    return queryInput_ != null;
  }
  /**
   *
   *
   *

   * Required. The input specification. It can be set to:
   * 1.  an audio config which instructs the speech recognizer how to process
   *     the speech audio,
   * 2.  a conversational query in the form of text, or
   * 3.  an event that specifies which intent to trigger.
   *

   *
   * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
   */
  public com.google.cloud.dialogflow.v2.QueryInput getQueryInput() {
    return queryInput_ == null
        ? com.google.cloud.dialogflow.v2.QueryInput.getDefaultInstance()
        : queryInput_;
  }
  /**
   *
   *
   *

   * Required. The input specification. It can be set to:
   * 1.  an audio config which instructs the speech recognizer how to process
   *     the speech audio,
   * 2.  a conversational query in the form of text, or
   * 3.  an event that specifies which intent to trigger.
   *

   *
   * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
   */
  public com.google.cloud.dialogflow.v2.QueryInputOrBuilder getQueryInputOrBuilder() {
    return getQueryInput();
  }

  public static final int SINGLE_UTTERANCE_FIELD_NUMBER = 4;
  private boolean singleUtterance_;
  /**
   *
   *
   *

   * Optional. If `false` (default), recognition does not cease until the
   * client closes the stream.
   * If `true`, the recognizer will detect a single spoken utterance in input
   * audio. Recognition ceases when it detects the audio's voice has
   * stopped or paused. In this case, once a detected intent is received, the
   * client should close the stream and start a new request with a new stream as
   * needed.
   * This setting is ignored when `query_input` is a piece of text or an event.
   *

   *
   * bool single_utterance = 4;
   */
  public boolean getSingleUtterance() {
    return singleUtterance_;
  }

  public static final int INPUT_AUDIO_FIELD_NUMBER = 6;
  private com.google.protobuf.ByteString inputAudio_;
  /**
   *
   *
   *

   * Optional. The input audio content to be recognized. Must be sent if
   * `query_input` was set to a streaming input audio config. The complete audio
   * over all streaming messages must not exceed 1 minute.
   *

   *
   * bytes input_audio = 6;
   */
  public com.google.protobuf.ByteString getInputAudio() {
    return inputAudio_;
  }

  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 (!getSessionBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, session_);
    }
    if (queryParams_ != null) {
      output.writeMessage(2, getQueryParams());
    }
    if (queryInput_ != null) {
      output.writeMessage(3, getQueryInput());
    }
    if (singleUtterance_ != false) {
      output.writeBool(4, singleUtterance_);
    }
    if (!inputAudio_.isEmpty()) {
      output.writeBytes(6, inputAudio_);
    }
    unknownFields.writeTo(output);
  }

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

    size = 0;
    if (!getSessionBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, session_);
    }
    if (queryParams_ != null) {
      size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getQueryParams());
    }
    if (queryInput_ != null) {
      size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getQueryInput());
    }
    if (singleUtterance_ != false) {
      size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, singleUtterance_);
    }
    if (!inputAudio_.isEmpty()) {
      size += com.google.protobuf.CodedOutputStream.computeBytesSize(6, inputAudio_);
    }
    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.dialogflow.v2.StreamingDetectIntentRequest)) {
      return super.equals(obj);
    }
    com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest other =
        (com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest) obj;

    boolean result = true;
    result = result && getSession().equals(other.getSession());
    result = result && (hasQueryParams() == other.hasQueryParams());
    if (hasQueryParams()) {
      result = result && getQueryParams().equals(other.getQueryParams());
    }
    result = result && (hasQueryInput() == other.hasQueryInput());
    if (hasQueryInput()) {
      result = result && getQueryInput().equals(other.getQueryInput());
    }
    result = result && (getSingleUtterance() == other.getSingleUtterance());
    result = result && getInputAudio().equals(other.getInputAudio());
    result = result && unknownFields.equals(other.unknownFields);
    return result;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + SESSION_FIELD_NUMBER;
    hash = (53 * hash) + getSession().hashCode();
    if (hasQueryParams()) {
      hash = (37 * hash) + QUERY_PARAMS_FIELD_NUMBER;
      hash = (53 * hash) + getQueryParams().hashCode();
    }
    if (hasQueryInput()) {
      hash = (37 * hash) + QUERY_INPUT_FIELD_NUMBER;
      hash = (53 * hash) + getQueryInput().hashCode();
    }
    hash = (37 * hash) + SINGLE_UTTERANCE_FIELD_NUMBER;
    hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSingleUtterance());
    hash = (37 * hash) + INPUT_AUDIO_FIELD_NUMBER;
    hash = (53 * hash) + getInputAudio().hashCode();
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

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

  public static com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest 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.dialogflow.v2.StreamingDetectIntentRequest parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest 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.dialogflow.v2.StreamingDetectIntentRequest parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

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

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

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

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

  public static com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest 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.dialogflow.v2.StreamingDetectIntentRequest 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;
  }
  /**
   *
   *
   *

   * The top-level message sent by the client to the
   * `StreamingDetectIntent` method.
   * Multiple request messages should be sent in order:
   * 1.  The first message must contain `session`, `query_input` plus optionally
   *     `query_params` and/or `single_utterance`. The message must not contain
   *     `input_audio`.
   * 2.  If `query_input` was set to a streaming input audio config,
   *     all subsequent messages must contain only `input_audio`.
   *     Otherwise, finish the request stream.
   *

   *
   * Protobuf type {@code google.cloud.dialogflow.v2.StreamingDetectIntentRequest}
   */
  public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
      implements
      // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.StreamingDetectIntentRequest)
      com.google.cloud.dialogflow.v2.StreamingDetectIntentRequestOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
      return com.google.cloud.dialogflow.v2.SessionProto
          .internal_static_google_cloud_dialogflow_v2_StreamingDetectIntentRequest_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.cloud.dialogflow.v2.SessionProto
          .internal_static_google_cloud_dialogflow_v2_StreamingDetectIntentRequest_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.class,
              com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.Builder.class);
    }

    // Construct using com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.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();
      session_ = "";

      if (queryParamsBuilder_ == null) {
        queryParams_ = null;
      } else {
        queryParams_ = null;
        queryParamsBuilder_ = null;
      }
      if (queryInputBuilder_ == null) {
        queryInput_ = null;
      } else {
        queryInput_ = null;
        queryInputBuilder_ = null;
      }
      singleUtterance_ = false;

      inputAudio_ = com.google.protobuf.ByteString.EMPTY;

      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
      return com.google.cloud.dialogflow.v2.SessionProto
          .internal_static_google_cloud_dialogflow_v2_StreamingDetectIntentRequest_descriptor;
    }

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

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

    @java.lang.Override
    public com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest buildPartial() {
      com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest result =
          new com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest(this);
      result.session_ = session_;
      if (queryParamsBuilder_ == null) {
        result.queryParams_ = queryParams_;
      } else {
        result.queryParams_ = queryParamsBuilder_.build();
      }
      if (queryInputBuilder_ == null) {
        result.queryInput_ = queryInput_;
      } else {
        result.queryInput_ = queryInputBuilder_.build();
      }
      result.singleUtterance_ = singleUtterance_;
      result.inputAudio_ = inputAudio_;
      onBuilt();
      return result;
    }

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

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

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

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

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

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

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

    public Builder mergeFrom(com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest other) {
      if (other == com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest.getDefaultInstance())
        return this;
      if (!other.getSession().isEmpty()) {
        session_ = other.session_;
        onChanged();
      }
      if (other.hasQueryParams()) {
        mergeQueryParams(other.getQueryParams());
      }
      if (other.hasQueryInput()) {
        mergeQueryInput(other.getQueryInput());
      }
      if (other.getSingleUtterance() != false) {
        setSingleUtterance(other.getSingleUtterance());
      }
      if (other.getInputAudio() != com.google.protobuf.ByteString.EMPTY) {
        setInputAudio(other.getInputAudio());
      }
      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.dialogflow.v2.StreamingDetectIntentRequest parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage =
            (com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

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

     * Required. The name of the session the query is sent to.
     * Format of the session name:
     * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
     * caller to choose an appropriate <Session ID>. It can be a random number or
     * some type of user identifier (preferably hashed). The length of the session
     * ID must not exceed 36 characters.
     *

     *
     * string session = 1;
     */
    public java.lang.String getSession() {
      java.lang.Object ref = session_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        session_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * Required. The name of the session the query is sent to.
     * Format of the session name:
     * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
     * caller to choose an appropriate <Session ID>. It can be a random number or
     * some type of user identifier (preferably hashed). The length of the session
     * ID must not exceed 36 characters.
     *

     *
     * string session = 1;
     */
    public com.google.protobuf.ByteString getSessionBytes() {
      java.lang.Object ref = session_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        session_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * Required. The name of the session the query is sent to.
     * Format of the session name:
     * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
     * caller to choose an appropriate <Session ID>. It can be a random number or
     * some type of user identifier (preferably hashed). The length of the session
     * ID must not exceed 36 characters.
     *

     *
     * string session = 1;
     */
    public Builder setSession(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

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

     * Required. The name of the session the query is sent to.
     * Format of the session name:
     * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
     * caller to choose an appropriate <Session ID>. It can be a random number or
     * some type of user identifier (preferably hashed). The length of the session
     * ID must not exceed 36 characters.
     *

     *
     * string session = 1;
     */
    public Builder clearSession() {

      session_ = getDefaultInstance().getSession();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * Required. The name of the session the query is sent to.
     * Format of the session name:
     * `projects/<Project ID>/agent/sessions/<Session ID>`. It's up to the API
     * caller to choose an appropriate <Session ID>. It can be a random number or
     * some type of user identifier (preferably hashed). The length of the session
     * ID must not exceed 36 characters.
     *

     *
     * string session = 1;
     */
    public Builder setSessionBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

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

    private com.google.cloud.dialogflow.v2.QueryParameters queryParams_ = null;
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.dialogflow.v2.QueryParameters,
            com.google.cloud.dialogflow.v2.QueryParameters.Builder,
            com.google.cloud.dialogflow.v2.QueryParametersOrBuilder>
        queryParamsBuilder_;
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public boolean hasQueryParams() {
      return queryParamsBuilder_ != null || queryParams_ != null;
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public com.google.cloud.dialogflow.v2.QueryParameters getQueryParams() {
      if (queryParamsBuilder_ == null) {
        return queryParams_ == null
            ? com.google.cloud.dialogflow.v2.QueryParameters.getDefaultInstance()
            : queryParams_;
      } else {
        return queryParamsBuilder_.getMessage();
      }
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public Builder setQueryParams(com.google.cloud.dialogflow.v2.QueryParameters value) {
      if (queryParamsBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        queryParams_ = value;
        onChanged();
      } else {
        queryParamsBuilder_.setMessage(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public Builder setQueryParams(
        com.google.cloud.dialogflow.v2.QueryParameters.Builder builderForValue) {
      if (queryParamsBuilder_ == null) {
        queryParams_ = builderForValue.build();
        onChanged();
      } else {
        queryParamsBuilder_.setMessage(builderForValue.build());
      }

      return this;
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public Builder mergeQueryParams(com.google.cloud.dialogflow.v2.QueryParameters value) {
      if (queryParamsBuilder_ == null) {
        if (queryParams_ != null) {
          queryParams_ =
              com.google.cloud.dialogflow.v2.QueryParameters.newBuilder(queryParams_)
                  .mergeFrom(value)
                  .buildPartial();
        } else {
          queryParams_ = value;
        }
        onChanged();
      } else {
        queryParamsBuilder_.mergeFrom(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public Builder clearQueryParams() {
      if (queryParamsBuilder_ == null) {
        queryParams_ = null;
        onChanged();
      } else {
        queryParams_ = null;
        queryParamsBuilder_ = null;
      }

      return this;
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public com.google.cloud.dialogflow.v2.QueryParameters.Builder getQueryParamsBuilder() {

      onChanged();
      return getQueryParamsFieldBuilder().getBuilder();
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    public com.google.cloud.dialogflow.v2.QueryParametersOrBuilder getQueryParamsOrBuilder() {
      if (queryParamsBuilder_ != null) {
        return queryParamsBuilder_.getMessageOrBuilder();
      } else {
        return queryParams_ == null
            ? com.google.cloud.dialogflow.v2.QueryParameters.getDefaultInstance()
            : queryParams_;
      }
    }
    /**
     *
     *
     *

     * Optional. The parameters of this query.
     *

     *
     * .google.cloud.dialogflow.v2.QueryParameters query_params = 2;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.dialogflow.v2.QueryParameters,
            com.google.cloud.dialogflow.v2.QueryParameters.Builder,
            com.google.cloud.dialogflow.v2.QueryParametersOrBuilder>
        getQueryParamsFieldBuilder() {
      if (queryParamsBuilder_ == null) {
        queryParamsBuilder_ =
            new com.google.protobuf.SingleFieldBuilderV3<
                com.google.cloud.dialogflow.v2.QueryParameters,
                com.google.cloud.dialogflow.v2.QueryParameters.Builder,
                com.google.cloud.dialogflow.v2.QueryParametersOrBuilder>(
                getQueryParams(), getParentForChildren(), isClean());
        queryParams_ = null;
      }
      return queryParamsBuilder_;
    }

    private com.google.cloud.dialogflow.v2.QueryInput queryInput_ = null;
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.dialogflow.v2.QueryInput,
            com.google.cloud.dialogflow.v2.QueryInput.Builder,
            com.google.cloud.dialogflow.v2.QueryInputOrBuilder>
        queryInputBuilder_;
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public boolean hasQueryInput() {
      return queryInputBuilder_ != null || queryInput_ != null;
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public com.google.cloud.dialogflow.v2.QueryInput getQueryInput() {
      if (queryInputBuilder_ == null) {
        return queryInput_ == null
            ? com.google.cloud.dialogflow.v2.QueryInput.getDefaultInstance()
            : queryInput_;
      } else {
        return queryInputBuilder_.getMessage();
      }
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public Builder setQueryInput(com.google.cloud.dialogflow.v2.QueryInput value) {
      if (queryInputBuilder_ == null) {
        if (value == null) {
          throw new NullPointerException();
        }
        queryInput_ = value;
        onChanged();
      } else {
        queryInputBuilder_.setMessage(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public Builder setQueryInput(
        com.google.cloud.dialogflow.v2.QueryInput.Builder builderForValue) {
      if (queryInputBuilder_ == null) {
        queryInput_ = builderForValue.build();
        onChanged();
      } else {
        queryInputBuilder_.setMessage(builderForValue.build());
      }

      return this;
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public Builder mergeQueryInput(com.google.cloud.dialogflow.v2.QueryInput value) {
      if (queryInputBuilder_ == null) {
        if (queryInput_ != null) {
          queryInput_ =
              com.google.cloud.dialogflow.v2.QueryInput.newBuilder(queryInput_)
                  .mergeFrom(value)
                  .buildPartial();
        } else {
          queryInput_ = value;
        }
        onChanged();
      } else {
        queryInputBuilder_.mergeFrom(value);
      }

      return this;
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public Builder clearQueryInput() {
      if (queryInputBuilder_ == null) {
        queryInput_ = null;
        onChanged();
      } else {
        queryInput_ = null;
        queryInputBuilder_ = null;
      }

      return this;
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public com.google.cloud.dialogflow.v2.QueryInput.Builder getQueryInputBuilder() {

      onChanged();
      return getQueryInputFieldBuilder().getBuilder();
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    public com.google.cloud.dialogflow.v2.QueryInputOrBuilder getQueryInputOrBuilder() {
      if (queryInputBuilder_ != null) {
        return queryInputBuilder_.getMessageOrBuilder();
      } else {
        return queryInput_ == null
            ? com.google.cloud.dialogflow.v2.QueryInput.getDefaultInstance()
            : queryInput_;
      }
    }
    /**
     *
     *
     *

     * Required. The input specification. It can be set to:
     * 1.  an audio config which instructs the speech recognizer how to process
     *     the speech audio,
     * 2.  a conversational query in the form of text, or
     * 3.  an event that specifies which intent to trigger.
     *

     *
     * .google.cloud.dialogflow.v2.QueryInput query_input = 3;
     */
    private com.google.protobuf.SingleFieldBuilderV3<
            com.google.cloud.dialogflow.v2.QueryInput,
            com.google.cloud.dialogflow.v2.QueryInput.Builder,
            com.google.cloud.dialogflow.v2.QueryInputOrBuilder>
        getQueryInputFieldBuilder() {
      if (queryInputBuilder_ == null) {
        queryInputBuilder_ =
            new com.google.protobuf.SingleFieldBuilderV3<
                com.google.cloud.dialogflow.v2.QueryInput,
                com.google.cloud.dialogflow.v2.QueryInput.Builder,
                com.google.cloud.dialogflow.v2.QueryInputOrBuilder>(
                getQueryInput(), getParentForChildren(), isClean());
        queryInput_ = null;
      }
      return queryInputBuilder_;
    }

    private boolean singleUtterance_;
    /**
     *
     *
     *

     * Optional. If `false` (default), recognition does not cease until the
     * client closes the stream.
     * If `true`, the recognizer will detect a single spoken utterance in input
     * audio. Recognition ceases when it detects the audio's voice has
     * stopped or paused. In this case, once a detected intent is received, the
     * client should close the stream and start a new request with a new stream as
     * needed.
     * This setting is ignored when `query_input` is a piece of text or an event.
     *

     *
     * bool single_utterance = 4;
     */
    public boolean getSingleUtterance() {
      return singleUtterance_;
    }
    /**
     *
     *
     *

     * Optional. If `false` (default), recognition does not cease until the
     * client closes the stream.
     * If `true`, the recognizer will detect a single spoken utterance in input
     * audio. Recognition ceases when it detects the audio's voice has
     * stopped or paused. In this case, once a detected intent is received, the
     * client should close the stream and start a new request with a new stream as
     * needed.
     * This setting is ignored when `query_input` is a piece of text or an event.
     *

     *
     * bool single_utterance = 4;
     */
    public Builder setSingleUtterance(boolean value) {

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

     * Optional. If `false` (default), recognition does not cease until the
     * client closes the stream.
     * If `true`, the recognizer will detect a single spoken utterance in input
     * audio. Recognition ceases when it detects the audio's voice has
     * stopped or paused. In this case, once a detected intent is received, the
     * client should close the stream and start a new request with a new stream as
     * needed.
     * This setting is ignored when `query_input` is a piece of text or an event.
     *

     *
     * bool single_utterance = 4;
     */
    public Builder clearSingleUtterance() {

      singleUtterance_ = false;
      onChanged();
      return this;
    }

    private com.google.protobuf.ByteString inputAudio_ = com.google.protobuf.ByteString.EMPTY;
    /**
     *
     *
     *

     * Optional. The input audio content to be recognized. Must be sent if
     * `query_input` was set to a streaming input audio config. The complete audio
     * over all streaming messages must not exceed 1 minute.
     *

     *
     * bytes input_audio = 6;
     */
    public com.google.protobuf.ByteString getInputAudio() {
      return inputAudio_;
    }
    /**
     *
     *
     *

     * Optional. The input audio content to be recognized. Must be sent if
     * `query_input` was set to a streaming input audio config. The complete audio
     * over all streaming messages must not exceed 1 minute.
     *

     *
     * bytes input_audio = 6;
     */
    public Builder setInputAudio(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }

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

     * Optional. The input audio content to be recognized. Must be sent if
     * `query_input` was set to a streaming input audio config. The complete audio
     * over all streaming messages must not exceed 1 minute.
     *

     *
     * bytes input_audio = 6;
     */
    public Builder clearInputAudio() {

      inputAudio_ = getDefaultInstance().getInputAudio();
      onChanged();
      return this;
    }

    @java.lang.Override
    public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFieldsProto3(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.dialogflow.v2.StreamingDetectIntentRequest)
  }

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

  static {
    DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest();
  }

  public static com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

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

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

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

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


text:
package android.widget.listview.arrowscroll;

import android.test.ActivityInstrumentationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.KeyEvent;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.listview.ListItemFocusablesClose;

public class ListItemFocusablesCloseTest extends ActivityInstrumentationTestCase<ListItemFocusablesClose> {
    private ListView mListView;
    private int mListTop;
    private int mListBottom;

    public ListItemFocusablesCloseTest() {
        super("com.android.frameworks.coretests", ListItemFocusablesClose.class);
    }

    @Override
    protected void setUp() throws Exception{
        super.setUp();
        mListView = getActivity().getListView();
        mListTop = mListView.getListPaddingTop();
        mListBottom = mListView.getHeight() - mListView.getListPaddingBottom();
    }

    @MediumTest
    public void testPreconditions() {
        assertNotNull(mListView);
        assertTrue(mListView.getAdapter().areAllItemsEnabled());
        assertTrue(mListView.getItemsCanFocus());
        assertEquals(0, mListView.getSelectedItemPosition());
        final LinearLayout first = (LinearLayout) mListView.getSelectedView();
        getInstrumentation().waitForIdleSync();
        assertEquals("first item should be at top of screen",
                mListView.getListPaddingTop(),
                first.getTop());
        assertTrue("first button of first list item should have focus",
                first.getChildAt(0).isFocused());
        assertTrue("item should be shorter than list for this test to make sense",
                first.getHeight() < mListView.getHeight());
        assertEquals("two items should be on screen",
                2, mListView.getChildCount());
        assertTrue("first button of second item should be on screen",
                getActivity().getChildOfItem(1, 0).getBottom() < mListBottom);
    }

    @MediumTest
    public void testChangeFocusWithinItem() {
        final LinearLayout first = (LinearLayout) mListView.getSelectedView();
        final int topOfFirstItemBefore = first.getTop();
        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        assertTrue("focus should have moved to second button of first item",
                first.getChildAt(2).isFocused());
        assertEquals("selection should not have changed",
                0, mListView.getSelectedItemPosition());
        assertEquals("list item should not have been shifted",
                topOfFirstItemBefore, first.getTop());

        sendKeys(KeyEvent.KEYCODE_DPAD_UP);
        assertTrue("focus should have moved back to first button of first item",
                first.getChildAt(0).isFocused());
        assertEquals("list item should not have been shifted",
                topOfFirstItemBefore, first.getTop());
    }

    @MediumTest
    public void testMoveDownToButtonInDifferentSelection() {
        final LinearLayout first = (LinearLayout) mListView.getSelectedView();
        final int topOfFirstItemBefore = first.getTop();
        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);

        assertEquals("selection should have moved to second item",
                1, mListView.getSelectedItemPosition());
        final LinearLayout selectedItem = (LinearLayout) mListView.getSelectedView();
        assertTrue("first button of second item should have focus",
                selectedItem.getChildAt(0).isFocused());
        assertEquals("list item should not have been shifted",
                topOfFirstItemBefore, first.getTop());
    }

    @MediumTest
    public void testMoveUpToButtonInDifferentSelection() {
        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        assertEquals(1, mListView.getSelectedItemPosition());
        assertTrue("first button of second item should have focus",
                getActivity().getChildOfItem(1, 0).hasFocus());

        sendKeys(KeyEvent.KEYCODE_DPAD_UP);
        assertEquals("first list item should have selection", 0,
                mListView.getSelectedItemPosition());
        assertTrue("second button of first item should have focus",
                getActivity().getChildOfItem(0, 2).hasFocus());
    }
}


text:
package main

import (
	"net/http"
	"net/url"
	"strings"
	"time"
)

// extractMapFromRequestParam combines request params with the same
// prefix into a map.
//
// If params is a map like this:
//
//   map[string]string{
//       "headers[foo]": "bar",
//       "headers[baz]": "boz",
//   }
//
// The result for key 'headers' would be:
//
//   map[string]string{
//       "foo": "bar",
//       "baz": "boz",
//   }
func extractMapFromRequestParam(key string, params url.Values) map[string]string {
	a := make(map[string]string, 0)
	for k, _ := range params {
		if strings.Index(k, key+"[") == 0 {
			a[k[strings.Index(k, "[")+1:strings.Index(k, "]")]] = params.Get(k)
		}
	}
	return a
}

// newRequest takes the form arguments from one HTTP requests
// to initialize and configure a new HTTP request.
func newRequest(data url.Values) (*http.Request, error) {
	rqst, err := http.NewRequest(data.Get("method"), data.Get("url"), nil)
	if err != nil {
		return nil, err
	}

	for k, v := range extractMapFromRequestParam("headers", data) {
		rqst.Header.Set(k, v)
	}

	switch data.Get("auth") {
	case "basic":
		rqst.SetBasicAuth(data.Get("username"), data.Get("password"))
	}

	return rqst, nil
}

type proxyResponse struct {
	Request  proxyRequest          `json:"request"`
	Response proxyResponseResponse `json:"response"`
}

type proxyResponseResponse struct {
	StatusCode int         `json:"status_code"`
	Duration   string      `json:"duration"`
	Time       time.Time   `json:"time"`
	Headers    http.Header `json:"headers"`
	Body       string      `json:"body"`
}

type proxyRequest struct {
	URL      string      `json:"url"`
	Scheme   string      `json:"scheme"`
	Host     string      `json:"host"`
	Fragment string      `json:"fragment"`
	Path     string      `json:"path"`
	Query    string      `json:"query"`
	Method   string      `json:"method"`
	Headers  http.Header `json:"headers"`
	PostData url.Values  `json:"post_data"`
}


text:
let clicked = false;

export default {
	props: {
		tag: 'div',
		onClick: () => clicked = true
	},
	html: '
Foo
',

	async test({ assert, target, window }) {
		const div = target.querySelector('div');
		await div.dispatchEvent(new window.MouseEvent('click'));

		assert.equal(clicked, true);
	}
};


text:
import os
import pytest
import random
import shutil
import tempfile
from raven.utils.testutils import TestCase

from raven.base import Client
from raven.contrib.zerorpc import SentryMiddleware

zerorpc = pytest.importorskip("zerorpc")
gevent = pytest.importorskip("gevent")

class TempStoreClient(Client):
    def __init__(self, **kwargs):
        self.events = []
        super(TempStoreClient, self).__init__(**kwargs)

    def is_enabled(self):
        return True

    def send(self, **kwargs):
        self.events.append(kwargs)

class ZeroRPCTest(TestCase):
    def setUp(self):
        self._socket_dir = tempfile.mkdtemp(prefix='ravenzerorpcunittest')
        self._server_endpoint = 'ipc://{0}'.format(
            os.path.join(self._socket_dir, 'random_zeroserver'))

        self._sentry = TempStoreClient()
        zerorpc.Context.get_instance().register_middleware(
            SentryMiddleware(client=self._sentry))

    def test_zerorpc_middleware_with_reqrep(self):
        self._server = zerorpc.Server(random)
        self._server.bind(self._server_endpoint)
        gevent.spawn(self._server.run)

        self._client = zerorpc.Client()
        self._client.connect(self._server_endpoint)

        try:
            self._client.choice([])
        except zerorpc.exceptions.RemoteError as ex:
            self.assertEqual(ex.name, 'IndexError')
            self.assertEqual(len(self._sentry.events), 1)
            exc = self._sentry.events[0]['exception']
            self.assertEqual(exc['type'], 'IndexError')
            frames = exc['stacktrace']['frames']
            self.assertEqual(frames[0]['function'], 'choice')
            self.assertEqual(frames[0]['module'], 'random')
        else:
            self.fail('An IndexError exception should have been raised an catched')

    def test_zerorpc_middleware_with_pushpull(self):
        self._server = zerorpc.Puller(random)
        self._server.bind(self._server_endpoint)
        gevent.spawn(self._server.run)

        self._client = zerorpc.Pusher()
        self._client.connect(self._server_endpoint)

        self._client.choice([])

        for attempt in xrange(0, 10):
            gevent.sleep(0.1)
            if len(self._sentry.events):
                exc = self._sentry.events[0]['exception']
                self.assertEqual(exc['type'], 'IndexError')
                frames = exc['stacktrace']['frames']
                self.assertEqual(frames[0]['function'], 'choice')
                self.assertEqual(frames[0]['module'], 'random')
                return

        self.fail('An IndexError exception should have been sent to Sentry')

    def tearDown(self):
        self._client.close()
        self._server.close()
        shutil.rmtree(self._socket_dir, ignore_errors=True)


text:
<!doctype html>

    <title>Code coverage report for All files</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="prettify.css" />
    <link rel="stylesheet" href="base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files

        65.85%
        Statements
        27/41

        45.45%
        Branches
        10/22

        87.5%
        Functions
        7/8

        67.5%
        Lines
        27/40

   File

   Statements

   Branches

   Functions

   Lines

	medix.ts

	65.85%
	27/41
	45.45%
	10/22
	87.5%
	7/8
	67.5%
	27/40

  Code coverage
  generated by istanbul at Wed Oct 04 2017 23:44:35 GMT-0500 (CDT)


text:
'use strict';

var Promise = null;
var log = null;

var utils = null;
var product = null;

// the API consumer will get the args and fill in the blanks
// the SDK will pull out the non-empty values and execute the request
var argsForInput = {
  consignments: {
    fetchById: function() {
      return {
        apiId: {
          required: true,
          value: undefined
        }
      };
    },
    products: {
      create: function() {
        return {
          consignmentId: {
            required: true,
            key: 'consignment_id',
            value: undefined
          },
          productId: {
            required: true,
            key: 'product_id',
            value: undefined
          },
          count: {
            required: true,
            key: 'count',
            value: undefined
          },
          cost: {
            required: true,
            key: 'cost',
            value: undefined
          },
          sequenceNumber: {
            required: false,
            key: 'sequence_number',
            value: undefined
          },
          received: {
            required: false,
            key: 'received',
            value: undefined
          }
        };
      },
      update: function() {
        return {
          apiId: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          },
          body: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          }
        };
      },
      remove: function() {
        return {
          apiId: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          }
        };
      },
      fetchById: function() {
        return {
          apiId: {
            required: true,
            value: undefined
          }
        };
      },
      fetchAllByConsignment: function() {
        return {
          consignmentId: {
            required: true,
            key: 'consignment_id',
            value: undefined
          },
          page: {
            required: false,
            key: 'page',
            value: undefined
          },
          pageSize: {
            required: false,
            key: 'page_size',
            value: undefined
          }
        };
      }
    },
    stockOrders: {
      create: function() {
        return {
          name: {
            required: true,
            key: 'name',
            value: undefined
          },
          outletId: {
            required: true,
            key: 'outlet_id',
            value: undefined
          },
          supplierId: {
            required: true, // can be null according to Vend, but we decided to make it mandatory, hmmm...
            key: 'supplier_id',
            value: undefined
          },
          dueAt: {
            required: false, // can be null, ok by Vend
            key: 'due_at',
            value: undefined
          }
        };
      },
      markAsSent: function() {
        return {
          apiId: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          },
          body: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          }
        };
      },
      markAsReceived: function() {
        return {
          apiId: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          },
          body: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          }
        };
      },
      remove: function() {
        return {
          apiId: {
            required: true,
            //id: undefined, // does not travel as a key/value property in the JSON payload
            value: undefined
          }
        };
      }
    }
  }
};

// TODO: need to add a test
var defaultMethod_ForProcessingPagedResults_ForConsignmentProducts = function(pagedData, previousData){ // eslint-disable-line camelcase
  log.debug('defaultMethod_ForProcessingPagedResults_ForConsignmentProducts');
  if (previousData && previousData.length>0) {
    //log.verbose(JSON.stringify(pagedData.consignment_products,replacer,2));
    if (pagedData.consignment_products && pagedData.consignment_products.length>0) {
      log.debug('previousData: ', previousData.length);
      pagedData.consignment_products = pagedData.consignment_products.concat(previousData); // eslint-disable-line camelcase
      log.debug('combined: ', pagedData.consignment_products.length);
    }
    else {
      pagedData.consignment_products = previousData; // eslint-disable-line camelcase
    }
  }
  //log.silly('finalData: ', pagedData.consignment_products);
  log.debug('finalData.length: ', pagedData.consignment_products.length);
  return Promise.resolve(pagedData.consignment_products);
};

// TODO: need to add a test
var fetchStockOrdersForSuppliers = function(args, connectionInfo, retryCounter) {
  log.debug('inside fetchStockOrderForSuppliers()');
  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment';
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.debug('GET ' + vendUrl);
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    method: 'GET',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Accept': 'application/json'
    },
    qs: {
      page: args.page.value,
      page_size: args.pageSize.value // eslint-disable-line camelcase
    }
  };

  return utils.sendRequest(options, args, connectionInfo, fetchStockOrdersForSuppliers, retryCounter);
};

// TODO: need to add a test
var fetchAllStockOrdersForSuppliers = function(connectionInfo, processPagedResults) {
  var args = {
    page: {value: 1},//{value: 25},
    pageSize: {value: 200}
  };
  // set a default function if none is provided
  if (!processPagedResults) {
    processPagedResults = function(pagedData, previousData){
      if (previousData && previousData.length>0) {
        if (pagedData.consignments.length>0) {
          log.debug('previousData: ', previousData.length);
          pagedData.consignments = pagedData.consignments.concat(previousData);
          log.debug('combined: ', pagedData.consignments.length);
        }
        else {
          pagedData.consignments = previousData;
        }
      }
      return Promise.resolve(pagedData.consignments);
    };
  }
  return utils.processPagesRecursively(args, connectionInfo, fetchStockOrdersForSuppliers, processPagedResults);
};

var fetchConsignment  = function(args, connectionInfo, retryCounter) {
  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/1.0/consignment/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  log.debug('Requesting vend consignment ' + vendUrl);
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.debug('GET ' + vendUrl);
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Accept': 'application/json'
    }
  };

  return utils.sendRequest(options, args, connectionInfo, fetchConsignment, retryCounter);
};

// TODO: need to add a test
var fetchProductsByConsignment  = function(args, connectionInfo, retryCounter) {
  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment_product';
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  log.debug('Requesting vend product ' + vendUrl);
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.debug('GET ' + vendUrl);
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Accept': 'application/json'
    },
    qs: {
      consignment_id: args.consignmentId.value, // eslint-disable-line camelcase
      page: args.page.value,
      page_size: args.pageSize.value // eslint-disable-line camelcase
    }
  };

  return utils.sendRequest(options, args, connectionInfo, fetchProductsByConsignment, retryCounter);
};

// TODO: need to add a test
var fetchAllProductsByConsignment = function(args, connectionInfo, processPagedResults) {
  args.page = {value: 1};
  args.pageSize = {value: 200};
  // set a default function if none is provided
  if (!processPagedResults) {
    processPagedResults = defaultMethod_ForProcessingPagedResults_ForConsignmentProducts; // eslint-disable-line camelcase
  }
  return utils.processPagesRecursively(args, connectionInfo, fetchProductsByConsignment, processPagedResults);
};

// TODO: need to add a test
var fetchAllProductsByConsignments = function(args, connectionInfo, processPagedResults) {
  // args.consignmentIds.value MUST already be set
  args.page = {value: 1};
  args.pageSize = {value: 200};
  args.consignmentIdIndex = {value: 0};
  args.consignmentId = {value: args.consignmentIds.value[args.consignmentIdIndex.value]};
  args.getArray = function(){
    return this.consignmentIds.value;
  };
  args.getArrayIndex = function(){
    return this.consignmentIdIndex.value;
  };

  // iterate serially through a promise chain for all args.consignmentIds.value
  return utils.processPromisesSerially(
    args.consignmentIds.value,
    args.consignmentIdIndex.value,
    args,
    function mergeStrategy(newData, previousData){
      log.debug('inside mergeStrategy()');
      //log.silly('newData ', newData);
      //log.silly('previousData ', previousData);
      if (previousData && previousData.length>0) {
        if (newData.length>0) {
          log.debug('previousData.length: ', previousData.length);
          newData = newData.concat(previousData);
          log.debug('combinedData.length: ', newData.length);
        }
        else {
          newData = previousData;
        }
      }
      //log.silly('finalData ', newData);
      log.debug('finalData.length ', newData.length);
      return Promise.resolve(newData); // why do we need a promise?
    },
    function setupNext(updateArgs){
      updateArgs.consignmentIdIndex.value = updateArgs.consignmentIdIndex.value + 1;
      if (updateArgs.consignmentIdIndex.value < updateArgs.consignmentIds.value.length) {
        updateArgs.consignmentId.value = updateArgs.consignmentIds.value[updateArgs.consignmentIdIndex.value];
        log.debug('next is consignmentId: ' + updateArgs.consignmentId.value);
      }
      else {
        updateArgs.consignmentId.value = null;
        log.debug('finished iterating through all the consignmentIds');
      }
      return updateArgs;
    },
    function executeNext(updatedArgs){
      log.debug('executing for consignmentId: ' + updatedArgs.consignmentId.value);
      //log.silly('updatedArgs: ', updatedArgs);
      return fetchAllProductsByConsignment(updatedArgs, connectionInfo, processPagedResults);
    }
  );
};

// TODO: need to add a test
var resolveMissingSuppliers = function(args, connectionInfo) {
  // args.consignmentIdToProductIdMap.value MUST already be set by the caller
  // args.consignmentProductId.value MUST be set for the very first call
  args.arrayIndex = {value: 0};
  args.consignmentProductId = {value: args.consignmentIdToProductIdMap.value[args.arrayIndex.value].productId};
  args.getArray = function(){
    return this.consignmentIdToProductIdMap.value;
  };
  args.getArrayIndex = function(){
    return this.arrayIndex.value;
  };

  // iterate serially through a promise chain for all args.consignmentIds.value
  return utils.processPromisesSerially(
    args.getArray(),
    args.getArrayIndex(),
    args,
    function mergeStrategy(newData, previousData, args){
      log.debug('resolveMissingSuppliers - inside mergeStrategy()');
      var product = newData.products[0];
      //log.silly('newData: ', newData);
      //log.silly('product: ', product);
      var updateMe = args.getArray()[args.getArrayIndex()];
      updateMe.supplier = product.supplier_name || product.supplier_code;
      log.debug('updated consignmentIdToProductIdMap: ', args.getArray()[args.getArrayIndex()]);

      previousData = args.getArray();
      return Promise.resolve(previousData); // why do we need a promise?
    },
    function setupNext(updateArgs){
      log.debug('resolveMissingSuppliers - inside setupNext()');
      updateArgs.arrayIndex.value = updateArgs.getArrayIndex() + 1;
      if (updateArgs.getArrayIndex() < updateArgs.getArray().length) {
        updateArgs.consignmentProductId.value = updateArgs.getArray()[updateArgs.getArrayIndex()].productId;
        log.debug('resolveMissingSuppliers - next is consignmentId: ' + updateArgs.consignmentProductId.value);
      }
      else {
        updateArgs.consignmentProductId.value = null;
        log.debug('resolveMissingSuppliers - finished iterating through all the consignmentIds');
      }
      return updateArgs;
    },
    function executeNext(updatedArgs){
      log.debug('resolveMissingSuppliers - inside executeNext()');
      log.debug('resolveMissingSuppliers - executing for consignmentProductId: ' + updatedArgs.consignmentProductId.value);
      //log.silly('updatedArgs: ', updatedArgs);
      var args = argsForInput.products.fetchById();
      args.apiId.value = updatedArgs.consignmentProductId.value;
      return product.endpoints.fetchProduct(args, connectionInfo);
    }
  );
};

var fetchConsignmentProductById  = function(args, connectionInfo, retryCounter) {
  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/1.0/consignment_product/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  log.debug('Requesting vend consignment product ' + vendUrl);
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.debug('GET ' + vendUrl);
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Accept': 'application/json'
    }
  };

  return utils.sendRequest(options, args, connectionInfo, fetchConsignment, retryCounter);
};

var createConsignmentProduct = function(args, connectionInfo, retryCounter) {
  log.debug('inside createConsignmentProduct()');

  var body = null;
  if (args && args.body) {
    body = args.body;
  }
  else {
    if ( !(args && utils.argsAreValid(args)) ) {
      return Promise.reject('missing required arguments for createConsignmentProduct()');
    }
    body = {
      'consignment_id': args.consignmentId.value,
      'product_id': args.productId.value,
      'count': args.count.value,
      'cost': args.cost.value,
      'sequence_number': args.sequenceNumber.value,
      'received': args.received.value,
    };
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment_product';
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    method: 'POST',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    json: body
  };
  log.debug(options.method + ' ' + options.url);

  return utils.sendRequest(options, args, connectionInfo, createConsignmentProduct, retryCounter);
};

var createStockOrder = function(args, connectionInfo, retryCounter) {
  log.debug('inside createStockOrder()');

  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for createStockOrder()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment';
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;

  var body = {
    'type': 'SUPPLIER',
    'status': 'OPEN',
    'name': args.name.value,
    'due_at': args.dueAt.value, // caller must format it as `YYYY-MM-DD HH:mm:ss', example: '2010-01-01 14:01:01'
    'outlet_id': args.outletId.value,
    'supplier_id': args.supplierId.value
  };
  var options = {
    method: 'POST',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    json: body
  };
  log.debug(options.method + ' ' + options.url);

  return utils.sendRequest(options, args, connectionInfo, createStockOrder, retryCounter);
};

// TODO: need to add a test
var updateConsignmentProduct = function(args, connectionInfo, retryCounter) {
  log.debug('inside updateConsignmentProduct()', args);

  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for updateConsignmentProduct()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment_product/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?
  var body = args.body.value;

  var options = {
    method: 'PUT',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    json: body
  };
  log.debug(options.method, options.url);
  log.debug('body:', options.json);

  return utils.sendRequest(options, args, connectionInfo, updateConsignmentProduct, retryCounter);
};

var markStockOrderAsSent = function(args, connectionInfo, retryCounter) {
  log.debug('inside markStockOrderAsSent()', args);

  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for markStockOrderAsSent()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?
  var body = args.body.value;
  body.status = 'SENT';

  var options = {
    method: 'PUT',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    json: body
  };
  log.debug(options.method, options.url);
  log.debug('body:', options.json);

  return utils.sendRequest(options, args, connectionInfo, markStockOrderAsSent, retryCounter);
};

var markStockOrderAsReceived = function(args, connectionInfo, retryCounter) {
  log.debug('inside markStockOrderAsReceived()', args);

  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for markStockOrderAsReceived()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  var path = '/api/consignment/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?
  var body = args.body.value;
  body.status = 'RECEIVED';

  var options = {
    method: 'PUT',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    json: body
  };
  log.debug(options.method, options.url);
  log.debug('body:', options.json);

  return utils.sendRequest(options, args, connectionInfo, markStockOrderAsReceived, retryCounter);
};

var deleteStockOrder = function(args, connectionInfo, retryCounter) {
  log.debug('inside deleteStockOrder()');

  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for deleteStockOrder()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  log.debug(args.apiId.value);
  var path = '/api/consignment/' + args.apiId.value;
  log.debug(path);
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    method: 'DELETE',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  };
  log.debug(options.method + ' ' + options.url);

  return utils.sendRequest(options, args, connectionInfo, deleteStockOrder, retryCounter);
};

var deleteConsignmentProduct = function(args, connectionInfo, retryCounter) {
  log.debug('inside deleteConsignmentProduct()');

  log.debug(args);
  if ( !(args && utils.argsAreValid(args)) ) {
    return Promise.reject('missing required arguments for deleteStockOrder()');
  }

  if (!retryCounter) {
    retryCounter = 0;
  } else {
    log.debug('retry # ' + retryCounter);
  }

  log.debug('args.apiId.value: ' + args.apiId.value);
  var path = '/api/consignment_product/' + args.apiId.value;
  var vendUrl = 'https://' + connectionInfo.domainPrefix + '.vendhq.com' + path;
  var authString = 'Bearer ' + connectionInfo.accessToken;
  log.silly('Authorization: ' + authString); // TODO: sensitive data ... do not log?

  var options = {
    method: 'DELETE',
    url: vendUrl,
    headers: {
      'Authorization': authString,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  };
  log.debug(options.method + ' ' + options.url);

  return utils.sendRequest(options, args, connectionInfo, deleteConsignmentProduct, retryCounter);
};

module.exports = function(dependencies) {
  // (1) initialize dependencies such that code can be reused both on client and server side
  Promise = dependencies.bluebird;
  log = dependencies.winston;

  // (2) initialize any module-scoped variables which need the dependencies
  utils = dependencies.utils;
  product = dependencies.product;

  // (3) expose the SDK
  return {
    args: argsForInput.consignments,
    endpoints: {
      fetchById: fetchConsignment,
      stockOrders: {
        create: createStockOrder,
        markAsSent: markStockOrderAsSent,
        markAsReceived: markStockOrderAsReceived,
        fetch: fetchStockOrdersForSuppliers,
        fetchAll: fetchAllStockOrdersForSuppliers,
        resolveMissingSuppliers: resolveMissingSuppliers,
        remove: deleteStockOrder
      },
      products: {
        create: createConsignmentProduct,
        update: updateConsignmentProduct,
        fetch: fetchProductsByConsignment,
        fetchById: fetchConsignmentProductById,
        fetchAllByConsignment: fetchAllProductsByConsignment,
        fetchAllForConsignments: fetchAllProductsByConsignments,
        remove: deleteConsignmentProduct
      }
    }
  };
};


text:
/* Arrays of unknown size with element type a VLA type should not be
   initialized (C99 isn't clear about whether such arrays are VLAs,
   but this is the only reasonable interpretation).  Bug 16409, first
   testcase.  */
/* { dg-do compile } */
/* { dg-options "" } */

const int i = 1;
void foo() { char a[][i] = {""}; } /* { dg-error "error: variable-sized object may not be initialized" } */
/* { dg-error "array size missing in 'a'" "extra error" { target *-*-* } 9 } */


text:
/* eslint-disable @typescript-eslint/no-var-requires */
import { ComponentWrapper } from '../../shared/component-wrapper/component-wrapper.component';
import { NgbdApiPage } from '../../shared/api-page/api-page.component';
import { NgbdExamplesPage } from '../../shared/examples-page/examples.component';
import { NgbdRatingBasic } from './demos/basic/rating-basic';
import { NgbdRatingConfig } from './demos/config/rating-config';
import { NgbdRatingDecimal } from './demos/decimal/rating-decimal';
import { NgbdRatingEvents } from './demos/events/rating-events';
import { NgbdRatingForm } from './demos/form/rating-form';
import { NgbdRatingTemplate } from './demos/template/rating-template';
import { Routes } from '@angular/router';
import { ENVIRONMENT_INITIALIZER, inject } from '@angular/core';
import { NgbdDemoListService } from '../../services/demo-list.service';

const DEMOS = {
	basic: {
		title: 'Basic demo',
		type: NgbdRatingBasic,
		code: require('!!raw-loader!./demos/basic/rating-basic').default,
		markup: require('!!raw-loader!./demos/basic/rating-basic.html').default,
	},
	events: {
		title: 'Events and readonly ratings',
		type: NgbdRatingEvents,
		code: require('!!raw-loader!./demos/events/rating-events').default,
		markup: require('!!raw-loader!./demos/events/rating-events.html').default,
	},
	template: {
		title: 'Custom star template',
		type: NgbdRatingTemplate,
		code: require('!!raw-loader!./demos/template/rating-template').default,
		markup: require('!!raw-loader!./demos/template/rating-template.html').default,
	},
	decimal: {
		title: 'Custom decimal rating',
		type: NgbdRatingDecimal,
		code: require('!!raw-loader!./demos/decimal/rating-decimal').default,
		markup: require('!!raw-loader!./demos/decimal/rating-decimal.html').default,
	},
	form: {
		title: 'Form integration',
		type: NgbdRatingForm,
		code: require('!!raw-loader!./demos/form/rating-form').default,
		markup: require('!!raw-loader!./demos/form/rating-form.html').default,
	},
	config: {
		title: 'Global configuration of ratings',
		type: NgbdRatingConfig,
		code: require('!!raw-loader!./demos/config/rating-config').default,
		markup: require('!!raw-loader!./demos/config/rating-config.html').default,
	},
};

export const ROUTES: Routes = [
	{ path: '', pathMatch: 'full', redirectTo: 'examples' },
	{
		path: '',
		component: ComponentWrapper,
		providers: [
			{
				provide: ENVIRONMENT_INITIALIZER,
				multi: true,
				useValue: () => inject(NgbdDemoListService).register('rating', DEMOS),
			},
		],
		children: [
			{ path: 'examples', component: NgbdExamplesPage },
			{ path: 'api', component: NgbdApiPage },
		],
	},
];


text:
const keytar = require('keytar');
const debug = require('debug')('mongodb-storage-mixin:backends:secure-main');

if (process && process.type === 'browser') {
  const ipc = require('hadron-ipc');

  /**
   * Clear the entire namespace. Use with caution!
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:clear', (evt, meta) => {
    debug('Clearing all secure values for', meta.serviceName);

    let promise;
    try {
      promise = keytar.findCredentials(meta.serviceName);
    } catch (e) {
      debug('Error calling findCredentials', e);
      throw e;
    }

    promise.then(function(accounts) {
      return Promise.all(
        accounts.map(function(entry) {
          const accountName = entry.account;
          return keytar
            .deletePassword(meta.serviceName, accountName)
            .then(function() {
              debug('Deleted account %s successfully', accountName);
              return accountName;
            })
            .catch(function(err) {
              debug('Failed to delete', accountName, err);
              throw err;
            });
        })
      );
    })
      .then(function(accountNames) {
        debug(
          'Cleared %d accounts for serviceName %s',
          accountNames.length,
          meta.serviceName,
          accountNames
        );
      })
      .catch(function(err) {
        debug('Failed to clear credentials!', err);
      });
  });

  /**
   * Remove a credential.
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:remove', (evt, meta) => {
    keytar
      .deletePassword(meta.serviceName, meta.accountName)
      .then(function() {
        debug('Removed password for', {
          service: meta.serviceName,
          account: meta.accountName
        });
      })
      .catch((err) => {
        debug('Error removing password', err);
      });
  });

  /**
   * Update a credential.
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:update', (evt, meta) => {
    keytar
      .setPassword(meta.serviceName, meta.accountName, meta.value)
      .then(function() {
        debug('Updated password successfully for', {
          service: meta.serviceName,
          account: meta.accountName
        });
      })
      .catch(function(err) {
        debug('Error updating password', err);
      });
  });

  /**
   * Create a credential.
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:create', (evt, meta) => {
    keytar
      .setPassword(meta.serviceName, meta.accountName, meta.value)
      .then(function() {
        debug('Successfully dreated password for', {
          service: meta.serviceName,
          account: meta.accountName
        });
      })
      .catch(function(err) {
        debug('Error creating password', err);
      });
  });

  /**
   * Find a credential.
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:find-one', (evt, meta) => {
    keytar
      .getPassword(meta.serviceName, meta.accountName)
      .then(function(rawJsonString) {
        ipc.broadcast('storage-mixin:find-one:result', {
          uuid: meta.uuid,
          rawJsonString: rawJsonString
        });
      })
      .catch(function(err) {
        debug('Error finding one', err);
      });
  });

  /**
   * Find all credentials.
   *
   * @param {Event} evt - The event.
   * @param {Object} meta - The metadata.
   */
  ipc.respondTo('storage-mixin:find', (evt, meta) => {
    keytar
      .findCredentials(meta.namespace)
      .then(function(credentials) {
        ipc.broadcast('storage-mixin:find:result', {
          namespace: meta.namespace,
          credentials: credentials,
          callId: meta.callId
        });
      })
      .catch(function(err) {
        debug('Error finding', err);
      });
  });
}