text:
<?php

# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/appengine/api/urlfetch_service.proto

namespace dummy {
  require_once 'google/appengine/runtime/proto/ProtocolMessage.php';
}
namespace google\appengine\URLFetchServiceError {
  class ErrorCode {
    const OK = 0;
    const INVALID_URL = 1;
    const FETCH_ERROR = 2;
    const UNSPECIFIED_ERROR = 3;
    const RESPONSE_TOO_LARGE = 4;
    const DEADLINE_EXCEEDED = 5;
    const SSL_CERTIFICATE_ERROR = 6;
    const DNS_ERROR = 7;
    const CLOSED = 8;
    const INTERNAL_TRANSIENT_ERROR = 9;
    const TOO_MANY_REDIRECTS = 10;
    const MALFORMED_REPLY = 11;
    const CONNECTION_ERROR = 12;
  }
}
namespace google\appengine {
  class URLFetchServiceError extends \google\net\ProtocolMessage {
    public function clear() {
    }
    public function byteSizePartial() {
      $res = 0;
      return $res;
    }
    public function outputPartial($out) {
    }
    public function tryMerge($d) {
      while($d->avail() > 0) {
        $tt = $d->getVarInt32();
        switch ($tt) {
          case 0:
            throw new \google\net\ProtocolBufferDecodeError();
            break;
          default:
            $d->skipData($tt);
        }
      };
    }
    public function checkInitialized() {
      return null;
    }
    public function mergeFrom($x) {
      if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
    }
    public function equals($x) {
      if ($x === $this) { return true; }
      return true;
    }
    public function shortDebugString($prefix = "") {
      $res = '';
      return $res;
    }
  }
}
namespace google\appengine\URLFetchRequest {
  class RequestMethod {
    const GET = 1;
    const POST = 2;
    const HEAD = 3;
    const PUT = 4;
    const DELETE = 5;
    const PATCH = 6;
  }
}
namespace google\appengine\URLFetchRequest {
  class Header extends \google\net\ProtocolMessage {
    public function getKey() {
      if (!isset($this->Key)) {
        return '';
      }
      return $this->Key;
    }
    public function setKey($val) {
      $this->Key = $val;
      return $this;
    }
    public function clearKey() {
      unset($this->Key);
      return $this;
    }
    public function hasKey() {
      return isset($this->Key);
    }
    public function getValue() {
      if (!isset($this->Value)) {
        return '';
      }
      return $this->Value;
    }
    public function setValue($val) {
      $this->Value = $val;
      return $this;
    }
    public function clearValue() {
      unset($this->Value);
      return $this;
    }
    public function hasValue() {
      return isset($this->Value);
    }
    public function clear() {
      $this->clearKey();
      $this->clearValue();
    }
    public function byteSizePartial() {
      $res = 0;
      if (isset($this->Key)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Key));
      }
      if (isset($this->Value)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Value));
      }
      return $res;
    }
    public function outputPartial($out) {
      if (isset($this->Key)) {
        $out->putVarInt32(34);
        $out->putPrefixedString($this->Key);
      }
      if (isset($this->Value)) {
        $out->putVarInt32(42);
        $out->putPrefixedString($this->Value);
      }
    }
    public function tryMerge($d) {
      while($d->avail() > 0) {
        $tt = $d->getVarInt32();
        switch ($tt) {
          case 28: return;
          case 34:
            $length = $d->getVarInt32();
            $this->setKey(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 42:
            $length = $d->getVarInt32();
            $this->setValue(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 0:
            throw new \google\net\ProtocolBufferDecodeError();
            break;
          default:
            $d->skipData($tt);
        }
      };
    }
    public function checkInitialized() {
      if (!isset($this->Key)) return 'Key';
      if (!isset($this->Value)) return 'Value';
      return null;
    }
    public function mergeFrom($x) {
      if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
      if ($x->hasKey()) {
        $this->setKey($x->getKey());
      }
      if ($x->hasValue()) {
        $this->setValue($x->getValue());
      }
    }
    public function equals($x) {
      if ($x === $this) { return true; }
      if (isset($this->Key) !== isset($x->Key)) return false;
      if (isset($this->Key) && $this->Key !== $x->Key) return false;
      if (isset($this->Value) !== isset($x->Value)) return false;
      if (isset($this->Value) && $this->Value !== $x->Value) return false;
      return true;
    }
    public function shortDebugString($prefix = "") {
      $res = '';
      if (isset($this->Key)) {
        $res .= $prefix . "Key: " . $this->debugFormatString($this->Key) . "\n";
      }
      if (isset($this->Value)) {
        $res .= $prefix . "Value: " . $this->debugFormatString($this->Value) . "\n";
      }
      return $res;
    }
  }
}
namespace google\appengine {
  class URLFetchRequest extends \google\net\ProtocolMessage {
    private $header = array();
    public function getMethod() {
      if (!isset($this->Method)) {
        return 1;
      }
      return $this->Method;
    }
    public function setMethod($val) {
      $this->Method = $val;
      return $this;
    }
    public function clearMethod() {
      unset($this->Method);
      return $this;
    }
    public function hasMethod() {
      return isset($this->Method);
    }
    public function getUrl() {
      if (!isset($this->Url)) {
        return '';
      }
      return $this->Url;
    }
    public function setUrl($val) {
      $this->Url = $val;
      return $this;
    }
    public function clearUrl() {
      unset($this->Url);
      return $this;
    }
    public function hasUrl() {
      return isset($this->Url);
    }
    public function getHeaderSize() {
      return sizeof($this->header);
    }
    public function getHeaderList() {
      return $this->header;
    }
    public function mutableHeader($idx) {
      if (!isset($this->header[$idx])) {
        $val = new \google\appengine\URLFetchRequest\Header();
        $this->header[$idx] = $val;
        return $val;
      }
      return $this->header[$idx];
    }
    public function getHeader($idx) {
      if (isset($this->header[$idx])) {
        return $this->header[$idx];
      }
      if ($idx >= end(array_keys($this->header))) {
        throw new \OutOfRangeException('index out of range: ' + $idx);
      }
      return new \google\appengine\URLFetchRequest\Header();
    }
    public function addHeader() {
      $val = new \google\appengine\URLFetchRequest\Header();
      $this->header[] = $val;
      return $val;
    }
    public function clearHeader() {
      $this->header = array();
    }
    public function getPayload() {
      if (!isset($this->Payload)) {
        return '';
      }
      return $this->Payload;
    }
    public function setPayload($val) {
      $this->Payload = $val;
      return $this;
    }
    public function clearPayload() {
      unset($this->Payload);
      return $this;
    }
    public function hasPayload() {
      return isset($this->Payload);
    }
    public function getFollowredirects() {
      if (!isset($this->FollowRedirects)) {
        return true;
      }
      return $this->FollowRedirects;
    }
    public function setFollowredirects($val) {
      $this->FollowRedirects = $val;
      return $this;
    }
    public function clearFollowredirects() {
      unset($this->FollowRedirects);
      return $this;
    }
    public function hasFollowredirects() {
      return isset($this->FollowRedirects);
    }
    public function getDeadline() {
      if (!isset($this->Deadline)) {
        return 0.0;
      }
      return $this->Deadline;
    }
    public function setDeadline($val) {
      $this->Deadline = $val;
      return $this;
    }
    public function clearDeadline() {
      unset($this->Deadline);
      return $this;
    }
    public function hasDeadline() {
      return isset($this->Deadline);
    }
    public function getMustvalidateservercertificate() {
      if (!isset($this->MustValidateServerCertificate)) {
        return true;
      }
      return $this->MustValidateServerCertificate;
    }
    public function setMustvalidateservercertificate($val) {
      $this->MustValidateServerCertificate = $val;
      return $this;
    }
    public function clearMustvalidateservercertificate() {
      unset($this->MustValidateServerCertificate);
      return $this;
    }
    public function hasMustvalidateservercertificate() {
      return isset($this->MustValidateServerCertificate);
    }
    public function clear() {
      $this->clearMethod();
      $this->clearUrl();
      $this->clearHeader();
      $this->clearPayload();
      $this->clearFollowredirects();
      $this->clearDeadline();
      $this->clearMustvalidateservercertificate();
    }
    public function byteSizePartial() {
      $res = 0;
      if (isset($this->Method)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->Method);
      }
      if (isset($this->Url)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Url));
      }
      $this->checkProtoArray($this->header);
      $res += 2 * sizeof($this->header);
      foreach ($this->header as $value) {
        $res += $value->byteSizePartial();
      }
      if (isset($this->Payload)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Payload));
      }
      if (isset($this->FollowRedirects)) {
        $res += 2;
      }
      if (isset($this->Deadline)) {
        $res += 9;
      }
      if (isset($this->MustValidateServerCertificate)) {
        $res += 2;
      }
      return $res;
    }
    public function outputPartial($out) {
      if (isset($this->Method)) {
        $out->putVarInt32(8);
        $out->putVarInt32($this->Method);
      }
      if (isset($this->Url)) {
        $out->putVarInt32(18);
        $out->putPrefixedString($this->Url);
      }
      $this->checkProtoArray($this->header);
      foreach ($this->header as $value) {
        $out->putVarInt32(27);
        $value->outputPartial($out);
        $out->putVarInt32(28);
      }
      if (isset($this->Payload)) {
        $out->putVarInt32(50);
        $out->putPrefixedString($this->Payload);
      }
      if (isset($this->FollowRedirects)) {
        $out->putVarInt32(56);
        $out->putBoolean($this->FollowRedirects);
      }
      if (isset($this->Deadline)) {
        $out->putVarInt32(65);
        $out->putDouble($this->Deadline);
      }
      if (isset($this->MustValidateServerCertificate)) {
        $out->putVarInt32(72);
        $out->putBoolean($this->MustValidateServerCertificate);
      }
    }
    public function tryMerge($d) {
      while($d->avail() > 0) {
        $tt = $d->getVarInt32();
        switch ($tt) {
          case 8:
            $this->setMethod($d->getVarInt32());
            break;
          case 18:
            $length = $d->getVarInt32();
            $this->setUrl(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 27:
            $this->addHeader()->tryMerge($d);
            break;
          case 50:
            $length = $d->getVarInt32();
            $this->setPayload(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 56:
            $this->setFollowredirects($d->getBoolean());
            break;
          case 65:
            $this->setDeadline($d->getDouble());
            break;
          case 72:
            $this->setMustvalidateservercertificate($d->getBoolean());
            break;
          case 0:
            throw new \google\net\ProtocolBufferDecodeError();
            break;
          default:
            $d->skipData($tt);
        }
      };
    }
    public function checkInitialized() {
      if (!isset($this->Method)) return 'Method';
      if (!isset($this->Url)) return 'Url';
      foreach ($this->header as $value) {
        if (!$value->isInitialized()) return 'header';
      }
      return null;
    }
    public function mergeFrom($x) {
      if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
      if ($x->hasMethod()) {
        $this->setMethod($x->getMethod());
      }
      if ($x->hasUrl()) {
        $this->setUrl($x->getUrl());
      }
      foreach ($x->getHeaderList() as $v) {
        $this->addHeader()->copyFrom($v);
      }
      if ($x->hasPayload()) {
        $this->setPayload($x->getPayload());
      }
      if ($x->hasFollowredirects()) {
        $this->setFollowredirects($x->getFollowredirects());
      }
      if ($x->hasDeadline()) {
        $this->setDeadline($x->getDeadline());
      }
      if ($x->hasMustvalidateservercertificate()) {
        $this->setMustvalidateservercertificate($x->getMustvalidateservercertificate());
      }
    }
    public function equals($x) {
      if ($x === $this) { return true; }
      if (isset($this->Method) !== isset($x->Method)) return false;
      if (isset($this->Method) && $this->Method !== $x->Method) return false;
      if (isset($this->Url) !== isset($x->Url)) return false;
      if (isset($this->Url) && $this->Url !== $x->Url) return false;
      if (sizeof($this->header) !== sizeof($x->header)) return false;
      foreach (array_map(null, $this->header, $x->header) as $v) {
        if (!$v[0]->equals($v[1])) return false;
      }
      if (isset($this->Payload) !== isset($x->Payload)) return false;
      if (isset($this->Payload) && $this->Payload !== $x->Payload) return false;
      if (isset($this->FollowRedirects) !== isset($x->FollowRedirects)) return false;
      if (isset($this->FollowRedirects) && $this->FollowRedirects !== $x->FollowRedirects) return false;
      if (isset($this->Deadline) !== isset($x->Deadline)) return false;
      if (isset($this->Deadline) && $this->Deadline !== $x->Deadline) return false;
      if (isset($this->MustValidateServerCertificate) !== isset($x->MustValidateServerCertificate)) return false;
      if (isset($this->MustValidateServerCertificate) && $this->MustValidateServerCertificate !== $x->MustValidateServerCertificate) return false;
      return true;
    }
    public function shortDebugString($prefix = "") {
      $res = '';
      if (isset($this->Method)) {
        $res .= $prefix . "Method: " . ($this->Method) . "\n";
      }
      if (isset($this->Url)) {
        $res .= $prefix . "Url: " . $this->debugFormatString($this->Url) . "\n";
      }
      foreach ($this->header as $value) {
        $res .= $prefix . "Header {\n" . $value->shortDebugString($prefix . "  ") . $prefix . "}\n";
      }
      if (isset($this->Payload)) {
        $res .= $prefix . "Payload: " . $this->debugFormatString($this->Payload) . "\n";
      }
      if (isset($this->FollowRedirects)) {
        $res .= $prefix . "FollowRedirects: " . $this->debugFormatBool($this->FollowRedirects) . "\n";
      }
      if (isset($this->Deadline)) {
        $res .= $prefix . "Deadline: " . $this->debugFormatDouble($this->Deadline) . "\n";
      }
      if (isset($this->MustValidateServerCertificate)) {
        $res .= $prefix . "MustValidateServerCertificate: " . $this->debugFormatBool($this->MustValidateServerCertificate) . "\n";
      }
      return $res;
    }
  }
}
namespace google\appengine\URLFetchResponse {
  class Header extends \google\net\ProtocolMessage {
    public function getKey() {
      if (!isset($this->Key)) {
        return '';
      }
      return $this->Key;
    }
    public function setKey($val) {
      $this->Key = $val;
      return $this;
    }
    public function clearKey() {
      unset($this->Key);
      return $this;
    }
    public function hasKey() {
      return isset($this->Key);
    }
    public function getValue() {
      if (!isset($this->Value)) {
        return '';
      }
      return $this->Value;
    }
    public function setValue($val) {
      $this->Value = $val;
      return $this;
    }
    public function clearValue() {
      unset($this->Value);
      return $this;
    }
    public function hasValue() {
      return isset($this->Value);
    }
    public function clear() {
      $this->clearKey();
      $this->clearValue();
    }
    public function byteSizePartial() {
      $res = 0;
      if (isset($this->Key)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Key));
      }
      if (isset($this->Value)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Value));
      }
      return $res;
    }
    public function outputPartial($out) {
      if (isset($this->Key)) {
        $out->putVarInt32(34);
        $out->putPrefixedString($this->Key);
      }
      if (isset($this->Value)) {
        $out->putVarInt32(42);
        $out->putPrefixedString($this->Value);
      }
    }
    public function tryMerge($d) {
      while($d->avail() > 0) {
        $tt = $d->getVarInt32();
        switch ($tt) {
          case 28: return;
          case 34:
            $length = $d->getVarInt32();
            $this->setKey(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 42:
            $length = $d->getVarInt32();
            $this->setValue(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 0:
            throw new \google\net\ProtocolBufferDecodeError();
            break;
          default:
            $d->skipData($tt);
        }
      };
    }
    public function checkInitialized() {
      if (!isset($this->Key)) return 'Key';
      if (!isset($this->Value)) return 'Value';
      return null;
    }
    public function mergeFrom($x) {
      if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
      if ($x->hasKey()) {
        $this->setKey($x->getKey());
      }
      if ($x->hasValue()) {
        $this->setValue($x->getValue());
      }
    }
    public function equals($x) {
      if ($x === $this) { return true; }
      if (isset($this->Key) !== isset($x->Key)) return false;
      if (isset($this->Key) && $this->Key !== $x->Key) return false;
      if (isset($this->Value) !== isset($x->Value)) return false;
      if (isset($this->Value) && $this->Value !== $x->Value) return false;
      return true;
    }
    public function shortDebugString($prefix = "") {
      $res = '';
      if (isset($this->Key)) {
        $res .= $prefix . "Key: " . $this->debugFormatString($this->Key) . "\n";
      }
      if (isset($this->Value)) {
        $res .= $prefix . "Value: " . $this->debugFormatString($this->Value) . "\n";
      }
      return $res;
    }
  }
}
namespace google\appengine {
  class URLFetchResponse extends \google\net\ProtocolMessage {
    private $header = array();
    public function getContent() {
      if (!isset($this->Content)) {
        return '';
      }
      return $this->Content;
    }
    public function setContent($val) {
      $this->Content = $val;
      return $this;
    }
    public function clearContent() {
      unset($this->Content);
      return $this;
    }
    public function hasContent() {
      return isset($this->Content);
    }
    public function getStatuscode() {
      if (!isset($this->StatusCode)) {
        return 0;
      }
      return $this->StatusCode;
    }
    public function setStatuscode($val) {
      $this->StatusCode = $val;
      return $this;
    }
    public function clearStatuscode() {
      unset($this->StatusCode);
      return $this;
    }
    public function hasStatuscode() {
      return isset($this->StatusCode);
    }
    public function getHeaderSize() {
      return sizeof($this->header);
    }
    public function getHeaderList() {
      return $this->header;
    }
    public function mutableHeader($idx) {
      if (!isset($this->header[$idx])) {
        $val = new \google\appengine\URLFetchResponse\Header();
        $this->header[$idx] = $val;
        return $val;
      }
      return $this->header[$idx];
    }
    public function getHeader($idx) {
      if (isset($this->header[$idx])) {
        return $this->header[$idx];
      }
      if ($idx >= end(array_keys($this->header))) {
        throw new \OutOfRangeException('index out of range: ' + $idx);
      }
      return new \google\appengine\URLFetchResponse\Header();
    }
    public function addHeader() {
      $val = new \google\appengine\URLFetchResponse\Header();
      $this->header[] = $val;
      return $val;
    }
    public function clearHeader() {
      $this->header = array();
    }
    public function getContentwastruncated() {
      if (!isset($this->ContentWasTruncated)) {
        return false;
      }
      return $this->ContentWasTruncated;
    }
    public function setContentwastruncated($val) {
      $this->ContentWasTruncated = $val;
      return $this;
    }
    public function clearContentwastruncated() {
      unset($this->ContentWasTruncated);
      return $this;
    }
    public function hasContentwastruncated() {
      return isset($this->ContentWasTruncated);
    }
    public function getExternalbytessent() {
      if (!isset($this->ExternalBytesSent)) {
        return "0";
      }
      return $this->ExternalBytesSent;
    }
    public function setExternalbytessent($val) {
      if (is_double($val)) {
        $this->ExternalBytesSent = sprintf('%0.0F', $val);
      } else {
        $this->ExternalBytesSent = $val;
      }
      return $this;
    }
    public function clearExternalbytessent() {
      unset($this->ExternalBytesSent);
      return $this;
    }
    public function hasExternalbytessent() {
      return isset($this->ExternalBytesSent);
    }
    public function getExternalbytesreceived() {
      if (!isset($this->ExternalBytesReceived)) {
        return "0";
      }
      return $this->ExternalBytesReceived;
    }
    public function setExternalbytesreceived($val) {
      if (is_double($val)) {
        $this->ExternalBytesReceived = sprintf('%0.0F', $val);
      } else {
        $this->ExternalBytesReceived = $val;
      }
      return $this;
    }
    public function clearExternalbytesreceived() {
      unset($this->ExternalBytesReceived);
      return $this;
    }
    public function hasExternalbytesreceived() {
      return isset($this->ExternalBytesReceived);
    }
    public function getFinalurl() {
      if (!isset($this->FinalUrl)) {
        return '';
      }
      return $this->FinalUrl;
    }
    public function setFinalurl($val) {
      $this->FinalUrl = $val;
      return $this;
    }
    public function clearFinalurl() {
      unset($this->FinalUrl);
      return $this;
    }
    public function hasFinalurl() {
      return isset($this->FinalUrl);
    }
    public function getApicpumilliseconds() {
      if (!isset($this->ApiCpuMilliseconds)) {
        return '0';
      }
      return $this->ApiCpuMilliseconds;
    }
    public function setApicpumilliseconds($val) {
      if (is_double($val)) {
        $this->ApiCpuMilliseconds = sprintf('%0.0F', $val);
      } else {
        $this->ApiCpuMilliseconds = $val;
      }
      return $this;
    }
    public function clearApicpumilliseconds() {
      unset($this->ApiCpuMilliseconds);
      return $this;
    }
    public function hasApicpumilliseconds() {
      return isset($this->ApiCpuMilliseconds);
    }
    public function getApibytessent() {
      if (!isset($this->ApiBytesSent)) {
        return '0';
      }
      return $this->ApiBytesSent;
    }
    public function setApibytessent($val) {
      if (is_double($val)) {
        $this->ApiBytesSent = sprintf('%0.0F', $val);
      } else {
        $this->ApiBytesSent = $val;
      }
      return $this;
    }
    public function clearApibytessent() {
      unset($this->ApiBytesSent);
      return $this;
    }
    public function hasApibytessent() {
      return isset($this->ApiBytesSent);
    }
    public function getApibytesreceived() {
      if (!isset($this->ApiBytesReceived)) {
        return '0';
      }
      return $this->ApiBytesReceived;
    }
    public function setApibytesreceived($val) {
      if (is_double($val)) {
        $this->ApiBytesReceived = sprintf('%0.0F', $val);
      } else {
        $this->ApiBytesReceived = $val;
      }
      return $this;
    }
    public function clearApibytesreceived() {
      unset($this->ApiBytesReceived);
      return $this;
    }
    public function hasApibytesreceived() {
      return isset($this->ApiBytesReceived);
    }
    public function clear() {
      $this->clearContent();
      $this->clearStatuscode();
      $this->clearHeader();
      $this->clearContentwastruncated();
      $this->clearExternalbytessent();
      $this->clearExternalbytesreceived();
      $this->clearFinalurl();
      $this->clearApicpumilliseconds();
      $this->clearApibytessent();
      $this->clearApibytesreceived();
    }
    public function byteSizePartial() {
      $res = 0;
      if (isset($this->Content)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->Content));
      }
      if (isset($this->StatusCode)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->StatusCode);
      }
      $this->checkProtoArray($this->header);
      $res += 2 * sizeof($this->header);
      foreach ($this->header as $value) {
        $res += $value->byteSizePartial();
      }
      if (isset($this->ContentWasTruncated)) {
        $res += 2;
      }
      if (isset($this->ExternalBytesSent)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->ExternalBytesSent);
      }
      if (isset($this->ExternalBytesReceived)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->ExternalBytesReceived);
      }
      if (isset($this->FinalUrl)) {
        $res += 1;
        $res += $this->lengthString(strlen($this->FinalUrl));
      }
      if (isset($this->ApiCpuMilliseconds)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->ApiCpuMilliseconds);
      }
      if (isset($this->ApiBytesSent)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->ApiBytesSent);
      }
      if (isset($this->ApiBytesReceived)) {
        $res += 1;
        $res += $this->lengthVarInt64($this->ApiBytesReceived);
      }
      return $res;
    }
    public function outputPartial($out) {
      if (isset($this->Content)) {
        $out->putVarInt32(10);
        $out->putPrefixedString($this->Content);
      }
      if (isset($this->StatusCode)) {
        $out->putVarInt32(16);
        $out->putVarInt32($this->StatusCode);
      }
      $this->checkProtoArray($this->header);
      foreach ($this->header as $value) {
        $out->putVarInt32(27);
        $value->outputPartial($out);
        $out->putVarInt32(28);
      }
      if (isset($this->ContentWasTruncated)) {
        $out->putVarInt32(48);
        $out->putBoolean($this->ContentWasTruncated);
      }
      if (isset($this->ExternalBytesSent)) {
        $out->putVarInt32(56);
        $out->putVarInt64($this->ExternalBytesSent);
      }
      if (isset($this->ExternalBytesReceived)) {
        $out->putVarInt32(64);
        $out->putVarInt64($this->ExternalBytesReceived);
      }
      if (isset($this->FinalUrl)) {
        $out->putVarInt32(74);
        $out->putPrefixedString($this->FinalUrl);
      }
      if (isset($this->ApiCpuMilliseconds)) {
        $out->putVarInt32(80);
        $out->putVarInt64($this->ApiCpuMilliseconds);
      }
      if (isset($this->ApiBytesSent)) {
        $out->putVarInt32(88);
        $out->putVarInt64($this->ApiBytesSent);
      }
      if (isset($this->ApiBytesReceived)) {
        $out->putVarInt32(96);
        $out->putVarInt64($this->ApiBytesReceived);
      }
    }
    public function tryMerge($d) {
      while($d->avail() > 0) {
        $tt = $d->getVarInt32();
        switch ($tt) {
          case 10:
            $length = $d->getVarInt32();
            $this->setContent(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 16:
            $this->setStatuscode($d->getVarInt32());
            break;
          case 27:
            $this->addHeader()->tryMerge($d);
            break;
          case 48:
            $this->setContentwastruncated($d->getBoolean());
            break;
          case 56:
            $this->setExternalbytessent($d->getVarInt64());
            break;
          case 64:
            $this->setExternalbytesreceived($d->getVarInt64());
            break;
          case 74:
            $length = $d->getVarInt32();
            $this->setFinalurl(substr($d->buffer(), $d->pos(), $length));
            $d->skip($length);
            break;
          case 80:
            $this->setApicpumilliseconds($d->getVarInt64());
            break;
          case 88:
            $this->setApibytessent($d->getVarInt64());
            break;
          case 96:
            $this->setApibytesreceived($d->getVarInt64());
            break;
          case 0:
            throw new \google\net\ProtocolBufferDecodeError();
            break;
          default:
            $d->skipData($tt);
        }
      };
    }
    public function checkInitialized() {
      if (!isset($this->StatusCode)) return 'StatusCode';
      foreach ($this->header as $value) {
        if (!$value->isInitialized()) return 'header';
      }
      return null;
    }
    public function mergeFrom($x) {
      if ($x === $this) { throw new \IllegalArgumentException('Cannot copy message to itself'); }
      if ($x->hasContent()) {
        $this->setContent($x->getContent());
      }
      if ($x->hasStatuscode()) {
        $this->setStatuscode($x->getStatuscode());
      }
      foreach ($x->getHeaderList() as $v) {
        $this->addHeader()->copyFrom($v);
      }
      if ($x->hasContentwastruncated()) {
        $this->setContentwastruncated($x->getContentwastruncated());
      }
      if ($x->hasExternalbytessent()) {
        $this->setExternalbytessent($x->getExternalbytessent());
      }
      if ($x->hasExternalbytesreceived()) {
        $this->setExternalbytesreceived($x->getExternalbytesreceived());
      }
      if ($x->hasFinalurl()) {
        $this->setFinalurl($x->getFinalurl());
      }
      if ($x->hasApicpumilliseconds()) {
        $this->setApicpumilliseconds($x->getApicpumilliseconds());
      }
      if ($x->hasApibytessent()) {
        $this->setApibytessent($x->getApibytessent());
      }
      if ($x->hasApibytesreceived()) {
        $this->setApibytesreceived($x->getApibytesreceived());
      }
    }
    public function equals($x) {
      if ($x === $this) { return true; }
      if (isset($this->Content) !== isset($x->Content)) return false;
      if (isset($this->Content) && $this->Content !== $x->Content) return false;
      if (isset($this->StatusCode) !== isset($x->StatusCode)) return false;
      if (isset($this->StatusCode) && !$this->integerEquals($this->StatusCode, $x->StatusCode)) return false;
      if (sizeof($this->header) !== sizeof($x->header)) return false;
      foreach (array_map(null, $this->header, $x->header) as $v) {
        if (!$v[0]->equals($v[1])) return false;
      }
      if (isset($this->ContentWasTruncated) !== isset($x->ContentWasTruncated)) return false;
      if (isset($this->ContentWasTruncated) && $this->ContentWasTruncated !== $x->ContentWasTruncated) return false;
      if (isset($this->ExternalBytesSent) !== isset($x->ExternalBytesSent)) return false;
      if (isset($this->ExternalBytesSent) && !$this->integerEquals($this->ExternalBytesSent, $x->ExternalBytesSent)) return false;
      if (isset($this->ExternalBytesReceived) !== isset($x->ExternalBytesReceived)) return false;
      if (isset($this->ExternalBytesReceived) && !$this->integerEquals($this->ExternalBytesReceived, $x->ExternalBytesReceived)) return false;
      if (isset($this->FinalUrl) !== isset($x->FinalUrl)) return false;
      if (isset($this->FinalUrl) && $this->FinalUrl !== $x->FinalUrl) return false;
      if (isset($this->ApiCpuMilliseconds) !== isset($x->ApiCpuMilliseconds)) return false;
      if (isset($this->ApiCpuMilliseconds) && !$this->integerEquals($this->ApiCpuMilliseconds, $x->ApiCpuMilliseconds)) return false;
      if (isset($this->ApiBytesSent) !== isset($x->ApiBytesSent)) return false;
      if (isset($this->ApiBytesSent) && !$this->integerEquals($this->ApiBytesSent, $x->ApiBytesSent)) return false;
      if (isset($this->ApiBytesReceived) !== isset($x->ApiBytesReceived)) return false;
      if (isset($this->ApiBytesReceived) && !$this->integerEquals($this->ApiBytesReceived, $x->ApiBytesReceived)) return false;
      return true;
    }
    public function shortDebugString($prefix = "") {
      $res = '';
      if (isset($this->Content)) {
        $res .= $prefix . "Content: " . $this->debugFormatString($this->Content) . "\n";
      }
      if (isset($this->StatusCode)) {
        $res .= $prefix . "StatusCode: " . $this->debugFormatInt32($this->StatusCode) . "\n";
      }
      foreach ($this->header as $value) {
        $res .= $prefix . "Header {\n" . $value->shortDebugString($prefix . "  ") . $prefix . "}\n";
      }
      if (isset($this->ContentWasTruncated)) {
        $res .= $prefix . "ContentWasTruncated: " . $this->debugFormatBool($this->ContentWasTruncated) . "\n";
      }
      if (isset($this->ExternalBytesSent)) {
        $res .= $prefix . "ExternalBytesSent: " . $this->debugFormatInt64($this->ExternalBytesSent) . "\n";
      }
      if (isset($this->ExternalBytesReceived)) {
        $res .= $prefix . "ExternalBytesReceived: " . $this->debugFormatInt64($this->ExternalBytesReceived) . "\n";
      }
      if (isset($this->FinalUrl)) {
        $res .= $prefix . "FinalUrl: " . $this->debugFormatString($this->FinalUrl) . "\n";
      }
      if (isset($this->ApiCpuMilliseconds)) {
        $res .= $prefix . "ApiCpuMilliseconds: " . $this->debugFormatInt64($this->ApiCpuMilliseconds) . "\n";
      }
      if (isset($this->ApiBytesSent)) {
        $res .= $prefix . "ApiBytesSent: " . $this->debugFormatInt64($this->ApiBytesSent) . "\n";
      }
      if (isset($this->ApiBytesReceived)) {
        $res .= $prefix . "ApiBytesReceived: " . $this->debugFormatInt64($this->ApiBytesReceived) . "\n";
      }
      return $res;
    }
  }
}


