Process the exams in the exam_num folder for the time.
347178
def process(exam_num: int, time: str, date: str) -> None:
    """"""
    prefix = Path(f"exams/exam-{exam_num}")

    problems = list(prefix.glob(f"exam-{exam_num}-{time}-[0-9].ipynb"))
    problems = sorted(problems, key=lambda k: k.stem[-1])

    output_directory = (prefix / "output").resolve()
    fw = FilesWriter(build_directory=str(output_directory))

    assignment_zip_name = output_directory / f"exam-{exam_num}-{time}.zip"
    solution_zip_name = output_directory / f"exam-{exam_num}-{time}-soln.zip"

    solution_pdfs: List[BytesIO] = []

    exam_date_time = datetime.strptime(time + date, "%H%M%d-%b-%Y")
    res: Dict[str, Union[str, int]] = {
        "exam_num": exam_num,
        "time": exam_date_time.strftime("%I:%M %p"),
        "date": exam_date_time.strftime("%b. %d, %Y"),
        "delete_pymarkdown": True,
    }

    for problem in problems:
        res["unique_key"] = problem.stem
        problem_fname = str(problem.resolve())
        if problem.stem.endswith("1"):

            assignment_nb, _ = sa_nb_exp.from_filename(problem_fname, resources=res)

            with ZipFile(assignment_zip_name, mode="a") as zip_file:
                zip_file.writestr(problem.name, assignment_nb)
        else:
            assignment_nb, _ = prob_nb_exp.from_filename(problem_fname, resources=res)

            with ZipFile(assignment_zip_name, mode="a") as zip_file:
                zip_file.writestr(problem.name, assignment_nb)

        solution_pdf, _ = solution_pdf_exp.from_filename(problem_fname, resources=res)
        solution_pdfs.append(BytesIO(solution_pdf))

        solution_nb, _ = solution_nb_exp.from_filename(problem_fname, resources=res)
        with ZipFile(solution_zip_name, mode="a") as zip_file:
            zip_file.writestr(problem.name, solution_nb)

    resources: Dict[str, Any] = {
        "metadata": {
            "name": f"exam-{exam_num}-{time}-soln",
            "path": str(prefix),
            "modified_date": datetime.today().strftime("%B %d, %Y"),
        },
        "output_extension": ".pdf",
    }
    fw.write(
        combine_pdf_as_bytes(solution_pdfs), resources, f"exam-{exam_num}-{time}-soln"
    )
487774
public function execute() {
        global $CFG, $DB;

        if (!empty($CFG->gradehistorylifetime)) {
            $now = time();
            $histlifetime = $now - ($CFG->gradehistorylifetime * DAYSECS);
            $tables = [
                'grade_outcomes_history',
                'grade_categories_history',
                'grade_items_history',
                'grade_grades_history',
                'scale_history'
            ];
            foreach ($tables as $table) {
                if ($DB->delete_records_select($table, "timemodified < ?", [$histlifetime])) {
                    mtrace("    Deleted old grade history records from '$table'");
                }
            }
        }
    }
402541
def process_files():
    

    with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar:
        for num in range(100):  # pylint: disable=unused-variable
            time.sleep(0.05)
            pbar.update()
84207
def run(self, messages):
        """"""
        statistics = {}
        statistics['time'] = str(datetime.now())
        statistics['time-utc'] = str(datetime.utcnow())
        statistics['unlock'] = self.args.unlock

        if self.args.question:
            statistics['question'] = [t.name for t in self.assignment.specified_tests]
            statistics['requested-questions'] = self.args.question

            if self.args.suite:
                statistics['requested-suite'] = self.args.suite
            if self.args.case:
                statistics['requested-case'] = self.args.case

        messages['analytics'] = statistics
        self.log_run(messages)
1109275
def clear_on_run(self, prefix="Running Tests:"):
        """"""
        if platform.system() == 'Windows':
            os.system('cls')
        else:
            os.system('clear')
        if prefix:
            print(prefix)
30789
def process_files(self):
        
        config.LOGGER.info("\t*** Processing images for exercise: {}".format(self.title))
        downloaded = super(ExerciseNode, self).process_files()
        for question in self.questions:
            downloaded += question.process_question()

        self.process_exercise_data()

        config.LOGGER.info("\t*** Images for {} have been processed".format(self.title))
        return downloaded
