Iterate recommend/update procedure and compute incremental recall.

        Args:
            test_events (list of Event): Positive test events.

        Returns:
            list of tuples: (rank, recommend time, update time)
964688
def evaluate(self, test_events):
        
        for i, e in enumerate(test_events):
            self.__validate(e)

            # target items (all or unobserved depending on a detaset)
            unobserved = set(self.item_buffer)
            if not self.repeat:
                unobserved -= self.rec.users[e.user.index]['known_items']

            # item i interacted by user u must be in the recommendation candidate
            # even if it is a new item
            unobserved.add(e.item.index)

            candidates = np.asarray(list(unobserved))

            # make top-{at} recommendation for the 1001 items
            start = time.clock()
            recos, scores = self.__recommend(e, candidates)
            recommend_time = (time.clock() - start)

            rank = np.where(recos == e.item.index)[0][0]

            # Step 2: update the model with the observed event
            self.rec.users[e.user.index]['known_items'].add(e.item.index)
            start = time.clock()
            self.rec.update(e)
            update_time = (time.clock() - start)

            self.item_buffer.append(e.item.index)

            # (top-1 score, where the correct item is ranked, rec time, update time)
            yield scores[0], rank, recommend_time, update_time
357572
def OrEvent(*events):
    '''
    
    '''
    or_event = threading.Event()

    def changed():
        '''
        Set ``or_event`` if any of the specified events have been set.
        '''
        bools = [event_i.is_set() for event_i in events]
        if any(bools):
            or_event.set()
        else:
            or_event.clear()
    for event_i in events:
        # Override ``set`` and ``clear`` methods on event to update state of
        # `or_event` after performing default behaviour.
        orify(event_i, changed)

    # Set initial state of `or_event`.
    changed()
    return or_event
914016
def results_iterator(self, scan_id, pop_res):
        
        if pop_res:
            result_aux = self.scans_table[scan_id]['results']
            self.scans_table[scan_id]['results'] = list()
            return iter(result_aux)

        return iter(self.scans_table[scan_id]['results'])
398604
def recall_curve(self, delta_tau=0.01):
        
        # compute thresholds based on the sorted probabilities
        orig_thresh = self.threshold
        sorted_labels, sorted_probs = self.sorted_values

        scores = []
        taus = []
        tau = 0
        for k in range(len(sorted_labels)):
            # compute new accuracy
            self.threshold = tau
            scores.append(self.recall)
            taus.append(tau)

            # update threshold
            tau = sorted_probs[k]

        # add last datapoint
        tau = 1.0
        self.threshold = tau
        scores.append(1.0)
        taus.append(tau)

        self.threshold = orig_thresh
        return scores, taus
1328643
def iterate_specific_event_range():
    """"""
    now = datetime.utcnow()
    start = now - timedelta(hours=1)

    total = 0
    for event in archive.list_events(start=start, stop=now):
        total += 1
        # print(event)
    print('Found', total, 'events in range')
845741
private int sequentialFailureCount(List<AuditEvent> events) {
        int failureCount = 0;
        for (AuditEvent event : events) {
            if (event.getType() == failureEventType) {
                failureCount++;
            } else if (event.getType() == successEventType) {
                // Successful authentication occurred within last allowable
                // failures, so ignore
                break;
            }
        }
        return failureCount;
    }
1097138
def event_loop(self):
        
        if not self._event_loop:
            self._event_loop = asyncio.get_event_loop()
        return self._event_loop
1332594
def __event_exist(self, event_type):
        
        for i in range(self.len()):
            if self.events_list[i][1] < 0 and self.events_list[i][3] == event_type:
                return i
        return -1
17980
def recentEvents(self):
        '''
        
        '''
        return Event.objects.filter(
            Q(pk__in=self.individualEvents.values_list('pk',flat=True)) |
            Q(session__in=self.eventSessions.all()) |
            Q(publicevent__category__in=self.eventCategories.all()) |
            Q(series__category__in=self.seriesCategories.all())
        ).filter(
            Q(startTime__lte=timezone.now() + timedelta(days=60)) &
            Q(endTime__gte=timezone.now() - timedelta(days=60))
        )
81511
def _bucket_events(self, event_iterable):
    

    current_bucket_time = None
    current_bucket_events = None
    for event in event_iterable:
      event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
      if current_bucket_time is None or current_bucket_time < event_bucket_time:
        if current_bucket_events is not None:
          yield current_bucket_events
        current_bucket_time = event_bucket_time
        current_bucket_events = []
      current_bucket_events.append(event)
    if current_bucket_events is not None and current_bucket_events != []:
      yield current_bucket_events
