Save the event to Mongo via mongo_handle
344357
def save mongo_handle

# See above
      date_collection = self["date"]
      if self["time"] < @@cut_off_time
        date_collection = (Time.parse(self["date"]) - 86400).strftime "%F"
      end

      # Save to each of these collections
      clxns = [
        "events",
        self["type"],
        self["subtype"],
        date_collection
      ]

      clxns.each do |c|
        if c
          mongo_handle.db.collection(c).update(
            {
              "serial" => self["serial"]
            },
            self,
            {
              # Upsert: update if exists, otherwise insert
              :upsert => true
            }
          )
        end
      end
    end
1130788
function(dbOrUri, stream, callback) {
    if (arguments.length === 2) {
      callback = stream;
      stream = undefined;
    }
    if (!stream) {
      stream = process.stdout;
    }
    var db;
    var out = stream;
    var endOfCollection = crypto.pseudoRandomBytes(8).toString('base64');
    write({
      type: 'mongo-dump-stream',
      version: '2',
      endOfCollection: endOfCollection
    });
    return async.series({
      connect: function(callback) {
        if (typeof(dbOrUri) !== 'string') {
          // Already a mongodb connection
          db = dbOrUri;
          return setImmediate(callback);
        }
        return mongodb.MongoClient.connect(dbOrUri, function(err, _db) {
          if (err) {
            return callback(err);
          }
          db = _db;
          return callback(null);
        });
      },
      getCollections: function(callback) {
        return db.collections(function(err, _collections) {
          if (err) {
            return callback(err);
          }
          collections = _collections;
          return callback(null);
        });
      },
      dumpCollections: function(callback) {
        return async.eachSeries(collections, function(collection, callback) {
          if (collection.collectionName.match(/^system\./)) {
            return setImmediate(callback);
          }
          return async.series({
            getIndexes: function(callback) {
              return collection.indexInformation({ full: true }, function(err, info) {
                if (err) {
                  return callback(err);
                }
                write({
                  type: 'collection',
                  name: collection.collectionName,
                  indexes: info
                });
                return callback(null);
              });
            },
            getDocuments: function(callback) {
              var cursor = collection.find({}, { raw: true });
              iterate();
              function iterate() {
                return cursor.nextObject(function(err, item) {
                  if (err) {
                    return callback(err);
                  }
                  if (!item) {
                    write({
                      // Ensures we don't confuse this with
                      // a legitimate database object
                      endOfCollection: endOfCollection
                    });
                    return callback(null);
                  }
                  // v2: just a series of actual data documents
                  out.write(item);

                  // If we didn't have the raw BSON document,
                  // we could do this instead, but it would be very slow
                  // write({
                  //   type: 'document',
                  //   document: item
                  // });

                  return setImmediate(iterate);
                });
              }
            },
          }, callback);
        }, callback);
      },
      endDatabase: function(callback) {
        write({
          type: 'endDatabase'
        }, callback);
      }
    }, function(err) {
      if (err) {
        return callback(err);
      }
      return callback(null);
    });
    function write(o, callback) {
      out.write(BSON.serialize(o, false, true, false), callback);
    }
  }
790447
def _handle_event(self, connection, event):
        
        with self.mutex:
            matching_handlers = sorted(
                self.handlers.get("all_events", [])
                + self.handlers.get(event.type, [])
            )
            for handler in matching_handlers:
                result = handler.callback(connection, event)
                if result == "NO MORE":
                    return
270685
def main():
    
    import sys, signal

    def _exit():
        print("Thank you for playing Simple Mongo Query!")
        sys.exit(0)

    signal.signal(signal.SIGINT, lambda s, f: sys.stdout.write("\n") or _exit())

    while 1:
        expr = input("Enter query: ").strip()
        if not expr:
            break
        try:
            q = to_mongo(expr)
        except BadExpression as e:
            print(("Error! Cannot parse '{}'".format(e.expr)))
            continue
        print(("Result: {}".format(q)))
    _exit()
894844
function(self, callback) {
  if (self.cursorState.dead && self.cursorState.killed) {
    handleCallback(callback, new MongoError('cursor is dead'));
    return true;
  }

  return false;
}
1369459
def _process_event(self, event, tagged_data):
    """"""
    event_type = event.WhichOneof('what')
    # Handle the most common case first.
    if event_type == 'summary':
      for value in event.summary.value:
        value = data_compat.migrate_value(value)
        tag, metadata, values = tagged_data.get(value.tag, (None, None, []))
        values.append((event.step, event.wall_time, value.tensor))
        if tag is None:
          # Store metadata only from the first event.
          tagged_data[value.tag] = sqlite_writer.TagData(
              value.tag, value.metadata, values)
    elif event_type == 'file_version':
      pass  # TODO: reject file version < 2 (at loader level)
    elif event_type == 'session_log':
      if event.session_log.status == event_pb2.SessionLog.START:
        pass  # TODO: implement purging via sqlite writer truncation method
    elif event_type in ('graph_def', 'meta_graph_def'):
      pass  # TODO: support graphs
    elif event_type == 'tagged_run_metadata':
      pass
