Sometime creating the descriptor for new agent we cannot know in
        which shard it will endup. If it is None or set to lobby, the HA
        will update the field to match his own
512755
def _update_descriptor(self, state, allocation):
        ''''''
        if state.descriptor.shard is None or state.descriptor.shard == 'lobby':
            own_shard = state.agent.get_shard_id()
            state.descriptor.shard = own_shard
        state.descriptor.resources = allocation.alloc
        f = fiber.succeed(state.descriptor)
        f.add_callback(state.agent.save_document)
        f.add_callback(self._store_descriptor)
        return f
1315864
public boolean cchanged(String descriptor) {
		if (liveVersion != null) {
			boolean b = liveVersion.hasConstructorChanged(descriptor);
			return b;
		}
		return false;
	}
276719
function ensureFieldHasChanged (obj1, obj2) {
  return isNullsy(obj1) || isNullsy(obj2)
    ? () => false
    : field => obj1[field] !== obj2[field];
}
492856
def __FieldDescriptorFromProperties(self, name, index, attrs):
        """"""
        field = descriptor.FieldDescriptor()
        field.name = self.__names.CleanName(name)
        field.number = index
        field.label = self.__ComputeLabel(attrs)
        new_type_name_hint = self.__names.ClassName(
            '%sValue' % self.__names.ClassName(name))
        type_info = self.__GetTypeInfo(attrs, new_type_name_hint)
        field.type_name = type_info.type_name
        field.variant = type_info.variant
        if 'default' in attrs:
            # TODO(craigcitro): Correctly handle non-primitive default values.
            default = attrs['default']
            if not (field.type_name == 'string' or
                    field.variant == messages.Variant.ENUM):
                default = str(json.loads(default))
            if field.variant == messages.Variant.ENUM:
                default = self.__names.NormalizeEnumName(default)
            field.default_value = default
        extended_field = extended_descriptor.ExtendedFieldDescriptor()
        extended_field.name = field.name
        extended_field.description = util.CleanDescription(
            attrs.get('description', 'A %s attribute.' % field.type_name))
        extended_field.field_descriptor = field
        return extended_field
701218
def update_field(self, name, update):
        
        for field in self.__next_descriptor['fields']:
            if field['name'] == name:
                field.update(update)
                return True
        return False
1101319
def _init(self, state, initiate_arg):
        '''
        
        '''
        state.descriptor = None
        state.hosts = state.agent.query_partners('hosts')
        state.current_index = -1

        self.log('%s task initiated, will be trying to start a '
                 '%r on one of the hosts: %r', str(self.__class__.__name__),
                 initiate_arg, state.hosts)
        if len(state.hosts) == 0:
            # FIXME: Here would be a good idea to put an alert
            return self._fail('Shard Agent cannot start partner %r as it has '
                              'no Host Partners!' % (initiate_arg, ))
942669
def create_db_in_shard(db_name, shard, client=None):
    
    client = client or pymongo.MongoClient()
    # flush the router config to ensure it's not stale
    res = client.admin.command('flushRouterConfig')
    if not res.get('ok'):
        raise RuntimeError("unable to flush router config")
    if shard not in get_ids(client.config.shards):
        raise ValueError(f"Unknown shard {shard}")
    if db_name in get_ids(client.config.databases):
        raise ValueError("database already exists")
    # MongoDB doesn't have a 'create database' command, so insert an
    #  item into a collection and then drop the collection.
    client[db_name].foo.insert({'foo': 1})
    client[db_name].foo.drop()
    if client[db_name].collection_names():
        raise ValueError("database has collections")
    primary = client['config'].databases.find_one(db_name)['primary']
    if primary != shard:
        res = client.admin.command(
            'movePrimary', value=db_name, to=shard)
        if not res.get('ok'):
            raise RuntimeError(str(res))
    return (
        f"Successfully created {db_name} in {shard} via {client.nodes} "
        f"from {hostname}")
307050
def _get_next_open_shard(stream_details, shard_id):
    '''
    
    '''
    found = False
    for shard in stream_details["OpenShards"]:
        current_shard_id = shard["ShardId"]
        if current_shard_id == shard_id:
            found = True
            continue
        if found:
            return current_shard_id
319581
@Check
	public void checkFinalFieldInitialization(SarlAgent agent) {
		final JvmGenericType inferredType = this.associations.getInferredType(agent);
		if (inferredType != null) {
			checkFinalFieldInitialization(inferredType);
		}
	}
