Find the corresponding choice id of the first correct answer of a shortanswer question.
choice is added to the randomsamatch question if it doesn't already exist.
@param object $wrappedquestion short answer question.
@return int correct choice id.
354977
public function find_right_answer($wrappedquestion) {
        // We only take into account *one* (the first) correct answer.
        while ($answer = array_shift($wrappedquestion->answers)) {
            if (!question_state::graded_state_for_fraction(
                    $answer->fraction)->is_incorrect()) {
                // Store this answer as a choice, only if this is a new one.
                $key = array_search($answer->answer, $this->choices);
                if ($key === false) {
                    $key = $answer->id;
                    $this->choices[$key] = $answer->answer;
                }
                return $key;
            }
        }
        // We should never get there.
        throw new coding_exception('shortanswerquestionwithoutrightanswer', $wrappedquestion->id);

    }
1147209
public function evaluateQuestion(array $question, PhpStringParser $parser, GeneratorDataObject $generator)
    {
        return $this->getInstance($question)->ask($question, $parser, $generator);
    }
621674
protected function get_correct_answers($question) {
        $arrayofchoices = $this->get_array_of_choices($question);
        $arrayofplaceholdeers = $this->get_array_of_placeholders($question);

        $correctplayers = array();
        foreach ($arrayofplaceholdeers as $ph) {
            foreach ($arrayofchoices as $key => $choice) {
                if ($key + 1 == $ph) {
                    $correctplayers[] = $choice;
                }
            }
        }
        return $correctplayers;
    }
833906
private function get_number_of_questions_to_add_choices() {
        $maxrand = 100;
        $randomcount = array();
        for ($i = 1; $i <= min(10, $maxrand); $i++) {
            $randomcount[$i] = $i;
        }
        for ($i = 20; $i <= min(100, $maxrand); $i += 10) {
            $randomcount[$i] = $i;
        }
        return $randomcount;
    }
369507
public function getSafeList($count = null, $maxId = null, $sinceId = null)
    {
        $parameters = array(
          'count' => $count,
          'max_id' => $maxId,
          'since_id' => $sinceId,
        );

        $parameters = array_filter($parameters, function($val) {return !is_null($val);});

        return $this->online->call('/storage/c14/safe', 'GET', $parameters);
    }
764296
public function choice($question, $choices = array(), $allowedMultiple = false)
    {
        $this->output->writeln($question);

        $this->output->writeln(join(',', $choices));

        $answer = $this->input->getInput();

        $valid = $this->validateChoices($answer, $choices, $allowedMultiple);

        if ($valid !== false) {
            return $valid;
        }

        $this->output->writeln($this->wrongChoiceErrorMessage);

        return false;
    }
1017831
public function getNextQuestion()
    {
        $nextQuestionId = $this->getCurrentQuestion() + 1;
        $questions = $this->getUserConfiguration()->getQuestions();

        if (!isset($questions[$nextQuestionId])) {
            return false;
        }

        $this->setQuestion($nextQuestionId);

        return $this->getQuestion();
    }
1203112
public function correctAnswer(AbstractItem $question, $answer)
    {
        $corrected = new CorrectedAnswer();

        if (!is_null($answer)) {
            foreach ($answer as $holeAnswer) {
                $hole = $question->getHole($holeAnswer['holeId']);
                if ($hole) {
                    $keyword = $hole->getKeyword($holeAnswer['answerText']);
                    if (!empty($keyword)) {
                        if (0 < $keyword->getScore()) {
                            $corrected->addExpected($keyword);
                        } else {
                            $corrected->addUnexpected($keyword);
                        }
                    } else {
                        // Retrieve the best answer for the hole
                        $corrected->addMissing($this->findHoleExpectedAnswer($hole));
                    }
                }
            }
        } else {
            $holes = $question->getHoles();

            foreach ($holes as $hole) {
                $corrected->addMissing($this->findHoleExpectedAnswer($hole));
            }
        }

        return $corrected;
    }
675941
public function getQuestion() : ?string 
    {
        if ( ! $this->hasQuestion()) {
            $this->setQuestion($this->getDefaultQuestion());
        }
        return $this->question;
    }
1225507
public function askWithCompletion($question, array $choices, $default = null, $attempts = null, $strict = false)
    {
        $question = new Question($question, $default);
        $question->setMaxAttempts($attempts)->setAutocompleterValues($choices);

        if ($strict) {
            $question->setValidator(function($result) use ($choices) {
                if (!in_array($result, $choices)) {
                    throw new \InvalidArgumentException(sprintf(
                        'The provided answer is ambiguous. Value should be one of %s',
                        implode(' or ', $choices)));
                }

                return $result;
            });
        }

        return $this->askQuestion($question);
    }
610
private function choice($question, array $choices, $default, InputInterface $input, OutputInterface $output)
    {
        $helper = new QuestionHelper();

        $result = $helper->ask($input, $output, new ChoiceQuestion(
            $question,
            $choices,
            $choices[$default]
        ));

        $output->writeln('');

        return $result;
    }