668117
def _run_pass(self):
        """"""
        while True:
            try:
                data = self._file.read(4096)
            except IOError, e:
                if e.errno == errno.ESTALE:
                    self.active = False
                    return False

            lines = self._buffer_extract(data)

            if not lines:
                # Before returning, check if an event (maybe partial) is waiting for too long.
                if self._current_event and time.time() - self._last_activity > 1:
                    event = '\n'.join(self._current_event)
                    self._current_event.clear()
                    self._callback_wrapper([event])
                break

            self._last_activity = time.time()

            if self._multiline_regex_after or self._multiline_regex_before:
                # Multiline is enabled for this file.
                events = multiline_merge(
                        lines,
                        self._current_event,
                        self._multiline_regex_after,
                        self._multiline_regex_before)
            else:
                events = lines

            if events:
                self._callback_wrapper(events)

            if self._sincedb_path:
                current_line_count = len(lines)
                self._sincedb_update_position(lines=current_line_count)

        self._sincedb_update_position()
1354002
protected function process_courses() {
        global $DB;
        $this->progress->start_progress(get_string('migratingcourses', 'tool_lpmigrate'), count($this->coursescompetencies));

        // Process each course.
        foreach ($this->coursescompetencies as $courseid => $competencyids) {
            $this->progress->increment_progress();

            $competenciestoremovefromcourse = array();
            $skipcompetencies = array();

            // First, add all the new competencies to the course.
            foreach ($competencyids as $key => $competencyid) {
                $this->coursecompetencyexpectedmigrations++;
                $mapto = isset($this->mappings[$competencyid]) ? $this->mappings[$competencyid] : false;

                // Skip the competencies that are not mapped.
                if ($mapto === false) {
                    $this->missingmappings[$competencyid] = true;

                    if ($this->removewhenmappingismissing) {
                        $competenciestoremovefromcourse[$competencyid] = true;
                    }

                    continue;
                }

                $transaction = $DB->start_delegated_transaction();
                try {
                    // Add the new competency to the course.
                    if (api::add_competency_to_course($courseid, $mapto)) {

                        // Find the added course competency.
                        $cc = course_competency::get_record(array('courseid' => $courseid, 'competencyid' => $mapto));

                        // Set the rule.
                        api::set_course_competency_ruleoutcome($cc, $this->coursescompetenciesoutcomes[$courseid][$competencyid]);

                        // Adapt the sortorder.
                        api::reorder_course_competency($courseid, $mapto, $competencyid);

                        $competenciestoremovefromcourse[$competencyid] = true;
                        $this->coursecompetencymigrations++;

                    } else {
                        // The competency was already in the course...
                        if ($this->removeoriginalwhenalreadypresent) {
                            $competenciestoremovefromcourse[$competencyid] = true;
                        } else {
                            $this->log_warning($courseid, $competencyid, null,
                                get_string('warningdestinationcoursecompetencyalreadyexists', 'tool_lpmigrate'));
                        }
                    }

                } catch (moodle_exception $e) {
                    // There was a major problem with this competency, we will ignore it entirely for the course.
                    $skipcompetencies[$competencyid] = true;

                    $this->log_error($courseid, $competencyid, null,
                        get_string('errorwhilemigratingcoursecompetencywithexception', 'tool_lpmigrate', $e->getMessage()));

                    try {
                        $transaction->rollback($e);
                    } catch (moodle_exception $e) {
                        // Catch the re-thrown exception.
                    }

                    continue;
                }
                $transaction->allow_commit();
            }

            // Then, convert the module competencies.
            if (!empty($this->modulecompetencies[$courseid])) {
                foreach ($this->modulecompetencies[$courseid] as $cmid => $competencyids) {
                    foreach ($competencyids as $competencyid) {
                        $this->modulecompetencyexpectedmigrations++;

                        // This mapped competency was not added to the course.
                        if (!empty($skipcompetencies[$competencyid])) {
                            continue;
                        }

                        $remove = true;
                        $mapto = isset($this->mappings[$competencyid]) ? $this->mappings[$competencyid] : false;

                        // We don't have mapping.
                        if ($mapto === false) {
                            if (!$this->removewhenmappingismissing) {
                                $remove = false;
                            }

                        } else {
                            // We have a mapping.
                            $transaction = $DB->start_delegated_transaction();
                            try {
                                // The competency was added successfully.
                                if (api::add_competency_to_course_module($cmid, $mapto)) {

                                    // Find the added module competency.
                                    $mc = course_module_competency::get_record(array('cmid' => $cmid, 'competencyid' => $mapto));

                                    // Set the competency rule.
                                    api::set_course_module_competency_ruleoutcome($mc,
                                        $this->modulecompetenciesoutcomes[$courseid][$cmid][$competencyid]);

                                    // Adapt the sortorder.
                                    api::reorder_course_module_competency($cmid, $mapto, $competencyid);

                                    $this->modulecompetencymigrations++;

                                } else {
                                    // The competency was already in the module.
                                    if (!$this->removeoriginalwhenalreadypresent) {
                                        $remove = false;
                                        $competencieswithissues[$competencyid] = true;
                                        $this->log_warning($courseid, $competencyid, $cmid,
                                            get_string('warningdestinationmodulecompetencyalreadyexists', 'tool_lpmigrate'));
                                    }
                                }

                            } catch (moodle_exception $e) {
                                // There was a major problem with this competency in this module.
                                $competencieswithissues[$competencyid] = true;
                                $message = get_string('errorwhilemigratingmodulecompetencywithexception', 'tool_lpmigrate',
                                    $e->getMessage());
                                $this->log_error($courseid, $competencyid, $cmid, $message);

                                try {
                                    $transaction->rollback($e);
                                } catch (moodle_exception $e) {
                                    // Catch the re-thrown exception.
                                }

                                continue;
                            }
                            $transaction->allow_commit();
                        }

                        try {
                            // Go away competency!
                            if ($remove && api::remove_competency_from_course_module($cmid, $competencyid)) {
                                $this->modulecompetencyremovals++;
                            }
                        } catch (moodle_exception $e) {
                            $competencieswithissues[$competencyid] = true;
                            $this->log_warning($courseid, $competencyid, $cmid,
                                get_string('warningcouldnotremovemodulecompetency', 'tool_lpmigrate'));
                        }
                    }
                }
            }

            // Finally, we remove the course competencies, but only for the 100% successful ones.
            foreach ($competenciestoremovefromcourse as $competencyid => $unused) {

                // Skip competencies with issues.
                if (isset($competencieswithissues[$competencyid])) {
                    continue;
                }

                try {
                    // Process the course competency.
                    api::remove_competency_from_course($courseid, $competencyid);
                    $this->coursecompetencyremovals++;
                } catch (moodle_exception $e) {
                    $this->log_warning($courseid, $competencyid, null,
                        get_string('warningcouldnotremovecoursecompetency', 'tool_lpmigrate'));
                }
            }
        }

        $this->progress->end_progress();
    }
