Specify the data sent to Intercom API according to event type
558971
def get_intercom_data(self):
        """"""
        data = {
            "event_name": self.get_type_display(),  # event type
            "created_at": calendar.timegm(self.created.utctimetuple()),  # date
            "metadata": self.metadata
        }
        if self.user:
            data["user_id"] = self.user.intercom_id
        return data
1268855
def write_event(self, event):
        """"""
        # Check if event is of type event_pb2.Event proto.
        if not isinstance(event, event_pb2.Event):
            raise TypeError("expected an event_pb2.Event proto, "
                            " but got %s" % type(event))
        return self._write_serialized_event(event.SerializeToString())
300451
def event_trigger(self, event_type):
        """"""
        def callback(**kwargs):
            self.queued_events.append(event_type(**kwargs))
        return callback
479583
def emit_event(project_slug, action_slug):
    

    if request.headers.get('Content-Type') == 'application/json':
        payload = request.get_json()
    elif request.method == 'POST':
        payload = request.form.to_dict()
    else:
        payload = request.args.to_dict()

    if not request.authorization:
        return jsonify({'message': 'unauthorized'}), 401

    sender_name = request.authorization.username
    sender_secret = request.authorization.password

    event_uuid = request.headers.get('X-Rio-Event-UUID') or \
           request.headers.get('X-B3-TraceId')

    data = _emit_event(project_slug, action_slug, payload, sender_name, sender_secret,
                       event_uuid=event_uuid)
    data['message'] = 'ok'

    event_received.send(None, project_slug=project_slug, data=data)

    return jsonify(data)
945465
def emit(event, data = {}, channel = nil)
      message = { event: event, data: MultiJson.dump(data) }
      message[:channel] = channel if channel

      PusherFake.log("SEND #{id}: #{message}")

      socket.send(MultiJson.dump(message))
    end
662749
def get_event(id, opts = {})
      data, _status_code, _headers = get_event_with_http_info(id, opts)
      return data
    end
828499
def push_intercom_event_task(obj_id):
    
    lock_id = "%s-push-intercom_event-%s" % (settings.ENV_PREFIX, obj_id)
    acquire_lock = lambda: cache.add(lock_id, "true", LOCK_EXPIRE)  # noqa: E731
    release_lock = lambda: cache.delete(lock_id)  # noqa: E731

    if acquire_lock():
        from aa_intercom.models import IntercomEvent
        try:
            instance = IntercomEvent.objects.get(pk=obj_id)
            if instance.is_sent:
                return

            data = instance.get_intercom_data()
            try:
                if instance.user:
                    upload_intercom_user(instance.user.pk)
                else:
                    upload_not_registered_user_data({"email": data["metadata"]["email"]})
                if not getattr(settings, "SKIP_INTERCOM", False):
                    intercom.events.create(**data)
                    IntercomEvent.objects.filter(pk=obj_id).update(
                        is_sent=True
                    )
            except IntercomError:
                IntercomEvent.objects.filter(pk=obj_id).update(
                    is_sent=False
                )
                release_lock()
                raise  # FIXME - to check when errror happens

        except IntercomEvent.DoesNotExist:
            release_lock()
            raise
        release_lock()
1069149
def process_event(message_id, event_type, event_detail, timestamp):
    
    # Load message
    try:
        message = Outbound.objects.select_related("channel").get(
            vumi_message_id=message_id
        )
    except ObjectDoesNotExist:
        return (False, "Cannot find message for ID {}".format(message_id))

    if event_type == "ack":
        message.delivered = True
        message.to_addr = ""
        message.metadata["ack_timestamp"] = timestamp
        message.metadata["ack_reason"] = event_detail
        message.save(update_fields=["delivered", "to_addr", "metadata"])
    elif event_type == "nack":
        message.metadata["nack_timestamp"] = timestamp
        message.metadata["nack_reason"] = event_detail
        message.save(update_fields=["metadata"])

        decr_message_count(message)

        send_message.delay(str(message.id))
    elif event_type == "delivery_succeeded":
        message.delivered = True
        message.to_addr = ""
        message.metadata["delivery_timestamp"] = timestamp
        message.metadata["delivery_reason"] = event_detail
        message.save(update_fields=["delivered", "metadata", "to_addr"])
    elif event_type == "delivery_failed":
        message.metadata["delivery_failed_reason"] = event_detail
        message.metadata["delivery_failed_timestamp"] = timestamp
        message.save(update_fields=["metadata"])

        decr_message_count(message)

        send_message.delay(str(message.id))
    elif event_type == "read":
        message.delivered = True
        message.to_addr = ""
        message.metadata["read_timestamp"] = timestamp
        message.save(update_fields=["delivered", "to_addr", "metadata"])

    outbound_event_total.labels(event_type, message.channel_id).inc()
    fire_delivery_hook(message)

    return (True, "Event processed")
638609
function sendTypingStatus() {
    if (currentDialog.type == 3) {
        QB.chat.sendIsTypingStatus(opponentId);
    } else if (currentDialog && currentDialog.xmpp_room_jid) {
        QB.chat.sendIsTypingStatus(currentDialog.xmpp_room_jid);
    }
}
302357
def handle_event(self, event):
        """"""
        string = '{id:<32} '
        if 'command' in event:
            string += '{command}'
        elif 'version' in event:
            if 'hardware' in event:
                string += '{hardware} {firmware} '
            string += 'V{version} R{revision}'
        else:
            string += '{value}'
            if event.get('unit'):
                string += ' {unit}'

        print(string.format(**event))