146884
public function multichoiceStatement($translatorevent, $questionAttempt, $question) {
        $choices = [];
        foreach ($question->answers as $answer) {
            $choices['moodle_quiz_question_answer_'.$answer->id] = strip_tags($answer->answer);
        }

        // If there are answers, assume multiple choice until proven otherwise.
        $translatorevent['interaction_type'] = 'choice';
        $translatorevent['interaction_choices'] = $choices;

        $responses = [];
        $correctResponses = [];

        // We can't simply explode $questionAttempt->responsesummary because responses may contain "; ". 
        foreach ($choices as $answerId => $choice) {
            if ($this->inResponsesSummary($questionAttempt->responsesummary, $choice, '; ', '; ')) {
                array_push($responses, $answerId);
            }
            if (!(strpos($questionAttempt->rightanswer, $choice) === false)) {
                array_push($correctResponses, $answerId);
            }
        }

        if ($responses != []) {
            $translatorevent['attempt_response'] = implode('[,]', $responses);
        }

        $translatorevent['interaction_correct_responses'] = [implode('[,]', $correctResponses)];

        // Special handling of true-false question type (some overlap with multichoice).
        if ($question->qtype == 'truefalse') {
            $translatorevent['interaction_type'] = 'true-false';
            $translatorevent['interaction_choices'] = null;

            if ($questionAttempt->responsesummary == 'True') {
                $translatorevent['attempt_response'] = 'true';
            } else if ($questionAttempt->responsesummary == 'False') {
                $translatorevent['attempt_response'] = 'false';
            }

            if ($questionAttempt->rightanswer == 'True') {
                $translatorevent['interaction_correct_responses'] = ['true'];
            } else if ($questionAttempt->rightanswer == 'False') {
                $translatorevent['interaction_correct_responses'] = ['false'];
            }
        }


        return $translatorevent;
    }
25494
protected function getSelectedQuestion($questionSlug = null)
    {
        $selectedQuestion = null;

        if ($questionSlug !== null) {
            $selectedQuestion = $this->getQuestionRepository()->findOneBySlug($questionSlug);
        }

        return $selectedQuestion;
    }
748216
private function serializeChoices(BooleanQuestion $question, array $options = [])
    {
        return array_map(function (BooleanChoice $choice) use ($options) {
            $choiceData = $this->contentSerializer->serialize($choice, $options);
            $choiceData['id'] = $choice->getUuid();

            return $choiceData;
        }, $question->getChoices()->toArray());
    }
315769
public function getPostQuestionAnswer($id, $sort = null)
    {
        $question = new Question($this->di->get("db"));
        $user     = new User($this->di->get("db"));

        if ($question->find("id", $id) == null) {
            return false;
        }
        $question = $question->getQuestion($id);


        // This is a bad practice and should be in the module, (fix this after kmom10 future)
        // getting actual user Objects for posts for reputation show in view.
        $question->question->userObj = $user->getUser($question->user);
        $question->userObj           = $user->getUser($question->user);

        $question->answers = array_map(function ($answer) {
            $user                = new User($this->di->get("db"));
            $answer->userObj     = $user->getUser($answer->user);
            $answer->vote->score = $answer->vote->score == null ? 0 : $answer->vote->score;
            return $answer;
        }, $question->answers);

        // Get query for up or down
        $order = isset($_GET["order"]) ? $_GET["order"] : "up";

        // Highest points
        if ($sort == "points") {
            usort($question->answers, function ($current, $next) {
                return $current->vote->score > $next->vote->score;
            });
        }

        // Accepted top
        if ($sort == "accepted") {
            usort($question->answers, function ($current, $next) {
                return $current->accepted == "yes" ? 1 : -1;
            });
        }


        // Highest votes
        if ($sort == "vote") {
            usort($question->answers, function ($current, $next) {
                return count($current->vote->likes) > count($next->vote->likes);
            });
        }

        // If up array_reverse, "down" is default from module
        if ($order == "up") {
            $question->answers = array_reverse($question->answers);
        }

        $form       = new CreateAnswerForm($this->di, $id);
        $form->check();

        $views = [
            ["comment/question/view/view-question", ["question" => $question], "question"],
            ["comment/question/view/view-answers",
            ["answers" => $question->answers, "questionId" => $question->question->questionId], "answer"],
            ["comment/question/view/post-answer", ["form" => $form->getHTML()], "form"],
            ["comment/question/view/wrappedField", ["question" => $question], "main"]
            ];
        $this->di->get("pageRenderComment")->renderPage([
            "views" => $views,
            "title" => "Fråga $question->id"
        ]);

        return false;
    }
928882
private String getAnswerValue(QueryQuestionNumericAnswer answer) {
    return answer != null && answer.getData() != null ? String.valueOf(Math.round(answer.getData())) : null;
  }
139007
private function serializeSolutions(BooleanQuestion $question)
    {
        return array_map(function (BooleanChoice $choice) {
            $solutionData = [
                'id' => $choice->getUuid(),
                'score' => $choice->getScore(),
            ];

            if ($choice->getFeedback()) {
                $solutionData['feedback'] = $choice->getFeedback();
            }

            return $solutionData;
        }, $question->getChoices()->toArray());
    }