179441
def run(self):
        '''
        
        '''
        tests = self._collect()

        if not tests:
            return

        self.times
        self.before_class()

        for test in tests:
            func = getattr(self, test)
            results = self.results[test] = Result()
            self._before(self, test)
            self.before()
            for i in range(self.times):
                self._before_each(self, test, i)
                result = self._run_one(func)
                results.total += result.duration
                if result.success:
                    results.has_success = True
                else:
                    results.has_errors = True
                self._after_each(self, test, i)
                if self.debug and not result.success:
                    results.error = result.result
                    break
            self.after()
            self._after(self, test)

        self.after_class()
932574
private void processAssignments() throws SQLException
   {
      List<Row> rows = getRows("select * from " + m_schema + "taskrsrc where proj_id=? and delete_date is null", m_projectID);
      m_reader.processAssignments(rows);
   }
699422
function sample(test, asap, minDuration, sampleSize, done) {
    var count = 0;
    var totalDuration = 0;
    var sampleDurations = [];
    next();
    function next() {
        measure(function (done) {
            test(asap, done);
        }, function (error, results, duration) {
            if (error) {
                done(error);
            }
            if (sampleDurations.length < sampleSize) {
                sampleDurations.push(duration);
            } else if (Math.random() < 1 / count) {
                sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1);
                sampleDurations.push(duration);
            }
            totalDuration += duration;
            count++;
            if (totalDuration >= minDuration) {
                done(null, {
                    name: test.name,
                    subjectName: asap.name,
                    count: count,
                    totalDuration: totalDuration,
                    averageFrequency: count / totalDuration,
                    averageDuration: totalDuration / count,
                    averageOpsHz: count / totalDuration,
                    sampleDurations: sampleDurations
                });
            } else {
                next();
            }
        });
    }
}
94866
def prep_folder(self, seq):
        """"""
        itasser_dir = op.join(self.root_dir, self.id)

        if not op.exists(itasser_dir):
            os.makedirs(itasser_dir)

        tmp = {self.id: seq}

        fasta.write_fasta_file_from_dict(indict=tmp,
                                         outname='seq',
                                         outext='.fasta',
                                         outdir=itasser_dir)
        return itasser_dir
652165
function processFolders(wwwPath) {
  foldersToProcess.forEach(function(folder) {
    processFiles(path.join(wwwPath, folder));
  });
}
816915
def run_study_nts(self, study, **kws):
        """"""
        goea_results = self.run_study(study, **kws)
        return MgrNtGOEAs(goea_results).get_goea_nts_all()
187110
public function process ()
		{
			if (!empty( $this->_params ))
			{
				if ($this->getIsUploading())
					$this->uploadChunk();
				else
					$this->testChunk();
			}
		}