text:
.. highlight:: c

.. _new-types-topics:

*****************************************
Defining Extension Types: Assorted Topics
*****************************************

.. _dnt-type-methods:

This section aims to give a quick fly-by on the various type methods you can
implement and what they do.

Here is the definition of :c:type:`PyTypeObject`, with some fields only used in
debug builds omitted:

.. literalinclude:: ../includes/typestruct.h

Now that's a *lot* of methods.  Don't worry too much though -- if you have
a type you want to define, the chances are very good that you will only
implement a handful of these.

As you probably expect by now, we're going to go over this and give more
information about the various handlers.  We won't go in the order they are
defined in the structure, because there is a lot of historical baggage that
impacts the ordering of the fields.  It's often easiest to find an example
that includes the fields you need and then change the values to suit your new
type. ::

   const char *tp_name; /* For printing */

The name of the type -- as mentioned in the previous chapter, this will appear in
various places, almost entirely for diagnostic purposes. Try to choose something
that will be helpful in such a situation! ::

   Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

These fields tell the runtime how much memory to allocate when new objects of
this type are created.  Python has some built-in support for variable length
structures (think: strings, tuples) which is where the :c:member:`~PyTypeObject.tp_itemsize` field
comes in.  This will be dealt with later. ::

   const char *tp_doc;

