recover the questions of an exercise in order to inject in step_question.
355568
private function checkDocument()
    {
        $this->log('Checking document ...');

        $checkQuery = '
            SELECT *
            FROM ujm_document
        ';

        $results = $this->connection->query($checkQuery)->fetchAll();
        foreach ($results as $res) {
            try {
                $this->connection->exec("
                INSERT INTO ujm_picture_temp
                VALUES ({$res['id']}, {$res['user_id']}, '"
                .addslashes($res['label'])."', '"
                .addslashes($res['url'])."', '"
                .addslashes($res['type'])."',
                0, 0
                )
            ");
            } catch (\Exception $e) {
                $this->log("Picture {$res['id']} already inserted");
            }
        }

        $this->checkInteractionGraphic();
    }
1074900
public void recover() {
    try {
      boolean checkpointExists = mUfs.isFile(mCheckpoint.toString());
      boolean backupCheckpointExists = mUfs.isFile(mBackupCheckpoint.toString());
      boolean tempBackupCheckpointExists = mUfs.isFile(mTempBackupCheckpoint.toString());
      Preconditions
          .checkState(!(checkpointExists && backupCheckpointExists && tempBackupCheckpointExists),
              "checkpoint, temp backup checkpoint, and backup checkpoint should never all exist ");
      if (tempBackupCheckpointExists) {
        // If mCheckpointPath also exists, step 2 must have implemented rename as copy + delete, and
        // failed during the delete.
        UnderFileSystemUtils.deleteFileIfExists(mUfs, mCheckpoint.toString());
        mUfs.renameFile(mTempBackupCheckpoint.toString(), mCheckpoint.toString());
      }
      if (backupCheckpointExists) {
        // We must have crashed after step 3
        if (checkpointExists) {
          // We crashed after step 4, so we can finish steps 5 and 6.
          mWriter.deleteCompletedLogs();
          mUfs.deleteFile(mBackupCheckpoint.toString());
        } else {
          // We crashed before step 4, so we roll back to the backup checkpoint.
          mUfs.renameFile(mBackupCheckpoint.toString(), mCheckpoint.toString());
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
597987
public function getStatistics(Item $question, Exercise $exercise = null, $finishedPapersOnly = false)
    {
        $questionStats = [];

        // We load all the answers for the question (we need to get the entities as the response in DB are not processable as is)
        $answers = $this->answerRepository->findByQuestion($question, $exercise, $finishedPapersOnly);

        // Number of Users that have seen the question
        $questionStats['seen'] = count($answers);

        // Grab answer data to pass it decoded to the question type
        // it doesn't need to know the whole Answer object
        $answersData = [];

        // get corrected answers for the Item in order to compute question success percentage
        $correctedAnswers = [];

        // Number of Users that have answered the question (no blank answer)
        $questionStats['answered'] = 0;

        if (!empty($answers)) {
            // Let the handler of the question type parse and compile the data
            $definition = $this->itemDefinitions->get($question->getMimeType());

            for ($i = 0; $i < $questionStats['seen']; ++$i) {
                $answer = $answers[$i];
                if (!empty($answer->getData())) {
                    ++$questionStats['answered'];
                    $answersData[] = json_decode($answer->getData(), true);
                }

                // for each answer get corresponding correction
                if ($definition instanceof AnswerableItemDefinitionInterface && isset($answersData[$i])) {
                    $corrected = $definition->correctAnswer($question->getInteraction(), $answersData[$i]);
                    $correctedAnswers[] = $corrected;
                }
            }

            // Let the handler of the question type parse and compile the data
            if ($definition instanceof AnswerableItemDefinitionInterface) {
                $questionStats['solutions'] = $definition->getStatistics($question->getInteraction(), $answersData, $questionStats['seen']);
            }
        }

        // get the number of good answers among all
        $nbGoodAnswers = 0;

        foreach ($correctedAnswers as $corrected) {
            if ($corrected instanceof CorrectedAnswer && 0 === count($corrected->getMissing()) && 0 === count($corrected->getUnexpected())) {
                ++$nbGoodAnswers;
            }
        }
        // compute question success percentage
        $questionStats['successPercent'] = $questionStats['answered'] > 0 ? (100 * $nbGoodAnswers) / $questionStats['answered'] : 0;

        return $questionStats;
    }
1220984
def ask_questions(self):
        
        out_config = {}

        for key in c.CONFIG_QUESTIONS:
            section = key[1]
            print
            for question in section:
                answer = utils.ask(question[1], question[2])
                out_config["{0}_{1}".format(key[0], question[0])] = answer

        for key in c.CONFIG_MULTIPLE_CHOICE_QUESTIONS:
            section = key[1]
            print
            # keep going until we get what we want
            while True:
                input = utils.ask(section[1], "")
                if (input.isdigit() and
                        int(input) > 0 and
                        int(input) <= section[0]):
                    answer = input

                    break
                print

            # store the answer as 1 less than it is, we're dealing with
            # a list to select the number which is 0 indexed
            answer = int(input) - 1

            if key[0] == "license":
                out_config["license_type"] = c.LICENSE_TYPES[answer][0]
                out_config["license_url"] = c.LICENSE_TYPES[answer][1]

        # merge in defaults without asking questions
        merged_config = dict(c.CONFIG_DEFAULTS.items() + out_config.items())

        return merged_config
1220550
def validate(self):
        
        try:
            assert self.question == "", "Assumption Failed: Perseus question should not have a question"
            assert self.question_type == exercises.PERSEUS_QUESTION, "Assumption Failed: Question should be perseus type"
            assert self.answers == [], "Assumption Failed: Answer list should be empty for perseus question"
            assert self.hints == [], "Assumption Failed: Hints list should be empty for perseus question"
            return super(PerseusQuestion, self).validate()
        except AssertionError as ae:
            raise InvalidQuestionException("Invalid question: {0}".format(self.__dict__))
297824
def load_item_for_objective(self):
        """"""
        mgr = self.my_osid_object._get_provider_manager('ASSESSMENT', local=True)
        if self.my_osid_object._my_map['itemBankId']:
            item_query_session = mgr.get_item_query_session_for_bank(Id(self.my_osid_object._my_map['itemBankId']),
                                                                     proxy=self.my_osid_object._proxy)
        else:
            item_query_session = mgr.get_item_query_session(proxy=self.my_osid_object._proxy)
        item_query_session.use_federated_bank_view()
        item_query = item_query_session.get_item_query()
        for objective_id_str in self.my_osid_object._my_map['learningObjectiveIds']:
            item_query.match_learning_objective_id(Id(objective_id_str), True)
        item_list = list(item_query_session.get_items_by_query(item_query))
        # Let's query all takens and their children sections for questions, to
        # remove seen ones
        taking_agent_id = self._assessment_section._assessment_taken.taking_agent_id
        atqs = mgr.get_assessment_taken_query_session(proxy=self.my_osid_object._proxy)
        atqs.use_federated_bank_view()
        querier = atqs.get_assessment_taken_query()
        querier.match_taking_agent_id(taking_agent_id, match=True)
        # let's seed this with the current section's questions
        seen_items = [item_id for item_id in self._assessment_section._item_id_list]
        taken_ids = [str(t.ident)
                     for t in atqs.get_assessments_taken_by_query(querier)]
        # Try to find the questions directly via Mongo query -- don't do
        # for section in taken._get_assessment_sections():
        #     seen_items += [question['itemId'] for question in section._my_map['questions']]
        # because standing up all the sections is wasteful
        collection = JSONClientValidated('assessment',
                                         collection='AssessmentSection',
                                         runtime=self.my_osid_object._runtime)
        results = collection.find({"assessmentTakenId": {"$in": taken_ids}})
        for section in results:
            if 'questions' in section:
                seen_items += [question['itemId'] for question in section['questions']]
        unseen_item_id = None
        # need to randomly shuffle this item_list
        shuffle(item_list)
        for item in item_list:
            if str(item.ident) not in seen_items:
                unseen_item_id = item.get_id()
                break
        if unseen_item_id is not None:
            self.my_osid_object._my_map['itemIds'] = [str(unseen_item_id)]
        elif self.my_osid_object._my_map['allowRepeatItems']:
            if len(item_list) > 0:
                self.my_osid_object._my_map['itemIds'] = [str(item_list[0].ident)]
            else:
                self.my_osid_object._my_map['itemIds'] = []  # don't put '' here, it will break when it tries to find an item with id ''
        else:
            self.my_osid_object._my_map['itemIds'] = []
237448
def getExerciseDetails(self, identifier):
        
        exercise = self._getExercise(identifier)
        response = {
            b"identifier": exercise.identifier,
            b"title": exercise.title,
            b"description": exercise.description,
            b"solved": exercise.wasSolvedBy(self.user)
        }
        return response
1299974
def _transform(self, data, transform, step_size):
    '''
    
    '''
    if callable(transform):
      data = transform(data, step_size)
    return data
967757
public function build() {

        // Move all the CONTEXT_MODULE question qcats to their
        // final (newly created) module context
        $this->add_step(new restore_move_module_questions_categories('move_module_question_categories'));

        // Create all the question files now that every question is in place
        // and every category has its final contextid associated
        $this->add_step(new restore_create_question_files('create_question_files'));

        // Review all the block_position records in backup_ids in order
        // match them now that all the contexts are created populating DB
        // as needed. Only if we are restoring blocks.
        if ($this->get_setting_value('blocks')) {
            $this->add_step(new restore_review_pending_block_positions('review_block_positions'));
        }

        // Gradebook. Don't restore the gradebook unless activities are being restored.
        if ($this->get_setting_value('activities')) {
            $this->add_step(new restore_gradebook_structure_step('gradebook_step','gradebook.xml'));
            $this->add_step(new restore_grade_history_structure_step('grade_history', 'grade_history.xml'));
        }

        // Course completion.
        $this->add_step(new restore_course_completion_structure_step('course_completion', 'completion.xml'));

        // Conditionally restore course badges.
        if ($this->get_setting_value('badges')) {
            $this->add_step(new restore_badges_structure_step('course_badges', 'badges.xml'));
        }

        // Review all the legacy module_availability records in backup_ids in
        // order to match them with existing modules / grade items and convert
        // into the new system.
        $this->add_step(new restore_process_course_modules_availability('process_modules_availability'));

        // Update restored availability data to account for changes in IDs
        // during backup/restore.
        $this->add_step(new restore_update_availability('update_availability'));

        // Refresh action events conditionally.
        if ($this->get_setting_value('activities')) {
            $this->add_step(new restore_calendar_action_events('restoring_action_events'));
        }

        // Decode all the interlinks
        $this->add_step(new restore_decode_interlinks('decode_interlinks'));

        // Restore course logs (conditionally). They are restored here because we need all
        // the activities to be already restored.
        if ($this->get_setting_value('logs')) {
            // Legacy logs.
            $this->add_step(new restore_course_logs_structure_step('course_logs', 'course/logs.xml'));
            // New log stores.
            $this->add_step(new restore_course_logstores_structure_step('course_logstores', 'course/logstores.xml'));
        }

        // Review all the executed tasks having one after_restore method
        // executing it to perform some final adjustments of information
        // not available when the task was executed.
        // This step is always the last one performing modifications on restored information
        // Don't add any new step after it. Only aliases queue, cache rebuild and clean are allowed.
        $this->add_step(new restore_execute_after_restore('executing_after_restore'));

        // All files were sent to the filepool by now. We need to process
        // the aliases yet as they were not actually created but stashed for us instead.
        // We execute this step after executing_after_restore so that there can't be no
        // more files sent to the filepool after this.
        $this->add_step(new restore_process_file_aliases_queue('process_file_aliases_queue'));

        // Rebuild course cache to see results, whoah!
        $this->add_step(new restore_rebuild_course_cache('rebuild_course_cache'));

        // Clean the temp dir (conditionally) and drop temp table
        $this->add_step(new restore_drop_and_clean_temp_stuff('drop_and_clean_temp_stuff'));

        // If restoring to a new course or overwriting config, reindex the whole course.
        if (\core_search\manager::is_indexing_enabled()) {
            $wholecourse = $this->get_target() == backup::TARGET_NEW_COURSE;
            $wholecourse = $wholecourse || $this->setting_exists('overwrite_conf') && $this->get_setting_value('overwrite_conf');
            if ($wholecourse) {
                $this->add_step(new restore_course_search_index('course_search_index'));
            }
        }

        $this->built = true;
    }
1193686
function Question(name, message, options) {
  if (utils.isObject(name)) {
    options = utils.merge({}, message, name);
    message = options.message;
    name = options.name;
  }

  if (utils.isObject(message)) {
    options = utils.merge({}, options, message);
    message = options.message;
  }

  utils.define(this, 'isQuestion', true);
  utils.define(this, 'cache', {});

  this.options = options || {};
  this.type = this.options.type || 'input';
  this.message = message || this.options.message;
  this.name = name || this.options.name;

  if (!this.message) {
    this.message = this.name;
  }

  utils.merge(this, this.options);
  createNext(this);
}
884087
def validate(self):
        
        try:
            assert self.question_type == exercises.SINGLE_SELECTION, "Assumption Failed: Question should be single selection type"
            assert len(self.answers) > 0, "Assumption Failed: Multiple selection question should have answers"
            correct_answers = 0
            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"
                correct_answers += 1 if a['correct'] else 0
            assert correct_answers == 1, "Assumption Failed: Single selection question should have only one correct answer"
            for h in self.hints:
                assert isinstance(h, str), "Assumption Failed: Hint in hints list is not a string"
            return super(SingleSelectQuestion, self).validate()
        except AssertionError as ae:
            raise InvalidQuestionException("Invalid question: {0}".format(self.__dict__))
1043908
function ask(questions, finish, answers, input, output) {
    finish = finish || function() {};
    input = input || function(cb) {process.stdin.on('data', cb);};
    output = output || function(a) {console.log(a);};

    var i = 0;
    var ret = {};
    var e = questions[0];
    var v = match(ops, e);

    output(getOutput(e, v));
    input(getInput);

    function getOutput(e, v) {
        var o = f.isFunction(v.output)? v.output(e): '';

        return e.q + o;
    }

    function getInput(t) {
        t = t.trim();
        var r = v.exec(t, e);

        if(f.isDefined(r)) {
            ret[e.id] = r;
            i++;

            if(i >= questions.length) {
                // XXX: separate this somehow
                process.stdin.removeListener('data', getInput);
                process.stdin.pause();

                finish(ret);
            }
            else {
                e = questions[i];
                v = match(ops, e);
                output(getOutput(e, v));
            }
        }
    }
}
945735
public function load_question_attempt_step($stepid) {
        $records = $this->db->get_recordset_sql("
SELECT
    quba.contextid,
    COALESCE(q.qtype, 'missingtype') AS qtype,
    qas.id AS attemptstepid,
    qas.questionattemptid,
    qas.sequencenumber,
    qas.state,
    qas.fraction,
    qas.timecreated,
    qas.userid,
    qasd.name,
    qasd.value

FROM      {question_attempt_steps}     qas
JOIN      {question_attempts}          qa   ON qa.id              = qas.questionattemptid
JOIN      {question_usages}            quba ON quba.id            = qa.questionusageid
LEFT JOIN {question}                   q    ON q.id               = qa.questionid
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id

WHERE
    qas.id = :stepid
        ", array('stepid' => $stepid));

        if (!$records->valid()) {
            throw new coding_exception('Failed to load question_attempt_step ' . $stepid);
        }

        $step = question_attempt_step::load_from_records($records, $stepid);
        $records->close();

        return $step;
    }
1007361
private void fillMissingSteps() {
        // correct only pending and undefined steps
        passedFeatures = fillMissingArray(passedFeatures);
        passedScenarios = fillMissingArray(passedScenarios);

        passedSteps = fillMissingArray(passedSteps);
        skippedSteps = fillMissingArray(skippedSteps);
        pendingSteps = fillMissingArray(pendingSteps);
        undefinedSteps = fillMissingArray(undefinedSteps);
    }
255289
@Override
    public void beforeStep(StepExecution stepExecution) {
        super.beforeStep(stepExecution);
        clearErrors();
        try {
            new Retrier().execute(new Retriable() {
                /*
                 * (non-Javadoc)
                 *
                 * @see org.duracloud.common.retry.Retriable#retry()
                 */
                @Override
                public Object retry() throws Exception {
                    RestoreStatus newStatus = RestoreStatus.VERIFYING_TRANSFERRED_CONTENT;
                    restoreManager.transitionRestoreStatus(restoreId, newStatus, "");
                    return null;
                }
            });
        } catch (Exception ex) {
            addError("failed to transition status to "
                     + RestoreStatus.VERIFYING_TRANSFERRED_CONTENT + ": " + ex.getMessage());
            stepExecution.addFailureException(ex);
        }
    }
943035
def add_answer_at_time(self, record, now):
        """"""
        if record is not None:
            if now == 0 or not record.is_expired(now):
                self.answers.append((record, now))
                if record.rrsig is not None:
                    self.answers.append((record.rrsig, now))
1013592
def run_step(self):
        """"""
        formatted_replacements = self.context.get_formatted_iterable(
            self.replace_pairs)

        iter = StreamReplacePairsRewriterStep.iter_replace_strings(
            formatted_replacements)
        rewriter = StreamRewriter(iter)
        super().run_step(rewriter)