Create an event with a message describing the replication
            state of a mongo node
425081
def create_event(self, state, server, agentConfig):
        """"""

        def get_state_description(state):
            if state == 0:
                return 'Starting Up'
            elif state == 1:
                return 'Primary'
            elif state == 2:
                return 'Secondary'
            elif state == 3:
                return 'Recovering'
            elif state == 4:
                return 'Fatal'
            elif state == 5:
                return 'Starting up (initial sync)'
            elif state == 6:
                return 'Unknown'
            elif state == 7:
                return 'Arbiter'
            elif state == 8:
                return 'Down'
            elif state == 9:
                return 'Rollback'

        status = get_state_description(state)
        msg_title = "%s is %s" % (server, status)
        msg = "TokuMX %s just reported as %s" % (server, status)

        self.event(
            {
                'timestamp': int(time.time()),
                'event_type': 'tokumx',
                'msg_title': msg_title,
                'msg_text': msg,
                'host': self.hostname,
            }
        )
822056
def to_event(self):
        
        msg = copy.deepcopy(self)
        for _ in ["id", "sign", "tunnel", "query", "param"]:
            if not hasattr(msg, _):
                continue
            delattr(msg, _)

        msg._type = Message.get_message_type(msg.__dict__)

        return msg
1098702
def event_callback(self, event_data):
        '''
        
        '''
        self.last_stdout_update = time.time()
        job_events_path = os.path.join(self.config.artifact_dir, 'job_events')
        if not os.path.exists(job_events_path):
            os.mkdir(job_events_path, 0o700)
        if 'uuid' in event_data:
            filename = '{}-partial.json'.format(event_data['uuid'])
            partial_filename = os.path.join(self.config.artifact_dir,
                                            'job_events',
                                            filename)
            full_filename = os.path.join(self.config.artifact_dir,
                                         'job_events',
                                         '{}-{}.json'.format(event_data['counter'],
                                                             event_data['uuid']))
            try:
                event_data.update(dict(runner_ident=str(self.config.ident)))
                try:
                    with codecs.open(partial_filename, 'r', encoding='utf-8') as read_file:
                        partial_event_data = json.load(read_file)
                    event_data.update(partial_event_data)
                    if self.remove_partials:
                        os.remove(partial_filename)
                except IOError:
                    debug("Failed to open ansible stdout callback plugin partial data file {}".format(partial_filename))
                if self.event_handler is not None:
                    should_write = self.event_handler(event_data)
                else:
                    should_write = True
                for plugin in ansible_runner.plugins:
                    ansible_runner.plugins[plugin].event_handler(self.config, event_data)
                if should_write:
                    with codecs.open(full_filename, 'w', encoding='utf-8') as write_file:
                        os.chmod(full_filename, stat.S_IRUSR | stat.S_IWUSR)
                        json.dump(event_data, write_file)
            except IOError as e:
                debug("Failed writing event data: {}".format(e))
775009
def start
      @nodes.each(&:start)
      @worker = Thread.start do
        Thread.abort_on_exception = true
        catch(:shutdown) do
          loop do
            Moped.logger.debug "replica_set: waiting for next client"
            server, client = @manager.next_client

            if server
              Moped.logger.debug "replica_set: proxying incoming request to mongo"
              server.proxy(client, @mongo)
            else
              Moped.logger.debug "replica_set: no requests; passing"
              Thread.pass
            end
          end
        end
      end
    end
78141
async def persist_event(topic, event, pool):
    
    # Event to json
    json_event = json.dumps(event.__dict__)

    # Connect to database or create and connect if non existent
    conn = await pool.acquire()

    # Insert event if not processed
    try:
        query = """
            CREATE TABLE IF NOT EXISTS public."topic_placeholder"
            (
              id SERIAL PRIMARY KEY,
              event json NOT NULL,
              issued_at timestamp without time zone NOT NULL
            )
            WITH (
              OIDS=FALSE
            );
            ALTER TABLE public."topic_placeholder"
              OWNER TO root;
        """
        query = query.replace('topic_placeholder', topic)
        await conn.execute(query)
        issued_at = datetime.utcnow()
        query = 'INSERT INTO "%s" (event, issued_at) VALUES ($1, $2)' % topic
        await conn.execute(query, json_event, issued_at)
    finally:
        await pool.release(conn)