Here you can put a string (or its address) that you want returned when the
Python script references ``obj.__doc__`` to retrieve the doc string.

Now we come to the basic type methods -- the ones most extension types will
implement.

Finalization and De-allocation
------------------------------

.. index::
   single: object; deallocation
   single: deallocation, object
   single: object; finalization
   single: finalization, of objects

::

   destructor tp_dealloc;

This function is called when the reference count of the instance of your type is
reduced to zero and the Python interpreter wants to reclaim it.  If your type
has memory to free or other clean-up to perform, you can put it here.  The
object itself needs to be freed here as well.  Here is an example of this
function::

   static void
   newdatatype_dealloc(newdatatypeobject *obj)
   {
       free(obj->obj_UnderlyingDatatypePtr);
       Py_TYPE(obj)->tp_free(obj);
   }

.. index::
   single: PyErr_Fetch()
   single: PyErr_Restore()

One important requirement of the deallocator function is that it leaves any
pending exceptions alone.  This is important since deallocators are frequently
called as the interpreter unwinds the Python stack; when the stack is unwound
due to an exception (rather than normal returns), nothing is done to protect the
deallocators from seeing that an exception has already been set.  Any actions
which a deallocator performs which may cause additional Python code to be
executed may detect that an exception has been set.  This can lead to misleading
errors from the interpreter.  The proper way to protect against this is to save
a pending exception before performing the unsafe action, and restoring it when
done.  This can be done using the :c:func:`PyErr_Fetch` and
:c:func:`PyErr_Restore` functions::

   static void
   my_dealloc(PyObject *obj)
   {
       MyObject *self = (MyObject *) obj;
       PyObject *cbresult;

       if (self->my_callback != NULL) {
           PyObject *err_type, *err_value, *err_traceback;

           /* This saves the current exception state */
           PyErr_Fetch(&err_type, &err_value, &err_traceback);

           cbresult = PyObject_CallObject(self->my_callback, NULL);
           if (cbresult == NULL)
               PyErr_WriteUnraisable(self->my_callback);
           else
               Py_DECREF(cbresult);

           /* This restores the saved exception state */
           PyErr_Restore(err_type, err_value, err_traceback);

           Py_DECREF(self->my_callback);
       }
       Py_TYPE(obj)->tp_free((PyObject*)self);
   }