1132621
def save(self, db):
        
        assert self.collection

        self._ensure_indexes(db)

        # XXX self.structure belongs to StructuredDictMixin !!
        outgoing = dict(dict_to_db(self, self.structure))

        object_id = db[self.collection].save(outgoing)

        if self.get('_id') is None:
            self['_id'] = object_id
        else:
            pass

        return object_id
1083918
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
        """"""
        event_dict = {
            'timestamp': int(time()),
            'source_type_name': self.SOURCE_TYPE_NAME,
            'msg_title': title,
            'event_type': event_type,
            'alert_type': severity,
            'msg_text': text,
            'tags': tags,
            'aggregation_key': aggregation_key,
        }
        self.event(event_dict)
528637
def put(self, event_type, event_data={}, **kwargs):
        
        event = dict(type=event_type, data=event_data)

        event["time"] = kwargs.get("time", datetime.utcnow().isoformat())

        if kwargs.get("id"):
            event["id"] = kwargs.get("id")

        data = json.dumps([event])

        r = requests.post(self.collector_url + 'event/put',
                          data=data,
                          headers={'content-type': 'application/json'})
        r.raise_for_status()

        return [event]
824323
function (event) {

	// check if connection object exists
	if (typeof event.conn === 'undefined') {
		LOG.error('no connection records, cannot respond to request', l_name);
		return false;
	}

	// if no mechanism to store (such as from a bot), just ignore
	// TODO: cleaner approach?
	if (event.conn.type !== 'socket' ||
    	event.conn.connector.queuedEvents === undefined) {
		return true;
	}

	var socket = event.conn.connector;

	// check if id exist
	if (socket.queuedEvents.hasOwnProperty(event.id) === false) {
		LOG.error('event not found. id = ' + event.id, l_name);
		LOG.stack();
		return false;
	}

	// remove current event from the socket's event queues
	delete socket.queuedEvents[event.id];

	return true;
}
300756
def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs):
        
        if event_type == "Exception":
            # never gather log stack for exceptions
            stack = False
        data = self._build_msg_for_logging(
            event_type, date=date, context=context, custom=custom, stack=stack, handled=handled, **kwargs
        )

        if data:
            # queue data, and flush the queue if this is an unhandled exception
            self.queue(ERROR, data, flush=not handled)
            return data["id"]
1299198
def make_event(event: Callable) -> Callable:
    """"""
    @property  # type: ignore
    @wraps(event)
    def actualevent(self):  # pylint: disable=missing-docstring
        name = event.__name__[3:]
        try:
            # the getter post processing function
            # is preserved with an underscore
            getter = event(self).__name__
        except AttributeError:
            getter = None
        return Event(name, self._uuid, getter)  # pylint: disable=protected-access

    return actualevent
210720
def event_happened(event_name, model)
      self.last_action = event_name
      self.last_updated_node = model
      self.updated_at = Time.zone.now
      self.save!
    end
225031
def handle(event):
        
        def dec(func):
            if not hasattr(func, '_handle_events'):
                func._handle_events = set()
            func._handle_events.add(event)
            return func

        return dec
554441
def save(self):
        '''  '''
        redis = type(self).get_redis()
        pipe = to_pipeline(redis)

        pipe.hset(self.key(), 'id', self.id)

        for fieldname, field in self.proxy:
            if not isinstance(field, Relation):
                field.save(getattr(self, fieldname), pipe, commit=False)

        pipe.sadd(type(self).members_key(), self.id)

        pipe.execute()

        if self.notify:
            data = json.dumps({
                'event': 'create' if not self._persisted else 'update',
                'data': self.to_json(),
            })
            redis.publish(type(self).cls_key(), data)
            redis.publish(self.key(), data)

        self._persisted = True

        return self
1105357
def event_return(events):
    '''
    
    '''
    options = _get_options()

    index = options['master_event_index']
    doc_type = options['master_event_doc_type']

    if options['index_date']:
        index = '{0}-{1}'.format(index,
            datetime.date.today().strftime('%Y.%m.%d'))

    _ensure_index(index)

    for event in events:
        data = {
            'tag': event.get('tag', ''),
            'data': event.get('data', '')
        }

    ret = __salt__['elasticsearch.document_create'](index=index,
                                                    doc_type=doc_type,
                                                    id=uuid.uuid4(),
                                                    body=salt.utils.json.dumps(data))
1291975
def trigger_event(event=None, **kwargs):
    '''
    
    '''

    res = {'result': False, 'message': 'Something went wrong'}

    data = {}
    for value in ('value1', 'value2', 'value3',
                  'Value1', 'Value2', 'Value3'):
        if value in kwargs:
            data[value.lower()] = kwargs[value]
    data['occurredat'] = time.strftime("%B %d, %Y %I:%M%p", time.localtime())
    result = _query(event=event,
                    method='POST',
                    data=salt.utils.json.dumps(data)
                    )
    if 'status' in result:
        if result['status'] == 200:
            res['result'] = True
            res['message'] = result['text']
        else:
            if 'error' in result:
                res['message'] = result['error']
    return res