text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#ifndef sharing_models_TYPES_H
#define sharing_models_TYPES_H

#include <iosfwd>

#include <thrift/Thrift.h>
#include <thrift/TApplicationException.h>
#include <thrift/protocol/TProtocol.h>
#include <thrift/transport/TTransport.h>

#include <thrift/cxxfunctional.h>

struct GroupCardinality {
  enum type {
    SINGLE_USER = 0,
    MULTI_USER = 1
  };
};

extern const std::map<int, const char*> _GroupCardinality_VALUES_TO_NAMES;

struct GroupType {
  enum type {
    DOMAIN_LEVEL_GROUP = 0,
    USER_LEVEL_GROUP = 1
  };
};

extern const std::map<int, const char*> _GroupType_VALUES_TO_NAMES;

struct GroupChildType {
  enum type {
    USER = 0,
    GROUP = 1
  };
};

extern const std::map<int, const char*> _GroupChildType_VALUES_TO_NAMES;

struct EntitySearchField {
  enum type {
    NAME = 0,
    DESCRIPTION = 1,
    FULL_TEXT = 2,
    PARRENT_ENTITY_ID = 3,
    OWNER_ID = 4,
    PERMISSION_TYPE_ID = 5,
    CREATED_TIME = 6,
    UPDATED_TIME = 7,
    ENTITY_TYPE_ID = 8,
    SHARED_COUNT = 9
  };
};

extern const std::map<int, const char*> _EntitySearchField_VALUES_TO_NAMES;

struct SearchCondition {
  enum type {
    EQUAL = 0,
    LIKE = 1,
    FULL_TEXT = 2,
    GTE = 3,
    LTE = 4,
    NOT = 5
  };
};

extern const std::map<int, const char*> _SearchCondition_VALUES_TO_NAMES;

struct SharingType {
  enum type {
    DIRECT_NON_CASCADING = 0,
    DIRECT_CASCADING = 1,
    INDIRECT_CASCADING = 2
  };
};

extern const std::map<int, const char*> _SharingType_VALUES_TO_NAMES;

class Domain;

class User;

class UserGroup;

class GroupMembership;

class EntityType;

class SearchCriteria;

class Entity;

class PermissionType;

class Sharing;

class SharingRegistryException;

typedef struct _Domain__isset {
  _Domain__isset() : domainId(true), name(false), description(false), createdTime(false), updatedTime(false) {}
  bool domainId :1;
  bool name :1;
  bool description :1;
  bool createdTime :1;
  bool updatedTime :1;
} _Domain__isset;

class Domain {
 public:

  Domain(const Domain&);
  Domain& operator=(const Domain&);
  Domain() : domainId("DO_NOT_SET_AT_CLIENTS_ID"), name(), description(), createdTime(0), updatedTime(0) {
  }

  virtual ~Domain() throw();
  std::string domainId;
  std::string name;
  std::string description;
  int64_t createdTime;
  int64_t updatedTime;

  _Domain__isset __isset;