.. note::
   There are limitations to what you can safely do in a deallocator function.
   First, if your type supports garbage collection (using :c:member:`~PyTypeObject.tp_traverse`
   and/or :c:member:`~PyTypeObject.tp_clear`), some of the object's members can have been
   cleared or finalized by the time :c:member:`~PyTypeObject.tp_dealloc` is called.  Second, in
   :c:member:`~PyTypeObject.tp_dealloc`, your object is in an unstable state: its reference
   count is equal to zero.  Any call to a non-trivial object or API (as in the
   example above) might end up calling :c:member:`~PyTypeObject.tp_dealloc` again, causing a
   double free and a crash.

   Starting with Python 3.4, it is recommended not to put any complex
   finalization code in :c:member:`~PyTypeObject.tp_dealloc`, and instead use the new
   :c:member:`~PyTypeObject.tp_finalize` type method.

   .. seealso::
      :pep:`442` explains the new finalization scheme.

.. index::
   single: string; object representation
   builtin: repr

Object Presentation
-------------------

In Python, there are two ways to generate a textual representation of an object:
the :func:`repr` function, and the :func:`str` function.  (The :func:`print`
function just calls :func:`str`.)  These handlers are both optional.

::

   reprfunc tp_repr;
   reprfunc tp_str;

The :c:member:`~PyTypeObject.tp_repr` handler should return a string object containing a
representation of the instance for which it is called.  Here is a simple
example::

   static PyObject *
   newdatatype_repr(newdatatypeobject * obj)
   {
       return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}",
                                   obj->obj_UnderlyingDatatypePtr->size);
   }

If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the interpreter will supply a
representation that uses the type's :c:member:`~PyTypeObject.tp_name` and a uniquely-identifying
value for the object.

The :c:member:`~PyTypeObject.tp_str` handler is to :func:`str` what the :c:member:`~PyTypeObject.tp_repr` handler
described above is to :func:`repr`; that is, it is called when Python code calls
:func:`str` on an instance of your object.  Its implementation is very similar
to the :c:member:`~PyTypeObject.tp_repr` function, but the resulting string is intended for human
consumption.  If :c:member:`~PyTypeObject.tp_str` is not specified, the :c:member:`~PyTypeObject.tp_repr` handler is
used instead.

Here is a simple example::

   static PyObject *
   newdatatype_str(newdatatypeobject * obj)
   {
       return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}",
                                   obj->obj_UnderlyingDatatypePtr->size);
   }

Attribute Management
--------------------

For every object which can support attributes, the corresponding type must
provide the functions that control how the attributes are resolved.  There needs
to be a function which can retrieve attributes (if any are defined), and another
to set attributes (if setting attributes is allowed).  Removing an attribute is
a special case, for which the new value passed to the handler is *NULL*.

Python supports two pairs of attribute handlers; a type that supports attributes
only needs to implement the functions for one pair.  The difference is that one
pair takes the name of the attribute as a :c:type:`char\*`, while the other
accepts a :c:type:`PyObject\*`.  Each type can use whichever pair makes more
sense for the implementation's convenience. ::

   getattrfunc  tp_getattr;        /* char * version */
   setattrfunc  tp_setattr;
   /* ... */
   getattrofunc tp_getattro;       /* PyObject * version */
   setattrofunc tp_setattro;

If accessing attributes of an object is always a simple operation (this will be
explained shortly), there are generic implementations which can be used to
provide the :c:type:`PyObject\*` version of the attribute management functions.
The actual need for type-specific attribute handlers almost completely
disappeared starting with Python 2.2, though there are many examples which have
not been updated to use some of the new generic mechanism that is available.

.. _generic-attribute-management:

Generic Attribute Management
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Most extension types only use *simple* attributes.  So, what makes the
attributes simple?  There are only a couple of conditions that must be met:

#. The name of the attributes must be known when :c:func:`PyType_Ready` is
   called.

#. No special processing is needed to record that an attribute was looked up or
   set, nor do actions need to be taken based on the value.

Note that this list does not place any restrictions on the values of the
attributes, when the values are computed, or how relevant data is stored.

When :c:func:`PyType_Ready` is called, it uses three tables referenced by the
type object to create :term:`descriptor`\s which are placed in the dictionary of the
type object.  Each descriptor controls access to one attribute of the instance
object.  Each of the tables is optional; if all three are *NULL*, instances of
the type will only have attributes that are inherited from their base type, and
should leave the :c:member:`~PyTypeObject.tp_getattro` and :c:member:`~PyTypeObject.tp_setattro` fields *NULL* as
well, allowing the base type to handle attributes.

The tables are declared as three fields of the type object::

   struct PyMethodDef *tp_methods;
   struct PyMemberDef *tp_members;
   struct PyGetSetDef *tp_getset;

If :c:member:`~PyTypeObject.tp_methods` is not *NULL*, it must refer to an array of
:c:type:`PyMethodDef` structures.  Each entry in the table is an instance of this
structure::

   typedef struct PyMethodDef {
       const char  *ml_name;       /* method name */
       PyCFunction  ml_meth;       /* implementation function */
       int          ml_flags;      /* flags */
       const char  *ml_doc;        /* docstring */
   } PyMethodDef;

One entry should be defined for each method provided by the type; no entries are
needed for methods inherited from a base type.  One additional entry is needed
at the end; it is a sentinel that marks the end of the array.  The
:attr:`ml_name` field of the sentinel must be *NULL*.

The second table is used to define attributes which map directly to data stored
in the instance.  A variety of primitive C types are supported, and access may
be read-only or read-write.  The structures in the table are defined as::

   typedef struct PyMemberDef {
       const char *name;
       int         type;
       int         offset;
       int         flags;
       const char *doc;
   } PyMemberDef;

For each entry in the table, a :term:`descriptor` will be constructed and added to the
type which will be able to extract a value from the instance structure.  The
:attr:`type` field should contain one of the type codes defined in the
:file:`structmember.h` header; the value will be used to determine how to
convert Python values to and from C values.  The :attr:`flags` field is used to
store flags which control how the attribute can be accessed.

The following flag constants are defined in :file:`structmember.h`; they may be
combined using bitwise-OR.

+---------------------------+----------------------------------------------+
| Constant                  | Meaning                                      |
+===========================+==============================================+
| :const:`READONLY`         | Never writable.                              |
+---------------------------+----------------------------------------------+
| :const:`READ_RESTRICTED`  | Not readable in restricted mode.             |
+---------------------------+----------------------------------------------+
| :const:`WRITE_RESTRICTED` | Not writable in restricted mode.             |
+---------------------------+----------------------------------------------+
| :const:`RESTRICTED`       | Not readable or writable in restricted mode. |
+---------------------------+----------------------------------------------+

.. index::
   single: READONLY
   single: READ_RESTRICTED
   single: WRITE_RESTRICTED
   single: RESTRICTED

