This method mirrors that in the Item.

        So that questions can also be inspected for learning objectives
542209
def get_learning_objective_ids(self):
        
        if 'learningObjectiveIds' not in self._my_map:  # Will this ever be the case?
            collection = JSONClientValidated('assessment',
                                             collection='Item',
                                             runtime=self._runtime)
            item_map = collection.find_one({'_id': ObjectId(Id(self._my_map['itemId']).get_identifier())})
            self._my_map['learningObjectiveIds'] = list(item_map['learningObjectiveIds'])
        return IdList(self._my_map['learningObjectiveIds'])
836093
def find_best_question(X, y, criterion):
    
    
    measure_impurity = gini_impurity if criterion == "gini" else entropy

    current_impurity = measure_impurity(y)
    best_info_gain = 0
    best_question = None

    for feature_n in range(X.shape[1]):
        for value in set(X[:, feature_n]):
            q = Question(feature_n, value)
            _, _, true_y, false_y = split(X, y, q)

            current_info_gain = info_gain(current_impurity, true_y, false_y, criterion)
            if current_info_gain >= best_info_gain:
                best_info_gain = current_info_gain
                best_question = q

    return best_info_gain, best_question
253905
def _update_questions(self):
        """"""
        if self.is_simple_section():
            return  # we don't need to go through any this for simple sections
        # ideally, we would update the parts map and questions list
        # at the same time as _get_parts(), to not run into the
        # issue where magic parts are initialized (with items)
        # ignorant of their "sibling" magic part items...
        # because the section hasn't been updated or saved to database
        part_list = self._get_parts()
        if len(part_list) > len(self._my_map['assessmentParts']):
            self._update_assessment_parts_map(part_list)
            self._update_questions_list(part_list)
            self._save()
700307
public function is_overridable_item() {
        if ($this->is_course_item() or $this->is_category_item()) {
            $overridable = (bool) get_config('moodle', 'grade_overridecat');
        } else {
            $overridable = false;
        }

        return !$this->is_outcome_item() and ($this->is_external_item() or $this->is_calculated() or $overridable);
    }
973191
def get_question(self):
        
        question_map = dict(self._my_map['question'])
        question_map['learningObjectiveIds'] = self._my_map['learningObjectiveIds']
        return Question(osid_object_map=question_map,
                        runtime=self._runtime,
                        proxy=self._proxy)
1188613
public function check_review_capability() {
        if ($this->get_attempt_state() == mod_quiz_display_options::IMMEDIATELY_AFTER) {
            $capability = 'mod/quiz:attempt';
        } else {
            $capability = 'mod/quiz:reviewmyattempts';
        }

        // These next tests are in a slighly funny order. The point is that the
        // common and most performance-critical case is students attempting a quiz
        // so we want to check that permisison first.

        if ($this->has_capability($capability)) {
            // User has the permission that lets you do the quiz as a student. Fine.
            return;
        }

        if ($this->has_capability('mod/quiz:viewreports') ||
                $this->has_capability('mod/quiz:preview')) {
            // User has the permission that lets teachers review. Fine.
            return;
        }

        // They should not be here. Trigger the standard no-permission error
        // but using the name of the student capability.
        // We know this will fail. We just want the stadard exception thown.
        $this->require_capability($capability);
    }
1041977
def validate(self):
        
        try:
            assert self.question_type == exercises.MULTIPLE_SELECTION, "Assumption Failed: Question should be multiple selection type"
            assert len(self.answers) > 0, "Assumption Failed: Multiple selection question should have answers"
            for a in self.answers:
                assert 'answer' in a and isinstance(a['answer'], str), "Assumption Failed: Answer in answer list is not a string"
                assert 'correct' in a and isinstance(a['correct'], bool), "Assumption Failed: Correct indicator is not a boolean in answer list"
            for h in self.hints:
                assert isinstance(h, str), "Assumption Failed: Hint in hint list is not a string"
            return super(MultipleSelectQuestion, self).validate()
        except AssertionError as ae:
            raise InvalidQuestionException("Invalid question: {0}".format(self.__dict__))
665588
boolean matchProcessingInstruction(
            final boolean blockMatching,
            final int markupLevel, final int markupBlockIndex) {

        checkMarkupLevel(markupLevel);

        if (this.markupSelectorItem.anyLevel() || markupLevel == 0 || (this.prev != null && this.prev.matchedMarkupLevels[markupLevel - 1])) {
            // This text has not matched yet, but might match, so we should check

            this.matchesThisLevel = this.markupSelectorItem.matchesProcessingInstruction(markupBlockIndex, this.markupBlockMatchingCounter);

            if (matchesPreviousOrCurrentLevel(markupLevel)) {
                // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

                if (this.next != null) {
                    return this.next.matchProcessingInstruction(blockMatching, markupLevel, markupBlockIndex);
                }
                return (blockMatching? true : this.matchesThisLevel);

            } else if (this.matchesThisLevel) {
                // This filter was not matched before. So the fact that it matches now means we need to consume it,
                // therefore not delegating.

                return (this.next == null);

            }

        } else if (matchesPreviousOrCurrentLevel(markupLevel)) {
            // This filter was already matched by a previous level (through an "open" event), so just delegate to next.

            if (this.next != null) {
                return this.next.matchProcessingInstruction(blockMatching, markupLevel, markupBlockIndex);
            }
            return blockMatching;

        }

        return false;

    }
