text:
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Definition of the ChannelRequest class. The request
 * object encapsulates the logic for making a single request, either for the
 * forward channel, back channel, or test channel, to the server. It contains
 * the logic for the two types of transports we use:
 * XMLHTTP and Image request. It provides timeout detection. More transports
 * to be added in future, such as Fetch, WebSocket.
 *
 * @visibility {:internal}
 */

goog.provide('goog.labs.net.webChannel.ChannelRequest');

goog.require('goog.Timer');
goog.require('goog.async.Throttle');
goog.require('goog.events.EventHandler');
goog.require('goog.labs.net.webChannel.Channel');
goog.require('goog.labs.net.webChannel.WebChannelDebug');
goog.require('goog.labs.net.webChannel.requestStats');
goog.require('goog.labs.net.webChannel.requestStats.ServerReachability');
goog.require('goog.labs.net.webChannel.requestStats.Stat');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.userAgent');

/**
 * A new ChannelRequest is created for each request to the server.
 *
 * @param {goog.labs.net.webChannel.Channel} channel
 *     The channel that owns this request.
 * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A
 *     WebChannelDebug to use for logging.
 * @param {string=} opt_sessionId The session id for the channel.
 * @param {string|number=} opt_requestId The request id for this request.
 * @param {number=} opt_retryId The retry id for this request.
 * @constructor
 * @struct
 * @final
 */
goog.labs.net.webChannel.ChannelRequest = function(
    channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
  /**
   * The channel object that owns the request.
   * @private {goog.labs.net.webChannel.Channel}
   */
  this.channel_ = channel;

  /**
   * The channel debug to use for logging
   * @private {goog.labs.net.webChannel.WebChannelDebug}
   */
  this.channelDebug_ = channelDebug;

  /**
   * The Session ID for the channel.
   * @private {string|undefined}
   */
  this.sid_ = opt_sessionId;

  /**
   * The RID (request ID) for the request.
   * @private {string|number|undefined}
   */
  this.rid_ = opt_requestId;

  /**
   * The attempt number of the current request.
   * @private {number}
   */
  this.retryId_ = opt_retryId || 1;

  /**
   * An object to keep track of the channel request event listeners.
   * @private {!goog.events.EventHandler<
   *     !goog.labs.net.webChannel.ChannelRequest>}
   */
  this.eventHandler_ = new goog.events.EventHandler(this);

  /**
   * The timeout in ms before failing the request.
   * @private {number}
   */
  this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;

  /**
   * A timer for polling responseText in browsers that don't fire
   * onreadystatechange during incremental loading of responseText.
   * @private {goog.Timer}
   */
  this.pollingTimer_ = new goog.Timer();

  this.pollingTimer_.setInterval(
      goog.labs.net.webChannel.ChannelRequest.POLLING_INTERVAL_MS_);

  /**
   * Extra HTTP headers to add to all the requests sent to the server.
   * @private {Object}
   */
  this.extraHeaders_ = null;

  /**
   * Whether the request was successful. This is only set to true after the
   * request successfully completes.
   * @private {boolean}
   */
  this.successful_ = false;

  /**
   * The TimerID of the timer used to detect if the request has timed-out.
   * @type {?number}
   * @private
   */
  this.watchDogTimerId_ = null;

  /**
   * The time in the future when the request will timeout.
   * @private {?number}
   */
  this.watchDogTimeoutTime_ = null;

  /**
   * The time the request started.
   * @private {?number}
   */
  this.requestStartTime_ = null;

  /**
   * The type of request (XMLHTTP, IMG)
   * @private {?number}
   */
  this.type_ = null;

  /**
   * The base Uri for the request. The includes all the parameters except the
   * one that indicates the retry number.
   * @private {goog.Uri}
   */
  this.baseUri_ = null;

  /**
   * The request Uri that was actually used for the most recent request attempt.
   * @private {goog.Uri}
   */
  this.requestUri_ = null;

  /**
   * The post data, if the request is a post.
   * @private {?string}
   */
  this.postData_ = null;

  /**
   * The XhrLte request if the request is using XMLHTTP
   * @private {goog.net.XhrIo}
   */
  this.xmlHttp_ = null;

  /**
   * The position of where the next unprocessed chunk starts in the response
   * text.
   * @private {number}
   */
  this.xmlHttpChunkStart_ = 0;

  /**
   * The verb (Get or Post) for the request.
   * @private {?string}
   */
  this.verb_ = null;

  /**
   * The last error if the request failed.
   * @private {?goog.labs.net.webChannel.ChannelRequest.Error}
   */
  this.lastError_ = null;

  /**
   * The last status code received.
   * @private {number}
   */
  this.lastStatusCode_ = -1;

  /**
   * Whether to send the Connection:close header as part of the request.
   * @private {boolean}
   */
  this.sendClose_ = true;

  /**
   * Whether the request has been cancelled due to a call to cancel.
   * @private {boolean}
   */
  this.cancelled_ = false;

  /**
   * A throttle time in ms for readystatechange events for the backchannel.
   * Useful for throttling when ready state is INTERACTIVE (partial data).
   * If set to zero no throttle is used.
   *
   * See WebChannelBase.prototype.readyStateChangeThrottleMs_
   *
   * @private {number}
   */
  this.readyStateChangeThrottleMs_ = 0;

  /**
   * The throttle for readystatechange events for the current request, or null
   * if there is none.
   * @private {goog.async.Throttle}
   */
  this.readyStateChangeThrottle_ = null;

  /**
   * Whether to the result is expected to be encoded for chunking and thus
   * requires decoding.
   * @private {boolean}
   */
  this.decodeChunks_ = false;
};