46505
def _create_dd_event(self, events, image, c_tags, priority='Normal'):
        """"""
        if not events:
            return

        max_timestamp = 0
        status = defaultdict(int)
        status_change = []

        for ev, c_name in events:
            max_timestamp = max(max_timestamp, int(ev['time']))
            status[ev['status']] += 1
            status_change.append([c_name, ev['status']])

        status_text = ", ".join(["%d %s" % (count, st) for st, count in status.iteritems()])
        msg_title = "%s %s on %s" % (image, status_text, self.hostname)
        msg_body = (
            "%%%\n"
            "{image_name} {status} on {hostname}\n"
            "```\n{status_changes}\n```\n"
            "%%%"
        ).format(
            image_name=image,
            status=status_text,
            hostname=self.hostname,
            status_changes="\n".join(
                ["%s \t%s" % (change[1].upper(), change[0]) for change in status_change])
        )

        if any(error in status_text for error in ERROR_ALERT_TYPE):
            alert_type = "error"
        else:
            alert_type = None

        return {
            'timestamp': max_timestamp,
            'host': self.hostname,
            'event_type': EVENT_TYPE,
            'msg_title': msg_title,
            'msg_text': msg_body,
            'source_type_name': EVENT_TYPE,
            'event_object': 'docker:%s' % image,
            'tags': list(c_tags),
            'alert_type': alert_type,
            'priority': priority
        }
450510
def getEvents(self, repo_user, repo_name, until_id=None):
        """"""
        done = False
        page = 0
        events = []
        while not done:
            new_events = yield self.api.makeRequest(
                    ['repos', repo_user, repo_name, 'events'],
                    page)

            # terminate if we find a matching ID
            if new_events:
                for event in new_events:
                    if event['id'] == until_id:
                        done = True
                        break
                    events.append(event)
            else:
                done = True

            page += 1
        defer.returnValue(events)
64456
async def emit_event(self, event):
        
        self.log.info("publishing event on %s", self.publish_topic)
        if self.config.extra['config']['pub_options']['retain']:
            try:
                await persist_event(
                    self.publish_topic,
                    event,
                    self.pool
                )
            except SystemError as error:
                self.log.error(error)
                return

        loop = asyncio.get_event_loop()
        producer = AIOKafkaProducer(
            loop=loop,
            bootstrap_servers=self.transport_host
        )
        await producer.start()

        try:
            event = json.dumps(event.__dict__).encode()
            await producer.send_and_wait(
                self.publish_topic,
                event
            )
        finally:
            await producer.stop()
701519
function createWatchEvent(type, record, event) {
    const payload = Object.assign({ type, key: record.id, modelName: record.modelName, pluralName: record.pluralName, modelConstructor: record.modelConstructor, dynamicPathProperties: record.dynamicPathComponents, compositeKey: record.compositeKey, dbPath: record.dbPath, localPath: record.localPath || "", localPostfix: record.META.localPostfix }, event);
    return payload;
}
54721
function(req, res, fromMessage) {
            var name = req.params.name;
            var doc  = req.body;
            var id   = this.toId(req.params.id || doc._id);
            if (typeof id === 'undefined' || id === '') {
                return res.send(400, "invalid id.");
            }
            doc._id   = id;
            doc._time = new Date().getTime();
            var collection = new mongodb.Collection(this.db, name);
            collection.update(
                { "_id" : id },
                doc,
                { safe:true, upsert:true },
                function(err, n) {
                    if(err) {
                        res.send("Oops!: " + err);
                    } else {
                        if (n==0) {
                            res.send(404, 'Document not found!');
                        } else {
                            var msg = {
                                method: 'update',
                                id: doc._id,
                                time: doc._time,
                                data: doc
                            };
                            rest.onSuccess(name, msg, fromMessage);
                            res.send(doc);
                        }
                    }
                }
            );
        }
150214
def _create_event():
    
    return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None)