505760
def validate_event_and_assign_id(event):
  
  event_time = event.get(TIMESTAMP_FIELD)

  if event_time is None:
    event[TIMESTAMP_FIELD] = event_time = epoch_time_to_kronos_time(time.time())
  elif type(event_time) not in (int, long):
    raise InvalidEventTime(event_time)

  # Generate a uuid1-like sequence from the event time with the non-time bytes
  # set to random values.
  _id = uuid_from_kronos_time(event_time)
  event[ID_FIELD] = str(_id)
  return _id, event
221867
def get_and_project_events(self, entity_id, gt=None, gte=None, lt=None, lte=None, limit=None, initial_state=None,
                               query_descending=False):
        
        # Decide if query is in ascending order.
        #  - A "speed up" for when events are stored in descending order (e.g.
        #  in Cassandra) and it is faster to get them in that order.
        #  - This isn't useful when 'until' or 'after' or 'limit' are set,
        #    because the inclusiveness or exclusiveness of until and after
        #    and the end of the stream that is truncated by limit both depend on
        #    the direction of the query. Also paging backwards isn't useful, because
        #    all the events are needed eventually, so it would probably slow things
        #    down. Paging is intended to support replaying longer event streams, and
        #    only makes sense to work in ascending order.
        if gt is None and gte is None and lt is None and lte is None and self.__page_size__ is None:
            is_ascending = False
        else:
            is_ascending = not query_descending

        # Get entity's domain events from the event store.
        domain_events = self.event_store.get_domain_events(
            originator_id=entity_id,
            gt=gt,
            gte=gte,
            lt=lt,
            lte=lte,
            limit=limit,
            is_ascending=is_ascending,
            page_size=self.__page_size__
        )

        # The events will be replayed in ascending order.
        if not is_ascending:
            domain_events = list(reversed(list(domain_events)))

        # Project the domain events onto the initial state.
        return self.project_events(initial_state, domain_events)
804397
def update_events(self, events_data: List[Tuple[str, int]]) -> None:
        """"""
        cursor = self.conn.cursor()
        cursor.executemany(
            'UPDATE state_events SET data=? WHERE identifier=?',
            events_data,
        )
        self.maybe_commit()
557658
def learn(self, matches, recall):
        '''
        
        '''
        compound_length = 2

        dupe_cover = Cover(self.blocker.predicates, matches)
        dupe_cover.dominators(cost=self.total_cover)
        dupe_cover.compound(compound_length)

        comparison_count = self.comparisons(dupe_cover, compound_length)

        dupe_cover.dominators(cost=comparison_count, comparison=True)

        coverable_dupes = set.union(*viewvalues(dupe_cover))
        uncoverable_dupes = [pair for i, pair in enumerate(matches)
                             if i not in coverable_dupes]

        epsilon = int((1.0 - recall) * len(matches))

        if len(uncoverable_dupes) > epsilon:
            logger.warning(OUT_OF_PREDICATES_WARNING)
            logger.debug(uncoverable_dupes)
            epsilon = 0
        else:
            epsilon -= len(uncoverable_dupes)

        for pred in dupe_cover:
            pred.count = comparison_count[pred]

        searcher = BranchBound(len(coverable_dupes) - epsilon, 2500)
        final_predicates = searcher.search(dupe_cover)

        logger.info('Final predicate set:')
        for predicate in final_predicates:
            logger.info(predicate)

        return final_predicates
833432
public void suggestReviewNow() {
        if (System.currentTimeMillis() > lastSuggestedReview + TimeUnit.SECONDS.toMillis(1)) {
            lastSuggestedReview = System.currentTimeMillis();
            Computer.threadPoolForRemoting.submit(new Runnable() {
                public void run() {
                    update();
                }
            });
        }
    }
12618
def get_experiment_summ_ids( self, coinc_event_id ):
		
		experiment_summ_ids = []
		for row in self:
			if row.coinc_event_id == coinc_event_id:
				experiment_summ_ids.append(row.experiment_summ_id)
		if len(experiment_summ_ids) == 0:
			raise ValueError("'%s' could not be found in the experiment_map table" % coinc_event_id)
		return experiment_summ_ids
995869
def matches(self, event):
        '''
        
        '''
        ret = []
        self._matches(event, set(), ret)
        return tuple(r[0] for r in ret)