goog.scope(function() {
var Channel = goog.labs.net.webChannel.Channel;
var ChannelRequest = goog.labs.net.webChannel.ChannelRequest;
var requestStats = goog.labs.net.webChannel.requestStats;
var WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;

/**
 * Default timeout in MS for a request. The server must return data within this
 * time limit for the request to not timeout.
 * @private {number}
 */
ChannelRequest.TIMEOUT_MS_ = 45 * 1000;

/**
 * How often to poll (in MS) for changes to responseText in browsers that don't
 * fire onreadystatechange during incremental loading of responseText.
 * @private {number}
 */
ChannelRequest.POLLING_INTERVAL_MS_ = 250;

/**
 * Enum for channel requests type
 * @enum {number}
 * @private
 */
ChannelRequest.Type_ = {
  /**
   * XMLHTTP requests.
   */
  XML_HTTP: 1,

  /**
   * IMG requests.
   */
  CLOSE_REQUEST: 2
};

/**
 * Enum type for identifying an error.
 * @enum {number}
 */
ChannelRequest.Error = {
  /**
   * Errors due to a non-200 status code.
   */
  STATUS: 0,

  /**
   * Errors due to no data being returned.
   */
  NO_DATA: 1,

  /**
   * Errors due to a timeout.
   */
  TIMEOUT: 2,

  /**
   * Errors due to the server returning an unknown.
   */
  UNKNOWN_SESSION_ID: 3,

  /**
   * Errors due to bad data being received.
   */
  BAD_DATA: 4,

  /**
   * Errors due to the handler throwing an exception.
   */
  HANDLER_EXCEPTION: 5,

  /**
   * The browser declared itself offline during the request.
   */
  BROWSER_OFFLINE: 6
};

/**
 * Returns a useful error string for debugging based on the specified error
 * code.
 * @param {?ChannelRequest.Error} errorCode The error code.
 * @param {number} statusCode The HTTP status code.
 * @return {string} The error string for the given code combination.
 */
ChannelRequest.errorStringFromCode = function(errorCode, statusCode) {
  switch (errorCode) {
    case ChannelRequest.Error.STATUS:
      return 'Non-200 return code (' + statusCode + ')';
    case ChannelRequest.Error.NO_DATA:
      return 'XMLHTTP failure (no data)';
    case ChannelRequest.Error.TIMEOUT:
      return 'HttpConnection timeout';
    default:
      return 'Unknown error';
  }
};

/**
 * Sentinel value used to indicate an invalid chunk in a multi-chunk response.
 * @private {Object}
 */
ChannelRequest.INVALID_CHUNK_ = {};

/**
 * Sentinel value used to indicate an incomplete chunk in a multi-chunk
 * response.
 * @private {Object}
 */
ChannelRequest.INCOMPLETE_CHUNK_ = {};

/**
 * Returns whether XHR streaming is supported on this browser.
 *
 * @return {boolean} Whether XHR streaming is supported.
 * @see http://code.google.com/p/closure-library/issues/detail?id=346
 */
ChannelRequest.supportsXhrStreaming = function() {
  return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);
};

/**
 * Sets extra HTTP headers to add to all the requests sent to the server.
 *
 * @param {Object} extraHeaders The HTTP headers.
 */
ChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {
  this.extraHeaders_ = extraHeaders;
};

/**
 * Sets the timeout for a request
 *
 * @param {number} timeout   The timeout in MS for when we fail the request.
 */
ChannelRequest.prototype.setTimeout = function(timeout) {
  this.timeout_ = timeout;
};

/**
 * Sets the throttle for handling onreadystatechange events for the request.
 *
 * @param {number} throttle The throttle in ms.  A value of zero indicates
 *     no throttle.
 */
ChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {
  this.readyStateChangeThrottleMs_ = throttle;
};

/**
 * Uses XMLHTTP to send an HTTP POST to the server.
 *
 * @param {goog.Uri} uri  The uri of the request.
 * @param {string} postData  The data for the post body.
 * @param {boolean} decodeChunks  Whether to the result is expected to be
 *     encoded for chunking and thus requires decoding.
 */
ChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {
  this.type_ = ChannelRequest.Type_.XML_HTTP;
  this.baseUri_ = uri.clone().makeUnique();
  this.postData_ = postData;
  this.decodeChunks_ = decodeChunks;
  this.sendXmlHttp_(null /* hostPrefix */);
};

/**
 * Uses XMLHTTP to send an HTTP GET to the server.
 *
 * @param {goog.Uri} uri  The uri of the request.
 * @param {boolean} decodeChunks  Whether to the result is expected to be
 *     encoded for chunking and thus requires decoding.
 * @param {?string} hostPrefix  The host prefix, if we might be using a
 *     secondary domain.  Note that it should also be in the URL, adding this
 *     won't cause it to be added to the URL.
 * @param {boolean=} opt_noClose   Whether to request that the tcp/ip connection
 *     should be closed.
 */
ChannelRequest.prototype.xmlHttpGet = function(
    uri, decodeChunks, hostPrefix, opt_noClose) {
  this.type_ = ChannelRequest.Type_.XML_HTTP;
  this.baseUri_ = uri.clone().makeUnique();
  this.postData_ = null;
  this.decodeChunks_ = decodeChunks;
  if (opt_noClose) {
    this.sendClose_ = false;
  }

  this.sendXmlHttp_(hostPrefix);
};

/**
 * Sends a request via XMLHTTP according to the current state of the request
 * object.
 *
 * @param {?string} hostPrefix The host prefix, if we might be using a secondary
 *     domain.
 * @private
 */
ChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {
  this.requestStartTime_ = goog.now();
  this.ensureWatchDogTimer_();

  // clone the base URI to create the request URI. The request uri has the
  // attempt number as a parameter which helps in debugging.
  this.requestUri_ = this.baseUri_.clone();
  this.requestUri_.setParameterValues('t', this.retryId_);

  // send the request either as a POST or GET
  this.xmlHttpChunkStart_ = 0;
  var useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();
  this.xmlHttp_ =
      this.channel_.createXhrIo(useSecondaryDomains ? hostPrefix : null);

  if (this.readyStateChangeThrottleMs_ > 0) {
    this.readyStateChangeThrottle_ = new goog.async.Throttle(
        goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),
        this.readyStateChangeThrottleMs_);
  }

  this.eventHandler_.listen(
      this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,
      this.readyStateChangeHandler_);

  var headers = this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};
  if (this.postData_) {
    this.verb_ = 'POST';
    headers['Content-Type'] = 'application/x-www-form-urlencoded';
    this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);
  } else {
    this.verb_ = 'GET';

    // If the user agent is webkit, we cannot send the close header since it is
    // disallowed by the browser.  If we attempt to set the "Connection: close"
    // header in WEBKIT browser, it will actually causes an error message.
    if (this.sendClose_ && !goog.userAgent.WEBKIT) {
      headers['Connection'] = 'close';
    }
    this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);
  }
  requestStats.notifyServerReachabilityEvent(
      requestStats.ServerReachability.REQUEST_MADE);
  this.channelDebug_.xmlHttpChannelRequest(
      this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);
};

/**
 * Handles a readystatechange event.
 * @param {goog.events.Event} evt The event.
 * @private
 */
ChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {
  var xhr = /** @type {goog.net.XhrIo} */ (evt.target);
  var throttle = this.readyStateChangeThrottle_;
  if (throttle &&
      xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {
    // Only throttle in the partial data case.
    this.channelDebug_.debug('Throttling readystatechange.');
    throttle.fire();
  } else {
    // If we haven't throttled, just handle response directly.
    this.xmlHttpHandler_(xhr);
  }
};

/**
 * XmlHttp handler
 * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.
 * @private
 */
ChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {
  requestStats.onStartExecution();

  /** @preserveTry */
  try {
    if (xmlhttp == this.xmlHttp_) {
      this.onXmlHttpReadyStateChanged_();
    } else {
      this.channelDebug_.warning(
          'Called back with an ' +
          'unexpected xmlhttp');
    }
  } catch (ex) {
    this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');
    if (this.xmlHttp_ && this.xmlHttp_.getResponseText()) {
      this.channelDebug_.dumpException(
          ex, 'ResponseText: ' + this.xmlHttp_.getResponseText());
    } else {
      this.channelDebug_.dumpException(ex, 'No response text');
    }
  } finally {
    requestStats.onEndExecution();
  }
};

/**
 * Called by the readystate handler for XMLHTTP requests.
 *
 * @private
 */
ChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {
  var readyState = this.xmlHttp_.getReadyState();
  var errorCode = this.xmlHttp_.getLastErrorCode();
  var statusCode = this.xmlHttp_.getStatus();

  // we get partial results in browsers that support ready state interactive.
  // We also make sure that getResponseText is not null in interactive mode
  // before we continue.  However, we don't do it in Opera because it only
  // fire readyState == INTERACTIVE once.  We need the following code to poll
  if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||
      readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&
          !goog.userAgent.OPERA && !this.xmlHttp_.getResponseText()) {
    // not yet ready
    return;
  }

  // Dispatch any appropriate network events.
  if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&
      errorCode != goog.net.ErrorCode.ABORT) {
    // Pretty conservative, these are the only known scenarios which we'd
    // consider indicative of a truly non-functional network connection.
    if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {
      requestStats.notifyServerReachabilityEvent(
          requestStats.ServerReachability.REQUEST_FAILED);
    } else {
      requestStats.notifyServerReachabilityEvent(
          requestStats.ServerReachability.REQUEST_SUCCEEDED);
    }
  }

  // got some data so cancel the watchdog timer
  this.cancelWatchDogTimer_();

  var status = this.xmlHttp_.getStatus();
  this.lastStatusCode_ = status;
  var responseText = this.xmlHttp_.getResponseText();
  if (!responseText) {
    this.channelDebug_.debug(
        'No response text for uri ' + this.requestUri_ + ' status ' + status);
  }
  this.successful_ = (status == 200);

  this.channelDebug_.xmlHttpChannelResponseMetaData(
      /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,
      this.retryId_, readyState, status);

  if (!this.successful_) {
    if (status == 400 && responseText.indexOf('Unknown SID') > 0) {
      // the server error string will include 'Unknown SID' which indicates the
      // server doesn't know about the session (maybe it got restarted, maybe
      // the user got moved to another server, etc.,). Handlers can special
      // case this error
      this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;
      requestStats.notifyStatEvent(
          requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);
      this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');
    } else {
      this.lastError_ = ChannelRequest.Error.STATUS;
      requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);
      this.channelDebug_.warning(
          'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');
    }
    this.cleanup_();
    this.dispatchFailure_();
    return;
  }

  if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
    this.cleanup_();
  }

  if (this.decodeChunks_) {
    this.decodeNextChunks_(readyState, responseText);
    if (goog.userAgent.OPERA && this.successful_ &&
        readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {
      this.startPolling_();
    }
  } else {
    this.channelDebug_.xmlHttpChannelResponseText(
        this.rid_, responseText, null);
    this.safeOnRequestData_(responseText);
  }

  if (!this.successful_) {
    return;
  }

  if (!this.cancelled_) {
    if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
      this.channel_.onRequestComplete(this);
    } else {
      // The default is false, the result from this callback shouldn't carry
      // over to the next callback, otherwise the request looks successful if
      // the watchdog timer gets called
      this.successful_ = false;
      this.ensureWatchDogTimer_();
    }
  }
};

