calculate_sample

@param int $sampleid
@param string $samplesorigin
@param int $starttime
@param int $endtime
@return float
177859
protected function calculate_sample($sampleid, $samplesorigin, $starttime = false, $endtime = false) {
        global $DB;

        $user = $this->retrieve('user', $sampleid);
        $course = \core_analytics\course::instance($this->retrieve('course', $sampleid));

        // Filter by context to use the db table index.
        $context = $this->retrieve('context', $sampleid);
        $select = "userid = :userid AND contextlevel = :contextlevel AND contextinstanceid = :contextinstanceid AND " .
            "timecreated > :end";
        $params = array('userid' => $user->id, 'contextlevel' => $context->contextlevel,
            'contextinstanceid' => $context->instanceid, 'end' => $course->get_end());
        $logstore = \core_analytics\manager::get_analytics_logstore();
        $nlogs = $logstore->get_events_select_count($select, $params);
        if ($nlogs) {
            return self::get_max_value();
        } else {
            return self::get_min_value();
        }

    }
272792
protected function filter_out_prediction_samples_and_ranges(array &$sampleids, array &$ranges,
            \core_analytics\local\time_splitting\base $timesplitting) {

        if (count($ranges) > 1) {
            throw new \coding_exception('$ranges argument should only contain one range');
        }

        $rangeindex = key($ranges);
        $predictedrange = $this->get_predict_samples_record($timesplitting, $rangeindex);

        if (!$predictedrange) {
            // Nothing to filter out.
            return null;
        }

        $predictedrange->sampleids = json_decode($predictedrange->sampleids, true);
        $missingsamples = array_diff_key($sampleids, $predictedrange->sampleids);
        if (count($missingsamples) === 0) {
            // All samples already calculated.
            unset($ranges[$rangeindex]);
            return null;
        }

        // Replace the list of samples by the one excluding samples that already got predictions at this range.
        $sampleids = $missingsamples;

        return $predictedrange;
    }
1076390
public SampleCount subtractPrecise(SampleCount that) throws ResamplingException
	{
		final long thatSamples = that.getSamplesPrecise(this.rate);

		if (thatSamples != 0)
		{
			return new SampleCount(this.samples - thatSamples, this.rate);
		}
		else
		{
			return this;
		}
	}
1285473
function initializeDB() {
  db = new loki('perftest');

  var start, end, totalTime;
  var totalTimes = [];
  var totalMS = 0.0;

  samplecoll = db.addCollection('samplecoll');
  /*
    {
      asyncListeners: true,
      disableChangesApi: true,
      transactional: false,
      clone: false 
    }
  ); 
  */

  for (var idx = 0; idx < arraySize; idx++) {
    var v1 = genRandomVal();
    var v2 = genRandomVal();

    start = process.hrtime();
    samplecoll.insert({
      customId: idx,
      val: v1,
      val2: v2,
      val3: "more data 1234567890"
    });
    end = process.hrtime(start);
    totalTimes.push(end);
  }

  for (var idx = 0; idx < totalTimes.length; idx++) {
    totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1] / 1e6;
  }


  //var totalMS = end[0] * 1e3 + end[1]/1e6;
  totalMS = totalMS.toFixed(2);
  var rate = arraySize * 1000 / totalMS;
  rate = rate.toFixed(2);
  console.log("load (insert) : " + totalMS + "ms (" + rate + ") ops/s");
}
88754
void addSample(StopwatchSample sample) {
		total += sample.getTotal();
		counter += sample.getCounter();

		if (min > sample.getMin()) {
			min = sample.getMin();
			minTimestamp = sample.getMinTimestamp();
		}

		if (max < sample.getMax()) {
			max = sample.getMax();
			maxTimestamp = sample.getMaxTimestamp();
		}

		active += sample.getActive();

		if (maxActive < sample.getMaxActive()) {
			maxActive = sample.getMaxActive();
			maxActiveTimestamp = sample.getMaxActiveTimestamp();
		}
	}
1033285
public final void sample()
  {
    long count = _count.get();
    long lastCount = _lastAvgCount.getAndSet(count);
    long time = _time.get();
    long lastTime = _lastAvgTime.getAndSet(time);

    if (count == lastCount)
      _value = 0;
    else
      _value = _scale * (time - lastTime) / (double) (count - lastCount);
  }
