Supports converting internal TaskData and WorkerData, as well as
        celery Task and Worker to proto buffers messages.

        Args:
            event (Union[TaskData|Task|WorkerData|Worker]):

        Returns:
            ProtoBuf object
768743
def _event_to_pb(event):
        
        if isinstance(event, (TaskData, Task)):
            key, klass = 'task', clearly_pb2.TaskMessage
        elif isinstance(event, (WorkerData, Worker)):
            key, klass = 'worker', clearly_pb2.WorkerMessage
        else:
            raise ValueError('unknown event')
        keys = klass.DESCRIPTOR.fields_by_name.keys()
        # noinspection PyProtectedMember
        data = {k: v for k, v in
                getattr(event, '_asdict',  # internal TaskData and WorkerData
                        lambda: {f: getattr(event, f) for f in event._fields})  # celery Task and Worker
                ().items() if k in keys}
        return key, klass(**data)
402385
def wrap_iter_with_message_events(
    request_or_response_iter,
    span,
    message_event_type
):
    
    for message_id, message in enumerate(request_or_response_iter, start=1):
        add_message_event(
            proto_message=message,
            span=span,
            message_event_type=message_event_type,
            message_id=message_id
        )
        yield message
1061526
def PushEvent(self, event):
    
    event_string = event.GetAttributeValuesString()
    heap_values = (event.timestamp, event.timestamp_desc, event_string, event)
    heapq.heappush(self._heap, heap_values)
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
790909
function(event) {
      // Usually, this method will be called while iterating over a list of
      // events sorted by start time, so this method won't usually change
      // this.start. However, this will sometimes be called for ProtoIRs created
      // by previous handlers, in which case event.start could possibly be
      // before this.start.
      this.start = Math.min(this.start, event.start);
      this.end = Math.max(this.end, event.end);
      this.associatedEvents.push(event);
    }
459176
def PopEvent(self):
    
    try:
      _, _, _, event = heapq.heappop(self._heap)
      return event

    except IndexError:
      return 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
20312
def send(self, event):
        # type(Event) -> bytes
        
        data = b""
        if isinstance(event, Request):
            data += self._initiate_connection(event)
        elif isinstance(event, AcceptConnection):
            data += self._accept(event)
        elif isinstance(event, RejectConnection):
            data += self._reject(event)
        elif isinstance(event, RejectData):
            data += self._send_reject_data(event)
        else:
            raise LocalProtocolError(
                "Event {} cannot be sent during the handshake".format(event)
            )
        return data
441154
def to_protobuf(self):
        """"""
        self._validate()
        kwargs = {k: _convert(getattr(self, k), 'to_protobuf')
                  for k in self._get_params()}
        return self._protobuf_cls(**kwargs)
1122397
def gevent_worker(self):
        
        while not self.task_queue.empty():
            task_kwargs = self.task_queue.get()
            handler_type = task_kwargs.pop('handler_type')

            if handler_type == 'link':
                super(Command, self).link_file(**task_kwargs)
            else:
                super(Command, self).copy_file(**task_kwargs)
411937
private void insertOrUpdateTasks(TaskStartEvent event) {
        Assignment old = event.getOldAssignment();
        Assignment current = event.getNewAssignment();

        Map<Integer, String> task2Component = event.getTask2Component();
        List<KVSerializable> taskTrackList = new ArrayList<>();

        // assign
        if (old == null) {
            Set<ResourceWorkerSlot> workers = current.getWorkers();
            logger.info("old workers are null, assigned workers:{}", Joiner.on(",").join(workers));
            for (ResourceWorkerSlot worker : workers) {
                Set<Integer> tasks = worker.getTasks();
                for (Integer task : tasks) {
                    TaskTrack track = new TaskTrack(
                            event.getClusterMetricsContext().getClusterName(), event.getTopologyId());
                    track.setStart(new Date(event.getTimestamp()));
                    track.setComponent(task2Component.get(task));
                    track.setHost(worker.getHostname());
                    track.setPort(worker.getPort());
                    track.setTaskId(task);

                    taskTrackList.add(track);
                }
            }
        } else { // rebalance, we only insert newly assigned tasks
            Set<ResourceWorkerSlot> oldWorkers = old.getWorkers();
            Joiner joiner = Joiner.on(",");
            logger.info("old workers:{}, new workers:{}", joiner.join(oldWorkers), joiner.join(current.getWorkers()));
            for (ResourceWorkerSlot worker : current.getWorkers()) {
                // a new worker, insert all tasks
                if (!oldWorkers.contains(worker)) {
                    for (Integer task : worker.getTasks()) {
                        TaskTrack track = new TaskTrack(
                                event.getClusterMetricsContext().getClusterName(),
                                event.getTopologyId());
                        track.setStart(new Date(event.getTimestamp()));
                        track.setComponent(task2Component.get(task));
                        track.setHost(worker.getHostname());
                        track.setPort(worker.getPort());
                        track.setTaskId(task);

                        taskTrackList.add(track);
                    }
                } else {
                    for (Integer task : worker.getTasks()) {
                        ResourceWorkerSlot oldWorker = old.getWorkerByTaskId(task);
                        if (oldWorker != null) {

                            // update end time of old task
                            TaskTrack oldTrack = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            oldTrack.setEnd(new Date(event.getTimestamp()));
                            oldTrack.setTaskId(task);
                            oldTrack.setHost(oldWorker.getHostname());
                            oldTrack.setPort(oldWorker.getPort());
                            taskTrackList.add(oldTrack);

                            // insert new task
                            TaskTrack track = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            track.setStart(new Date());
                            track.setComponent(task2Component.get(task));
                            track.setHost(worker.getHostname());
                            track.setPort(worker.getPort());
                            track.setTaskId(task);
                            taskTrackList.add(track);
                        }
                    }
                }
            }
        }
        if (taskTrackList.size() > 0) {
            batchAdd(taskTrackList, TABLE_TASK_TRACK);
        }
    }
1266989
def publish_event(self, channel, event, message):
        '''
        '''
        assert self.protocol is not None, "Protocol required"
        msg = {'event': event, 'channel': channel}
        if message:
            msg['data'] = message
        return self.publish(channel, msg)
343712
def send_events(self, events):
        
        message = riemann_client.riemann_pb2.Msg()
        for event in events:
            message.events.add().MergeFrom(event)
        return self.transport.send(message)
1025994
def process_event(self, event_id):
    """"""
    with db.session.begin_nested():
        event = Event.query.get(event_id)
        event._celery_task = self  # internal binding to a Celery task
        event.receiver.run(event)  # call run directly to avoid circular calls
        flag_modified(event, 'response')
        flag_modified(event, 'response_headers')
        db.session.add(event)
    db.session.commit()
705611
def create_event(data):
        
        event = riemann_client.riemann_pb2.Event()
        event.host = socket.gethostname()
        event.tags.extend(data.pop('tags', []))

        for key, value in data.pop('attributes', {}).items():
            attribute = event.attributes.add()
            attribute.key, attribute.value = key, value

        for name, value in data.items():
            if value is not None:
                setattr(event, name, value)
        return event
1110959
def processEvents(self, data):
        
        objc = self.objc
        bridge = self.bridge
        #: This must come after the above as it changes the arguments!
        objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
                                      ctypes.c_char_p, ctypes.c_int]
        objc.objc_msgSend(
            bridge, objc.sel_registerName('processEvents:length:'),
            data, len(data))
745223
def capture(self, *args, **kwargs):
        
        if not self.is_enabled():
            return

        data = self.build_msg(*args, **kwargs)

        future = self.send(callback=kwargs.get('callback', None), **data)

        return (data['event_id'], future)