551807
def AdjustDescriptor(self, fields):
    """"""

    for f in fields:
      if f.name == "args_rdf_name":
        f.name = "payload_type"

      if f.name == "args":
        f.name = "payload"

    return fields
253000
def update_from(self, res_list):
        
        for res in res_list:
            # We access the properties dictionary, in order to make sure
            # we don't drive additional HMC interactions.
            name = res.properties.get(self._manager._name_prop, None)
            uri = res.properties.get(self._manager._uri_prop, None)
            self.update(name, uri)
137014
def get_shard_id2num_examples(num_shards, total_num_examples):
  """"""
  # TODO(b/130353071): This has the strong assumption that the shards have
  # been written in a round-robin fashion. This assumption does not hold, for
  # instance, with Beam generation. The mapping shard_id=>num_examples
  # should be computed during generation.

  # Minimum number of example per shards
  num_example_in_shard = total_num_examples // num_shards
  shard_id2num_examples = [num_example_in_shard for _ in range(num_shards)]
  # If there are remaining examples, we add them to the first shards
  for shard_id in range(total_num_examples % num_shards):
    shard_id2num_examples[shard_id] += 1
  return shard_id2num_examples
61133
def _AddEqualsMethod(message_descriptor, cls):
  """"""
  def __eq__(self, other):
    if (not isinstance(other, message_mod.Message) or
        other.DESCRIPTOR != self.DESCRIPTOR):
      return False

    if self is other:
      return True

    if self.DESCRIPTOR.full_name == _AnyFullTypeName:
      any_a = _InternalUnpackAny(self)
      any_b = _InternalUnpackAny(other)
      if any_a and any_b:
        return any_a == any_b

    if not self.ListFields() == other.ListFields():
      return False

    # Sort unknown fields because their order shouldn't affect equality test.
    unknown_fields = list(self._unknown_fields)
    unknown_fields.sort()
    other_unknown_fields = list(other._unknown_fields)
    other_unknown_fields.sort()

    return unknown_fields == other_unknown_fields

  cls.__eq__ = __eq__
931534
def shard_key_selector
      selector = {}
      shard_key_fields.each do |field|
        selector[field.to_s] = new_record? ? send(field) : attribute_was(field)
      end
      selector
    end
607216
@Check
	public void checkFieldNameShadowing(SarlField field) {
		if (!isIgnored(VARIABLE_NAME_SHADOWING)
				&& !Utils.isHiddenMember(field.getName())) {
			final JvmField inferredField = this.associations.getJvmField(field);
			final Map<String, JvmField> inheritedFields = new TreeMap<>();
			Utils.populateInheritanceContext(
					inferredField.getDeclaringType(),
					null, null,
					inheritedFields,
					null, null,
					this.sarlActionSignatures);

			final JvmField inheritedField = inheritedFields.get(field.getName());
			if (inheritedField != null) {
				int nameIndex = 0;
				String newName = field.getName() + nameIndex;
				while (inheritedFields.containsKey(newName)) {
					++nameIndex;
					newName = field.getName() + nameIndex;
				}
				addIssue(MessageFormat.format(
						Messages.SARLValidator_42,
						field.getName(),
						inferredField.getDeclaringType().getQualifiedName(),
						inheritedField.getQualifiedName()),
						field,
						XTEND_FIELD__NAME,
						ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
						VARIABLE_NAME_SHADOWING,
						newName);
			}
		}
	}
598526
async def identify(self):
        """"""
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'discord.py',
                    '$device': 'discord.py',
                    '$referrer': '',
                    '$referring_domain': ''
                },
                'compress': True,
                'large_threshold': 250,
                'v': 3
            }
        }

        if not self._connection.is_bot:
            payload['d']['synced_guilds'] = []

        if self.shard_id is not None and self.shard_count is not None:
            payload['d']['shard'] = [self.shard_id, self.shard_count]

        state = self._connection
        if state._activity is not None or state._status is not None:
            payload['d']['presence'] = {
                'status': state._status,
                'game': state._activity,
                'since': 0,
                'afk': False
            }

        await self.send_as_json(payload)
        log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
1257072
def ensureHashIndex(self, fields, unique = False, sparse = True, deduplicate = False) :
        """"""
        data = {
            "type" : "hash",
            "fields" : fields,
            "unique" : unique,
            "sparse" : sparse,
            "deduplicate": deduplicate
        }
        ind = Index(self, creationData = data)
        self.indexes["hash"][ind.infos["id"]] = ind
        return ind