meta model subscriber on resource registration.

        We watch for PHD event that provides affected entities and register
        the health-event filter to the resources.
10260
def register_resources(klass, registry, resource_class):
        
        services = {'acm-certificate', 'directconnect', 'dms-instance', 'directory', 'ec2',
                    'dynamodb-table', 'cache-cluster', 'efs', 'app-elb', 'elb', 'emr', 'rds',
                    'storage-gateway'}
        if resource_class.type in services:
            resource_class.filter_registry.register('health-event', klass)
1282409
function register(metamodel) {
        var name, metaType;

        // Registering MetaTypes to global.meta
        for (name in metamodel) {
            if (metamodel.hasOwnProperty(name)) {
                metaType = metamodel[name];
                metaType.name = name;

                // Check duplicated MetaType
                if (_global.meta[name]) {
                    delete metamodel[name];
                    console.error("[MetaModelManager] MetaType '" + name + "' is already exists.");
                } else {
                    _global.meta[name] = metaType;
                }
            }
        }

        // Validate MetaTypes
        for (name in metamodel) {
            if (metamodel.hasOwnProperty(name)) {
                metaType = metamodel[name];
                try {
                    validateMetaType(name, metaType);
                } catch (err) {
                    console.error(err);
                }
            }
        }
    }
731949
def model_post_save(sender, instance, created=False, **kwargs):
    

    if sender._meta.app_label == 'rest_framework_reactive':
        # Ignore own events.
        return

    def notify():
        table = sender._meta.db_table
        if created:
            notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)
        else:
            notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)

    transaction.on_commit(notify)
599837
def subscribed(self, user):
        
        for who, record in self.logs:
            if (record["field_name"] == "cc" and
                    user.email in record["added"]):
                return True
        return False
1147287
def subscribe(self, event):
        """"""
        uuids = event.data

        if not isinstance(uuids, list):
            uuids = [uuids]

        subscribed = []
        for uuid in uuids:
            try:
                self._add_subscription(uuid, event)
                subscribed.append(uuid)
            except KeyError:
                continue

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'subscribe',
            'data': {
                'uuid': subscribed, 'success': True
            }
        }
        self._respond(None, result, event)
1175873
def query_metadata_agent_for_monitored_resource(local_resource_id)
      response = query_metadata_agent("monitoredResource/#{local_resource_id}")
      return nil if response.nil?
      begin
        resource = Google::Api::MonitoredResource.decode_json(response.to_json)
      rescue Google::Protobuf::ParseError, ArgumentError => e
        @log.error 'Error parsing monitored resource from Metadata Agent. ' \
                   "response: #{response.inspect}", error: e
        return nil
      end

      # TODO(qingling128): Use Google::Api::MonitoredResource directly after we
      # upgrade gRPC version to include the fix for the protobuf map
      # corruption issue.
      Google::Apis::LoggingV2::MonitoredResource.new(
        type: resource.type,
        labels: resource.labels.to_h
      )
    end
994456
function(clazz, metaData) {
        this.applyEvents(clazz, metaData.clazz_events || {});
        this.applyEvents(clazz.prototype, metaData.events || {});
    }
649466
private <T> void manageSubscription(EventStream<T> stream, Consumer<T> consumer) {
        manageSubscription(stream.subscribe(consumer));
    }
875309
def subscribe_to_events(config, subscriber, events, model=None):
    
    kwargs = {}
    if model is not None:
        kwargs['model'] = model

    for evt in events:
        config.add_subscriber(subscriber, evt, **kwargs)
323381
function subscribeToEvents() {
    const socket = _socket.get(this);

    function onEventApiError(error) {
        dbg('Event API connection error: ' + JSON.stringify(error));
    }

    socket.on('pong', (latency) => {
        dbg(`Event API latency: ${latency} ms`);
    });
    socket.on('connect_error', onEventApiError);
    socket.on('error', onEventApiError);
    socket.on('disconnect', onEventApiError);
    socket.on('reconnect_error', onEventApiError);
    socket.on('reconnect_failed', () => {
        onEventApiError('Reconnecting to the Event API failed');
    });

    socket.on('new_receipt', receiptJSON => {
        const receipt = Receipt.from(receiptJSON, _provider.get(this));
        _eventEmitter.get(this).emit(EventNames.newReceipt, receipt);
    });
}
750462
def register_observer(self, observer, events=None):
        
        if events is not None and not isinstance(events, (tuple, list)):
            events = (events,)

        if observer in self._observers:
            LOG.warning("Observer '%r' already registered, overwriting for events"
                        " %r", observer, events)
        self._observers[observer] = events
728923
function subscribe() {
    // starts to receive values after device regsiters
    connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] })
        .addListener((res) => logData(res, "OnRegistration"))
        .addLocalFilter(res => res.payload >= 20);

    // starts to reveive values immediatley
    connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] }, "OnValueUpdate")
        .addListener((res) => logData(res, "OnValueUpdate"));
}
106134
def register_entity(self, entity_config):
        
        if not issubclass(entity_config, EntityConfig):
            raise ValueError('Must register entity config class of subclass EntityConfig')

        if entity_config.queryset is None:
            raise ValueError('Entity config must define queryset')

        model = entity_config.queryset.model

        self._entity_registry[model] = entity_config()

        # Add watchers to the global look up table
        for watching_model, entity_model_getter in entity_config.watching:
            self._entity_watching[watching_model].append((model, entity_model_getter))
