/** * Will store input repository. */ public function testWillStoreInputRepository() { $repository = \Mockery::mock(SchemaRepository::class); $instance = new SchemaService($repository); $helper = \ClassHelper::instance($instance); static::assertSame($repository, $helper->repository); }
public function run() { list($name, $id) = $this->resolveNameID(); if (isset($this->htmlOptions['id'])) { $id = $this->htmlOptions['id']; } else { $this->htmlOptions['id'] = $id; } if (isset($this->htmlOptions['name'])) { $name = $this->htmlOptions['name']; } else { $this->htmlOptions['name'] = $name; } // Сохранение информации осуществляется через behavior if ($this->hasModel()) { $this->objects = array(get_class($this->model), 'id', $this->model->id); } $controls = array(); if (is_array($this->objects) && !empty($this->objects)) { $operations = ClassHelper::getBehaviorPropertyByClassName($this->objects[0], 'AccessCBehavior', 'operations'); if (!empty($operations)) { if ($this->operation) { $controls[] = array('label' => $operations[$this->operation], 'content' => $this->rightsForOperation($this->operation)); } else { foreach ($operations as $operationName => $operationTitle) { $controls[] = array('label' => $operations[$operationName], 'content' => $this->rightsForOperation($operationName)); } } } } if (!empty($controls)) { $this->render('AccessRights', array('controls' => $controls, 'instantSave' => $this->instantSave)); } }
/** * When table entries are passed then store them. */ public function testWhenTableEntriesArePassedThenStoreThem() { $input = [\Mockery::mock(Table::class), \Mockery::mock(Table::class)]; $instance = TableCollection::build($input); $helper = \ClassHelper::instance($instance); static::assertSame($input, $helper->entries); }
protected function call() { $helper = \ClassHelper::instance($this->command); $helper->container = $this->container; $response = $helper->call('execute', [$this->input, $this->output]); return $response; }
/** * When entries are passed then store them. */ public function testWhenEntriesArePassedThenStoreThem() { $fields = [new TableField(), new TableField()]; $response = TableFieldCollection::build($fields); $helper = \ClassHelper::instance($response); static::assertEquals($fields, $helper->entries); }
public static function getAttributesByClassName($className) { $ret = ClassHelper::getBehaviorPropertyByClassName($className, 'AccessRBehavior', 'attributes'); if (empty($ret)) { $ret = array(); } return $ret; }
/** * When fields are instances of TableIndex then store the entries and return the instance. */ public function testWhenFieldsAreInstancesOfTableIndexThenStoreTheEntriesAndReturnTheInstance() { $input = [new TableIndex(), new TableIndex(), new TableIndex()]; $response = TableIndexCollection::build($input); static::assertInstanceOf(TableIndexCollection::class, $response); $helper = \ClassHelper::instance($response); static::assertEquals($input, $helper->entries); }
/** * Will store a reflectionclass of the object in the target attribute. */ public function testWillStoreAReflectionclassOfTheObjectInTheTargetAttribute() { $input = new \BadMethodCallException(); $response = \ClassHelper::instance($input); /** @var \ReflectionClass $value */ $value = \PHPUnit_Framework_Assert::readAttribute($response, 'target'); static::assertInstanceOf(\ReflectionClass::class, $value); static::assertEquals('BadMethodCallException', $value->getName()); }
/** * Store entries. */ public function testStoreEntries() { $name = StringLiteral::fromNative('sample_table_name'); $fields = TableFieldCollection::build([]); $indexes = TableIndexCollection::build([]); $instance = Table::build($name, $fields, $indexes); static::assertInstanceOf(Table::class, $instance); $helper = \ClassHelper::instance($instance); static::assertSame($name, $helper->name); static::assertSame($fields, $helper->fields); static::assertSame($indexes, $helper->indexes); }
public function studentsAction() { $this->view->disable(); // Get our context (this takes care of starting the session, too) $context = $this->getDI()->getShared('ltiContext'); if (!$context->valid) { echo '[{"error":"Invalid lti context"}]'; return; } $classHelper = new ClassHelper(); $masteryHelper = new MasteryHelper(); $statementHelper = new StatementHelper(); $students = $classHelper->allStudents(); $studentInfo = []; for ($i = 0; $i < 10; $i++) { // For second parameter of what to query, see http://php.net/manual/en/mongocollection.find.php $statements = $statementHelper->getStatements("ayamel", ['statement.actor.name' => $students[$i]], ['statement.object.id' => true]); $count = $statements["cursor"]->count(); $studentInfo[] = ["name" => $students[$i], "count" => $count]; } echo json_encode($studentInfo); }
public function cacheTestAction() { $classHelper = new ClassHelper(); $studentIds = $classHelper->allStudents(); //$studentIds = ["John Logie Baird"]; // Calculate an overall mastery score for these units, as well as an average for concepts over the past 2 weeks $units = ["1", "2", "3", "4", "recent"]; // Go through each student and calculate unit mastery scores foreach ($studentIds as $studentId) { // See if we've already scored mastery scores for this student on the current day (this script just runs multiple times, until a better method to get around 60 second execution time limit is devised) $lastHistory = StudentMasteryHistory::findFirst(["email = '{$studentId}'", "order" => "time_stored DESC"]); if (!$lastHistory) { } echo "last history is false"; if (gettype($lastHistory)) { if (date("Y-m-d") == date("Y-m-d", strtotime($lastHistory->time_stored))) { echo " History already saved today for {$studentId}\n"; continue; } } } }
/** * Store input fields values. */ public function testStoreInputFieldsValues() { $table = new StringLiteral('sample-table'); $nonUnique = new StringLiteral('sample-nonUnique'); $keyName = new StringLiteral('sample-keyName'); $seqInIndex = new StringLiteral('sample-seqInIndex'); $columnName = new StringLiteral('sample-columnName'); $collation = new StringLiteral('sample-collation'); $cardinality = new StringLiteral('sample-cardinality'); $subPart = new StringLiteral('sample-subPart'); $packed = new StringLiteral('sample-packed'); $isNull = true; $indexType = new StringLiteral('sample-indexType'); $comment = new StringLiteral('sample-comment'); $indexComment = new StringLiteral('sample-indexComment'); $response = TableIndex::build($table, $nonUnique, $keyName, $seqInIndex, $columnName, $collation, $cardinality, $subPart, $packed, $isNull, $indexType, $comment, $indexComment); // assert output type static::assertInstanceOf(TableIndex::class, $response); $helper = \ClassHelper::instance($response); // check stored values static::assertSame($table, $helper->table); static::assertSame($nonUnique, $helper->nonUnique); static::assertSame($keyName, $helper->keyName); static::assertSame($seqInIndex, $helper->seqInIndex); static::assertSame($columnName, $helper->columnName); static::assertSame($collation, $helper->collation); static::assertSame($cardinality, $helper->cardinality); static::assertSame($subPart, $helper->subPart); static::assertSame($packed, $helper->packed); static::assertSame($isNull, $helper->isNull); static::assertSame($indexType, $helper->indexType); static::assertSame($comment, $helper->comment); static::assertSame($indexComment, $helper->indexComment); // check output toArray $expected = ['table' => 'sample-table', 'nonUnique' => 'sample-nonUnique', 'keyName' => 'sample-keyName', 'seqInIndex' => 'sample-seqInIndex', 'columnName' => 'sample-columnName', 'collation' => 'sample-collation', 'cardinality' => 'sample-cardinality', 'subPart' => 'sample-subPart', 'packed' => 'sample-packed', 'isNull' => true, 'indexType' => 'sample-indexType', 'comment' => 'sample-comment', 'indexComment' => 'sample-indexComment']; static::assertEquals($expected, $response->toArray()); }
public function allowed($action = 'read', $force = false) { // Не позволяем запускать условие два раза в одном запросе if (($force || !isset($this->getOwner()->getDbCriteria()->params['aco_class']) || !isset($this->getOwner()->getDbCriteria()->params['aro_class'])) && ClassHelper::getBehaviorPropertyByClassName(get_class($this->getOwner()), 'AccessCBehavior', 'class')) { $user = Yii::app()->user->data; if (ClassHelper::getBehaviorPropertyByClassName(get_class($user), 'AccessRBehavior', 'class') && !$user->checkFullAccess()) { $params = array('aco_class' => get_class($this->getOwner()), 'action' => $action); $acoWhere = array('(a.`aco_key` = "" AND a.`aco_value` = "")', '(a.`aco_key` = "id" AND a.`aco_value` = t.`id`)'); $cAttributes = AccessCBehavior::getAttributesByClassName($params['aco_class']); foreach ($cAttributes as $attrName) { $acoWhere[] = '(a.`aco_key` = "' . $attrName . '" AND a.`aco_value` = t.`' . $attrName . '`)'; } $acoWhereStatement = implode(' OR ', $acoWhere); $aroWhereStatement = AccessRBehavior::generateAroWhereStatement($user, $params, 'a.'); $this->getOwner()->getDbCriteria()->mergeWith(array('join' => 'INNER JOIN `' . AccessItem::tableName() . '` a ON a.action = :action AND a.aco_class = :aco_class AND a.aro_class = :aro_class AND (' . $acoWhereStatement . ') AND (' . $aroWhereStatement . ')', 'params' => $params)); } } return $this->getOwner(); }
/** @see PHPFIT_TypeAdapter_PhpTolerant in shelf folder * @return string type of PHPFIT_TypeAdapter */ static function getType($classOrObject, $name, $property) { return ClassHelper::adapterType(); }
public static function location_error_not_found($not_found_page_url = null) { if (!$not_found_page_url) { $not_found_page_url = ZPHP::get_actual_uri(); } $not_found_page_control_classname = ZPHP::get_config('redirect_control_special_pages_not_found_page_control'); if ($not_found_page_control_classname) { $not_found_page_control = ClassHelper::create_instance($not_found_page_control_classname); } else { $not_found_page_control = null; } header("HTTP/1.0 404 Not Found"); if ($not_found_page_control) { $not_found_page_control->out(); } die; }
public function scatterplotAction($scope = 'concept', $groupingId = '', $debug = false) { $this->view->disable(); // Get our context (this takes care of starting the session, too) $context = $this->getDI()->getShared('ltiContext'); if (!$context->valid) { echo '[{"error":"Invalid lti context"}]'; return; } // Get the list of questions associated with concepts for the given scope and grouping ID $questions = []; switch ($scope) { case "concept": // Filter based on concept $questions = MappingHelper::questionsInConcept($groupingId); break; case "unit": // Filter based on unit $questions = MappingHelper::questionsInConcepts(MappingHelper::conceptsInUnit($groupingId)); break; default: echo '[{"error":"Invalid scope option"}]'; return; break; } if ($debug) { echo "questions for scope {$scope} and grouping {$groupingId}: \n"; print_r($questions); } $classHelper = new ClassHelper(); // Array of questions with more details about each $questionDetails = array(); // Get some info about each question foreach ($questions as $question) { // Check that it's a valid question if ($question != false) { // Get number of attempts $question["attempts"] = MasteryHelper::countAttemptsForQuestion($context->getUserName(), $question["OA Quiz ID"], $question["Question Number"], $debug); $question["scaledAttemptScore"] = $classHelper->calculateScaledAttemptScoreForQuestion($question["attempts"], $question["OA Quiz ID"], $question["Question Number"], $debug); // Get amount of associated videos watched // Note that question ID is being used instead of assessment ID and question number, since we're searching the csv mapping and not dealing with assessment statements here $question["videoPercentage"] = MasteryHelper::calculateUniqueVideoPercentageForQuestion($context->getUserName(), $questionId); $questionDetails[] = $question; } } /* function randomPoint($group, $q) { // Randomly return outliers if (rand(0,30) == 5) { return [$group, $q["quizNumber"], $q["questionNumber"], rand(-10000, 1000), rand(-10000, 1000)]; } return [$group, $q["quizNumber"], $q["questionNumber"], rand(-100, 100), rand(-100, 100)]; } $result = []; // For now, return random points based on number of questions $numPoints = count($questionDetails); //foreach ($questionDetails as $q) { //$result [] = //} // for ($i=0; $i<$numPoints; $i++) { $result []= randomPoint("student", $questionDetails[$i]); for ($j=0; $j<10; $j++) { $result []= randomPoint("class", $questionDetails[$i]); } } $xValues = array_map(function($point) { return $point[3]; }, $result); $yValues = array_map(function($point) { return $point[4]; }, $result); // TODO check that xValues and yValues have a length, otherwise statshelper will spit out errors // Perform some statistics grossness // Remove any outliers for both axes, based on 1.5*IQR // Cap and floor x outliers $xStats = StatsHelper::boxPlotValues($xValues); $result = array_map(function($point) use ($xStats) { $x = $point[3]; // Floor upper outliers if ($x > $xStats['q3'] + (1.5 * $xStats['iqr'])) { $x = $xStats['q3'] + (.5 * $xStats['iqr']); } // Cap lower outliers if ($x < $xStats['q1'] - (1.5 * $xStats['iqr'])) { $x = $xStats['q1'] - (.5 * $xStats['iqr']); } $point[3] = $x; return $point; }, $result); // Scale all the scores from 0 to 10 // TODO // Cap and floor y outliers $yStats = StatsHelper::boxPlotValues($yValues); $result = array_map(function($point) use ($yStats) { $y = $point[4]; // Floor upper outliers if ($y > $yStats['q3'] + (1.5 * $yStats['iqr'])) { $y = $yStats['q3'] + (.5 * $yStats['iqr']); } // Cap lower outliers if ($y < $yStats['q1'] - (1.5 * $yStats['iqr'])) { $y = $yStats['q1'] - (.5 * $yStats['iqr']); } $point[4] = $y; return $point; }, $result); //print_r($result); //print_r($yStats); //die(); */ // X = video percentage, Y = question attempts $headerRow = ["group", "quiz_number", "question_number", "x", "y"]; $result = array_map(function ($q) { return ["student", $q["OA Quiz ID"], $q["Question Number"], $q["videoPercentage"], $q["scaledAttemptScore"]]; }, $questionDetails); if ($debug) { echo "question details for scope {$scope} and grouping {$groupingId}: \n"; print_r($questionDetails); print_r($result); } // Output data as csv so that we only have to send header information once for so many points if (!$debug) { header("Content-Type: text/csv"); } $output = fopen("php://output", "w"); fputcsv($output, $headerRow); foreach ($result as $row) { fputcsv($output, $row); // here you can change delimiter/enclosure } fclose($output); }
public function questionRecommendationsAction($scope = 'unit', $groupingId = '3', $debug = false) { $this->view->disable(); // Get our context (this takes care of starting the session, too) $context = $this->getDI()->getShared('ltiContext'); if (!$context->valid) { echo '[{"error":"Invalid lti context"}]'; return; } if (!isset($groupingId)) { echo '[{"error":"No scope grouping ID specified"}]'; return; } $classHelper = new ClassHelper(); $group1 = []; $group2 = []; $group3 = []; $group4 = []; // Get the list of questions associated with concepts for the given scope and grouping ID $questionRows = []; switch ($scope) { case "concept": // Filter based on concept $questionRows = MappingHelper::questionsInConcept($groupingId); break; case "unit": // Filter based on unit $questionRows = MappingHelper::questionsInConcepts(MappingHelper::conceptsInUnit($groupingId)); break; default: // Allowing all would take too long echo '[{"error":"Invalid scope option"}]'; return; break; } if ($debug) { echo "<pre>Getting information for these questions in scope {$scope} and ID {$groupingId}\n"; print_r($questionRows); } $questions = []; // Get some info about each question foreach ($questionRows as $question) { // Get number of attempts and number of correct attempts $question["attempts"] = MasteryHelper::countAttemptsForQuestion($context->getUserName(), $question["OA Quiz ID"], $question["Question Number"], $debug); $question["correctAttempts"] = MasteryHelper::countCorrectAttemptsForQuestion($context->getUserName(), $question["OA Quiz ID"], $question["Question Number"], $debug); // Get amount of associated videos watched $question["videoPercentage"] = MasteryHelper::calculateUniqueVideoPercentageForQuestion($context->getUserName(), $question); // Variables used in the display table // This is one place where we're just using correct, not better correct, attempts $question["correct"] = $question["correctAttempts"]["correct"] > 0; $question["classAverageAttempts"] = $classHelper->calculateAverageAttemptsForQuestion($question["OA Quiz ID"], $question["Question Number"], $debug); $question["classViewedHint"] = $classHelper->calculateViewedHintPercentageForQuestion($question["OA Quiz ID"], $question["Question Number"], $debug); $question["classViewedAnswer"] = $classHelper->calculateViewedAnswerPercentageForQuestion($question["OA Quiz ID"], $question["Question Number"], $debug); $questions[] = $question; } // Fetch question texts for all questions in these assessments // Get the Open Assessments API endpoint from config $assessmentsEndpoint = $this->getDI()->getShared('config')->openassessments_endpoint; // Extract a list of assessment IDs from our list of questions. We'll get question texts for these. $assessmentIDs = ["assessment_ids" => array_values(array_unique(array_column($questions, "OA Quiz ID")))]; $request = $assessmentsEndpoint . "api/question_text"; //$request = "http://192.168.33.102/api/question_text"; if ($debug) { echo "Fetching question texts for these assessment IDs:\n"; print_r(array_column($questions, "OA Quiz ID")); print_r($assessmentIDs); echo $request; } #print_r($assessmentIDs); #echo json_encode($request); $session = curl_init($request); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); curl_setopt($session, CURLOPT_POST, 1); curl_setopt($session, CURLOPT_POSTFIELDS, json_encode($assessmentIDs)); $response = curl_exec($session); #echo json_encode($questionRows); // Catch curl errors if (curl_errno($session)) { $error = "Curl error: " . curl_error($session); } curl_close($session); #print_r($response); $questionTexts = json_decode($response, true); if ($debug) { print_r($questionTexts); } foreach ($questions as $key => $q) { // Make sure the question text exists before setting it $questions[$key]["display"] = isset($questionTexts[$q["OA Quiz ID"]][$q["Question Number"] - 1]) ? $questionTexts[$q["OA Quiz ID"]][$q["Question Number"] - 1] : "Error getting question text for #{$q["OA Quiz ID"]} # #{$q["Question Number"]}-1"; // Avoid off-by-one error. The question id from statement object id will be 1 to n+1 //$q["questionText"] = $questionText; } // Now go through the questions for each group and find matching questions foreach ($questions as $question) { // Group 1: // Questions with 0 attempts if ($question["attempts"] == 0) { $group1[] = $question; } // Group 2: // >0 attempts for each question // No correct statements without a show answer statement in the preceding minute for each question (correctAttempts < 1) // Watched less than half of the videos associated with each question if ($question["attempts"] > 0 && $question["correctAttempts"]["betterCorrect"] == 0 && $question["videoPercentage"] < 0.5) { $group2[] = $question; } // Group 3: // >0 attempts for each question // No correct statements without a show answer statement in the preceding minute for each question (correctAttempts < 1) // Watched more than half of the videos associated with each question if ($question["attempts"] > 0 && $question["correctAttempts"]["betterCorrect"] == 0 && $question["videoPercentage"] >= 0.5) { $group3[] = $question; } // Group 4: // > 0 correct statements without a show answer statement in the preceding minute for each question (correctAttempts > 0) // More than 1 attempt if ($question["correctAttempts"]["betterCorrect"] > 0 && $question["attempts"] > 1) { $group4[] = $question; } } if ($debug) { print_r($questions); } $result = ["group1" => $group1, "group2" => $group2, "group3" => $group3, "group4" => $group4]; echo json_encode($result); }
public function setUp() { $this->instance = \ClassHelper::instance(new UnderTestGet()); }
public function type() { return ClassHelper::classToType(get_called_class()); }
public function setUp() { $this->origin = new UnderTestGet(); $this->instance = \ClassHelper::instance($this->origin); }
<?php $what = ''; if (array_key_exists(2, $_SERVER['argv'])) { $what = $_SERVER['argv'][2]; if (array_key_exists(3, $_SERVER['argv'])) { $classname = $_SERVER['argv'][3]; } } $helper = new ClassHelper(); switch ($what) { case 'core': $helper->setBase(CORE_PATH); $helper->create('Core', $classname); break; case '': Core_Console::output(file_get_contents(HELPTEXT_PATH . '/class.txt')); break; default: $helper->create('App', $classname); break; } class ClassHelper { public function create($type, $path) { } }
public function studentsAction($start, $finish) { $this->view->disable(); // Get our context (this takes care of starting the session, too) $context = $this->getDI()->getShared('ltiContext'); if (!$context->valid) { echo '[{"error":"Invalid lti context"}]'; return; } $timeArray[] = 280; $classHelper = new ClassHelper(); $masteryHelper = new MasteryHelper(); $statementHelper = new StatementHelper(); $recent_concepts = MappingHelper::conceptsWithin2Weeks(); $students = $classHelper->allStudents(); // $students = ["John Logie Baird","me"]; $studentInfo = []; $maxCount = 0; //count($students) for ($i = $start; $i < $finish; $i++) { $startTime = microtime(true); $studentAverages = StudentMasteryHistory::findFirst(["conditions" => "email = ?1", "bind" => array(1 => $students[$i]), "order" => 'time_stored DESC']); // For second parameter of what to query, see http://php.net/manual/en/mongocollection.find.php $visStatements = $statementHelper->getStatements("visualization", ['statement.actor.name' => $students[$i]], ['statement.object.id' => true]); $hints = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/showed-hint'], ['statement.object.id' => true]); $showAnswer = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/showed-answer'], ['statement.object.id' => true]); $questionsAnswered = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/answered'], ['statement.object.id' => true, 'statement.context.extensions' => true]); $hintsShowed = $hints["cursor"]->count(); $answersShowed = $showAnswer["cursor"]->count(); $high = 0; $medium = 0; $low = 0; $attempts = $questionsAnswered["cursor"]->count(); $correct = 0; foreach ($questionsAnswered["cursor"] as $confidenceCheck) { $confidenceCheck = StatementHelper::replaceHtmlEntity($confidenceCheck, true); if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/correct'] == true) { $correct++; } if (array_key_exists('http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level', $confidenceCheck['statement']['context']['extensions'])) { if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "high") { $high++; } if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "medium") { $medium++; } if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "low") { $low++; } } } $commonConfidence = max($high, $medium, $low); if ($commonConfidence == $high) { $medianConfidence = "High"; } else { if ($commonConfidence == $medium) { $medianConfidence = "Medium"; } else { $medianConfidence = "Low"; } } $count = $visStatements["cursor"]->count(); $escapedString = str_replace("'", "", $students[$i]); // echo $escapedString; $lastHistory = VideoHistory::findFirst(["student = '{$escapedString}'", "order" => "time_stored DESC"]); $vidPercent = $lastHistory->vidpercentage; if ($count > $maxCount && $students[$i] != 'John Logie Baird') { $maxCount = $count; } if (!is_object($studentAverages)) { $newStudent = ["name" => $students[$i], "average" => 0, "count" => $count, "vPercentage" => $vidPercent, "correct" => $correct, "attempts" => $attempts, "hintsShowed" => $hintsShowed, "answersShowed" => $answersShowed, "confidence" => $medianConfidence]; } else { $newStudent = ["name" => $studentAverages->email, "average" => $studentAverages->recent_average, "count" => $count, "vPercentage" => $vidPercent, "correct" => $correct, "attempts" => $attempts, "hintsShowed" => $hintsShowed, "answersShowed" => $answersShowed, "confidence" => $medianConfidence]; } if ($students[$i] != 'John Logie Baird' && $students[$i] != 'Bob Bodily') { $studentInfo[] = $newStudent; } $endTime = microtime(true); $timeArray[$i] = $endTime - $startTime; //echo "Execution time: " . ($endTime - $startTime) ." seconds\n"; } $avg = 0; foreach ($timeArray as $time) { $avg += $time; } $avg = $avg / 280; // echo "Average Time: ".$avg." seconds\n"; //Sorts the students by their recent mastery average, from highest to lowest. usort($studentInfo, function ($student1, $student2) { return $student1["average"] <= $student2["average"]; }); $firstRow = ["max" => $maxCount]; array_unshift($studentInfo, $firstRow); echo json_encode($studentInfo); }
/** * Loads the specified plugin and returns the instance * @param $name string Name of plugin to load * @return object returns the plugin instance */ public function plugin($name, $basePath = '') { if ($basePath == '') { $basePath = PLUGINS_PATH; } if (!in_array($name, self::$__loaded)) { if (!file_exists("{$basePath}/{$name}/class.php")) { throw new LoaderPluginNotFound($name); } include "{$basePath}/{$name}/class.php"; } if (!array_key_exists($name, self::$__plugins)) { $strName = ClassHelper::cleanClassName($name . 'Plugin'); self::$__plugins[$name] = new $strName(); } return self::$__plugins[$name]; }
/** * When the method doesn't exist then throw exception. * @expectedException \BadMethodCallException * @expectedExceptionMessage Method not found on object tests\ClassHelper\UnderTestCall. */ public function testWhenTheMethodDoesnTExistThenThrowException() { $this->instance->call('getNonexistingMethod'); }
function getArgTypesForMethod($classOrObject, $name, $params) { return ClassHelper::getArgTypesForMethod($classOrObject, $name); }
public function videoHistoryAction() { $config = $this->getDI()->getShared('config'); if (!isset($_GET["p"])) { die("No history saver password provided."); } if ($_GET["p"] != $config->historySaverPassword) { die("Invalid history saver password provided. Should be {$config->historySaverPassword}"); } // We want to time this $startTime = microtime(true); $raw = false; $debug = false; $classHelper = new ClassHelper(); $masteryHelper = new MasteryHelper(); $studentIds = $classHelper->allStudents(); $recent_concepts = MappingHelper::conceptsWithin2Weeks(); foreach ($studentIds as $student) { $escStudent = str_replace("'", "", $student); $lastHistory = VideoHistory::findFirst(["student = '{$escStudent}'", "order" => "time_stored DESC"]); if (date("Y-m-d") == date("Y-m-d", strtotime($lastHistory->time_stored))) { echo " History already saved today for student: {$student}\n"; continue; } $videoPercentage = $masteryHelper->calculateUniqueVideoPercentageForConcepts($student, $recent_concepts); $videoHistory = new VideoHistory(); $videoHistory->student = $escStudent; $videoHistory->vidpercentage = $videoPercentage; if ($videoHistory->create() == false) { echo "*** Error saving concept history for {$concept}\n"; } else { } } // Print total time taken $endTime = microtime(true); echo "Execution time: " . ($endTime - $startTime) . " seconds\n"; }
public function model($name, $basePath = '') { if ($basePath == '') { $basePath = $this->directory; } $classRef = new ClassReference(); $classRef->className = ClassHelper::cleanClassName($name); $classRef->classPath = "{$basePath}{$name}.php"; $this->managers[$name] = $classRef; }