A function that calculates the total difference between demand for an event
    and the slot capacity it is scheduled in.
15294
def efficiency_capacity_demand_difference(slots, events, X, **kwargs):
    
    overflow = 0
    for row, event in enumerate(events):
        for col, slot in enumerate(slots):
            overflow += (event.demand - slot.capacity) * X[row, col]
    return overflow
1159943
function getAvailabilitiesForDuration(duration, availabilities) {
    const durationAvailabilities = [];
    let startTime = '10:00';
    while (startTime !== '17:00') {
        if (availabilities.indexOf(startTime) !== -1) {
            if (duration === 30) {
                durationAvailabilities.push(startTime);
            } else if (availabilities.indexOf(incrementTimeByThirtyMins(startTime)) !== -1) {
                durationAvailabilities.push(startTime);
            }
        }
        startTime = incrementTimeByThirtyMins(startTime);
    }
    return durationAvailabilities;
}
1197816
function (scheduledEventId) {
      var i;
      for (i = 0; i < this._events.length; i++) {
         var evt = this._events[i];
         if (evt.eventId === scheduledEventId) {
            return evt.activityTaskScheduledEventAttributes.activityId;
         }
      }
      return false;
   }
1214054
def calculate(self, batch_info):
        
        value = self._value_function(batch_info)
        self.buffer += value
628385
def customerMeetsRequirement(self, customer, danceRole=None, registration=None):
        '''
        
        '''

        cust_reqs = self.customerrequirement_set.filter(customer=customer,met=True)
        if customer:
            cust_priors = customer.eventregistration_set.filter(event__series__isnull=False)
        else:
            cust_priors = EventRegistration.objects.none()

        # If there's an explicit object stating that this customer meets the requirement, then we're done.
        if self.roleEnforced and danceRole and cust_reqs.filter(role=danceRole).exists():
            return True
        elif not self.roleEnforced and cust_reqs.exists():
            return True
        elif self.roleEnforced and not danceRole:
            return False

        # Go through each item for this requirement and see if the customer meets that item
        for item in self.requirementitem_set.all():
            filter_dict = {}
            if item.requiredLevel:
                filter_dict['event__series__classDescription__danceTypeLevel'] = item.requiredLevel
            if item.requiredClass:
                filter_dict['event__series__classDescription'] = item.requiredClass
            if self.roleEnforced:
                filter_dict['role'] = danceRole

            current_matches = 0
            overlap_matches = 0
            nonconcurrent_filter = {'event__endTime__lte': timezone.now()}

            if registration:

                if isinstance(registration,Registration):
                    current_matches = registration.eventregistration_set.filter(**filter_dict).count()
                elif isinstance(registration,TemporaryRegistration):
                    current_matches = registration.temporaryeventregistration_set.filter(**filter_dict).count()

                nonconcurrent_filter = {'event__endTime__lte': registration.firstSeriesStartTime}
                overlap_matches = cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                    event__startTime__lte=registration.lastSeriesEndTime,
                ).count()

            priors_matches = cust_priors.filter(**filter_dict).filter(**nonconcurrent_filter).count()

            # The number of matches depends on the concurrency rule for this item
            if item.concurrentRule == item.ConcurrencyRule.prohibited:
                matches = priors_matches
            elif item.concurrentRule == item.ConcurrencyRule.allowOneOverlapClass:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(1)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowTwoOverlapClasses:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(2)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowed:
                matches = priors_matches + overlap_matches + \
                    (current_matches if isinstance(registration,TemporaryRegistration) else 0)
            elif item.concurrentRule == item.ConcurrencyRule.required:
                matches = overlap_matches + current_matches

            if matches >= item.quantity:
                # If this is an 'or' or a 'not' requirement, then we are done
                if self.booleanRule == self.BooleanChoice.booleanOr:
                    return True
                if self.booleanRule == self.BooleanChoice.booleanNot:
                    return False
            else:
                # If this is an 'and' requirement and we didn't meet, then we are done
                if self.booleanRule == self.BooleanChoice.booleanAnd:
                    return False

        # If we got this far, then either all 'and' requirements were met, or all 'or' and 'not' requirements were not met
        if self.booleanRule == self.BooleanChoice.booleanOr or self.requirementitem_set.count() == 0:
            return False
        return True
