text:
using namespace triagens::aql;
using Json = triagens::basics::Json;
using JsonHelper = triagens::basics::JsonHelper;

////////////////////////////////////////////////////////////////////////////////
/// @brief a quick method to decide whether a value is true
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isTrue () const {
  if (_type == JSON) {
    TRI_json_t* json = _json->json();
    if (TRI_IsBooleanJson(json) && json->_value._boolean) {
      return true;
    }
    else if (TRI_IsNumberJson(json) && json->_value._number != 0.0) {
      return true;
    }
    else if (TRI_IsStringJson(json) && json->_value._string.length != 1) {
      // the trailing NULL byte counts, too...
      return true;
    }
    else if (TRI_IsArrayJson(json) || TRI_IsObjectJson(json)) {
      return true;
    }
  }
  else if (_type == RANGE || _type == DOCVEC) {
    // a range or a docvec is equivalent to an array
    return true;
  }
  else if (_type == EMPTY) {
    return false;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destroy, explicit destruction, only when needed
////////////////////////////////////////////////////////////////////////////////

void AqlValue::destroy () {
  switch (_type) {
    case JSON: {
      delete _json;
      _json = nullptr;
      break;
    }
    case DOCVEC: {
      if (_vector != nullptr) {
        for (auto it = _vector->begin(); it != _vector->end(); ++it) {
          delete *it;
        }
        delete _vector;
        _vector = nullptr;
      }
      break;
    }
    case RANGE: {
      delete _range;
      _range = nullptr;
      break;
    }
    case SHAPED: {
      // do nothing here, since data pointers need not be freed
      break;
    }
    case EMPTY: {
      // do nothing
      break;
    }
  }

  // to avoid double freeing
  _type = EMPTY;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the name of an AqlValue type
////////////////////////////////////////////////////////////////////////////////

std::string AqlValue::getTypeString () const {
  switch (_type) {
    case JSON:
      return std::string("json (") + std::string(TRI_GetTypeStringJson(_json->json())) + std::string(")");
    case SHAPED:
      return "shaped";
    case DOCVEC:
      return "docvec";
    case RANGE:
      return "range";
    case EMPTY:
      return "empty";
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief clone for recursive copying
////////////////////////////////////////////////////////////////////////////////

AqlValue AqlValue::clone () const {
  switch (_type) {
    case JSON: {
      return AqlValue(new Json(_json->copy()));
    }

    case SHAPED: {
      return AqlValue(_marker);
    }

    case DOCVEC: {
      auto c = new std::vector<AqlItemBlock*>;
      try {
        c->reserve(_vector->size());
        for (auto it = _vector->begin(); it != _vector->end(); ++it) {
          c->emplace_back((*it)->slice(0, (*it)->size()));
        }
      }
      catch (...) {
        for (auto& x : *c) {
          delete x;
        }
        delete c;
        throw;
      }
      return AqlValue(c);
    }

    case RANGE: {
      return AqlValue(_range->_low, _range->_high);
    }

    case EMPTY: {
      return AqlValue();
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shallow clone
////////////////////////////////////////////////////////////////////////////////

AqlValue AqlValue::shallowClone () const {
  if (_type == JSON) {
    return AqlValue(new Json(TRI_UNKNOWN_MEM_ZONE, _json->json(), Json::NOFREE));
  }

  // fallback to regular deep-copying
  return clone();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains a string value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isString () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return TRI_IsStringJson(json);
    }

    case SHAPED:
    case DOCVEC:
    case RANGE:
    case EMPTY: {
      return false;
    }
  }

  TRI_ASSERT(false);
  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains a numeric value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isNumber () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return TRI_IsNumberJson(json);
    }

    case SHAPED:
    case DOCVEC:
    case RANGE:
    case EMPTY: {
      return false;
    }
  }

  TRI_ASSERT(false);
  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains a boolean value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isBoolean () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return TRI_IsBooleanJson(json);
    }

    case SHAPED:
    case DOCVEC:
    case RANGE:
    case EMPTY: {
      return false;
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains an array value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isArray () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return TRI_IsArrayJson(json);
    }

    case SHAPED: {
      return false;
    }

    case DOCVEC:
    case RANGE: {
      return true;
    }

    case EMPTY: {
      return false;
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains an object value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isObject () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return TRI_IsObjectJson(json);
    }

    case SHAPED: {
      return true;
    }

    case DOCVEC:
    case RANGE:
    case EMPTY: {
      return false;
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not the AqlValue contains a null value
////////////////////////////////////////////////////////////////////////////////

bool AqlValue::isNull (bool emptyIsNull) const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      return json == nullptr || json->_type == TRI_JSON_NULL;
    }

    case SHAPED: {
      return false;
    }

    case DOCVEC:
    case RANGE: {
      return false;
    }

    case EMPTY: {
      return emptyIsNull;
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief returns the array member at position i
////////////////////////////////////////////////////////////////////////////////

triagens::basics::Json AqlValue::at (triagens::arango::AqlTransaction* trx,
                                     size_t i) const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      if (TRI_IsArrayJson(json)) {
        if (i < TRI_LengthArrayJson(json)) {
          return triagens::basics::Json(TRI_UNKNOWN_MEM_ZONE, static_cast<TRI_json_t*>(TRI_AtVector(&json->_value._objects, i)), triagens::basics::Json::NOFREE);
        }
      }
      break; // fall-through to exception
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);
      // calculate the result list length
      size_t offset = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        auto current = (*it);
        size_t const n = current->size();

        if (offset + i < n) {
          auto vecCollection = current->getDocumentCollection(0);

          return current->getValue(i - offset, 0).toJson(trx, vecCollection, true);
        }

        offset += (*it)->size();
      }
      break; // fall-through to exception
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);
      return triagens::basics::Json(static_cast<double>(_range->at(i)));
    }

    case SHAPED:
    case EMPTY: {
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief returns the length of an AqlValue containing an array
////////////////////////////////////////////////////////////////////////////////

size_t AqlValue::arraySize () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();

      if (TRI_IsArrayJson(json)) {
        return TRI_LengthArrayJson(json);
      }
      return 0;
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);
      // calculate the result list length
      size_t totalSize = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        totalSize += (*it)->size();
      }
      return totalSize;
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);
      return _range->size();
    }

    case SHAPED:
    case EMPTY: {
    }
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the numeric value of an AqlValue
////////////////////////////////////////////////////////////////////////////////