41886
def process_pulls(self, testpulls=None, testarchive=None, expected=None):
        
        from datetime import datetime
        pulls = self.find_pulls(None if testpulls is None else testpulls.values())
        for reponame in pulls:
            for pull in pulls[reponame]:
                try:
                    archive = self.archive[pull.repokey]
                    if pull.snumber in archive:
                        #We pass the archive in so that an existing staging directory (if
                        #different from the configured one) can be cleaned up if the previous
                        #attempt failed and left the file system dirty.
                        pull.init(archive[pull.snumber])
                    else:
                        pull.init({})
                        
                    if self.testmode and testarchive is not None:
                        #Hard-coded start times so that the model output is reproducible
                        if pull.number in testarchive[pull.repokey]:
                            start = testarchive[pull.repokey][pull.number]["start"]
                        else:
                            start = datetime(2015, 4, 23, 13, 8)
                    else:
                        start = datetime.now()
                    archive[pull.snumber] = {"success": False, "start": start,
                                             "number": pull.number, "stage": pull.repodir,
                                             "completed": False, "finished": None}
                    #Once a local staging directory has been initialized, we add the sha
                    #signature of the pull request to our archive so we can track the rest
                    #of the testing process. If it fails when trying to merge the head of
                    #the pull request, the exception block should catch it and email the
                    #owner of the repo.
                    #We need to save the state of the archive now in case the testing causes
                    #an unhandled exception.
                    self._save_archive()

                    pull.begin()
                    self.cron.email(pull.repo.name, "start", self._get_fields("start", pull), self.testmode)
                    pull.test(expected[pull.number])
                    pull.finalize()

                    #Update the status of this pull request on the archive, save the archive
                    #file in case the next pull request throws an unhandled exception.
                    archive[pull.snumber]["completed"] = True
                    archive[pull.snumber]["success"] = abs(pull.percent - 1) < 1e-12

                    #This if block looks like a mess; it is necessary so that we can easily
                    #unit test this processing code by passing in the model outputs etc. that should
                    #have been returned from running live.
                    if (self.testmode and testarchive is not None and
                        pull.number in testarchive[pull.repokey] and
                        testarchive[pull.repokey][pull.number]["finished"] is not None):
                        archive[pull.snumber]["finished"] = testarchive[pull.repokey][pull.number]["finished"]
                    elif self.testmode:
                        archive[pull.snumber]["finished"] = datetime(2015, 4, 23, 13, 9)
                    else:
                        #This single line could replace the whole if block if we didn't have
                        #unit tests integrated with the main code.
                        archive[pull.snumber]["finished"] = datetime.now()
                    self._save_archive()

                    #We email after saving the archive in case the email server causes exceptions.
                    if archive[pull.snumber]["success"]:
                        key = "success"
                    else:
                        key = "failure"
                    self.cron.email(pull.repo.name, key, self._get_fields(key, pull), self.testmode)
                except:
                    import sys, traceback
                    e = sys.exc_info()
                    errmsg = '\n'.join(traceback.format_exception(e[0], e[1], e[2]))
                    err(errmsg)
                    self.cron.email(pull.repo.name, "error", self._get_fields("error", pull, errmsg),
                                    self.testmode)
623382
protected function compute(): void
    {
        $score = [];

        foreach ($this->_selfElection->getCandidatesList() as $oneCandidate) :
            $score[$this->_selfElection->getCandidateKey($oneCandidate)] = 0;
        endforeach;

        foreach ($this->_selfElection->getVotesManager() as $oneVote) :

            // Ignore vote who don't respect election constraints
            if(!$this->_selfElection->testIfVoteIsValidUnderElectionConstraints($oneVote)) :
                continue;
            endif;

            $weight = ($this->_selfElection->isVoteWeightIsAllowed()) ? $oneVote->getWeight() : 1;

            for ($i = 0; $i < $weight; $i++) :
                $oneRanking = $oneVote->getContextualRanking($this->_selfElection);

                foreach ($oneRanking[1] as $oneCandidateInRank) :
                    $score[$this->_selfElection->getCandidateKey($oneCandidateInRank)] += 1 / count($oneRanking[1]);
                endforeach;
            endfor;
        endforeach;

        arsort($score, SORT_NUMERIC);

        $rank = 0;
        $lastScore = null;
        $result = [];
        foreach ($score as $candidateKey => $candidateScore) :
            if ($candidateScore === $lastScore) :
                $result[$rank][] = $candidateKey;
            else :
                $result[++$rank] = [$candidateKey];
                $lastScore = $candidateScore;
            endif;
        endforeach;

        $this->_Stats = $score;
        $this->_Result = $this->createResult($result);
    }