/**
 * Decodes the next set of available chunks in the response.
 * @param {number} readyState The value of readyState.
 * @param {string} responseText The value of responseText.
 * @private
 */
ChannelRequest.prototype.decodeNextChunks_ = function(
    readyState, responseText) {
  var decodeNextChunksSuccessful = true;
  while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {
    var chunkText = this.getNextChunk_(responseText);
    if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {
      if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
        // should have consumed entire response when the request is done
        this.lastError_ = ChannelRequest.Error.BAD_DATA;
        requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);
        decodeNextChunksSuccessful = false;
      }
      this.channelDebug_.xmlHttpChannelResponseText(
          this.rid_, null, '[Incomplete Response]');
      break;
    } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {
      this.lastError_ = ChannelRequest.Error.BAD_DATA;
      requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);
      this.channelDebug_.xmlHttpChannelResponseText(
          this.rid_, responseText, '[Invalid Chunk]');
      decodeNextChunksSuccessful = false;
      break;
    } else {
      this.channelDebug_.xmlHttpChannelResponseText(
          this.rid_, /** @type {string} */ (chunkText), null);
      this.safeOnRequestData_(/** @type {string} */ (chunkText));
    }
  }
  if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&
      responseText.length == 0) {
    // also an error if we didn't get any response
    this.lastError_ = ChannelRequest.Error.NO_DATA;
    requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);
    decodeNextChunksSuccessful = false;
  }
  this.successful_ = this.successful_ && decodeNextChunksSuccessful;
  if (!decodeNextChunksSuccessful) {
    // malformed response - we make this trigger retry logic
    this.channelDebug_.xmlHttpChannelResponseText(
        this.rid_, responseText, '[Invalid Chunked Response]');
    this.cleanup_();
    this.dispatchFailure_();
  }
};

/**
 * Polls the response for new data.
 * @private
 */
ChannelRequest.prototype.pollResponse_ = function() {
  var readyState = this.xmlHttp_.getReadyState();
  var responseText = this.xmlHttp_.getResponseText();
  if (this.xmlHttpChunkStart_ < responseText.length) {
    this.cancelWatchDogTimer_();
    this.decodeNextChunks_(readyState, responseText);
    if (this.successful_ &&
        readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {
      this.ensureWatchDogTimer_();
    }
  }
};

/**
 * Starts a polling interval for changes to responseText of the
 * XMLHttpRequest, for browsers that don't fire onreadystatechange
 * as data comes in incrementally.  This timer is disabled in
 * cleanup_().
 * @private
 */
ChannelRequest.prototype.startPolling_ = function() {
  this.eventHandler_.listen(
      this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);
  this.pollingTimer_.start();
};

/**
 * Returns the next chunk of a chunk-encoded response. This is not standard
 * HTTP chunked encoding because browsers don't expose the chunk boundaries to
 * the application through XMLHTTP. So we have an additional chunk encoding at
 * the application level that lets us tell where the beginning and end of
 * individual responses are so that we can only try to eval a complete JS array.
 *
 * The encoding is the size of the chunk encoded as a decimal string followed
 * by a newline followed by the data.
 *
 * @param {string} responseText The response text from the XMLHTTP response.
 * @return {string|Object} The next chunk string or a sentinel object
 *                         indicating a special condition.
 * @private
 */
ChannelRequest.prototype.getNextChunk_ = function(responseText) {
  var sizeStartIndex = this.xmlHttpChunkStart_;
  var sizeEndIndex = responseText.indexOf('\n', sizeStartIndex);
  if (sizeEndIndex == -1) {
    return ChannelRequest.INCOMPLETE_CHUNK_;
  }

  var sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);
  var size = Number(sizeAsString);
  if (isNaN(size)) {
    return ChannelRequest.INVALID_CHUNK_;
  }

  var chunkStartIndex = sizeEndIndex + 1;
  if (chunkStartIndex + size > responseText.length) {
    return ChannelRequest.INCOMPLETE_CHUNK_;
  }

  var chunkText = responseText.substr(chunkStartIndex, size);
  this.xmlHttpChunkStart_ = chunkStartIndex + size;
  return chunkText;
};

/**
 * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.
 *
 * This is only currently used to terminate the connection, as an IMG tag is
 * the most reliable way to send something to the server while the page
 * is getting torn down.
 *
 * Navigator.sendBeacon is available on Chrome and Firefox as a formal
 * solution to ensure delivery without blocking window close. See
 * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
 *
 * For Chrome Apps, sendBeacon is always necessary due to Content Security
 * Policy (CSP) violation of using an IMG tag.
 *
 * @param {goog.Uri} uri The uri to send a request to.
 */
ChannelRequest.prototype.sendCloseRequest = function(uri) {
  this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;
  this.baseUri_ = uri.clone().makeUnique();

  var requestSent = false;

  if (goog.global.navigator && goog.global.navigator.sendBeacon) {
    // empty string body to avoid 413 error on chrome < 41
    requestSent =
        goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');
  }

  if (!requestSent) {
    var eltImg = new Image();
    eltImg.src = this.baseUri_;
  }

  this.requestStartTime_ = goog.now();
  this.ensureWatchDogTimer_();
};

/**
 * Cancels the request no matter what the underlying transport is.
 */
ChannelRequest.prototype.cancel = function() {
  this.cancelled_ = true;
  this.cleanup_();
};

/**
 * Ensures that there is watchdog timeout which is used to ensure that
 * the connection completes in time.
 *
 * @private
 */
ChannelRequest.prototype.ensureWatchDogTimer_ = function() {
  this.watchDogTimeoutTime_ = goog.now() + this.timeout_;
  this.startWatchDogTimer_(this.timeout_);
};

/**
 * Starts the watchdog timer which is used to ensure that the connection
 * completes in time.
 * @param {number} time The number of milliseconds to wait.
 * @private
 */
ChannelRequest.prototype.startWatchDogTimer_ = function(time) {
  if (this.watchDogTimerId_ != null) {
    // assertion
    throw Error('WatchDog timer not null');
  }
  this.watchDogTimerId_ =
      requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);
};

/**
 * Cancels the watchdog timer if it has been started.
 *
 * @private
 */
ChannelRequest.prototype.cancelWatchDogTimer_ = function() {
  if (this.watchDogTimerId_) {
    goog.global.clearTimeout(this.watchDogTimerId_);
    this.watchDogTimerId_ = null;
  }
};

/**
 * Called when the watchdog timer is triggered. It also handles a case where it
 * is called too early which we suspect may be happening sometimes
 * (not sure why)
 *
 * @private
 */
ChannelRequest.prototype.onWatchDogTimeout_ = function() {
  this.watchDogTimerId_ = null;
  var now = goog.now();
  if (now - this.watchDogTimeoutTime_ >= 0) {
    this.handleTimeout_();
  } else {
    // got called too early for some reason
    this.channelDebug_.warning('WatchDog timer called too early');
    this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);
  }
};

/**
 * Called when the request has actually timed out. Will cleanup and notify the
 * channel of the failure.
 *
 * @private
 */
ChannelRequest.prototype.handleTimeout_ = function() {
  if (this.successful_) {
    // Should never happen.
    this.channelDebug_.severe(
        'Received watchdog timeout even though request loaded successfully');
  }

  this.channelDebug_.timeoutResponse(this.requestUri_);

  // IMG or SendBeacon requests never notice if they were successful,
  // and always 'time out'. This fact says nothing about reachability.
  if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {
    requestStats.notifyServerReachabilityEvent(
        requestStats.ServerReachability.REQUEST_FAILED);
    requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);
  }

  this.cleanup_();

  // Set error and dispatch failure.
  // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.
  this.lastError_ = ChannelRequest.Error.TIMEOUT;
  this.dispatchFailure_();
};

/**
 * Notifies the channel that this request failed.
 * @private
 */
ChannelRequest.prototype.dispatchFailure_ = function() {
  if (this.channel_.isClosed() || this.cancelled_) {
    return;
  }

  this.channel_.onRequestComplete(this);
};

/**
 * Cleans up the objects used to make the request. This function is
 * idempotent.
 *
 * @private
 */
ChannelRequest.prototype.cleanup_ = function() {
  this.cancelWatchDogTimer_();

  goog.dispose(this.readyStateChangeThrottle_);
  this.readyStateChangeThrottle_ = null;

  // Stop the polling timer, if necessary.
  this.pollingTimer_.stop();

  // Unhook all event handlers.
  this.eventHandler_.removeAll();

  if (this.xmlHttp_) {
    // clear out this.xmlHttp_ before aborting so we handle getting reentered
    // inside abort
    var xmlhttp = this.xmlHttp_;
    this.xmlHttp_ = null;
    xmlhttp.abort();
    xmlhttp.dispose();
  }
};

