Calculates the social breadth of a sample.

@param int $sampleid
@param string $tablename
@param int $starttime
@param int $endtime
@return float|int|null
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;
    }
1260963
public function totalPage($page_id, $begin_date, $end_date)
    {
        $url = "https://api.weixin.qq.com/shakearound/statistics/page?access_token=ACCESS_TOKEN";
        $this->registerApi($url, __FUNCTION__, func_get_args());
        return $this->httpPostForJson($url, ['page_id' => $page_id, 'begin_date' => $begin_date, 'end_date' => $end_date]);
    }
1264471
protected function cognitive_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();

        // Iterate through the module activities/resources which due date is part of this time range.
        foreach ($useractivities as $contextid => $cm) {

            $potentiallevel = $this->get_cognitive_depth_level($cm);
            if (!is_int($potentiallevel)
                    || $potentiallevel > self::MAX_COGNITIVE_LEVEL
                    || $potentiallevel < self::COGNITIVE_LEVEL_1) {
                throw new \coding_exception('Activities\' potential cognitive depth go from 1 to 5.');
            }
            $scoreperlevel = $scoreperactivity / $potentiallevel;

            switch ($potentiallevel) {
                case self::COGNITIVE_LEVEL_5:
                    // Cognitive level 5 is to submit after feedback.
                    if ($this->any_feedback('submitted', $cm, $contextid, $user)) {
                        $score += $scoreperlevel * 5;
                        break;
                    }
                    // The user didn't reach the activity max cognitive depth, continue with level 2.

                case self::COGNITIVE_LEVEL_4:
                    // Cognitive level 4 is to comment on feedback.
                    if ($this->any_feedback('replied', $cm, $contextid, $user)) {
                        $score += $scoreperlevel * 4;
                        break;
                    }
                    // The user didn't reach the activity max cognitive depth, continue with level 2.

                case self::COGNITIVE_LEVEL_3:
                    // Cognitive level 3 is to view feedback.

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

                case self::COGNITIVE_LEVEL_2:
                    // Cognitive depth level 2 is to submit content.

                    if ($this->any_write_log($contextid, $user)) {
                        $score += $scoreperlevel * 2;
                        break;
                    }
                    // The user didn't reach the activity max cognitive depth, continue with level 1.

                case self::COGNITIVE_LEVEL_1:
                    // Cognitive depth level 1 is just accessing the activity.

                    if ($this->any_log($contextid, $user)) {
                        $score += $scoreperlevel;
                    }

                default:
            }
        }

        // 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;
    }
64652
public function checkinRecords(int $startTime, int $endTime, array $userList, int $type = 3)
    {
        $params = [
            'opencheckindatatype' => $type,
            'starttime' => $startTime,
            'endtime' => $endTime,
            'useridlist' => $userList,
        ];

        return $this->httpPostJson('cgi-bin/checkin/getcheckindata', $params);
    }
132783
public function performQuery(string $viewId, DateTime $startDate, DateTime $endDate, string $metrics, array $others = [])
    {
        $cacheName = $this->determineCacheName(func_get_args());

        if ($this->cacheLifeTimeInMinutes == 0) {
            $this->cache->forget($cacheName);
        }

        return $this->cache->remember($cacheName, $this->cacheLifeTimeInMinutes, function () use ($viewId, $startDate, $endDate, $metrics, $others) {
            $result = $this->service->data_ga->get(
                "ga:{$viewId}",
                $startDate->format('Y-m-d'),
                $endDate->format('Y-m-d'),
                $metrics,
                $others
            );

            while ($nextLink = $result->getNextLink()) {
                if (isset($others['max-results']) && count($result->rows) >= $others['max-results']) {
                    break;
                }

                $options = [];

                parse_str(substr($nextLink, strpos($nextLink, '?') + 1), $options);

                $response = $this->service->data_ga->call('get', [$options], 'Google_Service_Analytics_GaData');

                if ($response->rows) {
                    $result->rows = array_merge($result->rows, $response->rows);
                }

                $result->nextLink = $response->nextLink;
            }

            return $result;
        });
    }