int64_t AqlValue::toInt64 () const {
  switch (_type) {
    case JSON:
      return TRI_ToInt64Json(_json->json());
    case RANGE: {
      size_t rangeSize = _range->size();
      if (rangeSize == 1) {
        return _range->at(0);
      }
      return 0;
    }
    case DOCVEC:
    case SHAPED:
    case EMPTY:
      // cannot convert these types
      return 0;
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get the numeric value of an AqlValue
////////////////////////////////////////////////////////////////////////////////

double AqlValue::toNumber (bool& failed) const {
  switch (_type) {
    case JSON:
      return TRI_ToDoubleJson(_json->json(), failed);
    case RANGE: {
      size_t rangeSize = _range->size();
      if (rangeSize == 1) {
        return static_cast<double>(_range->at(0));
      }
      return 0.0;
    }
    case DOCVEC:
    case SHAPED:
    case EMPTY:
      // cannot convert these types
      return 0.0;
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get a string representation of the AqlValue
////////////////////////////////////////////////////////////////////////////////

std::string AqlValue::toString () const {
  switch (_type) {
    case JSON: {
      TRI_json_t const* json = _json->json();
      TRI_ASSERT(TRI_IsStringJson(json));
      return std::string(json->_value._string.data, json->_value._string.length - 1);
    }

    case SHAPED:
    case DOCVEC:
    case RANGE:
    case EMPTY: {
      // cannot convert these types
    }
  }

  return std::string("");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief construct a V8 value as input for the expression execution in V8
/// only construct those attributes that are needed in the expression
////////////////////////////////////////////////////////////////////////////////

v8::Handle<v8::Value> AqlValue::toV8Partial (v8::Isolate* isolate,
                                             triagens::arango::AqlTransaction* trx,
                                             std::unordered_set<std::string> const& attributes,
                                             TRI_document_collection_t const* document) const {
  TRI_ASSERT_EXPENSIVE(_type == JSON);

  TRI_json_t const* json = _json->json();

  if (TRI_IsObjectJson(json)) {
    size_t const n = TRI_LengthVector(&json->_value._objects);

    v8::Handle<v8::Object> result = v8::Object::New(isolate);

    // only construct those attributes needed
    size_t left = attributes.size();

    // we can only have got here if we had attributes
    TRI_ASSERT(left > 0);

    // iterate over all the object's attributes
    for (size_t i = 0; i < n; i += 2) {
      TRI_json_t const* key = static_cast<TRI_json_t const*>(TRI_AddressVector(&json->_value._objects, i));

      if (! TRI_IsStringJson(key)) {
        continue;
      }

      // check if we need to render this attribute
      auto it = attributes.find(std::string(key->_value._string.data, key->_value._string.length - 1));

      if (it == attributes.end()) {
        // we can skip the attribute
        continue;
      }

      TRI_json_t const* value = static_cast<TRI_json_t const*>(TRI_AddressVector(&json->_value._objects, (i + 1)));

      if (value != nullptr) {
        result->ForceSet(TRI_V8_STD_STRING((*it)), TRI_ObjectJson(isolate, value));
      }

      if (--left == 0) {
        // we have rendered all required attributes
        break;
      }
    }

    // return partial object
    return result;
  }

  // fallback
  return TRI_ObjectJson(isolate, json);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief construct a V8 value as input for the expression execution in V8
////////////////////////////////////////////////////////////////////////////////

v8::Handle<v8::Value> AqlValue::toV8 (v8::Isolate* isolate,
                                      triagens::arango::AqlTransaction* trx,
                                      TRI_document_collection_t const* document) const {
  switch (_type) {
    case JSON: {
      TRI_ASSERT(_json != nullptr);
      return TRI_ObjectJson(isolate, _json->json());
    }

    case SHAPED: {
      TRI_ASSERT(document != nullptr);
      TRI_ASSERT(_marker != nullptr);
      return TRI_WrapShapedJson<triagens::arango::AqlTransaction>(isolate, *trx, document->_info._cid, _marker);
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);

      // calculate the result array length
      size_t totalSize = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        totalSize += (*it)->size();
      }

      // allocate the result array
      v8::Handle<v8::Array> result = v8::Array::New(isolate, static_cast<int>(totalSize));
      uint32_t j = 0; // output row count

      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        auto current = (*it);
        size_t const n = current->size();
        auto vecCollection = current->getDocumentCollection(0);
        for (size_t i = 0; i < n; ++i) {
          result->Set(j++, current->getValueReference(i, 0).toV8(isolate, trx, vecCollection));
        }
      }
      return result;
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);

      // allocate the buffer for the result
      size_t const n = _range->size();
      v8::Handle<v8::Array> result = v8::Array::New(isolate, static_cast<int>(n));

      for (uint32_t i = 0; i < n; ++i) {
        // is it safe to use a double here (precision loss)?
        result->Set(i, v8::Number::New(isolate, static_cast<double>(_range->at(static_cast<size_t>(i)))));
      }

      return result;
    }

    case EMPTY: {
      return v8::Null(isolate);
    }
  }

  // should never get here
  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief toJson method
////////////////////////////////////////////////////////////////////////////////

Json AqlValue::toJson (triagens::arango::AqlTransaction* trx,
                       TRI_document_collection_t const* document,
                       bool copy) const {
  switch (_type) {
    case JSON: {
      if (copy) {
        return _json->copy();
      }
      return Json(_json->zone(), _json->json(), Json::NOFREE);
    }

    case SHAPED: {
      TRI_ASSERT(document != nullptr);
      TRI_ASSERT(_marker != nullptr);

      auto shaper = document->getShaper();
      return TRI_ExpandShapedJson(
        shaper,
        trx->resolver(),
        document->_info._cid,
        _marker
      );
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);

      // calculate the result array length
      size_t totalSize = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        totalSize += (*it)->size();
      }

      // allocate the result array
      Json json(Json::Array, static_cast<size_t>(totalSize));

      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        auto current = (*it);
        size_t const n = current->size();
        auto vecCollection = current->getDocumentCollection(0);
        for (size_t i = 0; i < n; ++i) {
          json.add(current->getValueReference(i, 0).toJson(trx, vecCollection, true));
        }
      }

      return json;
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);

      // allocate the buffer for the result
      size_t const n = _range->size();
      Json json(Json::Array, n);

      for (size_t i = 0; i < n; ++i) {
        // is it safe to use a double here (precision loss)?
        json.add(Json(static_cast<double>(_range->at(i))));
      }

      return json;
    }

    case EMPTY: {
      return Json(Json::Null);
    }
  }

  THROW_ARANGO_EXCEPTION(TRI_ERROR_INTERNAL);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief hashes the JSON contents
////////////////////////////////////////////////////////////////////////////////

uint64_t AqlValue::hash (triagens::arango::AqlTransaction* trx,
                         TRI_document_collection_t const* document) const {
  switch (_type) {
    case JSON: {
      return TRI_FastHashJson(_json->json());
    }

    case SHAPED: {
      TRI_ASSERT(document != nullptr);
      TRI_ASSERT(_marker != nullptr);

      auto shaper = document->getShaper();
      TRI_shaped_json_t shaped;
      TRI_EXTRACT_SHAPED_JSON_MARKER(shaped, _marker);
      Json json(shaper->memoryZone(), TRI_JsonShapedJson(shaper, &shaped));

      // append the internal attributes

      // _id, _key, _rev
      char const* key = TRI_EXTRACT_MARKER_KEY(_marker);
      std::string id(trx->resolver()->getCollectionName(document->_info._cid));
      id.push_back('/');
      id.append(key);
      json(TRI_VOC_ATTRIBUTE_ID, Json(id));
      json(TRI_VOC_ATTRIBUTE_REV, Json(std::to_string(TRI_EXTRACT_MARKER_RID(_marker))));
      json(TRI_VOC_ATTRIBUTE_KEY, Json(key));

      if (TRI_IS_EDGE_MARKER(_marker)) {
        // _from
        std::string from(trx->resolver()->getCollectionNameCluster(TRI_EXTRACT_MARKER_FROM_CID(_marker)));
        from.push_back('/');
        from.append(TRI_EXTRACT_MARKER_FROM_KEY(_marker));
        json(TRI_VOC_ATTRIBUTE_FROM, Json(from));

        // _to
        std::string to(trx->resolver()->getCollectionNameCluster(TRI_EXTRACT_MARKER_TO_CID(_marker)));
        to.push_back('/');
        to.append(TRI_EXTRACT_MARKER_TO_KEY(_marker));
        json(TRI_VOC_ATTRIBUTE_TO, Json(to));
      }

      return TRI_FastHashJson(json.json());
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);

      // calculate the result array length
      size_t totalSize = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        totalSize += (*it)->size();
      }

      // allocate the result array
      Json json(Json::Array, static_cast<size_t>(totalSize));

      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        auto current = (*it);
        size_t const n = current->size();
        auto vecCollection = current->getDocumentCollection(0);

        for (size_t i = 0; i < n; ++i) {
          json.add(current->getValueReference(i, 0).toJson(trx, vecCollection, true));
        }
      }

      return TRI_FastHashJson(json.json());
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);

      // allocate the buffer for the result
      size_t const n = _range->size();
      Json json(Json::Array, n);

      for (size_t i = 0; i < n; ++i) {
        // is it safe to use a double here (precision loss)?
        json.add(Json(static_cast<double>(_range->at(i))));
      }

      return TRI_FastHashJson(json.json());
    }

    case EMPTY: {
    }
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief extract an attribute value from the AqlValue
/// this will return an empty Json if the value is not an object
////////////////////////////////////////////////////////////////////////////////