/**
 * Indicates whether the request was successful. Only valid after the handler
 * is called to indicate completion of the request.
 *
 * @return {boolean} True if the request succeeded.
 */
ChannelRequest.prototype.getSuccess = function() {
  return this.successful_;
};

/**
 * If the request was not successful, returns the reason.
 *
 * @return {?ChannelRequest.Error}  The last error.
 */
ChannelRequest.prototype.getLastError = function() {
  return this.lastError_;
};

/**
 * Returns the status code of the last request.
 * @return {number} The status code of the last request.
 */
ChannelRequest.prototype.getLastStatusCode = function() {
  return this.lastStatusCode_;
};

/**
 * Returns the session id for this channel.
 *
 * @return {string|undefined} The session ID.
 */
ChannelRequest.prototype.getSessionId = function() {
  return this.sid_;
};

/**
 * Returns the request id for this request. Each request has a unique request
 * id and the request IDs are a sequential increasing count.
 *
 * @return {string|number|undefined} The request ID.
 */
ChannelRequest.prototype.getRequestId = function() {
  return this.rid_;
};

/**
 * Returns the data for a post, if this request is a post.
 *
 * @return {?string} The POST data provided by the request initiator.
 */
ChannelRequest.prototype.getPostData = function() {
  return this.postData_;
};

/**
 * Returns the XhrIo request object.
 *
 * @return {?goog.net.XhrIo} Any XhrIo request created for this object.
 */
ChannelRequest.prototype.getXhr = function() {
  return this.xmlHttp_;
};

/**
 * Returns the time that the request started, if it has started.
 *
 * @return {?number} The time the request started, as returned by goog.now().
 */
ChannelRequest.prototype.getRequestStartTime = function() {
  return this.requestStartTime_;
};

/**
 * Helper to call the callback's onRequestData, which catches any
 * exception and cleans up the request.
 * @param {string} data The request data.
 * @private
 */
ChannelRequest.prototype.safeOnRequestData_ = function(data) {
  /** @preserveTry */
  try {
    this.channel_.onRequestData(this, data);
    var stats = requestStats.ServerReachability;
    requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);
  } catch (e) {
    // Dump debug info, but keep going without closing the channel.
    this.channelDebug_.dumpException(e, 'Error in httprequest callback');
  }
};

/**
 * Convenience factory method.
 *
 * @param {Channel} channel The channel object that owns this request.
 * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.
 * @param {string=} opt_sessionId  The session id for the channel.
 * @param {string|number=} opt_requestId  The request id for this request.
 * @param {number=} opt_retryId  The retry id for this request.
 * @return {!ChannelRequest} The created channel request.
 */
ChannelRequest.createChannelRequest = function(
    channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
  return new ChannelRequest(
      channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);
};
});  // goog.scope


text:
using Prism.Unity;
using ArcMovies.Views;
using Xamarin.Forms;

namespace ArcMovies
{
    public partial class App : PrismApplication
    {
        public App() : base(null)
        {
        }

        public App(IPlatformInitializer initializer) : base(initializer)
        {
        }

        protected override void OnInitialized()
        {
            InitializeComponent();

            NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{nameof(MainPage)}");
        }

        protected override void RegisterTypes()
        {
            Container.RegisterTypeForNavigation<NavigationPage>();
            Container.RegisterTypeForNavigation<MainPage>();
            Container.RegisterTypeForNavigation<SearchMoviesPage>();
            Container.RegisterTypeForNavigation<MovieDetailPage>();
        }

        protected override void OnStart()
        {
            base.OnStart();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace DougKlassen.Revit.Perfect.Commands
{
    /// <summary>
    /// Create a quantity schedule using an Excel file as a template
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    class CreateQuantityScheduleCommand : IExternalCommand
    {
        private String filterParamColumnName = "tphase";
        private String labelColumnName = "Description";
        private String unitsColumnName = "Units";
        private String elementCategoryColumnName = "Category";
        private String projectParamColumnName = "Project Parameter";
        private String builtInParamColumnName = "BuiltIn Parameter";
        private String calculationColumnName = "Calculated Field";

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document dbDoc = commandData.Application.ActiveUIDocument.Document;

            String errorFilePath = FileLocations.AddInDirectory + "error" + Helpers.GetTimeStamp() + ".txt";
            String errorMessage = String.Empty;

            OpenFileDialog openDialog = new OpenFileDialog()
            {
                Filter = "Excel file|*.xlsx;*.xlsm",
                Title = "Schedule Template File"
            };
            DialogResult result = openDialog.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                return Result.Cancelled;
            }
            String templateFilePath = openDialog.FileName;
            IQuantityScheduleTemplateRepo repo = new QuantityScheduleTemplateExcelRepo(
                templateFilePath,
                filterParamColumnName,
                labelColumnName,
                unitsColumnName,
                elementCategoryColumnName,
                projectParamColumnName,
                builtInParamColumnName,
                calculationColumnName);

            List<QuantityScheduleTemplate> templates;
            try
            {
                templates = repo.LoadTemplates();
            }
            catch (Exception e)
            {
                errorMessage += "Data:\n";
                foreach (DictionaryEntry de in e.Data)
                {
                    errorMessage += "  " + de.Key.ToString() + ": " + de.Value + "\n";
                }
                errorMessage += "Message:\n" + e.Message + "\n";
                errorMessage += "Stack Trace:\n" + e.StackTrace + "\n";
                File.WriteAllText(errorFilePath, errorMessage);

                TaskDialog.Show(
                    "Create Quantity Schedule Error",
                    "Error reading template file " + templateFilePath + "\nSee error file " + errorFilePath);

                return Result.Failed;
            }

            ChooseScheduleWindow window = new ChooseScheduleWindow(templates);
            String msg = String.Empty;
            msg += String.Format("{0} templates found in file\n", templates.Count);
            window.messageTextBlock.Text = msg;
            Boolean? chooseScheduleResult = window.ShowDialog();
            if (!chooseScheduleResult.Value)
            {
                return Result.Cancelled;
            }

            List<String> errors = new List<String>();
            IEnumerable<QuantityScheduleTemplate> templatesToAdd = window.GetCheckedTemplates();
            foreach (QuantityScheduleTemplate template in templatesToAdd)
            {
                errors.AddRange(Helpers.CreateTemplate(dbDoc, template));
            }

            if (errors.Count > 0)
            {
                errorMessage += "Schedule Creation Errors: \n";
                foreach (String error in errors)
                {
                    errorMessage += "  " + error + "\n";
                }
                File.WriteAllText(errorFilePath, errorMessage);

                TaskDialog.Show(
                    "Couldn't Create Quantity Schedule",
                    "Error creating schedule\nSee error file " + errorFilePath);

                return Result.Failed;
            }

            return Result.Succeeded;
        }
    }
}


text:
// This file was generated using Parlex's cpp_generator

#ifndef INCLUDED_LESSER_CHAIN_LOOP_HPP
#define INCLUDED_LESSER_CHAIN_LOOP_HPP

#include <optional>
#include <variant>
#include <vector>

#include "erased.hpp"

#include "parlex/detail/abstract_syntax_tree.hpp"
#include "parlex/detail/builtins.hpp"
#include "parlex/detail/document.hpp"

#include "plange_grammar.hpp"

namespace plc {

struct EXPRESSION;
struct IC;
struct LESSER_CHAIN_LOOP;

struct LESSER_CHAIN_LOOP {
	struct field_4_t_1_t {
		std::vector<erased<IC>> field_1;

		erased<LESSER_CHAIN_LOOP> field_2;

		explicit field_4_t_1_t(
			std::vector<erased<IC>> && field_1, erased<LESSER_CHAIN_LOOP> && field_2) : field_1(std::move(field_1)), field_2(std::move(field_2)) {}

		field_4_t_1_t(field_4_t_1_t const & other) = default;
		field_4_t_1_t(field_4_t_1_t && move) = default;

		static field_4_t_1_t build(parlex::detail::node const * b, parlex::detail::document::walk & w);
	};

	std::variant<
		parlex::detail::document::text<literal_0x3D_t>,
		parlex::detail::document::text<literal_0x3C_t>,
		parlex::detail::document::text<literal_0x3D0x3C_t>,
		parlex::detail::document::text<literal_0xE20x890xA4_t>
	> field_1;

	std::vector<erased<IC>> field_2;

	erased<EXPRESSION> field_3;