668541
public function pageShakeAroundStatistics($page_id, $begin_date, $end_date)
    {
        if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
        $data = array('page_id' => $page_id, 'begin_date' => $begin_date, 'end_date' => $end_date);
        $result = Tools::httpPost(self::API_BASE_URL_PREFIX . self::SHAKEAROUND_STATISTICS_DEVICE . "access_token={$this->access_token}", Tools::json_encode($data));
        if ($result) {
            $json = json_decode($result, true);
            if (empty($json) || !empty($json['errcode'])) {
                $this->errCode = isset($json['errcode']) ? $json['errcode'] : '505';
                $this->errMsg = isset($json['errmsg']) ? $json['errmsg'] : '无法解析接口返回内容！';
                return $this->checkRetry(__FUNCTION__, func_get_args());
            }
            return $json;
        }
        return false;
    }
388141
@SuppressWarnings("PMD.UnusedFormalParameter")
    @Override
    public Double getInstanceCPUSinceLastRun(String instanceId, long lastUpdated) {

//        long offsetInMilliseconds = Math.min(ONE_DAY_MILLI_SECOND,System.currentTimeMillis() - lastUpdated);
        Dimension instanceDimension = new Dimension().withName("InstanceId")
                .withValue(instanceId);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, -1);
//        long oneDayAgo = cal.getTimeInMillis();

        GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
                .withMetricName("CPUUtilization")
                .withNamespace("AWS/EC2")
                .withPeriod(60 * 60)
                // one hour
                .withDimensions(instanceDimension)
                // to get metrics a specific
                // instance
                .withStatistics("Average")
                .withStartTime(new Date(new Date().getTime() - 1440 * 1000))
                .withEndTime(new Date());
        GetMetricStatisticsResult result = cloudWatchClient
                .getMetricStatistics(request);
        // to read data
        List<Datapoint> datapoints = result.getDatapoints();
        if (CollectionUtils.isEmpty(datapoints)) return 0.0;
        Datapoint datapoint = datapoints.get(0);
        return datapoint.getAverage();
    }
835808
public function getrecord($endtime, $pageindex, $pagesize, $starttime)
    {
        $recond_array = [
            'endtime'   => $endtime,
            'pageindex' => $pageindex,
            'pagesize'  => $pagesize,
            'starttime' => $starttime,
        ];

        $this->apitype = 'customservice';

        $this->module = 'msgrecord';

        $res = $this->_post('getrecord', $recond_array);

        return $res;
    }
86868
protected function calculate_sample($sampleid, $sampleorigin, $starttime = false, $endtime = false) {

        $actionevents = \core_calendar_external::get_calendar_action_events_by_timesort($starttime, $endtime, 0, 1,
            true, $sampleid);

        if ($actionevents->events) {

            // We first need to check that at least one of the core_calendar_provide_event_action
            // callbacks has the $userid param.
            foreach ($actionevents->events as $event) {
                $nparams = $this->get_provide_event_action_num_params($event->modulename);
                if ($nparams > 2) {
                    return self::get_max_value();
                }
            }
        }

        return self::get_min_value();
    }
463250
public function calculate_sample($sampleid, $sampleorigin, $notusedstarttime = false, $notusedendtime = false) {

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

        if (is_null($this->studentroleids)) {
            $this->studentroleids = array_keys(get_archetype_roles('student'));
        }

        foreach ($this->studentroleids as $role) {
            // We look for roles, not enrolments as a student assigned at category level is supposed to be a
            // course student.
            $students = get_role_users($role, $context, false, 'u.id', 'u.id');
            if ($students) {
                return self::get_max_value();
            }
        }

        return self::get_min_value();
    }
558622
private function getSource(int $startID, int $endID): string
    {
        $result = '';
        for ($tokenID = $startID; $tokenID <= $endID; ++$tokenID) {
            //Collecting function usage src
            $result .= $this->tokens[$tokenID][self::TOKEN_CODE];
        }

        return $result;
    }