1087433
function incrmsum( W ) {
	if ( !isPositiveInteger( W ) ) {
		throw new TypeError( 'incrmsum()::invalid input argument. Window size must be a positive integer. Value: `' + W + '`.' );
	}
	var arr = new Array( W ),
		sum = 0,
		N = 0,
		i = -1;
	/**
	* FUNCTION: incrmsum( [value] )
	*	If a `value` is provided, updates and returns the updated sum. If no `value` is provided, returns the current sum.
	*
	* @param {Number} [value] - value used to update the moving sum
	* @returns {Number|Null} sum or null
	*/
	return function incrmsum( x ) {
		if ( !arguments.length ) {
			if ( N === 0 ) {
				return null;
			}
			return sum;
		}
		// Update the index for managing the circular buffer...
		i = (i+1) % W;

		// Fill up the initial window; else, update the existing window...
		if ( N < W ) {
			N += 1;
			sum += x;
		} else {
			sum += x - arr[ i ];
		}
		arr[ i ] = x;
		return sum;
	};
}
598127
function msDiff(t1, t2) {
  t1 = (t1[0] * 1e9 + t1[1]) / 1e6;
  t2 = (t2[0] * 1e9 + t2[1]) / 1e6;
  return Math.ceil((t1 - t2) * 100) / 100;
}
1183581
function functionsWithinRange(startMillis, endMillis) {
    var fnsToRun = [];
    for (var timeoutKey in scheduledFunctions) {
      var scheduledFunc = scheduledFunctions[timeoutKey];
      if (scheduledFunc &&
          scheduledFunc.runAtMillis >= startMillis &&
            scheduledFunc.runAtMillis <= endMillis) {
        //remove fn -- we'll reschedule later if it is recurring.
        self.removeFunctionWithId(timeoutKey);
        if (!scheduledFunc.recurring) {
          fnsToRun.push(scheduledFunc); // schedules each function only once
        } else {
          fnsToRun.push(buildNthInstanceOf(scheduledFunc, 0));
          var additionalTimesFnRunsInRange =
            Math.floor((endMillis - scheduledFunc.runAtMillis) / scheduledFunc.millis);
          for (var i = 0; i < additionalTimesFnRunsInRange; i++) {
            fnsToRun.push(buildNthInstanceOf(scheduledFunc, i + 1));
          }
          reschedule(buildNthInstanceOf(scheduledFunc, additionalTimesFnRunsInRange));
        }
      }
    }

    return fnsToRun;
  }
647738
private LocalDate calculateIMMMonth(final boolean requestNextIMM, final LocalDate startDate, final int month) {
        int monthOffset;
        LocalDate date = startDate;
        switch (month) {
        case MARCH:
        case JUNE:
        case SEPTEMBER:
        case DECEMBER:
            final LocalDate immDate = calculate3rdWednesday(date);
            if (requestNextIMM && !date.isBefore(immDate)) {
                date = date.plusMonths(MONTHS_IN_QUARTER);
            } else if (!requestNextIMM && !date.isAfter(immDate)) {
                date = date.minusMonths(MONTHS_IN_QUARTER);
            }
            break;

        default:
            if (requestNextIMM) {
                monthOffset = (MONTH_IN_YEAR - month) % MONTHS_IN_QUARTER;
                date = date.plusMonths(monthOffset);
            } else {
                monthOffset = month % MONTHS_IN_QUARTER;
                date = date.minusMonths(monthOffset);
            }
            break;
        }
        return date;
    }
1308835
function calculateTimeIntervals(timeColumn) {
  // First we find the last time for all of the data (this is an optomisation for the calculateAvailability operation.
  const endTime = timeColumn.values.reduce(function(latest, value, index) {
    const current = finishFromIndex(timeColumn, index);
    if (
      !defined(latest) ||
      (defined(current) && JulianDate.greaterThan(current, latest))
    ) {
      return current;
    }
    return latest;
  }, finishFromIndex(timeColumn, 0));

  return timeColumn.values.map(function(value, index) {
    return calculateAvailability(timeColumn, index, endTime);
  });
}
766238
public long get(int slots) {
    checkArgument(slots <= windowSlots,
        "Requested window must be less than the total window slots");

    long sum = 0;

    for (int i = 0; i < slots; i++) {
      int currentIndex = headSlot - i;
      if (currentIndex < 0) {
        currentIndex = counters.size() + currentIndex;
      }
      sum += counters.get(currentIndex).get();
    }

    return sum;
  }
441125
def pollNextEvent(self, pEvent):
        

        fn = self.function_table.pollNextEvent
        result = fn(byref(pEvent), sizeof(VREvent_t))
        return result != 0
1114034
def _upper_bound_on_event_overflow(
    events, slots, X, beta, summation_type=None, **kwargs
):
    
    label = 'Artificial upper bound constraint'
    for row, event in enumerate(events):
        for col, slot in enumerate(slots):
            yield Constraint(
                f'{label} - slot: {col} and event: {row}',
                event.demand * X[row, col] - slot.capacity <= beta)
979385
def aggregate(self, event):
        """"""

        total = event.null()
        for function in compat_itervalues(self.functions):
            try:
                total = event.aggregate(total, function[event])
            except UndefinedEvent:
                return
        self[event] = total
436738
function compare(a, b, n) {
	var n2 = n,
		then = Date.now()
	while (n2--) {
		a === b
	}
	return (Date.now() - then) * 1e6 / n
}
1066888
function _check_slot(offset, result) {
        if (now - that.lastUpdate > SPINTIME) {
            var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT;
            if (c == result) {
                if (result == 0) {
                    if (Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
                        return true; // done
                    }
                } else if (Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {
                    return true; // done
                }
            }
        }
        return false;
    }
1213078
def netHours(self):
        '''
        
        '''
        if self.specifiedHours is not None:
            return self.specifiedHours
        return self.event.duration - sum([sub.netHours for sub in self.replacementFor.all()])