	std::optional<field_4_t_1_t> field_4;

	explicit LESSER_CHAIN_LOOP(
		std::variant<
			parlex::detail::document::text<literal_0x3D_t>,
			parlex::detail::document::text<literal_0x3C_t>,
			parlex::detail::document::text<literal_0x3D0x3C_t>,
			parlex::detail::document::text<literal_0xE20x890xA4_t>
		> && field_1, std::vector<erased<IC>> && field_2, erased<EXPRESSION> && field_3, std::optional<field_4_t_1_t> && field_4) : field_1(std::move(field_1)), field_2(std::move(field_2)), field_3(std::move(field_3)), field_4(std::move(field_4)) {}

	LESSER_CHAIN_LOOP(LESSER_CHAIN_LOOP const & other) = default;
	LESSER_CHAIN_LOOP(LESSER_CHAIN_LOOP && move) = default;

	static LESSER_CHAIN_LOOP build(parlex::detail::ast_node const & n);
	static parlex::detail::state_machine const & state_machine();

};

} // namespace plc

#endif //INCLUDED_LESSER_CHAIN_LOOP_HPP


text:
package org.apache.wss4j.stax.validate;

import java.util.Base64;

import javax.xml.bind.JAXBElement;

import org.apache.wss4j.binding.wss10.BinarySecurityTokenType;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.util.AttachmentUtils;
import org.apache.wss4j.stax.ext.WSSConfigurationException;
import org.apache.wss4j.stax.ext.WSSConstants;
import org.apache.wss4j.stax.ext.WSSSecurityProperties;
import org.apache.wss4j.stax.impl.securityToken.X509V3SecurityTokenImpl;
import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants;
import org.apache.wss4j.stax.impl.securityToken.KerberosServiceSecurityTokenImpl;
import org.apache.wss4j.stax.impl.securityToken.X509PKIPathv1SecurityTokenImpl;
import org.apache.xml.security.binding.xop.Include;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.stax.securityToken.InboundSecurityToken;

public class BinarySecurityTokenValidatorImpl implements BinarySecurityTokenValidator {

    private static final transient org.slf4j.Logger LOG =
        org.slf4j.LoggerFactory.getLogger(BinarySecurityTokenValidatorImpl.class);

    @Override
    public InboundSecurityToken validate(final BinarySecurityTokenType binarySecurityTokenType,
                                                 final TokenContext tokenContext)
            throws WSSecurityException {

        //only Base64Encoding is supported
        if (!WSSConstants.SOAPMESSAGE_NS10_BASE64_ENCODING.equals(binarySecurityTokenType.getEncodingType())) {
            throw new WSSecurityException(
                    WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "badEncoding",
                    new Object[] {binarySecurityTokenType.getEncodingType()});
        }

        try {
            byte[] securityTokenData =
                getBinarySecurityTokenBytes(binarySecurityTokenType, tokenContext.getWssSecurityProperties());

            if (WSSConstants.NS_X509_V3_TYPE.equals(binarySecurityTokenType.getValueType())) {
                Crypto crypto = getCrypto(tokenContext.getWssSecurityProperties());
                X509V3SecurityTokenImpl x509V3SecurityToken = new X509V3SecurityTokenImpl(
                        tokenContext.getWsSecurityContext(),
                        crypto,
                        tokenContext.getWssSecurityProperties().getCallbackHandler(),
                        securityTokenData, binarySecurityTokenType.getId(),
                        tokenContext.getWssSecurityProperties()
                );
                x509V3SecurityToken.setElementPath(tokenContext.getElementPath());
                x509V3SecurityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());
                return x509V3SecurityToken;
            } else if (WSSConstants.NS_X509_PKIPATH_V1.equals(binarySecurityTokenType.getValueType())) {
                Crypto crypto = getCrypto(tokenContext.getWssSecurityProperties());
                X509PKIPathv1SecurityTokenImpl x509PKIPathv1SecurityToken = new X509PKIPathv1SecurityTokenImpl(
                        tokenContext.getWsSecurityContext(),
                        crypto,
                        tokenContext.getWssSecurityProperties().getCallbackHandler(),
                        securityTokenData, binarySecurityTokenType.getId(),
                        WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE,
                        tokenContext.getWssSecurityProperties()
                );
                x509PKIPathv1SecurityToken.setElementPath(tokenContext.getElementPath());
                x509PKIPathv1SecurityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());
                return x509PKIPathv1SecurityToken;
            } else if (WSSConstants.NS_GSS_KERBEROS5_AP_REQ.equals(binarySecurityTokenType.getValueType())) {
                KerberosServiceSecurityTokenImpl kerberosServiceSecurityToken = new KerberosServiceSecurityTokenImpl(
                        tokenContext.getWsSecurityContext(),
                        tokenContext.getWssSecurityProperties().getCallbackHandler(),
                        securityTokenData, binarySecurityTokenType.getValueType(),
                        binarySecurityTokenType.getId(),
                        WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE
                );
                kerberosServiceSecurityToken.setElementPath(tokenContext.getElementPath());
                kerberosServiceSecurityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());
                return kerberosServiceSecurityToken;
            } else {
                throw new WSSecurityException(
                        WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "invalidValueType",
                        new Object[] {binarySecurityTokenType.getValueType()});
            }
        } catch (XMLSecurityException e) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, e);
        }
    }

    private byte[] getBinarySecurityTokenBytes(BinarySecurityTokenType binarySecurityTokenType,
                                               WSSSecurityProperties wssSecurityProperties) throws XMLSecurityException {

        StringBuilder sb = new StringBuilder();

        for (Object obj : binarySecurityTokenType.getContent()) {
            if (obj instanceof String) {
                sb.append((String)obj);
            } else if (obj instanceof JAXBElement<?>) {
                JAXBElement<?> element = (JAXBElement<?>)obj;
                if (XMLSecurityConstants.TAG_XOP_INCLUDE.equals(element.getName())) {
                    Include include = (Include)element.getValue();
                    if (include != null && include.getHref() != null && include.getHref().startsWith("cid:")) {
                        return AttachmentUtils.getBytesFromAttachment(include.getHref(),
                                                                      wssSecurityProperties.getAttachmentCallbackHandler(),
                                                                      true);
                    }
                }
            }
        }

        return Base64.getMimeDecoder().decode(sb.toString());
    }

    protected Crypto getCrypto(WSSSecurityProperties securityProperties) throws WSSConfigurationException {
        Crypto crypto = null;
        try {
            crypto = securityProperties.getSignatureVerificationCrypto();
        } catch (WSSConfigurationException e) {
            LOG.debug(e.getMessage(), e);
            //ignore
        }
        if (crypto == null) {
            crypto = securityProperties.getDecryptionCrypto();
        }
        return crypto;
    }
}


text:
<?php

interface InfiRest_Authorization_Interface {
	function isAuthorized($request, $object=null);
}


text:
package petset

import (
	"fmt"
	"sync"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apis/apps"
	"k8s.io/kubernetes/pkg/client/cache"
	appsclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/apps/internalversion"
	"k8s.io/kubernetes/pkg/controller"

	"github.com/golang/glog"
)

// overlappingStatefulSets sorts a list of StatefulSets by creation timestamp, using their names as a tie breaker.
// Generally used to tie break between StatefulSets that have overlapping selectors.
type overlappingStatefulSets []apps.StatefulSet

func (o overlappingStatefulSets) Len() int      { return len(o) }
func (o overlappingStatefulSets) Swap(i, j int) { o[i], o[j] = o[j], o[i] }

func (o overlappingStatefulSets) Less(i, j int) bool {
	if o[i].CreationTimestamp.Equal(o[j].CreationTimestamp) {
		return o[i].Name < o[j].Name
	}
	return o[i].CreationTimestamp.Before(o[j].CreationTimestamp)
}

// updatePetCount attempts to update the Status.Replicas of the given StatefulSet, with a single GET/PUT retry.
func updatePetCount(psClient appsclientset.StatefulSetsGetter, ps apps.StatefulSet, numPets int) (updateErr error) {
	if ps.Status.Replicas == int32(numPets) || psClient == nil {
		return nil
	}
	var getErr error
	for i, ps := 0, &ps; ; i++ {
		glog.V(4).Infof(fmt.Sprintf("Updating replica count for StatefulSet: %s/%s, ", ps.Namespace, ps.Name) +
			fmt.Sprintf("replicas %d->%d (need %d), ", ps.Status.Replicas, numPets, ps.Spec.Replicas))

		ps.Status = apps.StatefulSetStatus{Replicas: int32(numPets)}
		_, updateErr = psClient.StatefulSets(ps.Namespace).UpdateStatus(ps)
		if updateErr == nil || i >= statusUpdateRetries {
			return updateErr
		}
		if ps, getErr = psClient.StatefulSets(ps.Namespace).Get(ps.Name); getErr != nil {
			return getErr
		}
	}
}