51751
public function calculate_sample($sampleid, $sampleorigin, $notusedstarttime = false, $notusedendtime = false) {

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

        // It may not be available, but if it is the indicator checks if completion is enabled for the cm.
        $cm = $this->retrieve('course_modules', $sampleid);

        $completion = new \completion_info($course);

        if (!$completion->is_enabled($cm)) {
            $value = self::get_min_value();
        } else if (!$cm && !$completion->has_criteria()) {
            // Course completion enabled with no criteria counts as nothing.
            $value = self::get_min_value();
        } else {
            $value = self::get_max_value();
        }
        return $value;
    }
120534
public static function getMonthsRange($startData, $endDate) {
        $time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons
        $time2 = strtotime($endDate);
        //$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity
        //$my2 = date('mY', $time2);
        $year1 = date('Y', $time1);
        $year2 = date('Y', $time2);
        $years = range($year1, $year2);
        $months = Array();
        foreach ($years as $year) {
            $months[$year] = array();
            while ($time1 < $time2) {
                if (date('Y', $time1) == $year) {
                    $months[$year][] = date('m', $time1);
                    $time1 = strtotime(date('Y-m-d', $time1) . ' +1 month');
                } else {
                    break;
                }
            }
            continue;
        }

        return $months;
    }
354399
public function getDomainSummaryStatistics($options = array())
    {
        list($config, $startTime, $endTime) = $this->parseOptions(
            $options,
            'config',
            'startTime',
            'endTime'
        );

        if (empty($startTime)) {
            throw new BceClientException("The query parameter startTime "
                . "should NOT be null or empty string");
        }
        if (empty($endTime)) {
            throw new BceClientException("The query parameter endTime "
                . "should NOT be null or empty string");
        }

        $params = array(
            'startTime' => $startTime,
            'endTime' => $endTime,
        );

        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            "/statistics/domain/summary"
        );
    }