1231867
def execute_op_msg_no_results(self, sock_info, generator):
        
        db_name = self.collection.database.name
        client = self.collection.database.client
        listeners = client._event_listeners
        op_id = _randint()

        if not self.current_run:
            self.current_run = next(generator)
        run = self.current_run

        while run:
            cmd = SON([(_COMMANDS[run.op_type], self.collection.name),
                       ('ordered', False),
                       ('writeConcern', {'w': 0})])
            bwc = _BulkWriteContext(db_name, cmd, sock_info, op_id,
                                    listeners, None)

            while run.idx_offset < len(run.ops):
                check_keys = run.op_type == _INSERT
                ops = islice(run.ops, run.idx_offset, None)
                # Run as many ops as possible.
                request_id, msg, to_send = _do_bulk_write_command(
                    self.namespace, run.op_type, cmd, ops, check_keys,
                    self.collection.codec_options, bwc)
                if not to_send:
                    raise InvalidOperation("cannot do an empty bulk write")
                run.idx_offset += len(to_send)
                # Though this isn't strictly a "legacy" write, the helper
                # handles publishing commands and sending our message
                # without receiving a result. Send 0 for max_doc_size
                # to disable size checking. Size checking is handled while
                # the documents are encoded to BSON.
                bwc.legacy_write(request_id, msg, 0, False, to_send)
            self.current_run = run = next(generator, None)
1361896
def create_event(msg: EventMsgDict) -> Event:
    
    proto = msg.get('proto', '')
    cls = proto_dict.get(proto, Event)
    e = cls(msg['type'], msg)
    return e
1336431
def _create_event(self, event_state, event_type, event_value,
                      proc_list, proc_desc, peak_time):
        
        if event_state == "WARNING" or event_state == "CRITICAL":
            # Define the automatic process sort key
            self.set_process_sort(event_type)

            # Create the new log item
            # Time is stored in Epoch format
            # Epoch -> DMYHMS = datetime.fromtimestamp(epoch)
            item = [
                time.mktime(datetime.now().timetuple()),  # START DATE
                -1,  # END DATE
                event_state,  # STATE: WARNING|CRITICAL
                event_type,  # TYPE: CPU, LOAD, MEM...
                event_value,  # MAX
                event_value,  # AVG
                event_value,  # MIN
                event_value,  # SUM
                1,  # COUNT
                [],  # TOP 3 PROCESS LIST
                proc_desc,  # MONITORED PROCESSES DESC
                glances_processes.sort_key]  # TOP PROCESS SORTKEY

            # Add the item to the list
            self.events_list.insert(0, item)

            # Limit the list to 'events_max' items
            if self.len() > self.events_max:
                self.events_list.pop()

            return True
        else:
            return False
1305090
private void replicateInstanceActionsToPeers(Action action, String appName,
                                                 String id, InstanceInfo info, InstanceStatus newStatus,
                                                 PeerEurekaNode node) {
        try {
            InstanceInfo infoFromRegistry = null;
            CurrentRequestVersion.set(Version.V2);
            switch (action) {
                case Cancel:
                    node.cancel(appName, id);
                    break;
                case Heartbeat:
                    InstanceStatus overriddenStatus = overriddenInstanceStatusMap.get(id);
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.heartbeat(appName, id, infoFromRegistry, overriddenStatus, false);
                    break;
                case Register:
                    node.register(info);
                    break;
                case StatusUpdate:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.statusUpdate(appName, id, newStatus, infoFromRegistry);
                    break;
                case DeleteStatusOverride:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.deleteStatusOverride(appName, id, infoFromRegistry);
                    break;
            }
        } catch (Throwable t) {
            logger.error("Cannot replicate information to {} for action {}", node.getServiceUrl(), action.name(), t);
        }
    }
764666
function replayEvents(mongoClient, events) {
  for (let i = 0; i < events.length; i++) {
    mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
  }
}
239149
function push (state, docsOrIds) {
  var pushedObjects = []
  var errors = state.db.constructor.Errors

  return Promise.resolve(state.remote)

  .then(function (remote) {
    return new Promise(function (resolve, reject) {
      if (Array.isArray(docsOrIds)) {
        docsOrIds = docsOrIds.map(toId)
      } else {
        docsOrIds = docsOrIds && [toId(docsOrIds)]
      }

      if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) {
        return Promise.reject(errors.NOT_AN_OBJECT)
      }

      var replication = state.db.replicate.to(remote, {
        create_target: true,
        doc_ids: docsOrIds,
        include_docs: true
      })

      /* istanbul ignore next */
      replication.catch(function () {
        // handled trough 'error' event
      })

      replication.on('complete', function () {
        resolve(pushedObjects)
      })
      replication.on('error', reject)
      replication.on('change', function (change) {
        pushedObjects = pushedObjects.concat(change.docs)

        for (var i = 0; i < change.docs.length; i++) {
          state.emitter.emit('push', change.docs[i])
        }
      })
    })
  })
}