// unhealthyPetTracker tracks unhealthy pets for statefulsets.
type unhealthyPetTracker struct {
	pc        petClient
	store     cache.Store
	storeLock sync.Mutex
}

// Get returns a previously recorded blocking pet for the given statefulset.
func (u *unhealthyPetTracker) Get(ps *apps.StatefulSet, knownPets []*api.Pod) (*pcb, error) {
	u.storeLock.Lock()
	defer u.storeLock.Unlock()

	// We "Get" by key but "Add" by object because the store interface doesn't
	// allow us to Get/Add a related obj (eg statefulset: blocking pet).
	key, err := controller.KeyFunc(ps)
	if err != nil {
		return nil, err
	}
	obj, exists, err := u.store.GetByKey(key)
	if err != nil {
		return nil, err
	}

	hc := defaultPetHealthChecker{}
	// There's no unhealthy pet blocking a scale event, but this might be
	// a controller manager restart. If it is, knownPets can be trusted.
	if !exists {
		for _, p := range knownPets {
			if hc.isHealthy(p) && !hc.isDying(p) {
				glog.V(4).Infof("Ignoring healthy pod %v for StatefulSet %v", p.Name, ps.Name)
				continue
			}
			glog.V(4).Infof("No recorded blocking pod, but found unhealthy pod %v for StatefulSet %v", p.Name, ps.Name)
			return &pcb{pod: p, parent: ps}, nil
		}
		return nil, nil
	}

	// This is a pet that's blocking further creates/deletes of a statefulset. If it
	// disappears, it's no longer blocking. If it exists, it continues to block
	// till it turns healthy or disappears.
	bp := obj.(*pcb)
	blockingPet, exists, err := u.pc.Get(bp)
	if err != nil {
		return nil, err
	}
	if !exists {
		glog.V(4).Infof("Clearing blocking pod %v for StatefulSet %v because it's been deleted", bp.pod.Name, ps.Name)
		return nil, nil
	}
	blockingPetPod := blockingPet.pod
	if hc.isHealthy(blockingPetPod) && !hc.isDying(blockingPetPod) {
		glog.V(4).Infof("Clearing blocking pod %v for StatefulSet %v because it's healthy", bp.pod.Name, ps.Name)
		u.store.Delete(blockingPet)
		blockingPet = nil
	}
	return blockingPet, nil
}

// Add records the given pet as a blocking pet.
func (u *unhealthyPetTracker) Add(blockingPet *pcb) error {
	u.storeLock.Lock()
	defer u.storeLock.Unlock()

	if blockingPet == nil {
		return nil
	}
	glog.V(4).Infof("Adding blocking pod %v for StatefulSet %v", blockingPet.pod.Name, blockingPet.parent.Name)
	return u.store.Add(blockingPet)
}

// newUnHealthyPetTracker tracks unhealthy pets that block progress of statefulsets.
func newUnHealthyPetTracker(pc petClient) *unhealthyPetTracker {
	return &unhealthyPetTracker{pc: pc, store: cache.NewStore(pcbKeyFunc)}
}

// pcbKeyFunc computes the key for a given pcb.
// If it's given a key, it simply returns it.
func pcbKeyFunc(obj interface{}) (string, error) {
	if key, ok := obj.(string); ok {
		return key, nil
	}
	p, ok := obj.(*pcb)
	if !ok {
		return "", fmt.Errorf("not a valid pod control block %#v", p)
	}
	if p.parent == nil {
		return "", fmt.Errorf("cannot compute pod control block key without parent pointer %#v", p)
	}
	return controller.KeyFunc(p.parent)
}


text:
import logging
import logging.config
import sys
import bson

from yamajudge.util import options
from yamajudge import mq
from yamajudge import request
from yamajudge.job import task
from yamajudge.constant import record

options.define('log_format',
               default=('%(log_color)s[%(levelname).1s '
                        '%(asctime)s %(module)s:%(lineno)d]%(reset)s %(message)s'),
               help='Log format.')
options.define('debug', default=False, help='Enable debug mode.')

_logger = logging.getLogger(__name__)

def on_message(channel, method, header, body):
    rid = bson.BSON.decode(body)['rid']
    request.begin_judge(rid)
    try:
        judge_task = task.JudgeTask(rid)
        judge_task.run()
    except Exception as e:
        _logger.error(repr(e))
        request.end_judge(rid, record.STATUS_SYSTEM_ERROR)
    channel.basic_ack(method.delivery_tag)

def main():
    logging.config.dictConfig({
        'version': 1,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'colored',
            },
        },
        'formatters': {
            'colored': {
                '()': 'colorlog.ColoredFormatter',
                'format': options.options.log_format,
                'datefmt': '%y%m%d %H:%M:%S'
            }
        },
        'root': {
            'level': 'DEBUG' if options.options.debug else 'INFO',
            'handlers': ['console'],
        },
        'disable_existing_loggers': False,
    })

    request.init()
    channel = mq.channel('judge')
    channel.queue_declare('judge')
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_message, 'judge')
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()

if __name__ == '__main__':
    sys.exit(main())


text:
cd C:\Users\DanielaPaolo\nicePdOpenshift\MEAN\machine\frontend
npm start


text:
// Copyright 2013 Michel Kraemer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package de.undercouch.citeproc.helper.json;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.junit.Test;

/**
 * Tests the JSON builder that creates maps
 * @author Michel Kraemer
 */
public class MapJsonBuilderTest {
	private JsonBuilderFactory factory = new MapJsonBuilderFactory();

	/**
	 * Tests if a string array is converted correctly
	 */
	@Test
	public void toJsonStringArray() {
		String[] a = new String[] {
				"a", "b", "c", "That's it"
		};
		List<String> l = Arrays.asList(a);
		assertEquals(l, factory.createJsonBuilder().toJson(a));
	}

	/**
	 * Tests if a JsonObject is converted correctly
	 */
	@Test
	@SuppressWarnings("unchecked")
	public void toJsonObject() {
		JsonObject obj = new JsonObject() {
			@Override
			public Object toJson(JsonBuilder builder) {
				int[][] g = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
				builder.add("a", "test");
				builder.add("d", true);
				builder.add("f", 42);
				builder.add("g", g);
				return builder.build();
			}
		};
		Map<String, Object> m = (Map<String, Object>)obj.toJson(factory.createJsonBuilder());
		assertEquals(4, m.size());
		assertEquals(true, m.get("d"));
		assertEquals(42, m.get("f"));
		assertEquals(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4)), m.get("g"));
	}
}


text:
title: Sample Post 4
publishDate: 10/14/2015
tags:
  - sample
  - fourth
  - ruby
summary: |
  Summary of sample post 4 - In in ante auctor, suscipit magna sit amet, dignissim mi. Integer purus ante, sagittis vel sem eu, pretium feugiat justo. Phasellus ornare mauris id lorem tincidunt
---

Fourth sample post

Have some ruby?

