Add custom completion rules.

@return array Array of string IDs of added items, empty array if none
163835
public function add_completion_rules() {
        $mform =& $this->_form;

        $group=array();
        $group[] =& $mform->createElement('checkbox', 'completionpostsenabled', '', get_string('completionposts','forum'));
        $group[] =& $mform->createElement('text', 'completionposts', '', array('size'=>3));
        $mform->setType('completionposts',PARAM_INT);
        $mform->addGroup($group, 'completionpostsgroup', get_string('completionpostsgroup','forum'), array(' '), false);
        $mform->disabledIf('completionposts','completionpostsenabled','notchecked');

        $group=array();
        $group[] =& $mform->createElement('checkbox', 'completiondiscussionsenabled', '', get_string('completiondiscussions','forum'));
        $group[] =& $mform->createElement('text', 'completiondiscussions', '', array('size'=>3));
        $mform->setType('completiondiscussions',PARAM_INT);
        $mform->addGroup($group, 'completiondiscussionsgroup', get_string('completiondiscussionsgroup','forum'), array(' '), false);
        $mform->disabledIf('completiondiscussions','completiondiscussionsenabled','notchecked');

        $group=array();
        $group[] =& $mform->createElement('checkbox', 'completionrepliesenabled', '', get_string('completionreplies','forum'));
        $group[] =& $mform->createElement('text', 'completionreplies', '', array('size'=>3));
        $mform->setType('completionreplies',PARAM_INT);
        $mform->addGroup($group, 'completionrepliesgroup', get_string('completionrepliesgroup','forum'), array(' '), false);
        $mform->disabledIf('completionreplies','completionrepliesenabled','notchecked');

        return array('completiondiscussionsgroup','completionrepliesgroup','completionpostsgroup');
    }
691479
function completionHandler(currentInput, currentArgv) {
    commandExecuted = true
    const {scripts} = getPSConfig(currentArgv) || {}
    if (scripts) {
      return getCompletionScripts(scripts, currentInput)
    }
    return []
  }
1042852
def _get_completions(self):
        """"""
        completions = []
        self.begidx = self.l_buffer.point
        self.endidx = self.l_buffer.point
        buf=self.l_buffer.line_buffer
        if self.completer:
            # get the string to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in self.completer_delims:
                    self.begidx += 1
                    break
            text = ensure_str(u''.join(buf[self.begidx:self.endidx]))
            log(u'complete text="%s"' % ensure_unicode(text))
            i = 0
            while 1:
                try:
                    r = ensure_unicode(self.completer(text, i))
                except IndexError:
                    break
                i += 1
                if r is None:
                    break
                elif r and r not in completions:
                    completions.append(r)
                else:
                    pass
            log(u'text completions=<%s>' % map(ensure_unicode, completions))
        if (self.complete_filesystem == "on") and not completions:
            # get the filename to complete
            while self.begidx > 0:
                self.begidx -= 1
                if buf[self.begidx] in u' \t\n':
                    self.begidx += 1
                    break
            text = ensure_str(u''.join(buf[self.begidx:self.endidx]))
            log(u'file complete text="%s"' % ensure_unicode(text))
            completions = map(ensure_unicode, glob.glob(os.path.expanduser(text) + '*'))
            if self.mark_directories == u'on':
                mc = []
                for f in completions:
                    if os.path.isdir(f):
                        mc.append(f + os.sep)
                    else:
                        mc.append(f)
                completions = mc
            log(u'fnames=<%s>' % map(ensure_unicode, completions))
        return completions
376419
protected function _addValidators()
    {
        parent::_addValidators();

        //if hideIfNoValues and there are no values remove empty validator
        if ($this->getHideIfNoValues() && isset($this->_validators['notEmpty'])) {
            $store = $this->_getStoreData();
            if (!$store['data']) {
                unset($this->_validators['notEmpty']);
            }
        }
    }
1212895
protected function add_defaults() {
        $mform =& $this->_form;
        $strrequired = get_string('required');

        $mform->addElement('hidden', 'edit',  ($this->instance) ? $this->instance->id : 0);
        $mform->setType('edit', PARAM_INT);
        $mform->addElement('hidden', 'new',   $this->plugin);
        $mform->setType('new', PARAM_ALPHANUMEXT);
        $mform->addElement('hidden', 'plugin', $this->plugin);
        $mform->setType('plugin', PARAM_PLUGIN);
        $mform->addElement('hidden', 'typeid', $this->typeid);
        $mform->setType('typeid', PARAM_INT);
        $mform->addElement('hidden', 'contextid', $this->contextid);
        $mform->setType('contextid', PARAM_INT);

        $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
        $mform->addRule('name', $strrequired, 'required', null, 'client');
        $mform->setType('name', PARAM_TEXT);
    }
730314
private function getCompletionsForKeywords(string $prefix): \Generator
    {
        foreach (self::KEYWORDS as $keyword) {
            if (nameStartsWith($keyword, $prefix)) {
                $item = new CompletionItem($keyword, CompletionItemKind::KEYWORD);
                $item->insertText = $keyword;
                yield $keyword => $item;
            }
        }
    }
1037445
public static function override_activity_completion_status_returns() {

        return new external_single_structure(
            array(
                'cmid' => new external_value(PARAM_INT, 'The course module id'),
                'userid' => new external_value(PARAM_INT, 'The user id to which the completion info belongs'),
                'state'   => new external_value(PARAM_INT, 'The current completion state.'),
                'timecompleted' => new external_value(PARAM_INT, 'time of completion'),
                'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the status, or null'),
                'tracking'      => new external_value(PARAM_INT, 'type of tracking:
                                                                    0 means none, 1 manual, 2 automatic'),
            )
        );
    }