34947
protected function calculate_indicators(\core_analytics\local\time_splitting\base $timesplitting, array $sampleids,
            array $ranges): array {
        global $DB;

        $options = $this->analyser->get_options();

        $dataset = array();

        // Faster to run 1 db query per range.
        $existingcalculations = array();
        if ($timesplitting->cache_indicator_calculations()) {
            foreach ($ranges as $rangeindex => $range) {
                // Load existing calculations.
                $existingcalculations[$rangeindex] = \core_analytics\manager::get_indicator_calculations(
                    $timesplitting->get_analysable(), $range['start'], $range['end'], $this->analyser->get_samples_origin());
            }
        }

        // Here we store samples which calculations are not all null.
        $notnulls = array();

        // Fill the dataset samples with indicators data.
        $newcalculations = array();
        foreach ($this->analyser->get_indicators() as $indicator) {

            // Hook to allow indicators to store analysable-dependant data.
            $indicator->fill_per_analysable_caches($timesplitting->get_analysable());

            // Per-range calculations.
            foreach ($ranges as $rangeindex => $range) {

                // Indicator instances are per-range.
                $rangeindicator = clone $indicator;

                $prevcalculations = array();
                if (!empty($existingcalculations[$rangeindex][$rangeindicator->get_id()])) {
                    $prevcalculations = $existingcalculations[$rangeindex][$rangeindicator->get_id()];
                }

                // Calculate the indicator for each sample in this time range.
                list($samplesfeatures, $newindicatorcalculations, $indicatornotnulls) = $rangeindicator->calculate($sampleids,
                    $this->analyser->get_samples_origin(), $range['start'], $range['end'], $prevcalculations);

                // Copy the features data to the dataset.
                foreach ($samplesfeatures as $analysersampleid => $features) {

                    $uniquesampleid = $timesplitting->append_rangeindex($analysersampleid, $rangeindex);

                    if (!isset($notnulls[$uniquesampleid]) && !empty($indicatornotnulls[$analysersampleid])) {
                        $notnulls[$uniquesampleid] = $uniquesampleid;
                    }

                    // Init the sample if it is still empty.
                    if (!isset($dataset[$uniquesampleid])) {
                        $dataset[$uniquesampleid] = array();
                    }

                    // Append the features indicator features at the end of the sample.
                    $dataset[$uniquesampleid] = array_merge($dataset[$uniquesampleid], $features);
                }

                if (!$options['evaluation'] && $timesplitting->cache_indicator_calculations()) {
                    $timecreated = time();
                    foreach ($newindicatorcalculations as $sampleid => $calculatedvalue) {
                        // Prepare the new calculations to be stored into DB.

                        $indcalc = new \stdClass();
                        $indcalc->contextid = $timesplitting->get_analysable()->get_context()->id;
                        $indcalc->starttime = $range['start'];
                        $indcalc->endtime = $range['end'];
                        $indcalc->sampleid = $sampleid;
                        $indcalc->sampleorigin = $this->analyser->get_samples_origin();
                        $indcalc->indicator = $rangeindicator->get_id();
                        $indcalc->value = $calculatedvalue;
                        $indcalc->timecreated = $timecreated;
                        $newcalculations[] = $indcalc;
                    }
                }
            }

            if (!$options['evaluation'] && $timesplitting->cache_indicator_calculations()) {
                $batchsize = self::get_insert_batch_size();
                if (count($newcalculations) > $batchsize) {
                    // We don't want newcalculations array to grow too much as we already keep the
                    // system memory busy storing $dataset contents.

                    // Insert from the beginning.
                    $remaining = array_splice($newcalculations, $batchsize);

                    // Sorry mssql and oracle, this will be slow.
                    $DB->insert_records('analytics_indicator_calc', $newcalculations);
                    $newcalculations = $remaining;
                }
            }
        }

        if (!$options['evaluation'] && $timesplitting->cache_indicator_calculations() && $newcalculations) {
            // Insert the remaining records.
            $DB->insert_records('analytics_indicator_calc', $newcalculations);
        }

        // Delete rows where all calculations are null.
        // We still store the indicator calculation and we still store the sample id as
        // processed so we don't have to process this sample again, but we exclude it
        // from the dataset because it is not useful.
        $nulls = array_diff_key($dataset, $notnulls);
        foreach ($nulls as $uniqueid => $ignoredvalues) {
            unset($dataset[$uniqueid]);
        }

        return $dataset;
    }
342652
public function getTimeEntries($startdate = null, $enddate = null)
    {
        if (empty($startdate)) {
            $startdate = date('Y-m-d', time() - 86400);
        }
        if (empty($enddate)) {
            $enddate = $startdate;
        }
        $this->uri = 'https://toggl.com/reports/api/v2/details?user_agent=' . $this->user_agent . '&since=' . $startdate . '&until=' . $enddate . '&workspace_id=' . $this->workspace_id;

        $data = null;
        
        $response = $this->processRequest($data, self::GET);
        $this->_handleError($data, $response);
        $toggl_entries = $this->processTogglResponse($response);
        $timeEntries = [];
        foreach ($toggl_entries as $entry) {
            $te = new TimeEntry(
                $this,
                $entry->id,
                $entry->client,
                $entry->project,
                $entry->description
            );
            $te->setEntryDate(date('Y-m-d', strtotime($entry->start)));
            $te->setDurationTime($entry->dur);
            $te->setTask($entry->task);
            $te->setDescription($entry->description);
            $te->processTags($entry->tags);
            $te->setBillable($entry->is_billable);
            $timeEntries[] = $te;
        }
        return $timeEntries;
    }
32661
public function getApprovalData($startTime, $endTime, $nextSpNum = null)
    {
        $params = [
            'starttime'  => $startTime,
            'endtime'    => $endTime,
            'next_spnum' => $nextSpNum,
        ];

        return $this->parseJSON('json', [self::API_APPROVAL_DATA, $params]);
    }