```ruby
def postCount = 4;
def helloWorld
  puts "Hello World! #{postCount}"
end
```


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeRouteTablesRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeRouteTablesRequestMarshaller implements Marshaller<Request<DescribeRouteTablesRequest>, DescribeRouteTablesRequest> {

    public Request<DescribeRouteTablesRequest> marshall(DescribeRouteTablesRequest describeRouteTablesRequest) {

        if (describeRouteTablesRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeRouteTablesRequest> request = new DefaultRequest<DescribeRouteTablesRequest>(describeRouteTablesRequest, "AmazonEC2");
        request.addParameter("Action", "DescribeRouteTables");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        com.amazonaws.internal.SdkInternalList<String> describeRouteTablesRequestRouteTableIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeRouteTablesRequest
                .getRouteTableIds();
        if (!describeRouteTablesRequestRouteTableIdsList.isEmpty() || !describeRouteTablesRequestRouteTableIdsList.isAutoConstruct()) {
            int routeTableIdsListIndex = 1;

            for (String describeRouteTablesRequestRouteTableIdsListValue : describeRouteTablesRequestRouteTableIdsList) {
                if (describeRouteTablesRequestRouteTableIdsListValue != null) {
                    request.addParameter("RouteTableId." + routeTableIdsListIndex, StringUtils.fromString(describeRouteTablesRequestRouteTableIdsListValue));
                }
                routeTableIdsListIndex++;
            }
        }

        com.amazonaws.internal.SdkInternalList<Filter> describeRouteTablesRequestFiltersList = (com.amazonaws.internal.SdkInternalList<Filter>) describeRouteTablesRequest
                .getFilters();
        if (!describeRouteTablesRequestFiltersList.isEmpty() || !describeRouteTablesRequestFiltersList.isAutoConstruct()) {
            int filtersListIndex = 1;

            for (Filter describeRouteTablesRequestFiltersListValue : describeRouteTablesRequestFiltersList) {

                if (describeRouteTablesRequestFiltersListValue.getName() != null) {
                    request.addParameter("Filter." + filtersListIndex + ".Name", StringUtils.fromString(describeRouteTablesRequestFiltersListValue.getName()));
                }

                com.amazonaws.internal.SdkInternalList<String> filterValuesList = (com.amazonaws.internal.SdkInternalList<String>) describeRouteTablesRequestFiltersListValue
                        .getValues();
                if (!filterValuesList.isEmpty() || !filterValuesList.isAutoConstruct()) {
                    int valuesListIndex = 1;

                    for (String filterValuesListValue : filterValuesList) {
                        if (filterValuesListValue != null) {
                            request.addParameter("Filter." + filtersListIndex + ".Value." + valuesListIndex, StringUtils.fromString(filterValuesListValue));
                        }
                        valuesListIndex++;
                    }
                }
                filtersListIndex++;
            }
        }

        return request;
    }

}


text:
'use strict';
var Payload = require('./Payload');
module.exports.validatePayloadLength = function(options) {
    var json = this.processPayload(options);
    //将汉字转换成3个字符长度
    return json.replace(/[^\x00-\xff]/g,"011").length;
};
module.exports.processPayload = function(options) {
    var isValid = false;
    var pb = new Payload();
    if (options.locKey !== null && options.locKey.length > 0) {
        // loc-key
        pb.setAlertLocKey(options.locKey);
        // loc-args
        if (options.locArgs !== null && options.locArgs.length > 0) {
            pb.setAlertLocArgs(options.locArgs.split(","));
        }
        isValid = true;
    }

    // body
    if (options.message !== null && options.message.length > 0) {
        pb.setAlertBody(options.message);
        isValid = true;
    }

    // action-loc-key
    if (options.actionLocKey !== null && options.actionLocKey.length > 0) {
        pb.setAlertActionLocKey(options.actionLocKey);
    }

    // launch-image
    if (options.launchImage !== null && options.launchImage.length > 0) {
        pb.setAlertLaunchImage(options.launchImage);
    }

    // badge
    var badgeNum = isNaN(parseInt(options.badge)) ?  -1 : parseInt(options.badge);
    if (badgeNum >= 0) {
        pb.setBadge(badgeNum);
        isValid = true;
    }

    // sound
    if (options.sound !== null && options.sound.length > 0)  {
        pb.setSound(options.sound);
    } else {
        pb.setSound('default');
    }

    // payload
    if (options.payload !== null && options.payload.length > 0) {
        pb.addParam('payload', options.payload);
    }

    if (options.contentAvailable !== null && options.contentAvailable === 1) {
        pb.setContentAvailable(options.contentAvailable);
        isValid = true;
    }

    if(!isValid){
        throw new Error("one of the params(locKey,message,badge) must not be null or contentAvailable must be 1");
    }
    var json = pb.toString();

    if(!json){
        throw new Error("payload json is null");
    }
    return json;
};


text:
package se.uu.it.cs.recsys.ruleminer.api;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import se.uu.it.cs.recsys.ruleminer.datastructure.FPTree;
import se.uu.it.cs.recsys.ruleminer.datastructure.builder.FPTreeBuilder;
import se.uu.it.cs.recsys.ruleminer.impl.FPGrowthImpl;

/**
 *
 * @author Yong Huang <yong.e.huang@gmail.com>>
 */
@Component
public class RuleMiner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RuleMiner.class);

    @Autowired
    private FPTreeBuilder treeBuilder;

    @Autowired
    private FPGrowthImpl fpGrowthImpl;

    /**
     *
     * @param targets
     * @param threshold
     * @return pairs of (rule, support)
     */
    @Cacheable("FPPatterns")
    public Map<Set<Integer>, Integer> getPatterns(Set<Integer> targets, Integer threshold) {

        Map<Set<Integer>, Integer> allRules = getPatterns(threshold);

        return allRules.entrySet()
                .stream()
                .filter(intertectWithTargets(targets))
                .filter(entry -> entry.getKey().size() > 1)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    @Cacheable("FPPatterns")
    public Map<Set<Integer>, Integer> getPatterns (Integer threshold) {

        int minSupport = threshold == null ? FPGrowthImpl.DEFAULT_MIN_SUPPORT : threshold;

        FPTree tree = treeBuilder.buildTreeFromDB(minSupport);

        if (tree == null) {
            LOGGER.debug("No FP tree can be built to meet the min support {} ",
                    minSupport);
            return Collections.emptyMap();
        }

        return fpGrowthImpl.getAllFrequentPattern(tree, minSupport);

    }

    private static Predicate<Map.Entry<Set<Integer>, Integer>> intertectWithTargets(Set<Integer> targets) {
        return entry -> hasIntersection(entry.getKey(), targets);
    }

    private static boolean hasIntersection(Set<Integer> a, Set<Integer> b) {
        Set<Integer> aClone = new HashSet<>(a);
        Set<Integer> bClone = new HashSet<>(b);

        aClone.retainAll(bClone);

        return !aClone.isEmpty();
    }
}


text:
package com.fishercoder;

import com.fishercoder.solutions._668;
import org.junit.BeforeClass;
import org.junit.Test;

import static junit.framework.TestCase.assertEquals;

public class _668Test {
    private static _668.Solution1 solution1;
    private static _668.Solution2 solution2;

    @BeforeClass
    public static void setup() {
        solution1 = new _668.Solution1();
        solution2 = new _668.Solution2();
    }

    @Test
    public void test1() {
        assertEquals(3, solution1.findKthNumber(3, 3, 5));
        assertEquals(3, solution2.findKthNumber(3, 3, 5));
    }

    @Test
    public void test2() {
        assertEquals(6, solution1.findKthNumber(2, 3, 6));
        assertEquals(6, solution2.findKthNumber(2, 3, 6));
    }

    @Test
    public void test3() {
//        assertEquals(31666344, solution1.findKthNumber(9895, 28405, 100787757));//this will run into OOM error, so comment out
        assertEquals(31666344, solution2.findKthNumber(9895, 28405, 100787757));
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>edu.umn.biomedicus.measures</title>
<meta name="date" content="2018-07-03">
<meta name="keywords" content="edu.umn.biomedicus.measures package">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

edu.umn.biomedicus.measures

Classes

BiomedicusMeasuresModule

CandidateUnitOfMeasure

DetectNumbers

FuzzyValue

IndefiniteQuantifierCue

IndefiniteQuantifierDetector

MeasuresAnnotationTool

MeasuresModule

Number

NumberContextWriter

NumberModelLoader

NumberRange

NumberRangesLabeler

Quantifier

QuantifierDetector

QuantifiersKt

SimpleUnitOfMeasureAnnotator

StandaloneQuantifier

StandaloneQuantifierDetector

TimeFrequencyUnit

TimeFrequencyUnitDetector

TimeUnit

TimeUnitDetector

Enums

IndefiniteQuantifierType


text:
namespace {

const ::google::protobuf::Descriptor* MessageDeleteBlock_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
  MessageDeleteBlock_reflection_ = NULL;

}  // namespace

void protobuf_AssignDesc_MessageDeleteBlock_2eproto() {
  protobuf_AddDesc_MessageDeleteBlock_2eproto();
  const ::google::protobuf::FileDescriptor* file =
    ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
      "MessageDeleteBlock.proto");
  GOOGLE_CHECK(file != NULL);
  MessageDeleteBlock_descriptor_ = file->message_type(0);
  static const int MessageDeleteBlock_offsets_[2] = {
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageDeleteBlock, index_),
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageDeleteBlock, clientid_),
  };
  MessageDeleteBlock_reflection_ =
    new ::google::protobuf::internal::GeneratedMessageReflection(
      MessageDeleteBlock_descriptor_,
      MessageDeleteBlock::default_instance_,
      MessageDeleteBlock_offsets_,
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageDeleteBlock, _has_bits_[0]),
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageDeleteBlock, _unknown_fields_),
      -1,
      ::google::protobuf::DescriptorPool::generated_pool(),
      ::google::protobuf::MessageFactory::generated_factory(),
      sizeof(MessageDeleteBlock));
}