Json AqlValue::extractObjectMember (triagens::arango::AqlTransaction* trx,
                                    TRI_document_collection_t const* document,
                                    char const* name,
                                    bool copy,
                                    triagens::basics::StringBuffer& buffer) const {
  switch (_type) {
    case JSON: {
      TRI_ASSERT(_json != nullptr);
      TRI_json_t const* json = _json->json();

      if (TRI_IsObjectJson(json)) {
        TRI_json_t const* found = TRI_LookupObjectJson(json, name);

        if (found != nullptr) {
          if (copy) {
            // return a copy of the value
            return Json(TRI_UNKNOWN_MEM_ZONE, TRI_CopyJson(TRI_UNKNOWN_MEM_ZONE, found), triagens::basics::Json::AUTOFREE);
          }

          // return a pointer to the original value, without asking for its ownership
          return Json(TRI_UNKNOWN_MEM_ZONE, found, triagens::basics::Json::NOFREE);
        }
      }

      // attribute does not exist or something went wrong - fall-through to returning null below
      return Json(Json::Null);
    }

    case SHAPED: {
      TRI_ASSERT(document != nullptr);
      TRI_ASSERT(_marker != nullptr);

      // look for the attribute name in the shape
      if (*name == '_' && name[1] != '\0') {
        if (name[1] == 'k' && strcmp(name, TRI_VOC_ATTRIBUTE_KEY) == 0) {
          // _key value is copied into JSON
          return Json(TRI_UNKNOWN_MEM_ZONE, TRI_EXTRACT_MARKER_KEY(_marker));
        }
        if (name[1] == 'i' && strcmp(name, TRI_VOC_ATTRIBUTE_ID) == 0) {
          // _id
          buffer.reset();
          trx->resolver()->getCollectionName(document->_info._cid, buffer);
          buffer.appendChar('/');
          buffer.appendText(TRI_EXTRACT_MARKER_KEY(_marker));
          return Json(TRI_UNKNOWN_MEM_ZONE, buffer.c_str(), buffer.length());
        }
        if (name[1] == 'r' && strcmp(name, TRI_VOC_ATTRIBUTE_REV) == 0) {
          // _rev
          TRI_voc_rid_t rid = TRI_EXTRACT_MARKER_RID(_marker);
          buffer.reset();
          buffer.appendInteger(rid);
          return Json(TRI_UNKNOWN_MEM_ZONE, buffer.c_str(), buffer.length());
        }
        if (name[1] == 'f' &&
            strcmp(name, TRI_VOC_ATTRIBUTE_FROM) == 0 &&
            (_marker->_type == TRI_DOC_MARKER_KEY_EDGE ||
             _marker->_type == TRI_WAL_MARKER_EDGE)) {
          buffer.reset();
          trx->resolver()->getCollectionNameCluster(TRI_EXTRACT_MARKER_FROM_CID(_marker), buffer);
          buffer.appendChar('/');
          buffer.appendText(TRI_EXTRACT_MARKER_FROM_KEY(_marker));
          return Json(TRI_UNKNOWN_MEM_ZONE, buffer.c_str(), buffer.length());
        }
        if (name[1] == 't' &&
            strcmp(name, TRI_VOC_ATTRIBUTE_TO) == 0 &&
            (_marker->_type == TRI_DOC_MARKER_KEY_EDGE ||
            _marker->_type == TRI_WAL_MARKER_EDGE)) {
          buffer.reset();
          trx->resolver()->getCollectionNameCluster(TRI_EXTRACT_MARKER_TO_CID(_marker), buffer);
          buffer.appendChar('/');
          buffer.appendText(TRI_EXTRACT_MARKER_TO_KEY(_marker));
          return Json(TRI_UNKNOWN_MEM_ZONE, buffer.c_str(), buffer.length());
        }
      }

      auto shaper = document->getShaper();

      TRI_shape_pid_t pid = shaper->lookupAttributePathByName(name);

      if (pid != 0) {
        // attribute exists
        TRI_shaped_json_t document;
        TRI_EXTRACT_SHAPED_JSON_MARKER(document, _marker);

        TRI_shaped_json_t json;
        TRI_shape_t const* shape;

        bool ok = shaper->extractShapedJson(&document, 0, pid, &json, &shape);

        if (ok && shape != nullptr) {
          return Json(TRI_UNKNOWN_MEM_ZONE, TRI_JsonShapedJson(shaper, &json));
        }
      }

      // attribute does not exist or something went wrong - fall-through to returning null
      break;
    }

    case DOCVEC:
    case RANGE:
    case EMPTY: {
      break;
    }
  }

  return Json(Json::Null);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief extract a value from an array AqlValue
/// this will return null if the value is not an array
/// depending on the last parameter, the return value will either contain a
/// copy of the original value in the array or a reference to it (which must
/// not be freed)
////////////////////////////////////////////////////////////////////////////////

Json AqlValue::extractArrayMember (triagens::arango::AqlTransaction* trx,
                                   TRI_document_collection_t const* document,
                                   int64_t position,
                                   bool copy) const {
  switch (_type) {
    case JSON: {
      TRI_ASSERT(_json != nullptr);
      TRI_json_t const* json = _json->json();

      if (TRI_IsArrayJson(json)) {
        size_t const length = TRI_LengthArrayJson(json);
        if (position < 0) {
          // a negative position is allowed
          position = static_cast<int64_t>(length) + position;
        }

        if (position >= 0 && position < static_cast<int64_t>(length)) {
          // only look up the value if it is within array bounds
          TRI_json_t const* found = TRI_LookupArrayJson(json, static_cast<size_t>(position));

          if (found != nullptr) {
            if (copy) {
              // return a copy of the value
              return Json(TRI_UNKNOWN_MEM_ZONE, TRI_CopyJson(TRI_UNKNOWN_MEM_ZONE, found), triagens::basics::Json::AUTOFREE);
            }

            // return a pointer to the original value, without asking for its ownership
            return Json(TRI_UNKNOWN_MEM_ZONE, found, triagens::basics::Json::NOFREE);
          }
        }
      }

      // attribute does not exist or something went wrong - fall-through to returning null below
      return Json(Json::Null);
    }

    case RANGE: {
      TRI_ASSERT(_range != nullptr);
      size_t const n = _range->size();

      if (position < 0) {
        // a negative position is allowed
        position = static_cast<int64_t>(n) + position;
      }

      if (position >= 0 && position < static_cast<int64_t>(n)) {
        // only look up the value if it is within array bounds
        return Json(static_cast<double>(_range->at(static_cast<size_t>(position))));
      }
      break; // fall-through to returning null
    }

    case DOCVEC: {
      TRI_ASSERT(_vector != nullptr);
      size_t const p = static_cast<size_t>(position);

      // calculate the result array length
      size_t totalSize = 0;
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        if (p < totalSize + (*it)->size()) {
          // found the correct vector
          auto vecCollection = (*it)->getDocumentCollection(0);
          return (*it)->getValueReference(p - totalSize, 0).toJson(trx, vecCollection, copy);
        }
        totalSize += (*it)->size();
      }
      break; // fall-through to returning null
    }

    case SHAPED:
    case EMPTY: {
      break; // fall-through to returning null
    }
  }

  return Json(Json::Null);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief create an AqlValue from a vector of AqlItemBlock*s
////////////////////////////////////////////////////////////////////////////////

AqlValue AqlValue::CreateFromBlocks (triagens::arango::AqlTransaction* trx,
                                     std::vector<AqlItemBlock*> const& src,
                                     std::vector<std::string> const& variableNames) {
  size_t totalSize = 0;

  for (auto it = src.begin(); it != src.end(); ++it) {
    totalSize += (*it)->size();
  }

  auto json = std::make_unique<Json>(Json::Array, totalSize);

  for (auto it = src.begin(); it != src.end(); ++it) {
    auto current = (*it);
    RegisterId const n = current->getNrRegs();

    std::vector<std::pair<RegisterId, TRI_document_collection_t const*>> registers;
    for (RegisterId j = 0; j < n; ++j) {
      // temporaries don't have a name and won't be included
      if (variableNames[j][0] != '\0') {
        registers.emplace_back(std::make_pair(j, current->getDocumentCollection(j)));
      }
    }

    for (size_t i = 0; i < current->size(); ++i) {
      Json values(Json::Object, registers.size());

      // only enumerate the registers that are left
      for (auto const& reg : registers) {
        values.set(variableNames[reg.first], current->getValueReference(i, reg.first).toJson(trx, reg.second, true));
      }

      json->add(values);
    }
  }

  return AqlValue(json.release());
}

////////////////////////////////////////////////////////////////////////////////
/// @brief create an AqlValue from a vector of AqlItemBlock*s
////////////////////////////////////////////////////////////////////////////////

AqlValue AqlValue::CreateFromBlocks (triagens::arango::AqlTransaction* trx,
                                     std::vector<AqlItemBlock*> const& src,
                                     triagens::aql::RegisterId expressionRegister) {
  size_t totalSize = 0;

  for (auto it = src.begin(); it != src.end(); ++it) {
    totalSize += (*it)->size();
  }

  auto json = std::make_unique<Json>(Json::Array, totalSize);

  for (auto it = src.begin(); it != src.end(); ++it) {
    auto current = (*it);
    auto document = current->getDocumentCollection(expressionRegister);

    for (size_t i = 0; i < current->size(); ++i) {
      json->add(current->getValueReference(i, expressionRegister).toJson(trx, document, true));
    }
  }

  return AqlValue(json.release());
}

////////////////////////////////////////////////////////////////////////////////
/// @brief 3-way comparison for AqlValue objects
////////////////////////////////////////////////////////////////////////////////

int AqlValue::Compare (triagens::arango::AqlTransaction* trx,
                       AqlValue const& left,
                       TRI_document_collection_t const* leftcoll,
                       AqlValue const& right,
                       TRI_document_collection_t const* rightcoll,
                       bool compareUtf8) {
  if (left._type != right._type) {
    if (left._type == AqlValue::EMPTY) {
      return -1;
    }

    if (right._type == AqlValue::EMPTY) {
      return 1;
    }

    // JSON against x
    if (left._type == AqlValue::JSON &&
        (right._type == AqlValue::SHAPED ||
         right._type == AqlValue::RANGE ||
         right._type == AqlValue::DOCVEC)) {
        triagens::basics::Json rjson = right.toJson(trx, rightcoll, false);
      return TRI_CompareValuesJson(left._json->json(), rjson.json(), compareUtf8);
    }

    // SHAPED against x
    if (left._type == AqlValue::SHAPED) {
      triagens::basics::Json ljson = left.toJson(trx, leftcoll, false);

      if (right._type == AqlValue::JSON) {
        return TRI_CompareValuesJson(ljson.json(), right._json->json(), compareUtf8);
      }
      else if (right._type == AqlValue::RANGE ||
               right._type == AqlValue::DOCVEC) {
        triagens::basics::Json rjson = right.toJson(trx, rightcoll, false);
        return TRI_CompareValuesJson(ljson.json(), rjson.json(), compareUtf8);
      }
    }

    // RANGE against x
    if (left._type == AqlValue::RANGE) {
      triagens::basics::Json ljson = left.toJson(trx, leftcoll, false);

      if (right._type == AqlValue::JSON) {
        return TRI_CompareValuesJson(ljson.json(), right._json->json(), compareUtf8);
      }
      else if (right._type == AqlValue::SHAPED ||
               right._type == AqlValue::DOCVEC) {
        triagens::basics::Json rjson = right.toJson(trx, rightcoll, false);
        return TRI_CompareValuesJson(ljson.json(), rjson.json(), compareUtf8);
      }
    }

    // DOCVEC against x
    if (left._type == AqlValue::DOCVEC) {
      triagens::basics::Json ljson = left.toJson(trx, leftcoll, false);

      if (right._type == AqlValue::JSON) {
        return TRI_CompareValuesJson(ljson.json(), right._json->json(), compareUtf8);
      }
      else if (right._type == AqlValue::SHAPED ||
               right._type == AqlValue::RANGE) {
        triagens::basics::Json rjson = right.toJson(trx, rightcoll, false);
        return TRI_CompareValuesJson(ljson.json(), rjson.json(), compareUtf8);
      }
    }

    // No other comparisons are defined
    TRI_ASSERT(false);
  }

  // if we get here, types are equal

  switch (left._type) {
    case AqlValue::EMPTY: {
      return 0;
    }

    case AqlValue::JSON: {
      return TRI_CompareValuesJson(left._json->json(), right._json->json(), compareUtf8);
    }

    case AqlValue::SHAPED: {
      TRI_shaped_json_t l;
      TRI_shaped_json_t r;
      TRI_EXTRACT_SHAPED_JSON_MARKER(l, left._marker);
      TRI_EXTRACT_SHAPED_JSON_MARKER(r, right._marker);

      return TRI_CompareShapeTypes(nullptr, nullptr, &l, leftcoll->getShaper(),
                                   nullptr, nullptr, &r, rightcoll->getShaper());
    }

    case AqlValue::DOCVEC: {
      // use lexicographic ordering of AqlValues regardless of block,
      // DOCVECs have a single register coming from ReturnNode.
      size_t lblock = 0;
      size_t litem = 0;
      size_t rblock = 0;
      size_t ritem = 0;

      while (lblock < left._vector->size() &&
             rblock < right._vector->size()) {
        AqlValue lval = left._vector->at(lblock)->getValue(litem, 0);
        AqlValue rval = right._vector->at(rblock)->getValue(ritem, 0);

        int cmp = Compare(
          trx,
          lval,
          left._vector->at(lblock)->getDocumentCollection(0),
          rval,
          right._vector->at(rblock)->getDocumentCollection(0),
          compareUtf8
        );

        if (cmp != 0) {
          return cmp;
        }
        if (++litem == left._vector->size()) {
          litem = 0;
          lblock++;
        }
        if (++ritem == right._vector->size()) {
          ritem = 0;
          rblock++;
        }
      }

      if (lblock == left._vector->size() &&
          rblock == right._vector->size()){
        return 0;
      }

      return (lblock < left._vector->size() ? -1 : 1);
    }

    case AqlValue::RANGE: {
      if (left._range->_low < right._range->_low) {
        return -1;
      }
      if (left._range->_low > right._range->_low) {
        return 1;
      }
      if (left._range->_high < left._range->_high) {
        return -1;
      }
      if (left._range->_high > left._range->_high) {
        return 1;
      }
      return 0;
    }

    default: {
      TRI_ASSERT(false);
      return 0;
    }
  }
}

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:


text:
#include <aws/sagemaker/model/ChannelSpecification.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SageMaker
{
namespace Model
{

ChannelSpecification::ChannelSpecification() :
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_isRequired(false),
    m_isRequiredHasBeenSet(false),
    m_supportedContentTypesHasBeenSet(false),
    m_supportedCompressionTypesHasBeenSet(false),
    m_supportedInputModesHasBeenSet(false)
{
}

ChannelSpecification::ChannelSpecification(JsonView jsonValue) :
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_isRequired(false),
    m_isRequiredHasBeenSet(false),
    m_supportedContentTypesHasBeenSet(false),
    m_supportedCompressionTypesHasBeenSet(false),
    m_supportedInputModesHasBeenSet(false)
{
  *this = jsonValue;
}

ChannelSpecification& ChannelSpecification::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Description"))
  {
    m_description = jsonValue.GetString("Description");

    m_descriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("IsRequired"))
  {
    m_isRequired = jsonValue.GetBool("IsRequired");

    m_isRequiredHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SupportedContentTypes"))
  {
    Aws::Utils::Array<JsonView> supportedContentTypesJsonList = jsonValue.GetArray("SupportedContentTypes");
    for(unsigned supportedContentTypesIndex = 0; supportedContentTypesIndex < supportedContentTypesJsonList.GetLength(); ++supportedContentTypesIndex)
    {
      m_supportedContentTypes.push_back(supportedContentTypesJsonList[supportedContentTypesIndex].AsString());
    }
    m_supportedContentTypesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SupportedCompressionTypes"))
  {
    Aws::Utils::Array<JsonView> supportedCompressionTypesJsonList = jsonValue.GetArray("SupportedCompressionTypes");
    for(unsigned supportedCompressionTypesIndex = 0; supportedCompressionTypesIndex < supportedCompressionTypesJsonList.GetLength(); ++supportedCompressionTypesIndex)
    {
      m_supportedCompressionTypes.push_back(CompressionTypeMapper::GetCompressionTypeForName(supportedCompressionTypesJsonList[supportedCompressionTypesIndex].AsString()));
    }
    m_supportedCompressionTypesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SupportedInputModes"))
  {
    Aws::Utils::Array<JsonView> supportedInputModesJsonList = jsonValue.GetArray("SupportedInputModes");
    for(unsigned supportedInputModesIndex = 0; supportedInputModesIndex < supportedInputModesJsonList.GetLength(); ++supportedInputModesIndex)
    {
      m_supportedInputModes.push_back(TrainingInputModeMapper::GetTrainingInputModeForName(supportedInputModesJsonList[supportedInputModesIndex].AsString()));
    }
    m_supportedInputModesHasBeenSet = true;
  }

  return *this;
}

JsonValue ChannelSpecification::Jsonize() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_isRequiredHasBeenSet)
  {
   payload.WithBool("IsRequired", m_isRequired);

  }

  if(m_supportedContentTypesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> supportedContentTypesJsonList(m_supportedContentTypes.size());
   for(unsigned supportedContentTypesIndex = 0; supportedContentTypesIndex < supportedContentTypesJsonList.GetLength(); ++supportedContentTypesIndex)
   {
     supportedContentTypesJsonList[supportedContentTypesIndex].AsString(m_supportedContentTypes[supportedContentTypesIndex]);
   }
   payload.WithArray("SupportedContentTypes", std::move(supportedContentTypesJsonList));

  }

  if(m_supportedCompressionTypesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> supportedCompressionTypesJsonList(m_supportedCompressionTypes.size());
   for(unsigned supportedCompressionTypesIndex = 0; supportedCompressionTypesIndex < supportedCompressionTypesJsonList.GetLength(); ++supportedCompressionTypesIndex)
   {
     supportedCompressionTypesJsonList[supportedCompressionTypesIndex].AsString(CompressionTypeMapper::GetNameForCompressionType(m_supportedCompressionTypes[supportedCompressionTypesIndex]));
   }
   payload.WithArray("SupportedCompressionTypes", std::move(supportedCompressionTypesJsonList));

  }

  if(m_supportedInputModesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> supportedInputModesJsonList(m_supportedInputModes.size());
   for(unsigned supportedInputModesIndex = 0; supportedInputModesIndex < supportedInputModesJsonList.GetLength(); ++supportedInputModesIndex)
   {
     supportedInputModesJsonList[supportedInputModesIndex].AsString(TrainingInputModeMapper::GetNameForTrainingInputMode(m_supportedInputModes[supportedInputModesIndex]));
   }
   payload.WithArray("SupportedInputModes", std::move(supportedInputModesJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace SageMaker
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
var keystone = require('keystone'),
	async = require('async'),
	Types = keystone.Field.Types,
	snowcoins = require('wallets');

/**
 * Posts Model
 * ===========
 */

var WalletContacts = new keystone.List(snowcoins.get('model contacts'), {
	map: { name: 'name',address:'address' },
	autokey: { path: 'key', from: 'address', unique: true },
	track: true
});

WalletContacts.add({
	name: { type: String, required: true,index:true },
	//example: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true },
	owner: { type: Types.Relationship, ref: snowcoins.get('model user'), index: true, initial: true },
	createdDate: { type: Types.Date, default: Date.now, index: true },
	address: { type: String, required: true, index:true ,initial: true },
	notes: { type: Types.Markdown , initial: true },
	wallet: { type: Types.Relationship, ref: snowcoins.get('model wallets'), index: true,initial:true,many: true  },
});

/**
 * Virtuals
 * ========
 */

/**
 * Relationships
 * =============
 */

//Post.relationship({ ref: 'PostComment', refPath: 'post', path: 'comments' });

/**
 * Registration
 * ============
 */

WalletContacts.defaultColumns = 'name, address,wallet,  owner, notes';
//WalletContacts.addPattern('standard meta');
WalletContacts.register();


text:
function populate(form)
{
form.options.length = 0;
form.options[0] = new Option("Select a county of Connecticut","");
form.options[1] = new Option("Fairfield County","Fairfield County");
form.options[2] = new Option("Hartford County","Hartford County");
form.options[3] = new Option("Litchfield County","Litchfield County");
form.options[4] = new Option("Middlesex County","Middlesex County");
form.options[5] = new Option("New Haven County","New Haven County");
form.options[6] = new Option("New London County","New London County");
form.options[7] = new Option("Tolland County","Tolland County");
form.options[8] = new Option("Windham County","Windham County");
}


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Synapse.Models
{
    public partial class SelfHostedIntegrationRuntimeStatus
    {
        internal static SelfHostedIntegrationRuntimeStatus DeserializeSelfHostedIntegrationRuntimeStatus(JsonElement element)
        {
            IntegrationRuntimeType type = default;
            Optional<string> dataFactoryName = default;
            Optional<IntegrationRuntimeState> state = default;
            Optional<DateTimeOffset> createTime = default;
            Optional<string> taskQueueId = default;
            Optional<string> nodeCommunicationChannelEncryptionMode = default;
            Optional<IntegrationRuntimeInternalChannelEncryptionMode> internalChannelEncryption = default;
            Optional<string> version = default;
            Optional<IReadOnlyList<SelfHostedIntegrationRuntimeNode>> nodes = default;
            Optional<DateTimeOffset> scheduledUpdateDate = default;
            Optional<string> updateDelayOffset = default;
            Optional<string> localTimeZoneOffset = default;
            Optional<IReadOnlyDictionary<string, string>> capabilities = default;
            Optional<IReadOnlyList<string>> serviceUrls = default;
            Optional<IntegrationRuntimeAutoUpdate> autoUpdate = default;
            Optional<string> versionStatus = default;
            Optional<IReadOnlyList<LinkedIntegrationRuntime>> links = default;
            Optional<string> pushedVersion = default;
            Optional<string> latestVersion = default;
            Optional<DateTimeOffset> autoUpdateETA = default;
            Optional<string> serviceRegion = default;
            Optional<IReadOnlyList<string>> newerVersions = default;
            IReadOnlyDictionary<string, BinaryData> additionalProperties = default;
            Dictionary<string, BinaryData> additionalPropertiesDictionary = new Dictionary<string, BinaryData>();
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("type"))
                {
                    type = new IntegrationRuntimeType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("dataFactoryName"))
                {
                    dataFactoryName = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("state"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    state = new IntegrationRuntimeState(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("typeProperties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("createTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            createTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("taskQueueId"))
                        {
                            taskQueueId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("nodeCommunicationChannelEncryptionMode"))
                        {
                            nodeCommunicationChannelEncryptionMode = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("internalChannelEncryption"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            internalChannelEncryption = new IntegrationRuntimeInternalChannelEncryptionMode(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("version"))
                        {
                            version = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("nodes"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<SelfHostedIntegrationRuntimeNode> array = new List<SelfHostedIntegrationRuntimeNode>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(SelfHostedIntegrationRuntimeNode.DeserializeSelfHostedIntegrationRuntimeNode(item));
                            }
                            nodes = array;
                            continue;
                        }
                        if (property0.NameEquals("scheduledUpdateDate"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            scheduledUpdateDate = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("updateDelayOffset"))
                        {
                            updateDelayOffset = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("localTimeZoneOffset"))
                        {
                            localTimeZoneOffset = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("capabilities"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary<string, string> dictionary = new Dictionary<string, string>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, property1.Value.GetString());
                            }
                            capabilities = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("serviceUrls"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<string> array = new List<string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            serviceUrls = array;
                            continue;
                        }
                        if (property0.NameEquals("autoUpdate"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            autoUpdate = new IntegrationRuntimeAutoUpdate(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("versionStatus"))
                        {
                            versionStatus = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("links"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<LinkedIntegrationRuntime> array = new List<LinkedIntegrationRuntime>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(LinkedIntegrationRuntime.DeserializeLinkedIntegrationRuntime(item));
                            }
                            links = array;
                            continue;
                        }
                        if (property0.NameEquals("pushedVersion"))
                        {
                            pushedVersion = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("latestVersion"))
                        {
                            latestVersion = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("autoUpdateETA"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            autoUpdateETA = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("serviceRegion"))
                        {
                            serviceRegion = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("newerVersions"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<string> array = new List<string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            newerVersions = array;
                            continue;
                        }
                    }
                    continue;
                }
                additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText()));
            }
            additionalProperties = additionalPropertiesDictionary;
            return new SelfHostedIntegrationRuntimeStatus(type, dataFactoryName.Value, Optional.ToNullable(state), additionalProperties, Optional.ToNullable(createTime), taskQueueId.Value, nodeCommunicationChannelEncryptionMode.Value, Optional.ToNullable(internalChannelEncryption), version.Value, Optional.ToList(nodes), Optional.ToNullable(scheduledUpdateDate), updateDelayOffset.Value, localTimeZoneOffset.Value, Optional.ToDictionary(capabilities), Optional.ToList(serviceUrls), Optional.ToNullable(autoUpdate), versionStatus.Value, Optional.ToList(links), pushedVersion.Value, latestVersion.Value, Optional.ToNullable(autoUpdateETA), serviceRegion.Value, Optional.ToList(newerVersions));
        }
    }
}


text:
#pragma once

#include "tls/s2n_connection.h"
#include "stuffer/s2n_stuffer.h"

extern int s2n_extensions_client_supported_versions_recv(struct s2n_connection *conn, struct s2n_stuffer *extension);
extern int s2n_extensions_client_supported_versions_size(struct s2n_connection *conn);
extern int s2n_extensions_client_supported_versions_send(struct s2n_connection *conn, struct s2n_stuffer *out);


text:
<?php

namespace skeeks\cms\components;

/**
 * Class Storage
 * @package skeeks\cms\components
 */
class Storage extends storage\Storage
{
}


text:
package org.apache.activemq.artemis.tests.integration.jms.client;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.UUID;

import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.postoffice.QueueBinding;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQDestination;
import org.apache.activemq.artemis.jms.client.ActiveMQMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.tests.util.JMSTestBase;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;

/**
 * GroupingTest
 */
public class GroupingTest extends JMSTestBase {

   private Queue queue;

   @Override
   @Before
   public void setUp() throws Exception {
      super.setUp();

      queue = createQueue("TestQueue");
   }

   protected void setProperty(Message message) {
      ((ActiveMQMessage) message).getCoreMessage().putStringProperty(org.apache.activemq.artemis.api.core.Message.HDR_GROUP_ID, new SimpleString("foo"));
   }

   protected ConnectionFactory getCF() throws Exception {
      return cf;
   }

   @Test
   public void testGrouping() throws Exception {
      ConnectionFactory fact = getCF();
      Connection connection = fact.createConnection();

      Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(queue);

      MessageConsumer consumer1 = session.createConsumer(queue);
      MessageConsumer consumer2 = session.createConsumer(queue);
      MessageConsumer consumer3 = session.createConsumer(queue);

      connection.start();

      String jmsxgroupID = null;

      for (int j = 0; j < 100; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);

         setProperty(message);

         producer.send(message);

         String prop = message.getStringProperty("JMSXGroupID");

         assertNotNull(prop);

         if (jmsxgroupID != null) {
            assertEquals(jmsxgroupID, prop);
         } else {
            jmsxgroupID = prop;
         }
      }

      //All msgs should go to the first consumer
      for (int j = 0; j < 100; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), jmsxgroupID);
      }

      connection.close();

   }

   @Test
   public void testGroupingWithJMS2Producer() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);
      final String groupID = UUID.randomUUID().toString();
      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      JMSProducer producer = ctx.createProducer().setProperty("JMSXGroupID", groupID);

      JMSConsumer consumer1 = ctx.createConsumer(queue);
      JMSConsumer consumer2 = ctx.createConsumer(queue);
      JMSConsumer consumer3 = ctx.createConsumer(queue);

      ctx.start();

      for (int j = 0; j < 100; j++) {
         TextMessage message = ctx.createTextMessage("Message" + j);

         producer.send(queue, message);

         String prop = message.getStringProperty("JMSXGroupID");

         assertNotNull(prop);
         assertEquals(groupID, prop);
      }

      ctx.commit();

      //All msgs should go to the first consumer
      for (int j = 0; j < 100; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID);

         tm = (TextMessage) consumer2.receiveNoWait();
         assertNull(tm);
         tm = (TextMessage) consumer3.receiveNoWait();
         assertNull(tm);
      }

      ctx.commit();

      ctx.close();
   }

   @Test
   public void testManyGroups() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());

      Connection connection = fact.createConnection();

      Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(queue);

      MessageConsumer consumer1 = session.createConsumer(queue);
      MessageConsumer consumer2 = session.createConsumer(queue);
      MessageConsumer consumer3 = session.createConsumer(queue);

      connection.start();

      for (int j = 0; j < 1000; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);

         message.setStringProperty("_AMQ_GROUP_ID", "" + (j % 10));

         producer.send(message);

         String prop = message.getStringProperty("JMSXGroupID");

         assertNotNull(prop);

      }

      int msg1 = flushMessages(consumer1);
      int msg2 = flushMessages(consumer2);
      int msg3 = flushMessages(consumer3);

      assertNotSame(0, msg1);
      assertNotSame(0, msg2);
      assertNotSame(0, msg2);

      consumer1.close();
      consumer2.close();
      consumer3.close();

      connection.close();

   }

   @Test
   public void testGroupingRollbackOnClose() throws Exception {
      ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();
      fact.setConsumerWindowSize(1000);
      fact.setTransactionBatchSize(0);
      Connection connection = fact.createConnection();
      RemotingConnection rc = server.getRemotingService().getConnections().iterator().next();
      Connection connection2 = fact.createConnection();

      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      Session session2 = connection2.createSession(true, Session.SESSION_TRANSACTED);

      MessageProducer producer = session.createProducer(queue);

      MessageConsumer consumer1 = session.createConsumer(queue);
      MessageConsumer consumer2 = session2.createConsumer(queue);

      connection.start();
      connection2.start();

      String jmsxgroupID = null;

      for (int j = 0; j < 100; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);

         setProperty(message);

         producer.send(message);

         String prop = message.getStringProperty("JMSXGroupID");

         assertNotNull(prop);

         if (jmsxgroupID != null) {
            assertEquals(jmsxgroupID, prop);
         } else {
            jmsxgroupID = prop;
         }
      }
      session.commit();
      //consume 5 msgs from 1st first consumer
      for (int j = 0; j < 1; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), jmsxgroupID);
      }
      //session.rollback();
      //session.close();
      //consume all msgs from 2nd first consumer
      // ClientSession amqs = ((ActiveMQSession) session).getCoreSession();
      //  ((DelegatingSession) amqs).getChannel().close();
      rc.fail(new ActiveMQNotConnectedException());
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         long text = ((ActiveMQTextMessage) tm).getCoreMessage().getMessageID();
         //assertEquals("Message" + j, text);

         assertEquals(tm.getStringProperty("JMSXGroupID"), jmsxgroupID);
      }

      connection.close();
      connection2.close();
   }

   private int flushMessages(MessageConsumer consumer) throws JMSException {
      int received = 0;
      while (true) {
         TextMessage msg = (TextMessage) consumer.receiveNoWait();
         if (msg == null) {
            break;
         }
         msg.acknowledge();
         received++;
      }
      return received;
   }

   @Test
   public void testGroupBuckets() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);

      String testQueueName = getName() + "_bucket_group";

      server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST).setGroupBuckets(2));

      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      Queue testQueue = ctx.createQueue(testQueueName);

      final String groupID1 = "groupA";
      final String groupID2 = "groupB";
      final String groupID3 = "groupC";

      //Ensure the groups bucket as we expect.
      assertEquals((groupID1.hashCode() & Integer.MAX_VALUE) % 2, 0);
      assertEquals((groupID2.hashCode() & Integer.MAX_VALUE) % 2, 1);
      assertEquals((groupID3.hashCode() & Integer.MAX_VALUE) % 2, 0);

      JMSProducer producer1 = ctx.createProducer().setProperty("JMSXGroupID", groupID1);
      JMSProducer producer2 = ctx.createProducer().setProperty("JMSXGroupID", groupID2);
      JMSProducer producer3 = ctx.createProducer().setProperty("JMSXGroupID", groupID3);

      JMSConsumer consumer1 = ctx.createConsumer(testQueue);
      JMSConsumer consumer2 = ctx.createConsumer(testQueue);
      JMSConsumer consumer3 = ctx.createConsumer(testQueue);

      ctx.start();

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }

      ctx.commit();

      //First two set of msgs should go to the first two consumers only (buckets is 2)
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);

         tm = (TextMessage) consumer2.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + (j + 10), tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);

         assertNull(consumer3.receiveNoWait());
      }

      //Last set of msgs should go to the first consumer as bucketed queue with two bucket groups only
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);

         assertNull(consumer2.receiveNoWait());
         assertNull(consumer3.receiveNoWait());

      }

      ctx.commit();

      ctx.close();
   }

   @Test
   public void testGroupRebalance() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);
      String testQueueName = getName() + "_group_rebalance";

      server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST).setGroupRebalance(true));

      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      Queue testQueue = ctx.createQueue(testQueueName);

      final String groupID1 = "groupA";
      final String groupID2 = "groupB";
      final String groupID3 = "groupC";

      JMSProducer producer1 = ctx.createProducer().setProperty("JMSXGroupID", groupID1);
      JMSProducer producer2 = ctx.createProducer().setProperty("JMSXGroupID", groupID2);
      JMSProducer producer3 = ctx.createProducer().setProperty("JMSXGroupID", groupID3);

      JMSConsumer consumer1 = ctx.createConsumer(testQueue);
      JMSConsumer consumer2 = ctx.createConsumer(testQueue);

      ctx.start();

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }

      ctx.commit();

      //First set of msgs should go to the first consumer only
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);
      }

      //Second set of msgs should go to the second consumers only
      for (int j = 10; j < 20; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);
      }

      //Third set of msgs should go to the first consumer only
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);
      }
      ctx.commit();

      //Add new consumer, that should cause rebalance
      JMSConsumer consumer3 = ctx.createConsumer(testQueue);

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }
      ctx.commit();

      //First set of msgs should go to the first consumer only
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);
      }

      //Second set of msgs should go to the second consumers only
      for (int j = 10; j < 20; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);
      }

      //Third set of msgs should now go to the third consumer now
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer3.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);
      }

      ctx.commit();

      ctx.close();
   }

   /**
    * This tests ensures that when we have group rebalance and pause dispatch,
    * the broker pauses dispatch of new messages to consumers whilst rebalance and awaits existing inflight messages to be handled before restarting dispatch with new reblanced group allocations,
    * this allows us to provide a guarantee of message ordering even with rebalance, at the expense that during rebalance dispatch will pause till all consumers with inflight messages are handled.
    *
    * @throws Exception
    */
   @Test
   public void testGroupRebalancePauseDispatch() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);
      String testQueueName = getName() + "_group_rebalance";

      server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST).setGroupRebalance(true).setGroupRebalancePauseDispatch(true));

      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      Queue testQueue = ctx.createQueue(testQueueName);

      final String groupID1 = "groupA";
      final String groupID2 = "groupB";
      final String groupID3 = "groupC";

      JMSProducer producer1 = ctx.createProducer().setProperty("JMSXGroupID", groupID1);
      JMSProducer producer2 = ctx.createProducer().setProperty("JMSXGroupID", groupID2);
      JMSProducer producer3 = ctx.createProducer().setProperty("JMSXGroupID", groupID3);

      JMSConsumer consumer1 = ctx.createConsumer(testQueue);
      JMSConsumer consumer2 = ctx.createConsumer(testQueue);

      ctx.start();

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }

      ctx.commit();

      //First set of msgs should go to the first consumer only
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);
      }
      ctx.commit();

      //Second set of msgs should go to the second consumers only
      for (int j = 10; j < 20; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);
      }
      ctx.commit();

      //Add new consumer but where third set we have not consumed so should inflight, that should cause rebalance
      JMSConsumer consumer3 = ctx.createConsumer(testQueue);

      //Send next set of messages
      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }
      ctx.commit();

      //Ensure we dont get anything on the other consumers, whilst we rebalance and there is inflight messages. - e.g. ensure ordering guarentee.
      assertNull(consumer2.receiveNoWait());
      assertNull(consumer3.receiveNoWait());

      //Ensure the inflight set of msgs should go to the first consumer only
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);
      }
      ctx.commit();

      //Now we cleared the "inflightm messages" expect that consumers 1,2 and 3 are rebalanced and the messages sent earlier are received.

      //First set of msgs should go to the first consumer only
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);
      }

      //Second set of msgs should go to the second consumers only
      for (int j = 10; j < 20; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);
      }

      //Third set of msgs should now go to the third consumer now
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer3.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);
      }

      ctx.commit();

      ctx.close();
   }

   @Test
   public void testGroupFirstKey() throws Exception {
      String customFirstGroupKey = "my-custom-key";
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);
      String testQueueName = getName() + "_group_first_key";

      server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST).setGroupRebalance(true).setGroupFirstKey(customFirstGroupKey));

      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      Queue testQueue = ctx.createQueue(testQueueName);

      final String groupID1 = "groupA";
      final String groupID2 = "groupB";
      final String groupID3 = "groupC";

      JMSProducer producer1 = ctx.createProducer().setProperty("JMSXGroupID", groupID1);
      JMSProducer producer2 = ctx.createProducer().setProperty("JMSXGroupID", groupID2);
      JMSProducer producer3 = ctx.createProducer().setProperty("JMSXGroupID", groupID3);

      JMSConsumer consumer1 = ctx.createConsumer(testQueue);
      JMSConsumer consumer2 = ctx.createConsumer(testQueue);

      ctx.start();

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }

      ctx.commit();

      //First set of msgs should go to the first consumer only
      for (int j = 0; j < 10; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID1);
         if (j == 0) {
            assertTrue(tm.getBooleanProperty(customFirstGroupKey));
         } else {
            assertFalse(tm.propertyExists(customFirstGroupKey));
         }
      }

      //Second set of msgs should go to the second consumers only
      for (int j = 10; j < 20; j++) {
         TextMessage tm = (TextMessage) consumer2.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID2);

         if (j == 10) {
            assertTrue(tm.getBooleanProperty(customFirstGroupKey));
         } else {
            assertFalse(tm.propertyExists(customFirstGroupKey));
         }
      }

      //Third set of msgs should go to the first consumer only
      for (int j = 20; j < 30; j++) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         tm.acknowledge();

         assertEquals("Message" + j, tm.getText());

         assertEquals(tm.getStringProperty("JMSXGroupID"), groupID3);

         if (j == 20) {
            assertTrue(tm.getBooleanProperty(customFirstGroupKey));
         } else {
            assertFalse(tm.propertyExists(customFirstGroupKey));
         }
      }
      ctx.commit();

      ctx.close();
   }

   @Test
   public void testGroupDisable() throws Exception {
      ConnectionFactory fact = getCF();
      Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());
      Assume.assumeTrue("only makes sense withOUT explicit group-id", ((ActiveMQConnectionFactory) fact).getGroupID() == null);
      String testQueueName = getName() + "_group_disable";

      server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST).setGroupBuckets(0));

      JMSContext ctx = addContext(getCF().createContext(JMSContext.SESSION_TRANSACTED));

      Queue testQueue = ctx.createQueue(testQueueName);

      final String groupID1 = "groupA";
      final String groupID2 = "groupB";
      final String groupID3 = "groupC";

      JMSProducer producer1 = ctx.createProducer().setProperty("JMSXGroupID", groupID1);
      JMSProducer producer2 = ctx.createProducer().setProperty("JMSXGroupID", groupID2);
      JMSProducer producer3 = ctx.createProducer().setProperty("JMSXGroupID", groupID3);

      JMSConsumer consumer1 = ctx.createConsumer(testQueue);
      JMSConsumer consumer2 = ctx.createConsumer(testQueue);
      JMSConsumer consumer3 = ctx.createConsumer(testQueue);

      ctx.start();

      for (int j = 0; j < 10; j++) {
         send(ctx, testQueue, groupID1, producer1, j);
      }
      for (int j = 10; j < 20; j++) {
         send(ctx, testQueue, groupID2, producer2, j);
      }
      for (int j = 20; j < 30; j++) {
         send(ctx, testQueue, groupID3, producer3, j);
      }

      ctx.commit();

      //Msgs should just round robin and ignore grouping semantics
      int j = 0;
      while (j < 30) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), j < 10 ? groupID1 : j < 20 ? groupID2 : groupID3);
         j++;

         tm = (TextMessage) consumer2.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), j < 10 ? groupID1 : j < 20 ? groupID2 : groupID3);
         j++;

         tm = (TextMessage) consumer3.receive(10000);
         assertNotNull(tm);
         tm.acknowledge();
         assertEquals("Message" + j, tm.getText());
         assertEquals(tm.getStringProperty("JMSXGroupID"), j < 10 ? groupID1 : j < 20 ? groupID2 : groupID3);
         j++;
      }

      ctx.commit();

      ctx.close();
   }

   private void send(JMSContext ctx, Queue testQueue, String groupID1, JMSProducer producer1, int j) throws JMSException {
      TextMessage message = ctx.createTextMessage("Message" + j);
      producer1.send(testQueue, message);
      String prop = message.getStringProperty("JMSXGroupID");
      assertNotNull(prop);
      assertEquals(groupID1, prop);
   }

   @Test
   public void testGroupBucketUsingAddressQueueParameters() throws Exception {
      ConnectionFactory fact = getCF();
      Connection connection = fact.createConnection();

      try {

         Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

         String testQueueName = getName() + "group_bucket_param";

         Queue queue = session.createQueue(testQueueName + "?group-buckets=4");
         assertEquals(testQueueName, queue.getQueueName());

         ActiveMQDestination a = (ActiveMQDestination) queue;
         assertEquals(Integer.valueOf(4), a.getQueueAttributes().getGroupBuckets());
         assertEquals(Integer.valueOf(4), a.getQueueConfiguration().getGroupBuckets());

         MessageProducer producer = session.createProducer(queue);

         QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(testQueueName));
         assertEquals(4, queueBinding.getQueue().getGroupBuckets());
      } finally {
         connection.close();
      }
   }

   @Test
   public void testGroupRebalanceUsingAddressQueueParameters() throws Exception {
      ConnectionFactory fact = getCF();
      Connection connection = fact.createConnection();

      try {

         Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

         String testQueueName = getName() + "group_rebalance_param";

         Queue queue = session.createQueue(testQueueName + "?group-rebalance=true");
         assertEquals(testQueueName, queue.getQueueName());

         ActiveMQDestination a = (ActiveMQDestination) queue;
         assertTrue(a.getQueueAttributes().getGroupRebalance());
         assertTrue(a.getQueueConfiguration().isGroupRebalance());

         MessageProducer producer = session.createProducer(queue);

         QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(testQueueName));
         assertTrue(queueBinding.getQueue().isGroupRebalance());
      } finally {
         connection.close();
      }
   }

   @Test
   public void testGroupFirstKeyUsingAddressQueueParameters() throws Exception {
      ConnectionFactory fact = getCF();
      Connection connection = fact.createConnection();

      try {

         Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

         String testQueueName = getName() + "group_first_key_param";

         Queue queue = session.createQueue(testQueueName + "?group-first-key=my-custom-key");
         assertEquals(testQueueName, queue.getQueueName());

         ActiveMQDestination a = (ActiveMQDestination) queue;
         assertEquals("my-custom-key", a.getQueueAttributes().getGroupFirstKey().toString());

         MessageProducer producer = session.createProducer(queue);

         QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(testQueueName));
         assertEquals("my-custom-key", queueBinding.getQueue().getGroupFirstKey().toString());
      } finally {
         connection.close();
      }
   }

}