117756
public void onMessageEvent(javax.sip.RequestEvent event,
			ActivityContextInterface aci) {

		final Request request = event.getRequest();
		try {
			// message body should be *FIRST_TOKEN<timer value in
			// seconds>MIDDLE_TOKEN<msg to send back to UA>LAST_TOKEN*
			final String body = new String(request.getRawContent());
			final int firstTokenStart = body.indexOf(FIRST_TOKEN);
			final int timerDurationStart = firstTokenStart + FIRST_TOKEN_LENGTH;
			final int middleTokenStart = body.indexOf(MIDDLE_TOKEN,
					timerDurationStart);
			final int bodyMessageStart = middleTokenStart + MIDDLE_TOKEN_LENGTH;
			final int lastTokenStart = body.indexOf(LAST_TOKEN,
					bodyMessageStart);
			if (firstTokenStart > -1 && middleTokenStart > -1
					&& lastTokenStart > -1) {
				// extract the timer duration
				final int timerDuration = Integer.parseInt(body.substring(
						timerDurationStart, middleTokenStart));
				// create a null AC and attach the sbb local object
				final ActivityContextInterface timerACI = this.nullACIFactory
						.getActivityContextInterface(this.nullActivityFactory
								.createNullActivity());
				timerACI.attach(sbbContext.getSbbLocalObject());
				// set the timer on the null AC, because the one from this event
				// will end as soon as we send back the 200 ok
				this.timerFacility.setTimer(timerACI, null, System
						.currentTimeMillis()
						+ (timerDuration * 1000), new TimerOptions());
				// extract the body message
				final String bodyMessage = body.substring(bodyMessageStart,
						lastTokenStart);
				// store it in a cmp field
				setBody(bodyMessage);
				// do the same for the call id
				setCallId((CallIdHeader) request.getHeader(CallIdHeader.NAME));
				// also store the sender's address, so we can send the wake up
				// message
				final FromHeader fromHeader = (FromHeader) request
						.getHeader(FromHeader.NAME);
				if (tracer.isInfoEnabled()) {
					tracer.info("Received a valid message from "
							+ fromHeader.getAddress()
							+ " requesting a reply containing '" + bodyMessage
							+ "' after " + timerDuration + "s");
				}
				setSender(fromHeader.getAddress());
				// finally reply to the SIP message request
				sendResponse(event, Response.OK);
			} else {
				// parsing failed
				tracer.warning("Invalid msg '" + body + "' received");
				sendResponse(event, Response.BAD_REQUEST);
			}
		} catch (Throwable e) {
			// oh oh something wrong happened
			tracer.severe("Exception while processing MESSAGE", e);
			try {
				sendResponse(event, Response.SERVER_INTERNAL_ERROR);
			} catch (Exception f) {
				tracer.severe("Exception while sending SERVER INTERNAL ERROR",
						f);
			}
		}
	}
37022
function(params) {
        var data = {
          type: params.type
        };

        if (params.trackerId) {
          data.trackerId = params.trackerId;
        }

        sendPingTimeout && clearTimeout(sendPingTimeout);
        sendPingTimeout = setTimeout(function() {
          ping();
        }, connectionCheckTimeout);

        try {
          if (params.content) {
            data.content = JSON.stringify(params.content);
          }

          if (socket.readyState === 1) {
            socket.send(JSON.stringify(data));
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4004,
            errorMessage: "Error in Socket sendData!",
            errorEvent: error
          });
        }
      }
510111
def create_event_handler(event_type, handler):
    """"""

    target_name = '{hash}_{event_type}'.format(hash=hash(handler), event_type=event_type)

    def handle_comm_opened(comm, msg):
        @comm.on_msg
        def _handle_msg(msg):
            data = msg['content']['data']
            event = json.loads(data)
            return_value = handler(event)
            if return_value:
                comm.send(return_value)

        comm.send('Comm target "{target_name}" registered by vdom'.format(target_name=target_name))

    # Register a new comm for this event handler
    if get_ipython():
        get_ipython().kernel.comm_manager.register_target(target_name, handle_comm_opened)

    # Return a serialized object
    return target_name
359582
def trigger(self, event_name, data):
        
        if self.connection:
            if event_name.startswith("client-"):
                if self.name.startswith("private-") or self.name.startswith("presence-"):
                    self.connection.send_event(event_name, data, channel_name=self.name)
987356
def type(self):
        """"""
        return ffi.string(lib.EnvGetDefmessageHandlerType(
            self._env, self._cls, self._idx)).decode()
1148432
function(event) {
    var meta = _clientMeta[this.id];
    if (!(typeof event === "object" && event && event.type && meta)) {
      return;
    }
    var async = _shouldPerformAsync(event);
    var wildcardTypeHandlers = meta && meta.handlers["*"] || [];
    var specificTypeHandlers = meta && meta.handlers[event.type] || [];
    var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
    if (handlers && handlers.length) {
      var i, len, func, context, eventCopy, originalContext = this;
      for (i = 0, len = handlers.length; i < len; i++) {
        func = handlers[i];
        context = originalContext;
        if (typeof func === "string" && typeof _window[func] === "function") {
          func = _window[func];
        }
        if (typeof func === "object" && func && typeof func.handleEvent === "function") {
          context = func;
          func = func.handleEvent;
        }
        if (typeof func === "function") {
          eventCopy = _extend({}, event);
          _dispatchCallback(func, context, [ eventCopy ], async);
        }
      }
    }
  }
219953
function (eventType, params) {
    params = params || {
        bubbles: false,
        cancelable: false,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false
      };
    var mouseEvent = document.createEvent('MouseEvent');
    mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, 0, null);

    return mouseEvent;
  }