1267216
public function runCompletion()
    {
        if (!$this->context) {
            throw new \RuntimeException('A CompletionContext must be set before requesting completion.');
        }

        $cmdName = $this->getInput()->getFirstArgument();

        try {
            $this->command = $this->application->find($cmdName);
        } catch (\InvalidArgumentException $e) {
            // Exception thrown, when multiple or none commands are found.
        }

        $process = array(
            'completeForOptionValues',
            'completeForOptionShortcuts',
            'completeForOptionShortcutValues',
            'completeForOptions',
            'completeForCommandName',
            'completeForCommandArguments'
        );

        foreach ($process as $methodName) {
            $result = $this->{$methodName}();

            if (false !== $result) {
                // Return the result of the first completion mode that matches
                return $this->filterResults((array) $result);
            }
        }

        return array();
    }
772451
protected function fillItems()
    {
        $migrations = [];
        foreach (Directory::iterator($this->folder) as $file) {
            $class = $this->namespace . '\\' . Str::cut($file->getFilename(), '.php');
            $model = Model::fromClass($class);
            if ($this->mustBeFiltered($model)) {
                continue;
            }
            $migrations[] = $model;
        }

        $migrations = $this->sort($migrations);

        $this->items = $this->onlyOne
            ? count($migrations) ? [$migrations[0]] : []
            : ($this->last === null
                ? $migrations
                : Arr::last($migrations, $this->last)
            );
    }
1038474
public function getSimilarRecommListIds()
    {
        if ($this->_aSimilarRecommListIds === null) {
            $this->_aSimilarRecommListIds = false;

            $aList = $this->getArticleList();
            if ($aList && $aList->count() > 0) {
                $this->_aSimilarRecommListIds = $aList->arrayKeys();
            }
        }

        return $this->_aSimilarRecommListIds;
    }
1125678
def handle_completion_info_list(self, call_id, payload):
        """"""
        self.log.debug('handle_completion_info_list: in')
        # filter out completions without `typeInfo` field to avoid server bug. See #324
        completions = [c for c in payload["completions"] if "typeInfo" in c]
        self.suggestions = [completion_to_suggest(c) for c in completions]
        self.log.debug('handle_completion_info_list: %s', Pretty(self.suggestions))
619469
protected function getRelatedDocumentsForAutocompleter()
    {
        $documents = DMSDocument::get()->exclude('ID', $this->ID);
        $this->extend('updateRelatedDocumentsForAutocompleter', $documents);
        return $documents;
    }
667636
protected function getArrayableAppends()
    {
        return empty($this->appends) ? [] : $this->getArrayableItems(
            array_combine($this->appends, $this->appends)
        );
    }
982219
private function fill_defaults()
	{
		if ( ! array_key_exists('ID', $this->attributes) ) {

			$this->attributes['post_type'] = $this->type;

			$this->attributes['post_status'] = $this->status;

		}
	}
354418
protected function define_structure() {

        $cc = new backup_nested_element('course_completion_defaults');

        $defaults = new backup_nested_element('course_completion_default', array('id'), array(
            'modulename', 'completion', 'completionview', 'completionusegrade', 'completionexpected', 'customrules'
        ));

        // Use module name instead of module id so we can insert into another site later.
        $sourcesql = "SELECT d.id, m.name as modulename, d.completion, d.completionview, d.completionusegrade,
                  d.completionexpected, d.customrules
                FROM {course_completion_defaults} d join {modules} m on d.module = m.id
                WHERE d.course = ?";
        $defaults->set_source_sql($sourcesql, array(backup::VAR_COURSEID));

        $cc->add_child($defaults);
        return $cc;

    }
1177481
protected function process_completion_defaults($data) {
        global $DB;

        $data = (array)$data;
        $oldid = $data['id'];
        unset($data['id']);

        // Find the module by name since id may be different in another site.
        if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
            return;
        }
        unset($data['modulename']);

        // Find the existing record.
        $newid = $DB->get_field('course_completion_defaults', 'id',
            ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
        if (!$newid) {
            $newid = $DB->insert_record('course_completion_defaults',
                ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
        } else {
            $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
        }

        // Save id mapping for restoring associated events.
        $this->set_mapping('course_completion_defaults', $oldid, $newid);
    }
363493
protected function manageItems()
    {
        foreach ($this->_items as $item) {

            if ($item instanceof Rule) {
                $item_exist = $this->_auth->getRule($item->name);
            } elseif ($item instanceof Role) {
                $item_exist = $this->_auth->getRole($item->name);
            } elseif ($item instanceof Permission) {
                $item_exist = $this->_auth->getPermission($item->name);
            } else {
                throw new InvalidParamException('Adding unsupported object type.');
            }

            if ($item_exist) {
                if ($item_exist instanceof __PHP_Incomplete_Class) {
                    $need_update = true;
                } else if ($item_exist instanceof Rule) {
                    $item->updatedAt = $item_exist->updatedAt;
                    $need_update = serialize($item_exist) != serialize($item);
                } else {
                    $need_update = $item_exist->description != $item->description || $item_exist->ruleName != $item->ruleName || $item_exist->data != $item->data;
                }

                if ($need_update) {
                    Console::stdout("Updating $item->name item data.\n");
                    $this->_auth->update($item->name, $item);
                }

            } else {
                Console::stdout("New item added: $item->name\n");
                $this->_auth->add($item);
            }
        }

        /** @var Role|Permission|Rule $items */
        $items = ArrayHelper::merge($this->_auth->getRules(), $this->_auth->getRules(), $this->_auth->getPermissions());

        foreach ($items as $existing_item) {
            if (!isset($this->_items[$existing_item->name])) {
                Console::stdout(Console::ansiFormat('Item removed: ' . $existing_item->name . "\n", [Console::FG_RED]));
                $this->_auth->remove($existing_item);
            }
        }
    }