text:
title: django.utils.functional Promise Example Code
category: page
slug: django-utils-functional-promise-examples
sortorder: 500011455
toc: False
sidebartitle: django.utils.functional Promise
meta: Python example code for the Promise class from the django.utils.functional module of the Django project.

Promise is a class within the django.utils.functional module of the Django project.

## Example 1 from django-cms
[django-cms](https://github.com/divio/django-cms)
([project website](https://www.django-cms.org/en/)) is a Python-based
content management system (CMS) [library](https://pypi.org/project/django-cms/)
for use with Django web apps that is open sourced under the
[BSD 3-Clause "New"](https://github.com/divio/django-cms/blob/develop/LICENSE)
license.

[**django-cms / cms / toolbar / items.py**](https://github.com/divio/django-cms/blob/develop/cms/toolbar/items.py)

```python
# items.py
import json
from abc import ABCMeta
from collections import defaultdict

from django.template.loader import render_to_string
from django.utils.encoding import force_text
~~from django.utils.functional import Promise

from six import with_metaclass

from cms.constants import RIGHT, LEFT, REFRESH_PAGE, URL_CHANGE

class ItemSearchResult(object):
    def __init__(self, item, index):
        self.item = item
        self.index = index

    def __add__(self, other):
        return ItemSearchResult(self.item, self.index + other)

    def __sub__(self, other):
        return ItemSearchResult(self.item, self.index - other)

    def __int__(self):
        return self.index

def may_be_lazy(thing):
~~    if isinstance(thing, Promise):
        return thing._proxy____args[0]
    else:
        return thing

class ToolbarAPIMixin(with_metaclass(ABCMeta)):
    REFRESH_PAGE = REFRESH_PAGE
    URL_CHANGE = URL_CHANGE
    LEFT = LEFT
    RIGHT = RIGHT

    def __init__(self):
        self.items = []
        self.menus = {}
        self._memo = defaultdict(list)

    def _memoize(self, item):
        self._memo[item.__class__].append(item)

    def _unmemoize(self, item):
        self._memo[item.__class__].remove(item)

    def _item_position(self, item):
        return self.items.index(item)

## ... source file continues with no further Promise examples...

```

## Example 2 from django-jet
[django-jet](https://github.com/geex-arts/django-jet)
([project documentation](https://jet.readthedocs.io/en/latest/),
[PyPI project page](https://pypi.org/project/django-jet/) and
[more information](http://jet.geex-arts.com/))
is a fancy [Django](/django.html) Admin panel replacement.

The django-jet project is open source under the
[GNU Affero General Public License v3.0](https://github.com/geex-arts/django-jet/blob/dev/LICENSE).

[**django-jet / jet / utils.py**](https://github.com/geex-arts/django-jet/blob/dev/jet/./utils.py)

```python
# utils.py
import json
from django.template import Context
from django.utils import translation
from jet import settings
from jet.models import PinnedApplication

try:
    from django.apps.registry import apps
except ImportError:
    try:
        from django.apps import apps # Fix Django 1.7 import issue
    except ImportError:
        pass
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
try:
    from django.core.urlresolvers import reverse, resolve, NoReverseMatch
except ImportError: # Django 1.11
    from django.urls import reverse, resolve, NoReverseMatch

from django.contrib.admin import AdminSite
from django.utils.encoding import smart_text
from django.utils.text import capfirst
from django.contrib import messages
from django.utils.encoding import force_text
~~from django.utils.functional import Promise
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.utils.text import slugify

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict  # Python 2.6

class JsonResponse(HttpResponse):

    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs)

def get_app_list(context, order=True):
    admin_site = get_admin_site(context)

## ... source file abbreviated to get to Promise examples ...

def get_admin_site(context):
    try:
        current_resolver = resolve(context.get('request').path)
        index_resolver = resolve(reverse('%s:index' % current_resolver.namespaces[0]))

        if hasattr(index_resolver.func, 'admin_site'):
            return index_resolver.func.admin_site

        for func_closure in index_resolver.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass

    return admin.site

def get_admin_site_name(context):
    return get_admin_site(context).name

class LazyDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
            return obj.isoformat()
~~        elif isinstance(obj, Promise):
            return force_text(obj)
        return self.encode(obj)

def get_model_instance_label(instance):
    if getattr(instance, "related_label", None):
        return instance.related_label()
    return smart_text(instance)

class SuccessMessageMixin(object):
    success_message = ''

    def form_valid(self, form):
        response = super(SuccessMessageMixin, self).form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data

## ... source file continues with no further Promise examples...

```

## Example 3 from django-jsonfield
[django-jsonfield](https://github.com/dmkoch/django-jsonfield)
([jsonfield on PyPi](https://pypi.org/project/jsonfield/)) is a
[Django](/django.html) code library that makes it easier to store validated
JSON in a [Django object-relational mapper (ORM)](/django-orm.html) database
model.

The django-jsonfield project is open source under the
[MIT license](https://github.com/dmkoch/django-jsonfield/blob/master/LICENSE).

[**django-jsonfield / src/jsonfield / encoder.py**](https://github.com/dmkoch/django-jsonfield/blob/master/src/jsonfield/./encoder.py)

```python
# encoder.py
import datetime
import decimal
import json
import uuid

from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import force_str
~~from django.utils.functional import Promise

class JSONEncoder(json.JSONEncoder):
    def default(self, obj):  # noqa: C901
~~        if isinstance(obj, Promise):
            return force_str(obj)
        elif isinstance(obj, datetime.datetime):
            representation = obj.isoformat()
            if representation.endswith('+00:00'):
                representation = representation[:-6] + 'Z'
            return representation
        elif isinstance(obj, datetime.date):
            return obj.isoformat()
        elif isinstance(obj, datetime.time):
            if timezone and timezone.is_aware(obj):
                raise ValueError("JSON can't represent timezone-aware times.")
            representation = obj.isoformat()
            return representation
        elif isinstance(obj, datetime.timedelta):
            return str(obj.total_seconds())
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, uuid.UUID):
            return str(obj)
        elif isinstance(obj, QuerySet):
            return tuple(obj)
        elif isinstance(obj, bytes):
            return obj.decode()
        elif hasattr(obj, 'tolist'):

## ... source file continues with no further Promise examples...

```

## Example 4 from django-rest-framework
[Django REST Framework](https://github.com/encode/django-rest-framework)
([project homepage and documentation](https://www.django-rest-framework.org/),
[PyPI package information](https://pypi.org/project/djangorestframework/)
and [more resources on Full Stack Python](/django-rest-framework-drf.html)),
often abbreviated as "DRF", is a popular [Django](/django.html) extension
for building [web APIs](/application-programming-interfaces.html).
The project has fantastic documentation and a wonderful
[quickstart](https://www.django-rest-framework.org/tutorial/quickstart/)
that serve as examples of how to make it easier for newcomers
to get started.

The project is open sourced under the
[Encode OSS Ltd. license](https://github.com/encode/django-rest-framework/blob/master/LICENSE.md).

[**django-rest-framework / rest_framework / utils / encoders.py**](https://github.com/encode/django-rest-framework/blob/master/rest_framework/utils/encoders.py)

```python
# encoders.py
import datetime
import decimal
import json  # noqa
import uuid

from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import force_str
~~from django.utils.functional import Promise

from rest_framework.compat import coreapi

class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
~~        if isinstance(obj, Promise):
            return force_str(obj)
        elif isinstance(obj, datetime.datetime):
            representation = obj.isoformat()
            if representation.endswith('+00:00'):
                representation = representation[:-6] + 'Z'
            return representation
        elif isinstance(obj, datetime.date):
            return obj.isoformat()
        elif isinstance(obj, datetime.time):
            if timezone and timezone.is_aware(obj):
                raise ValueError("JSON can't represent timezone-aware times.")
            representation = obj.isoformat()
            return representation
        elif isinstance(obj, datetime.timedelta):
            return str(obj.total_seconds())
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, uuid.UUID):
            return str(obj)
        elif isinstance(obj, QuerySet):
            return tuple(obj)
        elif isinstance(obj, bytes):
            return obj.decode()
        elif hasattr(obj, 'tolist'):

## ... source file continues with no further Promise examples...

```


text:
AUTHFAILURE = 'AuthFailure'

# 操作失败。
FAILEDOPERATION = 'FailedOperation'

# 内部错误。
INTERNALERROR = 'InternalError'

# 参数错误。
INVALIDPARAMETER = 'InvalidParameter'

# 参数取值错误。
INVALIDPARAMETERVALUE = 'InvalidParameterValue'

# 超过配额限制。
LIMITEXCEEDED = 'LimitExceeded'

# 缺少参数错误。
MISSINGPARAMETER = 'MissingParameter'