An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` table to build
descriptors that are used at runtime is that any attribute defined this way can
have an associated doc string simply by providing the text in the table.  An
application can use the introspection API to retrieve the descriptor from the
class object, and get the doc string using its :attr:`__doc__` attribute.

As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry with a :attr:`name` value
of *NULL* is required.

.. XXX Descriptors need to be explained in more detail somewhere, but not here.

   Descriptor objects have two handler functions which correspond to the
   \member{tp_getattro} and \member{tp_setattro} handlers.  The
   \method{__get__()} handler is a function which is passed the descriptor,
   instance, and type objects, and returns the value of the attribute, or it
   returns \NULL{} and sets an exception.  The \method{__set__()} handler is
   passed the descriptor, instance, type, and new value;

Type-specific Attribute Management
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For simplicity, only the :c:type:`char\*` version will be demonstrated here; the
type of the name parameter is the only difference between the :c:type:`char\*`
and :c:type:`PyObject\*` flavors of the interface. This example effectively does
the same thing as the generic example above, but does not use the generic
support added in Python 2.2.  It explains how the handler functions are
called, so that if you do need to extend their functionality, you'll understand
what needs to be done.

The :c:member:`~PyTypeObject.tp_getattr` handler is called when the object requires an attribute
look-up.  It is called in the same situations where the :meth:`__getattr__`
method of a class would be called.

Here is an example::

   static PyObject *
   newdatatype_getattr(newdatatypeobject *obj, char *name)
   {
       if (strcmp(name, "data") == 0)
       {
           return PyLong_FromLong(obj->data);
       }

       PyErr_Format(PyExc_AttributeError,
                    "'%.50s' object has no attribute '%.400s'",
                    tp->tp_name, name);
       return NULL;
   }

The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:`__setattr__` or
:meth:`__delattr__` method of a class instance would be called.  When an
attribute should be deleted, the third parameter will be *NULL*.  Here is an
example that simply raises an exception; if this were really all you wanted, the
:c:member:`~PyTypeObject.tp_setattr` handler should be set to *NULL*. ::

   static int
   newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
   {
       PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
       return -1;
   }

Object Comparison
-----------------

::

   richcmpfunc tp_richcompare;

The :c:member:`~PyTypeObject.tp_richcompare` handler is called when comparisons are needed.  It is
analogous to the :ref:`rich comparison methods <richcmpfuncs>`, like
:meth:`__lt__`, and also called by :c:func:`PyObject_RichCompare` and
:c:func:`PyObject_RichCompareBool`.

This function is called with two Python objects and the operator as arguments,
where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, ``Py_GT``,
``Py_LT`` or ``Py_GT``.  It should compare the two objects with respect to the
specified operator and return ``Py_True`` or ``Py_False`` if the comparison is
successful, ``Py_NotImplemented`` to indicate that comparison is not
implemented and the other object's comparison method should be tried, or *NULL*
if an exception was set.

Here is a sample implementation, for a datatype that is considered equal if the
size of an internal pointer is equal::

   static PyObject *
   newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op)
   {
       PyObject *result;
       int c, size1, size2;

       /* code to make sure that both arguments are of type
          newdatatype omitted */

       size1 = obj1->obj_UnderlyingDatatypePtr->size;
       size2 = obj2->obj_UnderlyingDatatypePtr->size;

       switch (op) {
       case Py_LT: c = size1 <  size2; break;
       case Py_LE: c = size1 <= size2; break;
       case Py_EQ: c = size1 == size2; break;
       case Py_NE: c = size1 != size2; break;
       case Py_GT: c = size1 >  size2; break;
       case Py_GE: c = size1 >= size2; break;
       }
       result = c ? Py_True : Py_False;
       Py_INCREF(result);
       return result;
    }

Abstract Protocol Support
-------------------------

Python supports a variety of *abstract* 'protocols;' the specific interfaces
provided to use these interfaces are documented in :ref:`abstract`.

A number of these abstract interfaces were defined early in the development of
the Python implementation.  In particular, the number, mapping, and sequence
protocols have been part of Python since the beginning.  Other protocols have
been added over time.  For protocols which depend on several handler routines
from the type implementation, the older protocols have been defined as optional
blocks of handlers referenced by the type object.  For newer protocols there are
additional slots in the main type object, with a flag bit being set to indicate
that the slots are present and should be checked by the interpreter.  (The flag
bit does not indicate that the slot values are non-*NULL*. The flag may be set
to indicate the presence of a slot, but a slot may still be unfilled.) ::

   PyNumberMethods   *tp_as_number;
   PySequenceMethods *tp_as_sequence;
   PyMappingMethods  *tp_as_mapping;

If you wish your object to be able to act like a number, a sequence, or a
mapping object, then you place the address of a structure that implements the C
type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or
:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this
structure with appropriate values. You can find examples of the use of each of
these in the :file:`Objects` directory of the Python source distribution. ::

   hashfunc tp_hash;

This function, if you choose to provide it, should return a hash number for an
instance of your data type. Here is a simple example::

   static Py_hash_t
   newdatatype_hash(newdatatypeobject *obj)
   {
       Py_hash_t result;
       result = obj->some_size + 32767 * obj->some_number;
       if (result == -1)
          result = -2;
       return result;
   }

:c:type:`Py_hash_t` is a signed integer type with a platform-varying width.
Returning ``-1`` from :c:member:`~PyTypeObject.tp_hash` indicates an error,
which is why you should be careful to avoid returning it when hash computation
is successful, as seen above.

::

   ternaryfunc tp_call;

This function is called when an instance of your data type is "called", for
example, if ``obj1`` is an instance of your data type and the Python script
contains ``obj1('hello')``, the :c:member:`~PyTypeObject.tp_call` handler is invoked.

This function takes three arguments:

#. *self* is the instance of the data type which is the subject of the call.
   If the call is ``obj1('hello')``, then *self* is ``obj1``.

#. *args* is a tuple containing the arguments to the call.  You can use
   :c:func:`PyArg_ParseTuple` to extract the arguments.

#. *kwds* is a dictionary of keyword arguments that were passed. If this is
   non-*NULL* and you support keyword arguments, use
   :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments.  If you
   do not want to support keyword arguments and this is non-*NULL*, raise a
   :exc:`TypeError` with a message saying that keyword arguments are not supported.

Here is a toy ``tp_call`` implementation::

   static PyObject *
   newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds)
   {
       PyObject *result;
       const char *arg1;
       const char *arg2;
       const char *arg3;

       if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
           return NULL;
       }
       result = PyUnicode_FromFormat(
           "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n",
           obj->obj_UnderlyingDatatypePtr->size,
           arg1, arg2, arg3);
       return result;
   }

::

   /* Iterators */
   getiterfunc tp_iter;
   iternextfunc tp_iternext;

These functions provide support for the iterator protocol.  Both handlers
take exactly one parameter, the instance for which they are being called,
and return a new reference.  In the case of an error, they should set an
exception and return *NULL*.  :c:member:`~PyTypeObject.tp_iter` corresponds
to the Python :meth:`__iter__` method, while :c:member:`~PyTypeObject.tp_iternext`
corresponds to the Python :meth:`~iterator.__next__` method.

Any :term:`iterable` object must implement the :c:member:`~PyTypeObject.tp_iter`
handler, which must return an :term:`iterator` object.  Here the same guidelines
apply as for Python classes:

* For collections (such as lists and tuples) which can support multiple
  independent iterators, a new iterator should be created and returned by
  each call to :c:member:`~PyTypeObject.tp_iter`.
* Objects which can only be iterated over once (usually due to side effects of
  iteration, such as file objects) can implement :c:member:`~PyTypeObject.tp_iter`
  by returning a new reference to themselves -- and should also therefore
  implement the :c:member:`~PyTypeObject.tp_iternext`  handler.

Any :term:`iterator` object should implement both :c:member:`~PyTypeObject.tp_iter`
and :c:member:`~PyTypeObject.tp_iternext`.  An iterator's
:c:member:`~PyTypeObject.tp_iter` handler should return a new reference
to the iterator.  Its :c:member:`~PyTypeObject.tp_iternext` handler should
return a new reference to the next object in the iteration, if there is one.
If the iteration has reached the end, :c:member:`~PyTypeObject.tp_iternext`
may return *NULL* without setting an exception, or it may set
:exc:`StopIteration` *in addition* to returning *NULL*; avoiding
the exception can yield slightly better performance.  If an actual error
occurs, :c:member:`~PyTypeObject.tp_iternext` should always set an exception
and return *NULL*.

.. _weakref-support:

Weak Reference Support
----------------------

One of the goals of Python's weak reference implementation is to allow any type
to participate in the weak reference mechanism without incurring the overhead on
performance-critical objects (such as numbers).

.. seealso::
   Documentation for the :mod:`weakref` module.

For an object to be weakly referencable, the extension type must do two things:

#. Include a :c:type:`PyObject\*` field in the C object structure dedicated to
   the weak reference mechanism.  The object's constructor should leave it
   *NULL* (which is automatic when using the default
   :c:member:`~PyTypeObject.tp_alloc`).

#. Set the :c:member:`~PyTypeObject.tp_weaklistoffset` type member
   to the offset of the aforementioned field in the C object structure,
   so that the interpreter knows how to access and modify that field.

Concretely, here is how a trivial object structure would be augmented
with the required field::

   typedef struct {
       PyObject_HEAD
       PyObject *weakreflist;  /* List of weak references */
   } TrivialObject;

And the corresponding member in the statically-declared type object::

   static PyTypeObject TrivialType = {
       PyVarObject_HEAD_INIT(NULL, 0)
       /* ... other members omitted for brevity ... */
       .tp_weaklistoffset = offsetof(TrivialObject, weakreflist),
   };

The only further addition is that ``tp_dealloc`` needs to clear any weak
references (by calling :c:func:`PyObject_ClearWeakRefs`) if the field is
non-*NULL*::

   static void
   Trivial_dealloc(TrivialObject *self)
   {
       /* Clear weakrefs first before calling any destructors */
       if (self->weakreflist != NULL)
           PyObject_ClearWeakRefs((PyObject *) self);
       /* ... remainder of destruction code omitted for brevity ... */
       Py_TYPE(self)->tp_free((PyObject *) self);
   }

More Suggestions
----------------

In order to learn how to implement any specific method for your new data type,
get the :term:`CPython` source code.  Go to the :file:`Objects` directory,
then search the C source files for ``tp_`` plus the function you want
(for example, ``tp_richcompare``).  You will find examples of the function
you want to implement.

When you need to verify that an object is a concrete instance of the type you
are implementing, use the :c:func:`PyObject_TypeCheck` function.  A sample of
its use might be something like the following::

   if (!PyObject_TypeCheck(some_object, &MyType)) {
       PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
       return NULL;
   }

.. seealso::
   Download CPython source releases.
      https://www.python.org/downloads/source/

   The CPython project on GitHub, where the CPython source code is developed.
      https://github.com/python/cpython

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Text;
using Ecologylab.BigSemantics.PlatformSpecifics;
using Simpl.Fundamental.Net;
using Simpl.Serialization.Context;
using Simpl.Serialization.Types;
using Simpl.Serialization.Types.Scalar;
using System.Reflection;
using System.IO;

namespace Ecologylab.BigSemantics.MetadataNS.Scalar.Types
{
	public class MetadataScalarType : ReferenceType
	{
	    ScalarType              valueScalarType;
	    FieldInfo               valueField;
		private static Boolean  metadataScalarTypesRegistered = false;

        public MetadataScalarType()
            : this(typeof(MetadataScalarType), typeof(ScalarType))
        {

        }
		/// <summary>
		///
		/// </summary>
		/// <param name="metadataScalarTypeClass"></param>
		/// <param name="valueClass"></param>
		protected MetadataScalarType(Type metadataScalarTypeClass, Type valueClass)
            : base(metadataScalarTypeClass, metadataScalarTypeClass.Name, null, null)
		{
			// Get type handles for Test<String> and its field.

            this.valueScalarType = TypeRegistry.ScalarTypes[valueClass];
			valueField = metadataScalarTypeClass.GetRuntimeField(MetadataScalarBase<object>.VALUE_FIELD_NAME);
            if (ValueField == null)
				Debug.WriteLine(metadataScalarTypeClass.Name + " does not have a valueField");
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		FieldInfo ValueField
		{
			get{ return valueField; }
		}

	    public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext unmarshallingContext)
	    {
	        throw new NotImplementedException();
	    }

	    public override bool SetField(object context, FieldInfo field, string valueString, string[] format, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
			if (valueString == null || string.IsNullOrWhiteSpace(valueString))
				return true;
			bool result = false;

		    object valueObject = valueScalarType.GetInstance(valueString, format, scalarUnmarshallingContext);
			if (valueObject != null)
			{
				Object metadataScalarContext = field.GetValue(context);
				if (metadataScalarContext == null)
				{
					Type t = field.FieldType;
					metadataScalarContext = Activator.CreateInstance(t,new object[]{valueObject});
					field.SetValue(context, metadataScalarContext);
				}
				else
					ValueField.SetValue(metadataScalarContext, valueObject);
				result = true;
			}
			return result;
		}

	    public override string Marshall(object instance, TranslationContext context = null)
	    {
	        var metadataScalarInstance = instance as IMetadataScalar<object>;
	        return (metadataScalarInstance != null) ? OperativeScalarType.Marshall(metadataScalarInstance.Value, context) : instance.ToString();
	    }

	    public Object GetValueInstance(String value, String[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
			return OperativeScalarType.GetInstance(value, formatStrings, scalarUnmarshallingContext);
		}

        public override bool NeedsJsonQuotationWrap()
        {
            return OperativeScalarType.NeedsJsonQuotationWrap();
        }

		public static void init()
		{
			if (!metadataScalarTypesRegistered)
			{
				SimplType[]	METADATA_SCALAR_TYPES	=
			    {

                    new MetadataStringScalarType(),
				    new MetadataStringBuilderScalarType(),
				    new MetadataIntegerScalarType(),
				    new MetadataParsedURLScalarType(),
				    new MetadataDateScalarType(),
                    //new MetadataFileScalarType(),
                    new MetadataFloatScalarType(),
                    new MetadataDoubleScalarType(),
                    new MetadataBooleanScalarType(),
                    new MetadataScalarTypeType(),
                };

                //TypeRegistry.RegisterTypes(METADATA_SCALAR_TYPES); //TODO FIXME
				metadataScalarTypesRegistered = true;
			}
		}

	    public override bool SimplEquals(object left, object right)
	    {
	        throw new NotImplementedException();
	    }

        public override  ScalarType OperativeScalarType
        {
            get { return valueScalarType; }
        }
	}

	public class MetadataStringScalarType : MetadataScalarType
	{
		public MetadataStringScalarType()
			: base(typeof(MetadataString), typeof(String))
		{

		}
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
            return new MetadataString(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
		}
	}
	public class MetadataStringBuilderScalarType : MetadataScalarType
	{
		public MetadataStringBuilderScalarType()
			: base(typeof(MetadataStringBuilder), typeof(StringBuilder))
		{

		}
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
            return new MetadataStringBuilder(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
		}
	}
	public class MetadataIntegerScalarType : MetadataScalarType
	{
		public MetadataIntegerScalarType()
			: base(typeof(MetadataInteger), typeof(int))
		{

		}
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
            return new MetadataStringBuilder(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
		}
	}
    public class MetadataFloatScalarType : MetadataScalarType
    {
        public MetadataFloatScalarType()
            : base(typeof(MetadataFloat), typeof(float))
        {

        }
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
        {
            return new MetadataFloat(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
        }
    }

    public class MetadataParsedURLScalarType : MetadataScalarType
	{
		public MetadataParsedURLScalarType()
			: base(typeof(MetadataParsedURL), typeof(ParsedUri))
		{

		}
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
            return new MetadataParsedURL(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
		}
	}
	public class MetadataDateScalarType : MetadataScalarType
	{
		public MetadataDateScalarType()
			: base(typeof(MetadataDate), typeof(DateTime))
		{

		}
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
		{
            return new MetadataDate(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
		}

        public override string Marshall(object instance, TranslationContext context = null)
        {
            var metadataScalarInstance = instance as IMetadataScalar<DateTime>;
            return (metadataScalarInstance != null) ? OperativeScalarType.Marshall(metadataScalarInstance.Value, context) : instance.ToString();
        }
	}

    //TODO: to get file type right.
    //public class MetadataFileScalarType : MetadataScalarType
    //{
    //    public MetadataFileScalarType()
    //        : base(typeof(MetadataFile), typeof(FileTypeBase))
    //    {

    //    }
    //    public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
    //    {
    //        return new MetadataFile(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
    //    }
    //}

    public class MetadataDoubleScalarType : MetadataScalarType
    {
        public MetadataDoubleScalarType()
            : base(typeof(MetadataDouble), typeof(double))
        {

        }
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
        {
            return new MetadataDouble(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
        }
    }

    public class MetadataBooleanScalarType : MetadataScalarType
    {
        public MetadataBooleanScalarType()
            : base(typeof(MetadataBoolean), typeof(Boolean))
        {

        }
        public override object GetInstance(string value, string[] formatStrings, IScalarUnmarshallingContext scalarUnmarshallingContext)
        {
            return new MetadataBoolean(GetValueInstance(value, formatStrings, scalarUnmarshallingContext));
        }
    }
}


text:
define([
	"../validate"
], function( validate ) {

	return function( value, name, check, expected ) {
		validate( "E_INVALID_PAR_TYPE", check, {
			expected: expected,
			name: name,
			value: value
		});
	};

});


text:
/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package gov.nasa.ensemble.core.model.plan;

/**
 *
 * A representation of the model object 'EActivity Group'.
 *
 *
 *
 * A collection of activities. It is a plan parent because its activities are its children.
 *
 *
 *
 * @see gov.nasa.ensemble.core.model.plan.PlanPackage#getEActivityGroup()
 * @model
 * @generated
 */
public interface EActivityGroup extends EPlanChild, EPlanParent {
	/**
	 *
	 *

	 * If the meaning of the 'Parent' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 *
	 * The parent of the activity group. May be another activity group but must be a plan parent.
	 *
	 *
	 * @model kind="operation"
	 * @generated
	 */
	EPlanParent getParent();

} // EActivityGroup


text:
name "administrator"
description "Sets up the administrator box for chef-lab"
run_list "recipe[base]"


text:
CREATE TABLE t1(x);
INSERT INTO t1 VALUES(zeroblob(400));
INSERT INTO t1 VALUES(zeroblob(400));
INSERT INTO t1 SELECT * FROM t1;
INSERT INTO t1 SELECT * FROM t1;
INSERT INTO t1 SELECT * FROM t1;
SELECT rowid FROM t1;


text:
Documentation

Kafka Streams

Developer Guide


text:
namespace tfrt {

// NOTE: This should be writable as a normal TFRT_KERNEL but we need return a
// non-movable type.
static void TestAtomicCreateI32(Result<std::atomic<int32_t>> result) {
  result.Emplace(0);
}

// NOTE: This should be writable as a normal TFRT_KERNEL but we need to mutate
// an argument.
static Chain TestAtomicIncI32(Argument<std::atomic<int32_t>> in) {
  in->fetch_add(1);
  return Chain();
}

static Chain TestAtomicAddI32(Argument<std::atomic<int32_t>> in,
                              Argument<int32_t> value) {
  in->fetch_add(*value);
  return Chain();
}

static std::pair<int32_t, Chain> TestAtomicGetI32(
    Argument<std::atomic<int32_t>> in) {
  return {in->load(), Chain()};
}

// Install some atomic kernels and types for use by the test driver.
void RegisterAtomicTestKernels(KernelRegistry* registry) {
  registry->AddKernel("tfrt_test.atomic.create.i32",
                      TFRT_KERNEL(TestAtomicCreateI32));
  registry->AddKernel("tfrt_test.atomic.inc.i32",
                      TFRT_KERNEL(TestAtomicIncI32));
  registry->AddKernel("tfrt_test.atomic.add.i32",
                      TFRT_KERNEL(TestAtomicAddI32));
  registry->AddKernel("tfrt_test.atomic.get.i32",
                      TFRT_KERNEL(TestAtomicGetI32));
}
}  // namespace tfrt


text:
package net.saik0.android.unifiedpreference;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import net.saik0.android.unifiedpreference.internal.utils.XmlUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceActivity.Header;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.util.Xml;

public class UnifiedPreferenceHelper {
	private final PreferenceActivity mActivity;
	private int mHeaderRes;
	private List<LegacyHeader> mLegacyHeaders = new LinkedList<LegacyHeader>();
	private Boolean mSinglePane;
	private String mSharedPreferencesName;
	private int mSharedPreferencesMode;

	public UnifiedPreferenceHelper(PreferenceActivity activity) {
		mActivity = activity;
	}

	/**
	 * Default value for {@link Header#id Header.id} indicating that no
	 * identifier value is set. All other values (including those below -1) are
	 * valid.
	 */
	public static final long HEADER_ID_UNDEFINED = -1;

	/**
	 * Determines whether the simplified settings UI should be shown. This is
	 * true if device doesn't have newer APIs like {@link PreferenceFragment},
	 * or if forced via {@link onIsHidingHeaders}, or the device doesn't have an
	 * extra-large screen. In these cases, a single-pane "simplified" settings
	 * UI should be shown.
	 */
	public boolean isSinglePane() {
		if (mSinglePane == null) {
			mSinglePane = Boolean
					.valueOf(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
							|| !mActivity.onIsMultiPane()
							|| mActivity.onIsHidingHeaders());
		}
		return mSinglePane.booleanValue();
	}

	/**
	 * Returns the header resource to be used when building headers.
	 *
	 * @return The id of the header resource
	 */
	public int getHeaderRes() {
		return mHeaderRes;
	}

	/**
	 * Sets the header resource to be used when building headers.
	 * This must be called before super.onCreate unless overriding both
	 * {@link #onBuildHeaders(List)} and {@link #onBuildLegacyHeaders(List)}
	 *
	 * @param headerRes The id of the header resource
	 */
	public void setHeaderRes(int headerRes) {
		mHeaderRes = headerRes;
	}

	/**
	 * Returns the current name of the SharedPreferences file that preferences
	 * managed by this will use. Wraps
	 * {@link PreferenceManager#getSharedPreferencesName()} if single pane,
	 * otherwise returns a locally cached String.
	 *
	 * @return The name that can be passed to
	 *         {@link Context#getSharedPreferences(String, int)}
	 */
	@SuppressWarnings("deprecation")
	public String getSharedPreferencesName() {
		if (mActivity.getPreferenceManager() != null) {
			return mActivity.getPreferenceManager().getSharedPreferencesName();
		}
		return mSharedPreferencesName;
	}

	/**
	 * Sets the name of the SharedPreferences file that preferences managed by
	 * this will use. Wraps {@link PreferenceManager#setSharedPreferencesName()}
	 * if single pane, otherwise cache it for use by
	 * {@link UnifiedPreferenceFragment}.
	 *
	 * @param sharedPreferencesName The name of the SharedPreferences file.
	 */
	@SuppressWarnings("deprecation")
	public void setSharedPreferencesName(String sharedPreferencesName) {
		if (mActivity.getPreferenceManager() != null) {
			mActivity.getPreferenceManager().setSharedPreferencesName(
					sharedPreferencesName);
		}
		mSharedPreferencesName = sharedPreferencesName;
	}

	/**
	 * Returns the current mode of the SharedPreferences file that preferences
	 * managed by this will use. Wraps
	 * {@link PreferenceManager#getSharedPreferencesMode()} if single pane,
	 * otherwise returns a locally cached int.
	 *
	 * @return The mode that can be passed to
	 *         {@link Context#getSharedPreferences(String, int)}
	 */
	@SuppressWarnings("deprecation")
	public int getSharedPreferencesMode() {
		if (mActivity.getPreferenceManager() != null) {
			return mActivity.getPreferenceManager().getSharedPreferencesMode();
		}
		return mSharedPreferencesMode;
	}

	/**
	 * Sets the mode of the SharedPreferences file that preferences managed by
	 * this will use. Wraps {@link PreferenceManager#setSharedPreferencesMode()}
	 * if single pane, otherwise cache it for use by
	 * {@link UnifiedPreferenceFragment}.
	 *
	 * @param sharedPreferencesMode The mode of the SharedPreferences file.
	 */
	@SuppressWarnings("deprecation")
	public void setSharedPreferencesMode(int sharedPreferencesMode) {
		if (mActivity.getPreferenceManager() != null) {
			mActivity.getPreferenceManager().setSharedPreferencesMode(
					sharedPreferencesMode);
		}
		mSharedPreferencesMode = sharedPreferencesMode;
	}

	/**
	 * Shows the simplified settings UI if the device configuration if the
	 * device configuration dictates that a simplified, single-pane UI should be
	 * shown.
	 */
	@SuppressWarnings("deprecation")
	protected void onPostCreate(Bundle savedInstanceState) {
		if (isSinglePane()) {
			// In the simplified UI, fragments are not used at all and we
			// instead use the older PreferenceActivity APIs.

			// Set PreferenceManager options if the activity received them before onPostCreate
			if (!TextUtils.isEmpty(mSharedPreferencesName)) {
				mActivity.getPreferenceManager().setSharedPreferencesName(mSharedPreferencesName);
			}
			if (mSharedPreferencesMode != 0) {
				mActivity.getPreferenceManager().setSharedPreferencesMode(mSharedPreferencesMode);
			}

			onBuildLegacyHeaders(mLegacyHeaders);

			// Add all preferences, first create a new preference screen if necessary
			if (mActivity.getPreferenceScreen() == null) {
				mActivity.setPreferenceScreen(mActivity.getPreferenceManager()
						.createPreferenceScreen(mActivity));
			}
			for (LegacyHeader header : mLegacyHeaders) {
				PreferenceCategory category = new PreferenceCategory(mActivity);
				category.setTitle(header.getTitle(mActivity.getResources()));
				mActivity.getPreferenceScreen().addPreference(category);
				mActivity.addPreferencesFromResource(header.preferenceRes);
			}

			onBindPreferenceSummariesToValues();
		}
	}

	/**
	 * Called when the activity needs its list of headers built. By implementing
	 * this and adding at least one item to the list, you will cause the
	 * activity to run in its modern fragment mode. Note that this function may
	 * not always be called; for example, if the activity has been asked to
	 * display a particular fragment without the header list, there is no need
	 * to build the headers.
	 *
	 *

	 * Typical implementations will use {@link #loadHeadersFromResource} to fill
	 * in the list from a resource. For convenience this is done if a header
	 * resource has been set with {@link #setHeaderRes(int)}.
	 *
	 * @param target The list in which to place the headers.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void onBuildHeaders(List target) {
		// Do not build headers unless in single pane mode.
		if (!isSinglePane() && mHeaderRes > 0) {
			loadHeadersFromResource(mHeaderRes, target);
		}
	}

	/**
	 * Called when the activity needs its list of legacy headers built.
	 *
	 *

	 * Typical implementations will use {@link #loadLegacyHeadersFromResource}
	 * to fill in the list from a resource. For convenience this is done if a
	 * header resource has been set with {@link #setHeaderRes(int)}.
	 *
	 * @param target The list in which to place the legacy headers.
	 */
	public void onBuildLegacyHeaders(List<LegacyHeader> target) {
		if (mHeaderRes > 0) {
			loadLegacyHeadersFromResource(mHeaderRes, mLegacyHeaders);
		}
	}

	/**
	 * Bind the summaries of EditText/List/Dialog/Ringtone preferences to their
	 * values. When their values change, their summaries are updated to reflect
	 * the new value, per the Android Design guidelines.
	 */
	@SuppressWarnings("deprecation")
	public void onBindPreferenceSummariesToValues() {
		UnifiedPreferenceUtils.bindAllPreferenceSummariesToValues(mActivity
				.getPreferenceScreen());
	}

	/**
	 * Parse the given XML file as a header description, adding each parsed
	 * Header into the target list.
	 *
	 * @param resid The XML resource to load and parse.
	 * @param target The list in which the parsed headers should be placed.
	 */
	public void loadHeadersFromResource(int resid, List target) {
		XmlResourceParser parser = null;
		try {
			parser = mActivity.getResources().getXml(resid);
			AttributeSet attrs = Xml.asAttributeSet(parser);

			int type;
			while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
					&& type != XmlPullParser.START_TAG) {
				// Parse next until start tag is found
			}

			String nodeName = parser.getName();
			if (!"preference-headers".equals(nodeName)) {
				throw new RuntimeException(
						"XML document must start with <preference-headers> tag; found"
								+ nodeName + " at "
								+ parser.getPositionDescription());
			}

			Bundle curBundle = null;

			final int outerDepth = parser.getDepth();
			while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
					&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
				if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
					continue;
				}

				nodeName = parser.getName();
				if ("header".equals(nodeName)) {
					Header header = new Header();

					TypedArray sa = mActivity.getResources().obtainAttributes(
							attrs, R.styleable.PreferenceHeader);
					header.id = sa.getResourceId(
							R.styleable.PreferenceHeader_id,
							(int) HEADER_ID_UNDEFINED);
					TypedValue tv = sa
							.peekValue(R.styleable.PreferenceHeader_title);
					if (tv != null && tv.type == TypedValue.TYPE_STRING) {
						if (tv.resourceId != 0) {
							header.titleRes = tv.resourceId;
						} else {
							header.title = tv.string;
						}
					}
					tv = sa.peekValue(R.styleable.PreferenceHeader_summary);
					if (tv != null && tv.type == TypedValue.TYPE_STRING) {
						if (tv.resourceId != 0) {
							header.summaryRes = tv.resourceId;
						} else {
							header.summary = tv.string;
						}
					}
					tv = sa.peekValue(R.styleable.PreferenceHeader_breadCrumbTitle);
					if (tv != null && tv.type == TypedValue.TYPE_STRING) {
						if (tv.resourceId != 0) {
							header.breadCrumbTitleRes = tv.resourceId;
						} else {
							header.breadCrumbTitle = tv.string;
						}
					}
					tv = sa.peekValue(R.styleable.PreferenceHeader_breadCrumbShortTitle);
					if (tv != null && tv.type == TypedValue.TYPE_STRING) {
						if (tv.resourceId != 0) {
							header.breadCrumbShortTitleRes = tv.resourceId;
						} else {
							header.breadCrumbShortTitle = tv.string;
						}
					}
					header.iconRes = sa.getResourceId(
							R.styleable.PreferenceHeader_icon, 0);
					header.fragment = sa
							.getString(R.styleable.PreferenceHeader_fragment);

					if (curBundle == null) {
						curBundle = new Bundle();
					}

					// Add preference resource to fragmentArgs
					int preference = sa.getResourceId(
							R.styleable.PreferenceHeader_preferenceRes, 0);
					if (preference > 0) {
						curBundle.putInt(
								UnifiedPreferenceFragment.ARG_PREFERENCE_RES, preference);
					}
					sa.recycle();

					final int innerDepth = parser.getDepth();
					while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
							&& (type != XmlPullParser.END_TAG || parser
									.getDepth() > innerDepth)) {
						if (type == XmlPullParser.END_TAG
								|| type == XmlPullParser.TEXT) {
							continue;
						}

						String innerNodeName = parser.getName();
						if (innerNodeName.equals("extra")) {
							mActivity.getResources().parseBundleExtra("extra",
									attrs, curBundle);
							XmlUtils.skipCurrentTag(parser);

						} else if (innerNodeName.equals("intent")) {
							header.intent = Intent.parseIntent(
									mActivity.getResources(), parser, attrs);

						} else {
							XmlUtils.skipCurrentTag(parser);
						}
					}

					if (curBundle.size() > 0) {
						header.fragmentArguments = curBundle;
						curBundle = null;
					}

					target.add(header);
				} else {
					XmlUtils.skipCurrentTag(parser);
				}
			}

		} catch (XmlPullParserException e) {
			throw new RuntimeException("Error parsing headers", e);
		} catch (IOException e) {
			throw new RuntimeException("Error parsing headers", e);
		} finally {
			if (parser != null)
				parser.close();
		}
	}

	/**
	 * Parse the given XML file as a header description, adding each parsed
	 * LegacyHeader into the target list.
	 *
	 * @param resid The XML resource to load and parse.
	 * @param target The list in which the parsed headers should be placed.
	 */
	public void loadLegacyHeadersFromResource(int resid, List<LegacyHeader> target) {
		XmlResourceParser parser = null;
		try {
			parser = mActivity.getResources().getXml(resid);
			AttributeSet attrs = Xml.asAttributeSet(parser);

			int type;
			while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
					&& type != XmlPullParser.START_TAG) {
				// Parse next until start tag is found
			}

			String nodeName = parser.getName();
			if (!"preference-headers".equals(nodeName)) {
				throw new RuntimeException(
						"XML document must start with <preference-headers> tag; found"
								+ nodeName + " at "
								+ parser.getPositionDescription());
			}

			final int outerDepth = parser.getDepth();
			while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
					&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
				if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
					continue;
				}

				nodeName = parser.getName();
				if ("header".equals(nodeName)) {
					LegacyHeader header = new LegacyHeader();

					TypedArray sa = mActivity.getResources().obtainAttributes(
							attrs, R.styleable.PreferenceHeader);
					TypedValue tv = sa
							.peekValue(R.styleable.PreferenceHeader_title);
					if (tv != null && tv.type == TypedValue.TYPE_STRING) {
						if (tv.resourceId != 0) {
							header.titleRes = tv.resourceId;
						} else {
							header.title = tv.string;
						}
					}
					header.preferenceRes = sa.getResourceId(
							R.styleable.PreferenceHeader_preferenceRes, 0);

					sa.recycle();

					target.add(header);
				} else {
					XmlUtils.skipCurrentTag(parser);
				}
			}

		} catch (XmlPullParserException e) {
			throw new RuntimeException("Error parsing headers", e);
		} catch (IOException e) {
			throw new RuntimeException("Error parsing headers", e);
		} finally {
			if (parser != null)
				parser.close();
		}
	}
}


text:
using UnityEngine;
using System.Collections;

public class csMoveHeadingToPath : MonoBehaviour {
	string pathName = "MyPath";
	float pathTime = 18.0f;//5.0f
	Hashtable table = new Hashtable();
	void SetupPath(){
		table.Add( "path", iTweenPath.GetPath(pathName) );//ITween path hash data
		table.Add( "time", pathTime );
		table.Add( "easetype", iTween.EaseType.easeInOutSine );
		table.Add( "onstart", "cb_iTweenStart" );  //Handler func when iTween start
		table.Add( "onstartparams", "Start" );   //parameter of Handler func when iTween start
		table.Add( "oncomplete", "cb_iTweenComplete" ); //Handler func when iTween end
		table.Add( "oncompleteparams", "Complete" ); //parameter of Handler func when iTween end

		table.Add( "orienttopath", true ); //Head to forwarding vector (*Important*)
		table.Add( "lookTime", 1.0f ); //Time value for heading nose (*Important*)

		iTween.MoveTo(gameObject, table);
	}
	void cb_iTweenStart(string param){
		Debug.Log("[iTween] cb_iTweenStart: "+param);
	}
	void cb_iTweenComplete(string param){
		Debug.Log("[iTween] cb_iTweenComplete: "+param);
		iTween.MoveTo(gameObject, table);//Restart iTween.
	}

	void Start () {
		SetupPath();
	}
	void Update () {
	}
}


text:
/****************************************************************\
*                                                                *
*  indicate : Index a file using OBDA indexers                   *
*                                                                *
*  Steve Searle.        mailto:searle@sanger.ac.uk               *
*                                                                *
*  This source code is distributed under the terms of the        *
*  GNU Lesser General Public License. See the file COPYING       *
*  or http://www.fsf.org/copyleft/lesser.html for details        *
*                                                                *
*  If you use this code, please keep this notice intact.         *
*                                                                *
\****************************************************************/

#include <stdio.h>
#include <stdlib.h> /* For atoi() */
#include <sys/types.h>
#include <sys/stat.h>
#include <libgen.h>
#include <string.h>

#include "indicate.h"
#include "BioIndex.h"
#include "parsers.h"
#include "Error.h"
#include "StrUtil.h"

void Indicate_usage();

int main(int argc, char **argv){
  char *arg;
  char *file_prefix = NULL;
  char *index_dir = NULL;
  char *data_dir = NULL;
  char *primary_parser = NULL;
  char *secondary_parser = NULL;
  char *secondary_multi_parser = NULL;
  BioIndex_Parser_Func parser;
  BioIndex_Parser_Func sec_parser;
  BioIndex_MultiParser_Func sec_multi_parser;
  char *line_prefix = NULL;
  char *secondary_line_prefix = NULL;
  char *record_prefix = NULL;
  BioIndex_Index_Definition *primary_def;
  BioIndex_Index_Definition *secondary_def;
  Vector *secondary_defs = Vector_new();
  BioIndex *bi;
  struct stat dirStat;
  char *gtStr = ">";
  char *emptyStr = "";
  int argNum = 1;

  initEnsC(argc, argv);

  primary_parser = secondary_parser = secondary_multi_parser = emptyStr;
  line_prefix = secondary_line_prefix = record_prefix = gtStr;

  while (argNum < argc) {
    char *arg = argv[argNum];
    char *val;

    if (argNum == argc-1) {
      Indicate_usage();
    }

    val = argv[++argNum];
//    printf("%s %s\n",arg,val);

    if (!strcmp(arg, "-d") || !strcmp(arg,"--data_dir")) {
      StrUtil_copyString(&data_dir,val,0);
    } else if (!strcmp(arg, "-f") || !strcmp(arg,"--file_prefix")) {
      StrUtil_copyString(&file_prefix,val,0);
    } else if (!strcmp(arg, "-i") || !strcmp(arg,"--index")) {
      StrUtil_copyString(&index_dir,val,0);
    } else if (!strcmp(arg, "-p") || !strcmp(arg,"--parser")) {
      StrUtil_copyString(&primary_parser,val,0);
    } else if (!strcmp(arg, "-s") || !strcmp(arg,"--secondary_parser")) {
      StrUtil_copyString(&secondary_parser,val,0);
    } else if (!strcmp(arg, "-M") || !strcmp(arg,"--secondary_multi_parser")) {
      StrUtil_copyString(&secondary_multi_parser,val,0);
    } else if (!strcmp(arg, "-m") || !strcmp(arg,"--secondary_line_prefix")) {
      StrUtil_copyString(&secondary_line_prefix,val,0);
    } else if (!strcmp(arg, "-l") || !strcmp(arg,"--line_prefix")) {
      StrUtil_copyString(&line_prefix,val,0);
    } else if (!strcmp(arg, "-r") || !strcmp(arg,"--record_prefix")) {
      StrUtil_copyString(&record_prefix,val,0);
    } else {
      printf("Error in command line at %s\n\n",arg);
      Indicate_usage();
    }

    argNum++;
  }

  printf("Program for generating OBDA indices\n"
         "Steve M.J. Searle.  searle@sanger.ac.uk  Last update Feb 2004.\n");

  if (!file_prefix || !index_dir) {
    Indicate_usage();
  }

  printf("Using File:  [%s]\n"
         "      Index: [%s]\n", file_prefix, index_dir);

  if (!stat(index_dir,&dirStat)) {
    if (!(dirStat.st_mode & S_IFDIR)) {
      Error_write(EOBDA,"main",ERR_SEVERE,"Output dir %s is not a directory",index_dir);
    }
  } else {
    printf("Creating Index dir %s", index_dir);
    mkdir(index_dir,0755);
  }

  printf("Primary parser = %s\n",primary_parser);
  parser = Parser_lookup(primary_parser);
  printf("Got function address %p\n",parser);
  primary_def = BioIndex_Index_Definition_create(record_prefix,
                                                 line_prefix,
                                                 parser,
                                                 NULL,
                                                 "ACC");
  if (strlen(secondary_multi_parser)) {
    printf("Secondary multi parser = %s\n",secondary_multi_parser);
    sec_multi_parser = Parser_lookup(secondary_multi_parser);
    printf("Got function address %p\n",secondary_parser);
    secondary_def = BioIndex_Index_Definition_create(record_prefix,
                                                     secondary_line_prefix,
                                                     NULL,
                                                     sec_multi_parser,
                                                     "ID");
    Vector_addElement(secondary_defs,secondary_def);
  }

  if (strlen(secondary_parser)) {
    printf("Secondary parser = %s\n",secondary_parser);
    sec_parser = Parser_lookup(secondary_parser);
    printf("Got function = %p\n",sec_parser);
    secondary_def = BioIndex_Index_Definition_create(record_prefix,
                                                     secondary_line_prefix,
                                                     sec_parser,
                                                     NULL,
                                                     "ID");
    Vector_addElement(secondary_defs,secondary_def);
  }

  bi = BioIndex_generate_flat(index_dir,data_dir,file_prefix,data_dir,primary_def,
                              secondary_defs);

  printf("Completed Indexing\n");
  return 0;
}

void Indicate_usage() {
  printf("indicate \n"
         "-d --data_dir Path to files to be indexed\n"
         "-f --file_prefix File prefix of files to be indexed\n"
         "-i --index Output index dir name\n"
         "-p --parser Parser function used to parse the primary key line\n"
         "-s --secondary_parser Parser function used to parse the secondary key line\n"
         "-M --secondary_multi_parser Parser function used to parse the secondary key line\n"
         "-m --secondary_line_prefix The string used to identify secondary ID lines\n"
         "-l --line_prefix The string used to identify primary ID lines\n"
         "-r --record_prefix Line prefix at start of record\n");
  exit(1);
}


text:
public class Tape implements Media {
	private String tape = "";

	public Tape() {

	}

	public void saveOnTape(String sound) {
		tape = sound;
	}

	public String readTape() {
		return tape;
	}
}