1048786
def get_item_ids_for_assessment_part(self, assessment_part_id):
        """"""
        item_ids = []
        for question_map in self._my_map['questions']:
            if question_map['assessmentPartId'] == str(assessment_part_id):
                item_ids.append(Id(question_map['itemId']))
        return item_ids
1116033
def question_mark(self, request, obj):
        """"""
        obj.question = obj.question + '?'
        obj.save()
580272
def objectives(self, rank):
        
        self._check_rank(rank)
        return [result.obj for result in self.results[rank]]
56424
private static function question_structure() {
        return new external_single_structure(
            array(
                'slot' => new external_value(PARAM_INT, 'slot number'),
                'type' => new external_value(PARAM_ALPHANUMEXT, 'question type, i.e: multichoice'),
                'page' => new external_value(PARAM_INT, 'page of the quiz this question appears on'),
                'html' => new external_value(PARAM_RAW, 'the question rendered'),
                'sequencecheck' => new external_value(PARAM_INT, 'the number of real steps in this attempt', VALUE_OPTIONAL),
                'lastactiontime' => new external_value(PARAM_INT, 'the timestamp of the most recent step in this question attempt',
                                                        VALUE_OPTIONAL),
                'hasautosavedstep' => new external_value(PARAM_BOOL, 'whether this question attempt has autosaved data',
                                                            VALUE_OPTIONAL),
                'flagged' => new external_value(PARAM_BOOL, 'whether the question is flagged or not'),
                'number' => new external_value(PARAM_INT, 'question ordering number in the quiz', VALUE_OPTIONAL),
                'state' => new external_value(PARAM_ALPHA, 'the state where the question is in.
                    It will not be returned if the user cannot see it due to the quiz display correctness settings.',
                    VALUE_OPTIONAL),
                'status' => new external_value(PARAM_RAW, 'current formatted state of the question', VALUE_OPTIONAL),
                'blockedbyprevious' => new external_value(PARAM_BOOL, 'whether the question is blocked by the previous question',
                    VALUE_OPTIONAL),
                'mark' => new external_value(PARAM_RAW, 'the mark awarded.
                    It will be returned only if the user is allowed to see it.', VALUE_OPTIONAL),
                'maxmark' => new external_value(PARAM_FLOAT, 'the maximum mark possible for this question attempt.
                    It will be returned only if the user is allowed to see it.', VALUE_OPTIONAL),
            ),
            'The question data. Some fields may not be returned depending on the quiz display settings.'
        );
    }
717141
private void classifyNoSeq(List<IN> document) {
    if (flags.useReverse) {
      Collections.reverse(document);
    }

    if (flags.lowerNewgeneThreshold) {
      // Used to raise recall for task 1B
      System.err.println("Using NEWGENE threshold: " + flags.newgeneThreshold);
      for (int i = 0, docSize = document.size(); i < docSize; i++) {
        CoreLabel wordInfo = document.get(i);
        Datum<String, String> d = makeDatum(document, i, featureFactory);
        Counter<String> scores = classifier.scoresOf(d);
        //String answer = BACKGROUND;
        String answer = flags.backgroundSymbol;
        // HN: The evaluation of scoresOf seems to result in some
        // kind of side effect.  Specifically, the symptom is that
        // if scoresOf is not evaluated at every position, the
        // answers are different
        if ("NEWGENE".equals(wordInfo.get(GazAnnotation.class))) {
          for (String label : scores.keySet()) {
            if ("G".equals(label)) {
              System.err.println(wordInfo.word() + ':' + scores.getCount(label));
              if (scores.getCount(label) > flags.newgeneThreshold) {
                answer = label;
              }
            }
          }
        }
        wordInfo.set(AnswerAnnotation.class, answer);
      }
    } else {
      for (int i = 0, listSize = document.size(); i < listSize; i++) {
        String answer = classOf(document, i);
        CoreLabel wordInfo = document.get(i);
        //System.err.println("XXX answer for " +
        //        wordInfo.word() + " is " + answer);
        wordInfo.set(AnswerAnnotation.class, answer);
      }
      if (flags.justify && (classifier instanceof LinearClassifier)) {
        LinearClassifier<String, String> lc = (LinearClassifier<String, String>) classifier;
        for (int i = 0, lsize = document.size(); i < lsize; i++) {
          CoreLabel lineInfo = document.get(i);
          System.err.print("@@ Position " + i + ": ");
          System.err.println(lineInfo.word() + " chose " + lineInfo.get(AnswerAnnotation.class));
          lc.justificationOf(makeDatum(document, i, featureFactory));
        }
      }
    }
    if (flags.useReverse) {
      Collections.reverse(document);
    }
  }
1233286
function (question, defaultValue) {
  var choiceValues = _.map(question.choices, function (choice) {
    if (typeof choice === 'object') {
      return choice.value;
    } else {
      return choice;
    }
  });

  return choiceValues.indexOf(defaultValue);
}
847621
def _make_local_question_images(self, question_dict):
        
        question_dict = question_dict.copy()
        dest_path = 'exerciseimages/'

        if not os.path.exists(dest_path):
            os.mkdir(dest_path)

        # helper method
        def _process_string(string):
            image_regex = re.compile(MARKDOWN_IMAGE_REGEX, flags=re.IGNORECASE)
            contentstorage_prefix = '${☣ CONTENTSTORAGE}/'
            studio_storage = 'https://studio.learningequality.org/content/storage/'

            matches = image_regex.findall(string)

            # Parse all matches
            for match in matches:
                file_result = match[1]
                file_name = file_result.replace(contentstorage_prefix, '')
                file_url = studio_storage + file_name[0] + '/' + file_name[1] + '/' + file_name
                file_local_path = os.path.join(dest_path, file_name)
                response = requests.get(file_url)
                if response.status_code != 200:
                    print('Failed for image ' + str(response.status_code) + ' >> ' + file_url)
                    return string
                with open(file_local_path, 'wb') as local_file:
                    local_file.write(response.content)
                    print('saved image file', file_local_path)
                string = string.replace(file_result, file_local_path)

            return string

        # Process images in question
        new_question = _process_string(question_dict['question'])
        question_dict['question'] = new_question

        # Process images in answers
        answers = json.loads(question_dict['answers'])
        new_answers = []
        for ans in answers:
            new_ans = ans.copy()
            new_ans['answer'] = _process_string(new_ans['answer'])
            new_answers.append(new_ans)
        question_dict['answers'] = json.dumps(new_answers)

        # TODO: process hint images

        return question_dict
1055116
def show
      @question_sheet = @answer_sheet.question_sheet
      pf = Qe.table_name_prefix
      @elements = @question_sheet.pages.collect {|p| p.elements.includes(:pages).order("#{pf}pages.number,#{pf}page_elements.position").all}.flatten
      @elements = QuestionSet.new(@elements, @answer_sheet).elements.group_by{ |e| e.pages.first }
    end
187081
function(feedback) {
    var isCorrect = ($.isArray(feedback) && feedback.length === 0) ||
                    ('feedback' in feedback && feedback.success);

    // correctly solved but collection has more exercises
    if (isCorrect && $.isFunction(PARSONS_SETTINGS.next)) {
      $("#ul-sortable").sortable("destroy");
      $("#ul-sortableTrash").sortable("destroy");
      showDialog("Good Job!", "Click OK to go to the next question.", function() {
        PARSONS_SETTINGS.next();
      });
    } else if (isCorrect) { // correct and last question
      showDialog("Good Job!", "That was the last question. Click OK to go back to main page.", function() {
        window.location = "./index.html";
      });
    } else { // not correct, show feedback
      var now = new Date(),
          penaltyTime = 0,
          feedbackText;
      if ($.isArray(feedback)) { // line-based feedback
        feedbackText = feedback.join('\n');
      } else if ('feedback' in feedback) { // execution based feedback
        feedbackText = "Some tests failed for your solution. See the Last Feedback tab for details.";
      }
      if (feedbackTimeHistory.length > 1) { // 1st and 2nd feedback can't be too fast
        // we'll go through all the times in the feedback time history
        for (var i = 0; i < feedbackTimeHistory.length; i++) {
          // check if the corresponding feedbackwindow is bigger than time between now
          // and the i:th feedback time
          if (FEEDBACK_WINDOWS[i] > now - feedbackTimeHistory[i]) {
            penaltyTime += FEEDBACK_PENALTIES[i]; // add to penalty time
          }
        }
        // if there is penalty time, disable feedback and show a message to student
        if (penaltyTime > 0) {
          disableFeedback(penaltyTime);
          feedbackText += "\n\nDue to frequent use, feedback has been disabled for a while. It will be" +
                        "available once the button turns orange again. You can still continue solving the problem.";
        }
      }
      // add the current time to the feedbak history
      feedbackTimeHistory.unshift(now);
      // make sure we have at most as many feedback times in history as we have windows
      feedbackTimeHistory = feedbackTimeHistory.slice(0, FEEDBACK_WINDOWS.length);
      showDialog("Feedback", feedbackText);
    }
  }