1327915
def subscribe(self, session_id, dependencies=None):
        
        try:
            change_detection = self._meta.change_detection
            if change_detection not in [
                Options.CHANGE_DETECTION_PUSH,
                Options.CHANGE_DETECTION_POLL,
            ]:
                raise NotImplementedError(
                    "Change detection mechanism '{}' not implemented.".format(
                        change_detection
                    )
                )

            viewset_results = self._viewset_results()

            poll_interval = (
                self._meta.poll_interval
                if change_detection == Options.CHANGE_DETECTION_POLL
                else None
            )

            # Subscribe to observer in a single query. First, create an
            # observer, then create a subscriber, and finally subscribe to
            # the observer. If already subscribed, ignore the conflict.
            for retry in range(MAX_INTEGRITY_ERROR_RETRIES):
                is_subscribed = False
                cursor = connection.cursor()
                try:
                    cursor.execute(
                        """
                        WITH inserted_observer AS (
                            INSERT into {observer_table} ("id", "request", "poll_interval")
                            VALUES (%(observer_id)s, %(request)s, %(poll_interval)s)
                            ON CONFLICT DO NOTHING
                        ), inserted_subscriber AS (
                            INSERT into {subscriber_table} ("session_id", "created")
                            VALUES (%(subscriber_id)s, NOW())
                            ON CONFLICT DO NOTHING
                        )
                        INSERT INTO {observer_subscribers_table} ("observer_id", "subscriber_id")
                        VALUES (%(observer_id)s, %(subscriber_id)s)
                        """.format(
                            observer_table=models.Observer._meta.db_table,
                            subscriber_table=models.Subscriber._meta.db_table,
                            observer_subscribers_table=models.Observer.subscribers.through._meta.db_table,
                        ),
                        params={
                            'observer_id': self.id,
                            'request': pickle.dumps(self._request),
                            'poll_interval': poll_interval,
                            'subscriber_id': session_id,
                        },
                    )
                    is_subscribed = True
                except IntegrityError as err:
                    msg = str(err)
                    if (
                        'Key (observer_id, subscriber_id)' in msg
                        and 'already exists' in msg
                    ):
                        # Subscriber already subscribed, we're good.
                        is_subscribed = True
                    elif (
                        'Key (observer_id)' in msg or 'Key (subscriber_id)' in msg
                    ) and 'not present in table' in msg:
                        # Could not subscribe because observer, subscriber or
                        # both are missing, retry.
                        if retry == MAX_INTEGRITY_ERROR_RETRIES - 1:
                            raise
                    else:
                        raise
                finally:
                    cursor.close()

                if is_subscribed:
                    break

            # Determine who should notify us based on the configured change
            # detection mechanism.
            if change_detection == Options.CHANGE_DETECTION_PUSH:
                if dependencies:
                    tables = [model._meta.db_table for model in dependencies]
                else:
                    tables = [self._viewset.get_queryset().model._meta.db_table]

                # Register table dependencies for push observables.
                for table in tables:
                    try:
                        models.Dependency.objects.get_or_create(
                            observer_id=self.id, table=table
                        )
                    except models.Observer.DoesNotExist:
                        # The observer was removed before dependency tables
                        # were created.
                        return viewset_results

            elif self._meta.change_detection == Options.CHANGE_DETECTION_POLL:
                # Register poller.
                async_to_sync(get_channel_layer().send)(
                    CHANNEL_MAIN,
                    {
                        'type': TYPE_POLL,
                        'observer': self.id,
                        'interval': self._meta.poll_interval,
                    },
                )

            self._evaluate(viewset_results)

        except Exception:
            logger.exception(
                "Error while subscribing to observer ({})".format(
                    self._get_logging_id()
                ),
                extra=self._get_logging_extra(),
            )

        return viewset_results
125769
def register(self, resource_name, dependent=None):
        '''
        
        '''
        if dependent is None:
            # Give a partial usable as a decorator
            return partial(self.register, resource_name)

        dependent = self._unwrap_dependent(dependent)
        self._register_dependent(dependent, resource_name)
        self._register_resource_dependency(resource_name, dependent)

        # Return dependent to ease use as decorator
        return dependent
26993
async function registerMrHorse(server, logger, config) {
  const Log = logger.bind('register-MrHorse')

  let policyPath = ''

  if (config.enablePolicies) {
    if (config.absolutePolicyPath === true) {
      policyPath = config.policyPath
    } else {
      policyPath = __dirname.replace(
        'node_modules/rest-hapi',
        config.policyPath
      )
    }
  } else {
    policyPath = path.join(__dirname, '/policies')
  }
  await server.register([
    {
      plugin: Mrhorse,
      options: {
        policyDirectory: policyPath
      }
    }
  ])

  if (config.enablePolicies) {
    await server.plugins.mrhorse.loadPolicies(server, {
      policyDirectory: path.join(__dirname, '/policies')
    })
  }

  Log.info('MrHorse plugin registered')
}
435859
def subscribe_to_human_connection_events(
        self,
        subscriber: Callable[[events.HumanConnectionEvent], None],
    ) -> None:
        
        self._human_connection_subscribers.append(subscriber)