  void __set_domainId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_description(const std::string& val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const Domain & rhs) const
  {
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const Domain &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const Domain & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(Domain &a, Domain &b);

inline std::ostream& operator<<(std::ostream& out, const Domain& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _User__isset {
  _User__isset() : userId(false), domainId(false), userName(false), firstName(false), lastName(false), email(false), icon(false), createdTime(false), updatedTime(false) {}
  bool userId :1;
  bool domainId :1;
  bool userName :1;
  bool firstName :1;
  bool lastName :1;
  bool email :1;
  bool icon :1;
  bool createdTime :1;
  bool updatedTime :1;
} _User__isset;

class User {
 public:

  User(const User&);
  User& operator=(const User&);
  User() : userId(), domainId(), userName(), firstName(), lastName(), email(), icon(), createdTime(0), updatedTime(0) {
  }

  virtual ~User() throw();
  std::string userId;
  std::string domainId;
  std::string userName;
  std::string firstName;
  std::string lastName;
  std::string email;
  std::string icon;
  int64_t createdTime;
  int64_t updatedTime;

  _User__isset __isset;

  void __set_userId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_userName(const std::string& val);

  void __set_firstName(const std::string& val);

  void __set_lastName(const std::string& val);

  void __set_email(const std::string& val);

  void __set_icon(const std::string& val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const User & rhs) const
  {
    if (__isset.userId != rhs.__isset.userId)
      return false;
    else if (__isset.userId && !(userId == rhs.userId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.userName != rhs.__isset.userName)
      return false;
    else if (__isset.userName && !(userName == rhs.userName))
      return false;
    if (__isset.firstName != rhs.__isset.firstName)
      return false;
    else if (__isset.firstName && !(firstName == rhs.firstName))
      return false;
    if (__isset.lastName != rhs.__isset.lastName)
      return false;
    else if (__isset.lastName && !(lastName == rhs.lastName))
      return false;
    if (__isset.email != rhs.__isset.email)
      return false;
    else if (__isset.email && !(email == rhs.email))
      return false;
    if (__isset.icon != rhs.__isset.icon)
      return false;
    else if (__isset.icon && !(icon == rhs.icon))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const User &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const User & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(User &a, User &b);

inline std::ostream& operator<<(std::ostream& out, const User& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _UserGroup__isset {
  _UserGroup__isset() : groupId(false), domainId(false), name(false), description(false), ownerId(false), groupType(false), groupCardinality(false), createdTime(false), updatedTime(false) {}
  bool groupId :1;
  bool domainId :1;
  bool name :1;
  bool description :1;
  bool ownerId :1;
  bool groupType :1;
  bool groupCardinality :1;
  bool createdTime :1;
  bool updatedTime :1;
} _UserGroup__isset;

class UserGroup {
 public:

  UserGroup(const UserGroup&);
  UserGroup& operator=(const UserGroup&);
  UserGroup() : groupId(), domainId(), name(), description(), ownerId(), groupType((GroupType::type)0), groupCardinality((GroupCardinality::type)0), createdTime(0), updatedTime(0) {
  }

  virtual ~UserGroup() throw();
  std::string groupId;
  std::string domainId;
  std::string name;
  std::string description;
  std::string ownerId;
  GroupType::type groupType;
  GroupCardinality::type groupCardinality;
  int64_t createdTime;
  int64_t updatedTime;

  _UserGroup__isset __isset;

  void __set_groupId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_description(const std::string& val);

  void __set_ownerId(const std::string& val);

  void __set_groupType(const GroupType::type val);

  void __set_groupCardinality(const GroupCardinality::type val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const UserGroup & rhs) const
  {
    if (__isset.groupId != rhs.__isset.groupId)
      return false;
    else if (__isset.groupId && !(groupId == rhs.groupId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    if (__isset.ownerId != rhs.__isset.ownerId)
      return false;
    else if (__isset.ownerId && !(ownerId == rhs.ownerId))
      return false;
    if (__isset.groupType != rhs.__isset.groupType)
      return false;
    else if (__isset.groupType && !(groupType == rhs.groupType))
      return false;
    if (__isset.groupCardinality != rhs.__isset.groupCardinality)
      return false;
    else if (__isset.groupCardinality && !(groupCardinality == rhs.groupCardinality))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const UserGroup &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const UserGroup & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(UserGroup &a, UserGroup &b);

inline std::ostream& operator<<(std::ostream& out, const UserGroup& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _GroupMembership__isset {
  _GroupMembership__isset() : parentId(false), childId(false), domainId(false), childType(false), createdTime(false), updatedTime(false) {}
  bool parentId :1;
  bool childId :1;
  bool domainId :1;
  bool childType :1;
  bool createdTime :1;
  bool updatedTime :1;
} _GroupMembership__isset;

class GroupMembership {
 public:

  GroupMembership(const GroupMembership&);
  GroupMembership& operator=(const GroupMembership&);
  GroupMembership() : parentId(), childId(), domainId(), childType((GroupChildType::type)0), createdTime(0), updatedTime(0) {
  }

  virtual ~GroupMembership() throw();
  std::string parentId;
  std::string childId;
  std::string domainId;
  GroupChildType::type childType;
  int64_t createdTime;
  int64_t updatedTime;

  _GroupMembership__isset __isset;

  void __set_parentId(const std::string& val);

  void __set_childId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_childType(const GroupChildType::type val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const GroupMembership & rhs) const
  {
    if (__isset.parentId != rhs.__isset.parentId)
      return false;
    else if (__isset.parentId && !(parentId == rhs.parentId))
      return false;
    if (__isset.childId != rhs.__isset.childId)
      return false;
    else if (__isset.childId && !(childId == rhs.childId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.childType != rhs.__isset.childType)
      return false;
    else if (__isset.childType && !(childType == rhs.childType))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const GroupMembership &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const GroupMembership & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(GroupMembership &a, GroupMembership &b);

inline std::ostream& operator<<(std::ostream& out, const GroupMembership& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _EntityType__isset {
  _EntityType__isset() : entityTypeId(false), domainId(false), name(false), description(false), createdTime(false), updatedTime(false) {}
  bool entityTypeId :1;
  bool domainId :1;
  bool name :1;
  bool description :1;
  bool createdTime :1;
  bool updatedTime :1;
} _EntityType__isset;

class EntityType {
 public:

  EntityType(const EntityType&);
  EntityType& operator=(const EntityType&);
  EntityType() : entityTypeId(), domainId(), name(), description(), createdTime(0), updatedTime(0) {
  }

  virtual ~EntityType() throw();
  std::string entityTypeId;
  std::string domainId;
  std::string name;
  std::string description;
  int64_t createdTime;
  int64_t updatedTime;

  _EntityType__isset __isset;

  void __set_entityTypeId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_description(const std::string& val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const EntityType & rhs) const
  {
    if (__isset.entityTypeId != rhs.__isset.entityTypeId)
      return false;
    else if (__isset.entityTypeId && !(entityTypeId == rhs.entityTypeId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const EntityType &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const EntityType & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(EntityType &a, EntityType &b);

inline std::ostream& operator<<(std::ostream& out, const EntityType& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _SearchCriteria__isset {
  _SearchCriteria__isset() : searchField(false), value(false), searchCondition(false) {}
  bool searchField :1;
  bool value :1;
  bool searchCondition :1;
} _SearchCriteria__isset;

class SearchCriteria {
 public:

  SearchCriteria(const SearchCriteria&);
  SearchCriteria& operator=(const SearchCriteria&);
  SearchCriteria() : searchField((EntitySearchField::type)0), value(), searchCondition((SearchCondition::type)0) {
  }

  virtual ~SearchCriteria() throw();
  EntitySearchField::type searchField;
  std::string value;
  SearchCondition::type searchCondition;

  _SearchCriteria__isset __isset;

  void __set_searchField(const EntitySearchField::type val);

  void __set_value(const std::string& val);

  void __set_searchCondition(const SearchCondition::type val);

  bool operator == (const SearchCriteria & rhs) const
  {
    if (__isset.searchField != rhs.__isset.searchField)
      return false;
    else if (__isset.searchField && !(searchField == rhs.searchField))
      return false;
    if (__isset.value != rhs.__isset.value)
      return false;
    else if (__isset.value && !(value == rhs.value))
      return false;
    if (__isset.searchCondition != rhs.__isset.searchCondition)
      return false;
    else if (__isset.searchCondition && !(searchCondition == rhs.searchCondition))
      return false;
    return true;
  }
  bool operator != (const SearchCriteria &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const SearchCriteria & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(SearchCriteria &a, SearchCriteria &b);

inline std::ostream& operator<<(std::ostream& out, const SearchCriteria& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _Entity__isset {
  _Entity__isset() : entityId(false), domainId(false), entityTypeId(false), ownerId(false), parentEntityId(false), name(false), description(false), binaryData(false), fullText(false), sharedCount(true), originalEntityCreationTime(false), createdTime(false), updatedTime(false) {}
  bool entityId :1;
  bool domainId :1;
  bool entityTypeId :1;
  bool ownerId :1;
  bool parentEntityId :1;
  bool name :1;
  bool description :1;
  bool binaryData :1;
  bool fullText :1;
  bool sharedCount :1;
  bool originalEntityCreationTime :1;
  bool createdTime :1;
  bool updatedTime :1;
} _Entity__isset;

class Entity {
 public:

  Entity(const Entity&);
  Entity& operator=(const Entity&);
  Entity() : entityId(), domainId(), entityTypeId(), ownerId(), parentEntityId(), name(), description(), binaryData(), fullText(), sharedCount(0LL), originalEntityCreationTime(0), createdTime(0), updatedTime(0) {
  }

  virtual ~Entity() throw();
  std::string entityId;
  std::string domainId;
  std::string entityTypeId;
  std::string ownerId;
  std::string parentEntityId;
  std::string name;
  std::string description;
  std::string binaryData;
  std::string fullText;
  int64_t sharedCount;
  int64_t originalEntityCreationTime;
  int64_t createdTime;
  int64_t updatedTime;

  _Entity__isset __isset;

  void __set_entityId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_entityTypeId(const std::string& val);

  void __set_ownerId(const std::string& val);

  void __set_parentEntityId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_description(const std::string& val);

  void __set_binaryData(const std::string& val);

  void __set_fullText(const std::string& val);

  void __set_sharedCount(const int64_t val);

  void __set_originalEntityCreationTime(const int64_t val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const Entity & rhs) const
  {
    if (__isset.entityId != rhs.__isset.entityId)
      return false;
    else if (__isset.entityId && !(entityId == rhs.entityId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.entityTypeId != rhs.__isset.entityTypeId)
      return false;
    else if (__isset.entityTypeId && !(entityTypeId == rhs.entityTypeId))
      return false;
    if (__isset.ownerId != rhs.__isset.ownerId)
      return false;
    else if (__isset.ownerId && !(ownerId == rhs.ownerId))
      return false;
    if (__isset.parentEntityId != rhs.__isset.parentEntityId)
      return false;
    else if (__isset.parentEntityId && !(parentEntityId == rhs.parentEntityId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    if (__isset.binaryData != rhs.__isset.binaryData)
      return false;
    else if (__isset.binaryData && !(binaryData == rhs.binaryData))
      return false;
    if (__isset.fullText != rhs.__isset.fullText)
      return false;
    else if (__isset.fullText && !(fullText == rhs.fullText))
      return false;
    if (__isset.sharedCount != rhs.__isset.sharedCount)
      return false;
    else if (__isset.sharedCount && !(sharedCount == rhs.sharedCount))
      return false;
    if (__isset.originalEntityCreationTime != rhs.__isset.originalEntityCreationTime)
      return false;
    else if (__isset.originalEntityCreationTime && !(originalEntityCreationTime == rhs.originalEntityCreationTime))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const Entity &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const Entity & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(Entity &a, Entity &b);

inline std::ostream& operator<<(std::ostream& out, const Entity& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _PermissionType__isset {
  _PermissionType__isset() : permissionTypeId(false), domainId(false), name(false), description(false), createdTime(false), updatedTime(false) {}
  bool permissionTypeId :1;
  bool domainId :1;
  bool name :1;
  bool description :1;
  bool createdTime :1;
  bool updatedTime :1;
} _PermissionType__isset;

class PermissionType {
 public:

  PermissionType(const PermissionType&);
  PermissionType& operator=(const PermissionType&);
  PermissionType() : permissionTypeId(), domainId(), name(), description(), createdTime(0), updatedTime(0) {
  }

  virtual ~PermissionType() throw();
  std::string permissionTypeId;
  std::string domainId;
  std::string name;
  std::string description;
  int64_t createdTime;
  int64_t updatedTime;

  _PermissionType__isset __isset;

  void __set_permissionTypeId(const std::string& val);

  void __set_domainId(const std::string& val);

  void __set_name(const std::string& val);

  void __set_description(const std::string& val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const PermissionType & rhs) const
  {
    if (__isset.permissionTypeId != rhs.__isset.permissionTypeId)
      return false;
    else if (__isset.permissionTypeId && !(permissionTypeId == rhs.permissionTypeId))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.name != rhs.__isset.name)
      return false;
    else if (__isset.name && !(name == rhs.name))
      return false;
    if (__isset.description != rhs.__isset.description)
      return false;
    else if (__isset.description && !(description == rhs.description))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const PermissionType &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const PermissionType & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(PermissionType &a, PermissionType &b);

inline std::ostream& operator<<(std::ostream& out, const PermissionType& obj)
{
  obj.printTo(out);
  return out;
}

typedef struct _Sharing__isset {
  _Sharing__isset() : permissionTypeId(false), entityId(false), groupId(false), sharingType(false), domainId(false), inheritedParentId(false), createdTime(false), updatedTime(false) {}
  bool permissionTypeId :1;
  bool entityId :1;
  bool groupId :1;
  bool sharingType :1;
  bool domainId :1;
  bool inheritedParentId :1;
  bool createdTime :1;
  bool updatedTime :1;
} _Sharing__isset;

class Sharing {
 public:

  Sharing(const Sharing&);
  Sharing& operator=(const Sharing&);
  Sharing() : permissionTypeId(), entityId(), groupId(), sharingType((SharingType::type)0), domainId(), inheritedParentId(), createdTime(0), updatedTime(0) {
  }

  virtual ~Sharing() throw();
  std::string permissionTypeId;
  std::string entityId;
  std::string groupId;
  SharingType::type sharingType;
  std::string domainId;
  std::string inheritedParentId;
  int64_t createdTime;
  int64_t updatedTime;

  _Sharing__isset __isset;

  void __set_permissionTypeId(const std::string& val);

  void __set_entityId(const std::string& val);

  void __set_groupId(const std::string& val);

  void __set_sharingType(const SharingType::type val);

  void __set_domainId(const std::string& val);

  void __set_inheritedParentId(const std::string& val);

  void __set_createdTime(const int64_t val);

  void __set_updatedTime(const int64_t val);

  bool operator == (const Sharing & rhs) const
  {
    if (__isset.permissionTypeId != rhs.__isset.permissionTypeId)
      return false;
    else if (__isset.permissionTypeId && !(permissionTypeId == rhs.permissionTypeId))
      return false;
    if (__isset.entityId != rhs.__isset.entityId)
      return false;
    else if (__isset.entityId && !(entityId == rhs.entityId))
      return false;
    if (__isset.groupId != rhs.__isset.groupId)
      return false;
    else if (__isset.groupId && !(groupId == rhs.groupId))
      return false;
    if (__isset.sharingType != rhs.__isset.sharingType)
      return false;
    else if (__isset.sharingType && !(sharingType == rhs.sharingType))
      return false;
    if (__isset.domainId != rhs.__isset.domainId)
      return false;
    else if (__isset.domainId && !(domainId == rhs.domainId))
      return false;
    if (__isset.inheritedParentId != rhs.__isset.inheritedParentId)
      return false;
    else if (__isset.inheritedParentId && !(inheritedParentId == rhs.inheritedParentId))
      return false;
    if (__isset.createdTime != rhs.__isset.createdTime)
      return false;
    else if (__isset.createdTime && !(createdTime == rhs.createdTime))
      return false;
    if (__isset.updatedTime != rhs.__isset.updatedTime)
      return false;
    else if (__isset.updatedTime && !(updatedTime == rhs.updatedTime))
      return false;
    return true;
  }
  bool operator != (const Sharing &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const Sharing & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
};

void swap(Sharing &a, Sharing &b);

inline std::ostream& operator<<(std::ostream& out, const Sharing& obj)
{
  obj.printTo(out);
  return out;
}

class SharingRegistryException : public ::apache::thrift::TException {
 public:

  SharingRegistryException(const SharingRegistryException&);
  SharingRegistryException& operator=(const SharingRegistryException&);
  SharingRegistryException() : message() {
  }

  virtual ~SharingRegistryException() throw();
  std::string message;

  void __set_message(const std::string& val);

  bool operator == (const SharingRegistryException & rhs) const
  {
    if (!(message == rhs.message))
      return false;
    return true;
  }
  bool operator != (const SharingRegistryException &rhs) const {
    return !(*this == rhs);
  }

  bool operator < (const SharingRegistryException & ) const;

  uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
  uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;

  virtual void printTo(std::ostream& out) const;
  mutable std::string thriftTExceptionMessageHolder_;
  const char* what() const throw();
};

void swap(SharingRegistryException &a, SharingRegistryException &b);

inline std::ostream& operator<<(std::ostream& out, const SharingRegistryException& obj)
{
  obj.printTo(out);
  return out;
}

#endif


text:
layout:     post
title:      "Consul: failed to sync remote state: No cluster leader"
date:       2016-10-30 19:52:00
author:     "Harry"
header-img: "img/post-bg-2015.jpg"
tags:
    - Consul
---

### Consul: failed to sync remote state: No cluster leader

今天启动consul时,发现报这个错误,以下是配置文件和启动指令

启动指令

```shell
consul agent --config-file /etc/consul.d/basic_config.json
```

配置文件

```json
{
        "datacenter": "dc-dev",
        "data_dir": "/tmp/consul",
        "log_level": "INFO",
        "node_name": "service",
        "server": true,
        "services": [
                {
                    "name": "Shop",
                    "port": 9091
                },
                {
                    "name": "User",
                    "port": 9092
                }
        ]
}
```

配置文件没有什么特别之处,指令也没有设置其他参数,所以目测应该还是缺少某个关键参数

经过研究Consul的官方文档,看到了两个关键参数

- [`-bootstrap`](https://www.consul.io/docs/agent/options.html#_bootstrap) - This flag is used to control if a server is in "bootstrap" mode. It is important that no more than one server *per* datacenter be running in this mode. Technically, a server in bootstrap mode is allowed to self-elect as the Raft leader. It is important that only a single node is in this mode; otherwise, consistency cannot be guaranteed as multiple nodes are able to self-elect. It is not recommended to use this flag after a cluster has been bootstrapped.
- [`-bootstrap-expect`](https://www.consul.io/docs/agent/options.html#_bootstrap_expect) - This flag provides the number of expected servers in the datacenter. Either this value should not be provided or the value must agree with other servers in the cluster. When provided, Consul waits until the specified number of servers are available and then bootstraps the cluster. This allows an initial leader to be elected automatically. This cannot be used in conjunction with the legacy [`-bootstrap`](https://www.consul.io/docs/agent/options.html#_bootstrap) flag.

由上可见,consul启动之后需要选举出Leader,用于同步数据,而当server的节点只有一个时,需要设置-bootstrap的参数用于完成consul的自选举,不然就会报:failed to sync remote state: No cluster leader

当server的节点有多个时,则需设置-bootstrap-expect,用于设置预期的server数量,当server的数量达到预设值时,才启动选举机制,server的数量达不到预设值则也会报:failed to sync remote state: No cluster leader

通过上面的分析,我们可以对开头的错误给出两种解决方案

```shell
consul agent --config-file /etc/consul.d/basic_config.json -bootstrap
```

```shell
consul agent --config-file /etc/consul.d/basic_config.json -bootstrap-expect 1
```

redpajama_set_name: RedPajamaGithub


text:
#ifndef DescriptorVisitorParent_HPP
#define DescriptorVisitorParent_HPP

// Boost
#include <boost/graph/graph_traits.hpp>

/**
 * This is an abstract visitor that complies with the DescriptorVisitorConcept. It is available
 * so that we can store a container of DescriptorVisitors via their parent class pointer (e.g.
 * std::vector<DescriptorVisitorParent*> )
 */
template <typename TGraph>
struct DescriptorVisitorParent
{
  typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;

  virtual void InitializeVertex(VertexDescriptorType v) const = 0;

  /** This is not const because we typically have to set some properties of the
    * target patch when it is discovered. */
  virtual void DiscoverVertex(VertexDescriptorType v) = 0;

}; // DescriptorVisitorParent

#endif


text:
'use babel'

import tag from '../'
import escape from 'escape-html'

describe('tagged-template-literals', function() {
  function proxy(strings, ...values) {
    return tag(strings, values)
  }
  function escapingProxy(strings, ...values) {
    return tag(strings, values, escape)
  }

  it('merges strings and values properly', function() {
    expect(proxy`Hello ${'Dolly'}`).toBe('Hello Dolly')
  })
  it('works well even on all value stuff', function() {
    expect(proxy`${'Hello'}`).toBe('Hello')
  })
  it('works well even on all string stuff', function() {
    expect(proxy`Hello Dolly`).toBe('Hello Dolly')
  })
  it('works well with filtering callbacks', function() {
    expect(escapingProxy`Hello ${'<div />'}`).toBe('Hello <div />')
  })
  it('works with random stuff', function() {
    expect(proxy`Hello ${'Dolly'} This ${'is'} Steel`).toBe('Hello Dolly This is Steel')
  })
})


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class Changeset</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Class Changeset

Description

					Description |
													Vars (details)
						|											Methods (details)

Class representing a set of changes in the repository identified by a revision

author: Manuel Kiessling <manuel@kiessling.net>

copyright: 2011 Manuel Kiessling <manuel@kiessling.net>

link: http://manuelkiessling.github.com/PHPRestfulSubversion

usedby: RepoLogInterpreter

usedby: RepoCache

uses: Revision

uses: RepoPath

license: BSD License

			Located in /RestfulSubversion/Core/Changeset.php (line 57)

Variable Summary

			Description |
						Vars (details)
							|
									Methods (details)

					mixed
					$author

					mixed
					$dateTime

					mixed
					$message

					mixed
					$pathOperations

					mixed
					$revision

Method Summary

			Description |
																		Vars (details)

				|
						Methods (details)

											Changeset
										__construct
											(Revision $revision)

											void
										addPathOperation
											(string $action, RepoPath $path, [RepoPath $copyfromPath = null], [Revision $copyfromRev = null])

											Author
										getAuthor
										()

											Date
										getDateTime
										()

											Commit
										getMessage
										()

											Path
										getPathOperations
										()

											Revision
										getRevision
										()

											void
										setAuthor
											(string $author)

											void
										setDateTime
											(string $dateTime)

											void
										setMessage
											(string $message)

Variables

			Description |
										Vars (details)

										|
									Methods (details)

			mixed
			$author
			 =  null			(line 60)

access: protected

			mixed
			$dateTime
			 =  null			(line 61)

access: protected

			mixed
			$message
			 =  null			(line 62)

access: protected

			mixed
			$pathOperations
			 = array()			(line 63)

access: protected

			mixed
			$revision
			 =  null			(line 59)

access: protected

Methods

			Description |
															Vars (details)
																	Methods (details)

		Constructor __construct (line 68)

access: public

		Changeset

			__construct

					(Revision $revision)

				Revision
				$revision

		addPathOperation (line 107)

access: public

		void

			addPathOperation

					(string $action, RepoPath $path, [RepoPath $copyfromPath = null], [Revision $copyfromRev = null])

				string
				$action

				RepoPath
				$path

				null|RepoPath
				$copyfromPath

				null|Revision
				$copyfromRev

		getAuthor (line 127)

return: of the commit

access: public

		Author

			getAuthor

				()

		getDateTime (line 135)

return: and time of the commit

access: public

		Date

			getDateTime

				()

		getMessage (line 143)

return: message

access: public

		Commit

			getMessage

				()

		getPathOperations (line 151)

return: operations of this commit

access: public

		Path

			getPathOperations

				()

		getRevision (line 119)

return: of this changeset

access: public

		Revision

			getRevision

				()

		setAuthor (line 77)

access: public

		void

			setAuthor

					(string $author)

				string
				$author

		setDateTime (line 86)

access: public

		void

			setDateTime

					(string $dateTime)

				string
				$dateTime

		setMessage (line 95)

access: public

		void

			setMessage

					(string $message)

				string
				$message

		Documentation generated on Sun, 18 Sep 2011 16:11:12 +0200 by phpDocumentor 1.4.3


text:
package org.apache.commons.collections4.functors;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.collections4.Factory;
import org.apache.commons.collections4.FunctorException;

/**
 * Factory implementation that creates a new object instance by reflection.
 *
 * @since 3.0
 * @version $Id$
 */
public class InstantiateFactory<T> implements Factory<T>, Serializable {

    /** The serial version */
    private static final long serialVersionUID = -7732226881069447957L;

    /** The class to create */
    private final Class<T> iClassToInstantiate;
    /** The constructor parameter types */
    private final Class<?>[] iParamTypes;
    /** The constructor arguments */
    private final Object[] iArgs;
    /** The constructor */
    private transient Constructor<T> iConstructor = null;

    /**
     * Factory method that performs validation.
     *
     * @param <T>  the type the factory creates
     * @param classToInstantiate  the class to instantiate, not null
     * @param paramTypes  the constructor parameter types, cloned
     * @param args  the constructor arguments, cloned
     * @return a new instantiate factory
     * @throws NullPointerException if classToInstantiate is null
     * @throws IllegalArgumentException if paramTypes does not match args
     */
    public static <T> Factory<T> instantiateFactory(final Class<T> classToInstantiate,
                                                    final Class<?>[] paramTypes,
                                                    final Object[] args) {
        if (classToInstantiate == null) {
            throw new NullPointerException("Class to instantiate must not be null");
        }
        if (paramTypes == null && args != null
            || paramTypes != null && args == null
            || paramTypes != null && args != null && paramTypes.length != args.length) {
            throw new IllegalArgumentException("Parameter types must match the arguments");
        }

        if (paramTypes == null || paramTypes.length == 0) {
            return new InstantiateFactory<T>(classToInstantiate);
        }
        return new InstantiateFactory<T>(classToInstantiate, paramTypes, args);
    }

    /**
     * Constructor that performs no validation.
     * Use instantiateFactory if you want that.
     *
     * @param classToInstantiate  the class to instantiate
     */
    public InstantiateFactory(final Class<T> classToInstantiate) {
        super();
        iClassToInstantiate = classToInstantiate;
        iParamTypes = null;
        iArgs = null;
        findConstructor();
    }

    /**
     * Constructor that performs no validation.
     * Use instantiateFactory if you want that.
     *
     * @param classToInstantiate  the class to instantiate
     * @param paramTypes  the constructor parameter types, cloned
     * @param args  the constructor arguments, cloned
     */
    public InstantiateFactory(final Class<T> classToInstantiate, final Class<?>[] paramTypes, final Object[] args) {
        super();
        iClassToInstantiate = classToInstantiate;
        iParamTypes = paramTypes.clone();
        iArgs = args.clone();
        findConstructor();
    }

    /**
     * Find the Constructor for the class specified.
     */
    private void findConstructor() {
        try {
            iConstructor = iClassToInstantiate.getConstructor(iParamTypes);
        } catch (final NoSuchMethodException ex) {
            throw new IllegalArgumentException("InstantiateFactory: The constructor must exist and be public ");
        }
    }

    /**
     * Creates an object using the stored constructor.
     *
     * @return the new object
     */
    public T create() {
        // needed for post-serialization
        if (iConstructor == null) {
            findConstructor();
        }

        try {
            return iConstructor.newInstance(iArgs);
        } catch (final InstantiationException ex) {
            throw new FunctorException("InstantiateFactory: InstantiationException", ex);
        } catch (final IllegalAccessException ex) {
            throw new FunctorException("InstantiateFactory: Constructor must be public", ex);
        } catch (final InvocationTargetException ex) {
            throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex);
        }
    }

}


text:
use bit_field::BitField;
use bitflags::bitflags;

bitflags! {
    /// The redirection table starts at REG_TABLE and uses
    /// two registers to configure each interrupt.
    /// The first (low) register in a pair contains configuration bits.
    /// The second (high) register contains a bitmask telling which
    /// CPUs can serve that interrupt.
    struct RedirectionEntry: u32 {
        /// Interrupt disabled
        const DISABLED  = 0x00010000;
        /// Level-triggered (vs edge)
        const LEVEL     = 0x00008000;
        /// Active low (vs high)
        const ACTIVELOW = 0x00002000;
        /// Destination is CPU id (vs APIC ID)
        const LOGICAL   = 0x00000800;
        /// None
        const NONE		= 0x00000000;
    }
}

pub struct IoApic {
    reg: *mut u32,
    data: *mut u32,
}

impl IoApic {
    /// Instantiate a new IoApic.
    ///
    /// # Safety
    /// `addr` must point to the base of the IoApic.
    pub unsafe fn new(addr: usize) -> Self {
        IoApic {
            reg: addr as *mut u32,
            data: (addr + 0x10) as *mut u32,
        }
    }
    pub fn disable_all(&mut self) {
        // Mark all interrupts edge-triggered, active high, disabled,
        // and not routed to any CPUs.
        for i in 0..self.supported_interrupts() {
            self.write_irq(i, RedirectionEntry::DISABLED, 0);
        }
    }

    unsafe fn read(&mut self, reg: u8) -> u32 {
        self.reg.write_volatile(reg as u32);
        self.data.read_volatile()
    }

    unsafe fn write(&mut self, reg: u8, data: u32) {
        self.reg.write_volatile(reg as u32);
        self.data.write_volatile(data);
    }

    fn write_irq(&mut self, irq: u8, flags: RedirectionEntry, dest: u8) {
        unsafe {
            self.write(REG_TABLE + 2 * irq, (T_IRQ0 + irq) as u32 | flags.bits());
            self.write(REG_TABLE + 2 * irq + 1, (dest as u32) << 24);
        }
    }

    pub fn enable(&mut self, irq: u8, cpunum: u8) {
        // Mark interrupt edge-triggered, active high,
        // enabled, and routed to the given cpunum,
        // which happens to be that cpu's APIC ID.
        self.write_irq(irq, RedirectionEntry::NONE, cpunum);
    }

    pub fn id(&mut self) -> u8 {
        unsafe { self.read(REG_ID).get_bits(24..28) as u8 }
    }

    pub fn version(&mut self) -> u8 {
        unsafe { self.read(REG_VER).get_bits(0..8) as u8 }
    }

    /// Number of supported interrupts by this IO APIC.
    ///
    /// Max Redirection Entry = "how many IRQs can this I/O APIC handle - 1"
    /// The -1 is silly so we add one back to it.
    pub fn supported_interrupts(&mut self) -> u8 {
        unsafe { (self.read(REG_VER).get_bits(16..24) + 1) as u8 }
    }
}

/// Register index: ID
const REG_ID: u8 = 0x00;

/// Register index: version
const REG_VER: u8 = 0x01;

/// Redirection table base
const REG_TABLE: u8 = 0x10;

const T_IRQ0: u8 = 32;


text:
"""Support for KNX/IP covers."""
from xknx.devices import Cover as XknxCover

from homeassistant.components.cover import (
    ATTR_POSITION,
    ATTR_TILT_POSITION,
    DEVICE_CLASS_BLIND,
    DEVICE_CLASSES,
    SUPPORT_CLOSE,
    SUPPORT_CLOSE_TILT,
    SUPPORT_OPEN,
    SUPPORT_OPEN_TILT,
    SUPPORT_SET_POSITION,
    SUPPORT_SET_TILT_POSITION,
    SUPPORT_STOP,
    SUPPORT_STOP_TILT,
    CoverEntity,
)
from homeassistant.core import callback
from homeassistant.helpers.event import async_track_utc_time_change

from .const import DOMAIN
from .knx_entity import KnxEntity

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up cover(s) for KNX platform."""
    entities = []
    for device in hass.data[DOMAIN].xknx.devices:
        if isinstance(device, XknxCover):
            entities.append(KNXCover(device))
    async_add_entities(entities)

class KNXCover(KnxEntity, CoverEntity):
    """Representation of a KNX cover."""

    def __init__(self, device: XknxCover):
        """Initialize the cover."""
        super().__init__(device)

        self._unsubscribe_auto_updater = None

    @callback
    async def after_update_callback(self, device):
        """Call after device was updated."""
        self.async_write_ha_state()
        if self._device.is_traveling():
            self.start_auto_updater()

    @property
    def device_class(self):
        """Return the class of this device, from component DEVICE_CLASSES."""
        if self._device.device_class in DEVICE_CLASSES:
            return self._device.device_class
        if self._device.supports_angle:
            return DEVICE_CLASS_BLIND
        return None

    @property
    def supported_features(self):
        """Flag supported features."""
        supported_features = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION
        if self._device.supports_stop:
            supported_features |= SUPPORT_STOP
        if self._device.supports_angle:
            supported_features |= (
                SUPPORT_SET_TILT_POSITION
                | SUPPORT_OPEN_TILT
                | SUPPORT_CLOSE_TILT
                | SUPPORT_STOP_TILT
            )
        return supported_features

    @property
    def current_cover_position(self):
        """Return the current position of the cover.

        None is unknown, 0 is closed, 100 is fully open.
        """
        # In KNX 0 is open, 100 is closed.
        try:
            return 100 - self._device.current_position()
        except TypeError:
            return None

    @property
    def is_closed(self):
        """Return if the cover is closed."""
        # state shall be "unknown" when xknx travelcalculator is not initialized
        if self._device.current_position() is None:
            return None
        return self._device.is_closed()

    @property
    def is_opening(self):
        """Return if the cover is opening or not."""
        return self._device.is_opening()

    @property
    def is_closing(self):
        """Return if the cover is closing or not."""
        return self._device.is_closing()

    async def async_close_cover(self, **kwargs):
        """Close the cover."""
        await self._device.set_down()

    async def async_open_cover(self, **kwargs):
        """Open the cover."""
        await self._device.set_up()

    async def async_set_cover_position(self, **kwargs):
        """Move the cover to a specific position."""
        knx_position = 100 - kwargs[ATTR_POSITION]
        await self._device.set_position(knx_position)

    async def async_stop_cover(self, **kwargs):
        """Stop the cover."""
        await self._device.stop()
        self.stop_auto_updater()

    @property
    def current_cover_tilt_position(self):
        """Return current tilt position of cover."""
        if not self._device.supports_angle:
            return None
        try:
            return 100 - self._device.current_angle()
        except TypeError:
            return None

    async def async_set_cover_tilt_position(self, **kwargs):
        """Move the cover tilt to a specific position."""
        knx_tilt_position = 100 - kwargs[ATTR_TILT_POSITION]
        await self._device.set_angle(knx_tilt_position)

    async def async_open_cover_tilt(self, **kwargs):
        """Open the cover tilt."""
        await self._device.set_short_up()

    async def async_close_cover_tilt(self, **kwargs):
        """Close the cover tilt."""
        await self._device.set_short_down()

    async def async_stop_cover_tilt(self, **kwargs):
        """Stop the cover tilt."""
        await self._device.stop()
        self.stop_auto_updater()

    def start_auto_updater(self):
        """Start the autoupdater to update Home Assistant while cover is moving."""
        if self._unsubscribe_auto_updater is None:
            self._unsubscribe_auto_updater = async_track_utc_time_change(
                self.hass, self.auto_updater_hook
            )

    def stop_auto_updater(self):
        """Stop the autoupdater."""
        if self._unsubscribe_auto_updater is not None:
            self._unsubscribe_auto_updater()
            self._unsubscribe_auto_updater = None

    @callback
    def auto_updater_hook(self, now):
        """Call for the autoupdater."""
        self.async_write_ha_state()
        if self._device.position_reached():
            self.stop_auto_updater()

        self.hass.add_job(self._device.auto_stop_if_necessary())


text:
<?xml version="1.0"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>Sakai IFrame Portlet</display-name>

  <filter>
    <filter-name>sakai.request</filter-name>
    <filter-class>org.sakaiproject.util.RequestFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>sakai.request</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
  </filter-mapping>

  <servlet>
    <servlet-name>SakaiIFrame</servlet-name>
    <servlet-class>org.apache.pluto.core.PortletServlet</servlet-class>
    <init-param>
    <param-name>portlet-name</param-name>
    <param-value>SakaiIFrame</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
      <servlet-name>SakaiIFrame</servlet-name>
      <url-pattern>/PlutoInvoker/SakaiIFrame</url-pattern>
  </servlet-mapping>

</web-app>


text:
Pebble watchapp that displays the current status of the London Underground
(Tube) lines.

Data sourced from the London Underground TfL [Unified API](https://api.tfl.gov.uk/).

## TOTO

- More detailed documentation.


text:
package db

import "github.com/boltdb/bolt"

var credsBucket = []byte("credentials")

// An Credentials object holds a user's login credentials.
type Credentials struct {
	Username string
	PwdHash  []byte
}

// FindCreds returns the user's credentials.
func (st *Store) FindCreds(username string) (Credentials, error) {
	var c Credentials
	err := st.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket(credsBucket)
		if b == nil {
			return ErrNoBucket("credentials")
		}
		exists, err := get(b, []byte(username), &c)
		if err != nil {
			return err
		}
		if !exists {
			return ErrNotFound("credentials")
		}
		return nil
	})
	return c, err
}

// SaveCreds saves the user's credentials to the db.
func (st *Store) SaveCreds(c Credentials) error {
	return st.db.Update(func(tx *bolt.Tx) error {
		return saveCreds(tx, c)
	})
}

func saveCreds(tx *bolt.Tx, c Credentials) error {
	b := tx.Bucket(credsBucket)
	if b == nil {
		return ErrNoBucket("credentials")
	}
	return put(b, []byte(c.Username), c)
}


text:
// Copyright (c) Rotorz Limited. All rights reserved.

using UnityEditor;
using UnityEngine;

namespace Rotorz.Games.Collections
{
    /// <exclude/>
    [CustomPropertyDrawer(typeof(ReorderableListAttribute))]
    public sealed class ReorderableListPropertyDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            var attribute = (ReorderableListAttribute)this.attribute;
            var elementsProperty = property.FindPropertyRelative(attribute.ElementsPropertyName);
            var listAdaptor = new SerializedPropertyWithDropTargetAdaptor(elementsProperty, attribute.DroppableObjectType);

            float height = 0f;

            if (label != GUIContent.none) {
                height += 21f;
            }

            height += ReorderableListGUI.CalculateListFieldHeight(listAdaptor, attribute.Flags);

            return height;
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var attribute = (ReorderableListAttribute)this.attribute;
            var elementsProperty = property.FindPropertyRelative(attribute.ElementsPropertyName);
            var listAdaptor = new SerializedPropertyWithDropTargetAdaptor(elementsProperty, attribute.DroppableObjectType);

            var titlePosition = new Rect(position.x, position.y, position.width, 0f);
            if (label != GUIContent.none) {
                titlePosition.height = 21f;
                ReorderableListGUI.Title(titlePosition, label);
            }

            var listPosition = new Rect(position.x, titlePosition.yMax - 1f, position.width, position.height - titlePosition.height);
            ReorderableListGUI.ListFieldAbsolute(listPosition, listAdaptor, attribute.Flags);
        }
    }
}


text:
package com.svcet.cashportal.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.svcet.cashportal.domain.CountryMaster;
import com.svcet.cashportal.domain.OrganizationMaster;
import com.svcet.cashportal.domain.UserMaster;
import com.svcet.cashportal.exception.DuplicateUserException;
import com.svcet.cashportal.exception.OrganizationNotFoundException;
import com.svcet.cashportal.exception.UserNotFoundException;
import com.svcet.cashportal.repository.CountryMasterRepository;
import com.svcet.cashportal.repository.OrganizationRepository;
import com.svcet.cashportal.repository.UserRepository;
import com.svcet.cashportal.web.beans.UserRequest;
import com.svcet.cashportal.web.beans.UserResponse;

@Service
public class UserServiceImpl implements UserService {

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

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private OrganizationRepository organizationRepository;

	@Autowired
	private CountryMasterRepository countryMasterRepository;

	@Override
	public UserMaster findUserByUserNamePasswordOrgName(String userName, String password, String orgName) {
		try {
			OrganizationMaster organizationMaster = organizationRepository.findByOrgName(orgName);
			return userRepository.findOneByUserNameAndPasswordAndOrgId(userName, password, organizationMaster.getRid());
		} catch (IndexOutOfBoundsException e) {
			LOGGER.debug("No entity was found in repository with the id [{}]", userName);
		}
		return null;
	}

	@Override
	public UserMaster save(UserMaster userMaster) {
		return userRepository.save(userMaster);
	}

	@Override
	public UserResponse save(UserRequest userRequest) {
		try {
			UserMaster userMaster = userRepository.findOneByUserNameAndOrgId(userRequest.getUserName(),
					userRequest.getOrgId());
			throw new DuplicateUserException(userRequest);
		} catch (IndexOutOfBoundsException e) {
			UserMaster userMaster = new UserMaster();
			BeanUtils.copyProperties(userRequest, userMaster, "orgId", "countryId");
			OrganizationMaster organizationMaster = organizationRepository.findByRid(userRequest.getOrgId());
			userMaster.setOrgId(organizationMaster);

			CountryMaster countryId = countryMasterRepository.findByCountryCode(userRequest.getCountryId());
			userMaster.setCountryId(countryId);
			userMaster = userRepository.save(userMaster);

			UserResponse userResponse = new UserResponse();
			BeanUtils.copyProperties(userMaster, userResponse, "orgId");
			userResponse.setOrgId(userMaster.getOrgId().getRid());
			return userResponse;
		}
	}

	@Override
	public UserResponse findById(String id) {
		try {
			UserMaster userMaster = userRepository.findByRid(id);
			UserResponse userResponse = new UserResponse();
			BeanUtils.copyProperties(userMaster, userResponse, "orgId", "countryId");
			userResponse.setOrgId(userMaster.getOrgId().getRid());

			userResponse.setCountryId(userMaster.getCountryId().getCountryCode());

			return userResponse;
		} catch (IndexOutOfBoundsException e) {
			throw new UserNotFoundException();
		}
	}

	@Override
	public UserResponse update(UserRequest userRequest) {
		try {
			UserMaster userMaster = userRepository.findByRid(userRequest.getRid());
			BeanUtils.copyProperties(userRequest, userMaster, "orgId", "countryId");
			CountryMaster countryId = countryMasterRepository.findByCountryCode(userRequest.getCountryId());
			userMaster.setCountryId(countryId);
			OrganizationMaster organizationMaster = organizationRepository.findByRid(userRequest.getOrgId());
			userMaster.setOrgId(organizationMaster);

			userMaster = userRepository.save(userMaster);

			UserResponse userResponse = new UserResponse();
			BeanUtils.copyProperties(userMaster, userResponse, "orgId", "countryId");
			userResponse.setOrgId(userMaster.getOrgId().getRid());
			userResponse.setCountryId(userMaster.getCountryId().getCountryCode());
			return userResponse;
		} catch (IndexOutOfBoundsException e) {
			throw new UserNotFoundException();
		}
	}

	@Override
	public List<UserResponse> findAll(String orgId) {
		List<UserResponse> userResponseList = new ArrayList<UserResponse>();
		try {
			List<UserMaster> userMasterList = userRepository.findByOrgId(orgId);
			for (UserMaster userMaster : userMasterList) {
				UserResponse userResponse = new UserResponse();
				BeanUtils.copyProperties(userMaster, userResponse, "orgId", "countryId");
				userResponse.setOrgId(userMaster.getOrgId().getRid());
				userResponse.setCountryId(userMaster.getCountryId().getCountryCode());
				userResponseList.add(userResponse);
			}
		} catch (IndexOutOfBoundsException e) {
			throw new OrganizationNotFoundException();
		}
		return userResponseList;
	}

	@Override
	public UserMaster findOneByUserNameAndOrgId(String userName, String orgId) {
		try {
			return userRepository.findOneByUserNameAndOrgId(userName, orgId);
		} catch (IndexOutOfBoundsException e) {
			throw new UserNotFoundException();
		}
	}
}


text:
module FixtureGroup
  module FixtureGroupMethod
    extend ActiveSupport::Concern

    class_methods do
      # @param [String, Symbol] fixture_set_dirname
      # @param [Array<String, Symbol>] fixture_set_names
      # @example See `*_test.rb` in https://github.com/hidakatsuya/fixture_group/tree/master/test/integration
      def fixture_group(fixture_set_dirname, *fixture_set_names)
        fixture_set_path = Pathname(fixture_path).join(fixture_set_dirname.to_s)

        if fixture_set_names.first == :all
          fixture_set_names = Pathname.glob("#{fixture_set_path}/**/*.yml")
          fixture_set_names.map! do |f|
            f.relative_path_from(fixture_set_path).to_path[0..-5]
          end
        else
          fixture_set_names = fixture_set_names.map(&:to_s)
        end

        paths, classes = [], {}

        fixture_set_names.each do |fixture_name|
          path = "#{fixture_set_dirname}/#{fixture_name}"

          unless self.fixture_class_names.key?(path)
            classes[path] = fixture_name.singularize.camelize.constantize
          end
          paths << path
        end

        set_fixture_class(classes)
        fixtures(paths)
        setup_fixture_group_accessors(paths, fixture_set_names)

        register_fixture_group_dirname(fixture_set_dirname.to_s)
      end

      private

      def setup_fixture_group_accessors(paths, fixture_set_names)
        current_accessor_names = paths.map { |path| path.tr('/', '_').to_sym }
        new_accessor_names = fixture_set_names.map(&:to_sym)

        alias_accessor_names = Hash[current_accessor_names.zip(new_accessor_names)]
        alias_accessor_names.each do |current_name, new_name|
          alias_method new_name, current_name
        end
      end

      def register_fixture_group_dirname(dirname)
        return if FixtureGroup.fixture_group_dirnames.include?(dirname)
        FixtureGroup.fixture_group_dirnames << dirname
      end
    end
  end

  # @private
  def self.fixture_group_dirnames
    @fixture_group_dirnames ||= []
  end
end

ActiveRecord::TestFixtures.send :include, FixtureGroup::FixtureGroupMethod


text:
from flask import Flask, Response, request, render_template
import cv2
from controlServer import *

cam=cv2.VideoCapture(0)
if cam.isOpened()==False:
    print("cant open cam")
    exit()
cam.set(cv2.CAP_PROP_FRAME_WIDTH,320)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT,240)

app = Flask(__name__, template_folder='.')

def generate():
    while True:
        ret,image = cam.read()
        jpegdata=cv2.imencode(".jpeg",image)[1].tobytes()
        string = "--MjpgBound\r\n"
        string += "Content-Type: image/jpeg\r\n"
        string += "Content-length: "+str(len(jpegdata))+"\r\n\r\n"
        yield (string.encode("utf-8") + jpegdata + "\r\n\r\n".encode("utf-8"))

#stream camera
@app.route('/stream')
def do_stream():
    return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=--MjpgBound')

#control rccar
@app.route('/motor', methods=['POST'])
def control_rccar():
    command=request.form.get('command')
    print(command)
    if command == "GO":
        forward()
    elif command == "LEFT":
        left()
    elif command == "STOP":
        stop()
    elif command == "RIGHT":
        right()
    elif command == "BACK":
        backward()
    return ''

@app.route('/')
def do_route():
    return render_template("index.html")

if __name__ == '__main__':
    initMotors()
    app.run(host='localhost', port=8080)


text:
<template name="comment_edit">

    {{#with comment}}
    <form class="grid-block form-horizontal">

        {{i18n "Comment"}}

<textarea id="body" value="" class="input-xlarge">{{body}}</textarea>

        {{i18n "Delete Comment"}}
        <input type="submit" class="button" value="{{i18n "Submit"}}" title="(⌘+enter)" />

    </form>
    {{/with}}

</template>