762840
protected function social_calculate_sample($sampleid, $tablename, $starttime = false, $endtime = false) {

        // May not be available.
        $user = $this->retrieve('user', $sampleid);

        if (!$useractivities = $this->get_student_activities($sampleid, $tablename, $starttime, $endtime)) {
            // Null if no activities.
            return null;
        }

        $scoreperactivity = (self::get_max_value() - self::get_min_value()) / count($useractivities);

        $score = self::get_min_value();

        foreach ($useractivities as $contextid => $cm) {

            $potentiallevel = $this->get_social_breadth_level($cm);
            if (!is_int($potentiallevel)
                    || $potentiallevel > self::MAX_SOCIAL_LEVEL
                    || $potentiallevel < self::SOCIAL_LEVEL_1) {
                throw new \coding_exception('Activities\' potential social breadth go from 1 to ' .
                    community_of_inquiry_activity::MAX_SOCIAL_LEVEL . '.');
            }
            $scoreperlevel = $scoreperactivity / $potentiallevel;
            switch ($potentiallevel) {
                case self::SOCIAL_LEVEL_2:
                case self::SOCIAL_LEVEL_3:
                case self::SOCIAL_LEVEL_4:
                case self::SOCIAL_LEVEL_5:
                    // Core activities social breadth only reaches level 2, until core activities social
                    // breadth do not reach level 5 we limit it to what we currently support, which is level 2.

                    // Social breadth level 2 is to view feedback. (Same as cognitive level 3).

                    if ($this->any_feedback('viewed', $cm, $contextid, $user)) {
                        // Max score for level 2.
                        $score += $scoreperlevel * 2;
                        break;
                    }
                    // The user didn't reach the activity max social breadth, continue with level 1.

                case self::SOCIAL_LEVEL_1:
                    // Social breadth level 1 is just accessing the activity.
                    if ($this->any_log($contextid, $user)) {
                        $score += $scoreperlevel;
                    }
            }

        }

        // To avoid decimal problems.
        if ($score > self::MAX_VALUE) {
            return self::MAX_VALUE;
        } else if ($score < self::MIN_VALUE) {
            return self::MIN_VALUE;
        }
        return $score;
    }
423224
public static double pbarStd(double pbar, int sampleN, int populationN) {
        return Math.sqrt(pbarVariance(pbar, sampleN, populationN));
    }
748712
public synchronized SamplerResult<T> finishSampling(int count)
    {
        List<Counter<T>> results = Collections.EMPTY_LIST;
        long cardinality = 0;
        if (enabled)
        {
            enabled = false;
            results = summary.topK(count);
            cardinality = hll.cardinality();
        }
        return new SamplerResult<T>(results, cardinality);
    }
1138683
function getMean(sample) {
      return (_.reduce(sample, function(sum, x) {
        return sum + x;
      }) / sample.length) || 0;
    }
1374335
def add_sample(self, ts, **kwargs):
        """"""
        if not self.series.offsets:
            self.ts = ts
            offset = 0
        else:
            dt = ts - self.ts
            offset = (dt.days * 24 * 60 * 60 * 1000 + dt.seconds * 1000 +
                      dt.microseconds // 1000)
        self.series.add_sample(offset, **kwargs)
588028
public final double sampleCount()
  {
    long count = _count.get();
    long lastCount = _lastCount.getAndSet(count);

    return count - lastCount;
  }
285805
protected function calculate_sample($sampleid, \core_analytics\analysable $course, $starttime = false, $endtime = false) {

        $userenrol = $this->retrieve('user_enrolments', $sampleid);

        // We use completion as a success metric.
        $ccompletion = new \completion_completion(array('userid' => $userenrol->userid, 'course' => $course->get_id()));
        if ($ccompletion->is_complete()) {
            return 0;
        } else {
            return 1;
        }
    }
597114
protected boolean sample() {
        if (curr.increment() >= freq) {
            curr.set(0);
            target.set(rand.nextInt(freq));
        }
        return curr.get() == target.get();
    }
1118278
@Override
	public TimelineSample<StopwatchTimeRange> sample() {
		StopwatchTimeRange[] timeRangesCopy;
		synchronized (this) {
			timeRangesCopy = timeRanges.toArray(new StopwatchTimeRange[timeRanges.size()]);
		}
		// TODO sample each time-range by making a copy of it
		return new TimelineSample<>(timeRanges.getCapacity(), timeRangeWidth * SimonClock.NANOS_IN_MILLIS, timeRangesCopy);
	}
881253
public int[] getSample(int sampleSize)
  {
    int[] sample = new int[sampleSize];
    for(int i = 0; i< sampleSize;i++){
      sample[i] = randGenerator.nextInt(this.dataDimension()); //Just generate a random index
    }
    return sample;
  }
760106
public final double sampleTotalCount()
  {
    long count = _totalCount.get();
    long lastCount = _lastTotalCount;
    _lastTotalCount = count;

    return count - lastCount;
  }