namespace {

GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
  ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
                 &protobuf_AssignDesc_MessageDeleteBlock_2eproto);
}

void protobuf_RegisterTypes(const ::std::string&) {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
    MessageDeleteBlock_descriptor_, &MessageDeleteBlock::default_instance());
}

}  // namespace

void protobuf_ShutdownFile_MessageDeleteBlock_2eproto() {
  delete MessageDeleteBlock::default_instance_;
  delete MessageDeleteBlock_reflection_;
}

void protobuf_AddDesc_MessageDeleteBlock_2eproto() {
  static bool already_here = false;
  if (already_here) return;
  already_here = true;
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
    "\n\030MessageDeleteBlock.proto\"5\n\022MessageDel"
    "eteBlock\022\r\n\005Index\030\001 \002(\003\022\020\n\010ClientId\030\002 \002("
    "\003", 81);
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
    "MessageDeleteBlock.proto", &protobuf_RegisterTypes);
  MessageDeleteBlock::default_instance_ = new MessageDeleteBlock();
  MessageDeleteBlock::default_instance_->InitAsDefaultInstance();
  ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_MessageDeleteBlock_2eproto);
}

// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_MessageDeleteBlock_2eproto {
  StaticDescriptorInitializer_MessageDeleteBlock_2eproto() {
    protobuf_AddDesc_MessageDeleteBlock_2eproto();
  }
} static_descriptor_initializer_MessageDeleteBlock_2eproto_;

// ===================================================================

#ifndef _MSC_VER
const int MessageDeleteBlock::kIndexFieldNumber;
const int MessageDeleteBlock::kClientIdFieldNumber;
#endif  // !_MSC_VER

MessageDeleteBlock::MessageDeleteBlock()
  : ::google::protobuf::Message() {
  SharedCtor();
  // @@protoc_insertion_point(constructor:MessageDeleteBlock)
}

void MessageDeleteBlock::InitAsDefaultInstance() {
}

MessageDeleteBlock::MessageDeleteBlock(const MessageDeleteBlock& from)
  : ::google::protobuf::Message() {
  SharedCtor();
  MergeFrom(from);
  // @@protoc_insertion_point(copy_constructor:MessageDeleteBlock)
}

void MessageDeleteBlock::SharedCtor() {
  _cached_size_ = 0;
  index_ = GOOGLE_LONGLONG(0);
  clientid_ = GOOGLE_LONGLONG(0);
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
}

MessageDeleteBlock::~MessageDeleteBlock() {
  // @@protoc_insertion_point(destructor:MessageDeleteBlock)
  SharedDtor();
}

void MessageDeleteBlock::SharedDtor() {
  if (this != default_instance_) {
  }
}

void MessageDeleteBlock::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MessageDeleteBlock::descriptor() {
  protobuf_AssignDescriptorsOnce();
  return MessageDeleteBlock_descriptor_;
}

const MessageDeleteBlock& MessageDeleteBlock::default_instance() {
  if (default_instance_ == NULL) protobuf_AddDesc_MessageDeleteBlock_2eproto();
  return *default_instance_;
}

MessageDeleteBlock* MessageDeleteBlock::default_instance_ = NULL;

MessageDeleteBlock* MessageDeleteBlock::New() const {
  return new MessageDeleteBlock;
}

void MessageDeleteBlock::Clear() {
#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>(      \
  &reinterpret_cast<MessageDeleteBlock*>(16)->f) - \
   reinterpret_cast<char*>(16))

#define ZR_(first, last) do {                              \
    size_t f = OFFSET_OF_FIELD_(first);                    \
    size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last);  \
    ::memset(&first, 0, n);                                \
  } while (0)

  ZR_(index_, clientid_);

#undef OFFSET_OF_FIELD_
#undef ZR_

  ::memset(_has_bits_, 0, sizeof(_has_bits_));
  mutable_unknown_fields()->Clear();
}

bool MessageDeleteBlock::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
  ::google::protobuf::uint32 tag;
  // @@protoc_insertion_point(parse_start:MessageDeleteBlock)
  for (;;) {
    ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
    tag = p.first;
    if (!p.second) goto handle_unusual;
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // required int64 Index = 1;
      case 1: {
        if (tag == 8) {
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
                 input, &index_)));
          set_has_index();
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(16)) goto parse_ClientId;
        break;
      }

      // required int64 ClientId = 2;
      case 2: {
        if (tag == 16) {
         parse_ClientId:
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
                 input, &clientid_)));
          set_has_clientid();
        } else {
          goto handle_unusual;
        }
        if (input->ExpectAtEnd()) goto success;
        break;
      }

      default: {
      handle_unusual:
        if (tag == 0 ||
            ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
          goto success;
        }
        DO_(::google::protobuf::internal::WireFormat::SkipField(
              input, tag, mutable_unknown_fields()));
        break;
      }
    }
  }
success:
  // @@protoc_insertion_point(parse_success:MessageDeleteBlock)
  return true;
failure:
  // @@protoc_insertion_point(parse_failure:MessageDeleteBlock)
  return false;
#undef DO_
}

void MessageDeleteBlock::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:MessageDeleteBlock)
  // required int64 Index = 1;
  if (has_index()) {
    ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->index(), output);
  }

  // required int64 ClientId = 2;
  if (has_clientid()) {
    ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->clientid(), output);
  }

  if (!unknown_fields().empty()) {
    ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
        unknown_fields(), output);
  }
  // @@protoc_insertion_point(serialize_end:MessageDeleteBlock)
}

::google::protobuf::uint8* MessageDeleteBlock::SerializeWithCachedSizesToArray(
    ::google::protobuf::uint8* target) const {
  // @@protoc_insertion_point(serialize_to_array_start:MessageDeleteBlock)
  // required int64 Index = 1;
  if (has_index()) {
    target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->index(), target);
  }

  // required int64 ClientId = 2;
  if (has_clientid()) {
    target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->clientid(), target);
  }

  if (!unknown_fields().empty()) {
    target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
        unknown_fields(), target);
  }
  // @@protoc_insertion_point(serialize_to_array_end:MessageDeleteBlock)
  return target;
}

int MessageDeleteBlock::ByteSize() const {
  int total_size = 0;

  if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
    // required int64 Index = 1;
    if (has_index()) {
      total_size += 1 +
        ::google::protobuf::internal::WireFormatLite::Int64Size(
          this->index());
    }

    // required int64 ClientId = 2;
    if (has_clientid()) {
      total_size += 1 +
        ::google::protobuf::internal::WireFormatLite::Int64Size(
          this->clientid());
    }

  }
  if (!unknown_fields().empty()) {
    total_size +=
      ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
        unknown_fields());
  }
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = total_size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
  return total_size;
}

void MessageDeleteBlock::MergeFrom(const ::google::protobuf::Message& from) {
  GOOGLE_CHECK_NE(&from, this);
  const MessageDeleteBlock* source =
    ::google::protobuf::internal::dynamic_cast_if_available<const MessageDeleteBlock*>(
      &from);
  if (source == NULL) {
    ::google::protobuf::internal::ReflectionOps::Merge(from, this);
  } else {
    MergeFrom(*source);
  }
}

void MessageDeleteBlock::MergeFrom(const MessageDeleteBlock& from) {
  GOOGLE_CHECK_NE(&from, this);
  if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
    if (from.has_index()) {
      set_index(from.index());
    }
    if (from.has_clientid()) {
      set_clientid(from.clientid());
    }
  }
  mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}

void MessageDeleteBlock::CopyFrom(const ::google::protobuf::Message& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

void MessageDeleteBlock::CopyFrom(const MessageDeleteBlock& from) {
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

bool MessageDeleteBlock::IsInitialized() const {
  if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;

  return true;
}

void MessageDeleteBlock::Swap(MessageDeleteBlock* other) {
  if (other != this) {
    std::swap(index_, other->index_);
    std::swap(clientid_, other->clientid_);
    std::swap(_has_bits_[0], other->_has_bits_[0]);
    _unknown_fields_.Swap(&other->_unknown_fields_);
    std::swap(_cached_size_, other->_cached_size_);
  }
}

::google::protobuf::Metadata MessageDeleteBlock::GetMetadata() const {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::Metadata metadata;
  metadata.descriptor = MessageDeleteBlock_descriptor_;
  metadata.reflection = MessageDeleteBlock_reflection_;
  return metadata;
}

// @@protoc_insertion_point(namespace_scope)

// @@protoc_insertion_point(global_scope)