Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def main(model=None, output_dir=None, n_iter=15):
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
nlp = spacy.blank("en") # create blank Language class
print("Cr... | [
"Load the model, set up the pipeline and train the parser."
] |
Please provide a description of the function:def get_pipe(self, name):
for pipe_name, component in self.pipeline:
if pipe_name == name:
return component
raise KeyError(Errors.E001.format(name=name, opts=self.pipe_names)) | [
"Get a pipeline component for a given component name.\n\n name (unicode): Name of pipeline component to get.\n RETURNS (callable): The pipeline component.\n\n DOCS: https://spacy.io/api/language#get_pipe\n "
] |
Please provide a description of the function:def create_pipe(self, name, config=dict()):
if name not in self.factories:
if name == "sbd":
raise KeyError(Errors.E108.format(name=name))
else:
raise KeyError(Errors.E002.format(name=name))
fac... | [
"Create a pipeline component from a factory.\n\n name (unicode): Factory name to look up in `Language.factories`.\n config (dict): Configuration parameters to initialise component.\n RETURNS (callable): Pipeline component.\n\n DOCS: https://spacy.io/api/language#create_pipe\n "
] |
Please provide a description of the function:def add_pipe(
self, component, name=None, before=None, after=None, first=None, last=None
):
if not hasattr(component, "__call__"):
msg = Errors.E003.format(component=repr(component), name=name)
if isinstance(component, bas... | [
"Add a component to the processing pipeline. Valid components are\n callables that take a `Doc` object, modify it and return it. Only one\n of before/after/first/last can be set. Default behaviour is \"last\".\n\n component (callable): The pipeline component.\n name (unicode): Name of pi... |
Please provide a description of the function:def replace_pipe(self, name, component):
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
self.pipeline[self.pipe_names.index(name)] = (name, component) | [
"Replace a component in the pipeline.\n\n name (unicode): Name of the component to replace.\n component (callable): Pipeline component.\n\n DOCS: https://spacy.io/api/language#replace_pipe\n "
] |
Please provide a description of the function:def rename_pipe(self, old_name, new_name):
if old_name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=old_name, opts=self.pipe_names))
if new_name in self.pipe_names:
raise ValueError(Errors.E007.format(name=... | [
"Rename a pipeline component.\n\n old_name (unicode): Name of the component to rename.\n new_name (unicode): New name of the component.\n\n DOCS: https://spacy.io/api/language#rename_pipe\n "
] |
Please provide a description of the function:def remove_pipe(self, name):
if name not in self.pipe_names:
raise ValueError(Errors.E001.format(name=name, opts=self.pipe_names))
return self.pipeline.pop(self.pipe_names.index(name)) | [
"Remove a component from the pipeline.\n\n name (unicode): Name of the component to remove.\n RETURNS (tuple): A `(name, component)` tuple of the removed component.\n\n DOCS: https://spacy.io/api/language#remove_pipe\n "
] |
Please provide a description of the function:def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None):
if len(docs) != len(golds):
raise IndexError(Errors.E009.format(n_docs=len(docs), n_golds=len(golds)))
if len(docs) == 0:
return
if sg... | [
"Update the models in the pipeline.\n\n docs (iterable): A batch of `Doc` objects.\n golds (iterable): A batch of `GoldParse` objects.\n drop (float): The droput rate.\n sgd (callable): An optimizer.\n RETURNS (dict): Results from the update.\n\n DOCS: https://spacy.io/api/... |
Please provide a description of the function:def rehearse(self, docs, sgd=None, losses=None, config=None):
# TODO: document
if len(docs) == 0:
return
if sgd is None:
if self._optimizer is None:
self._optimizer = create_default_optimizer(Model.ops)... | [
"Make a \"rehearsal\" update to the models in the pipeline, to prevent\n forgetting. Rehearsal updates run an initial copy of the model over some\n data, and update the model so its current predictions are more like the\n initial ones. This is useful for keeping a pre-trained model on-track,\n ... |
Please provide a description of the function:def preprocess_gold(self, docs_golds):
for name, proc in self.pipeline:
if hasattr(proc, "preprocess_gold"):
docs_golds = proc.preprocess_gold(docs_golds)
for doc, gold in docs_golds:
yield doc, gold | [
"Can be called before training to pre-process gold data. By default,\n it handles nonprojectivity and adds missing tags to the tag map.\n\n docs_golds (iterable): Tuples of `Doc` and `GoldParse` objects.\n YIELDS (tuple): Tuples of preprocessed `Doc` and `GoldParse` objects.\n "
] |
Please provide a description of the function:def begin_training(self, get_gold_tuples=None, sgd=None, component_cfg=None, **cfg):
if get_gold_tuples is None:
get_gold_tuples = lambda: []
# Populate vocab
else:
for _, annots_brackets in get_gold_tuples():
... | [
"Allocate models, pre-process training data and acquire a trainer and\n optimizer. Used as a contextmanager.\n\n get_gold_tuples (function): Function returning gold data\n component_cfg (dict): Config parameters for specific components.\n **cfg: Config parameters.\n RETURNS: An op... |
Please provide a description of the function:def resume_training(self, sgd=None, **cfg):
if cfg.get("device", -1) >= 0:
util.use_gpu(cfg["device"])
if self.vocab.vectors.data.shape[1] >= 1:
self.vocab.vectors.data = Model.ops.asarray(self.vocab.vectors.data)
... | [
"Continue training a pre-trained model.\n\n Create and return an optimizer, and initialize \"rehearsal\" for any pipeline\n component that has a .rehearse() method. Rehearsal is used to prevent\n models from \"forgetting\" their initialised \"knowledge\". To perform\n rehearsal, collect ... |
Please provide a description of the function:def use_params(self, params, **cfg):
contexts = [
pipe.use_params(params)
for name, pipe in self.pipeline
if hasattr(pipe, "use_params")
]
# TODO: Having trouble with contextlib
# Workaround: these ... | [
"Replace weights of models in the pipeline with those provided in the\n params dictionary. Can be used as a contextmanager, in which case,\n models go back to their original weights after the block.\n\n params (dict): A dictionary of parameters keyed by model ID.\n **cfg: Config paramete... |
Please provide a description of the function:def pipe(
self,
texts,
as_tuples=False,
n_threads=-1,
batch_size=1000,
disable=[],
cleanup=False,
component_cfg=None,
):
if n_threads != -1:
deprecation_warning(Warnings.W016)
... | [
"Process texts as a stream, and yield `Doc` objects in order.\n\n texts (iterator): A sequence of texts to process.\n as_tuples (bool): If set to True, inputs should be a sequence of\n (text, context) tuples. Output will then be a sequence of\n (doc, context) tuples. Defaults to ... |
Please provide a description of the function:def to_disk(self, path, exclude=tuple(), disable=None):
if disable is not None:
deprecation_warning(Warnings.W014)
exclude = disable
path = util.ensure_path(path)
serializers = OrderedDict()
serializers["tokeni... | [
"Save the current state to a directory. If a model is loaded, this\n will include the model.\n\n path (unicode or Path): Path to a directory, which will be created if\n it doesn't exist.\n exclude (list): Names of components or serialization fields to exclude.\n\n DOCS: https... |
Please provide a description of the function:def from_disk(self, path, exclude=tuple(), disable=None):
if disable is not None:
deprecation_warning(Warnings.W014)
exclude = disable
path = util.ensure_path(path)
deserializers = OrderedDict()
deserializers["... | [
"Loads state from a directory. Modifies the object in place and\n returns it. If the saved `Language` object contains a model, the\n model will be loaded.\n\n path (unicode or Path): A path to a directory.\n exclude (list): Names of components or serialization fields to exclude.\n ... |
Please provide a description of the function:def to_bytes(self, exclude=tuple(), disable=None, **kwargs):
if disable is not None:
deprecation_warning(Warnings.W014)
exclude = disable
serializers = OrderedDict()
serializers["vocab"] = lambda: self.vocab.to_bytes()... | [
"Serialize the current state to a binary string.\n\n exclude (list): Names of components or serialization fields to exclude.\n RETURNS (bytes): The serialized form of the `Language` object.\n\n DOCS: https://spacy.io/api/language#to_bytes\n "
] |
Please provide a description of the function:def from_bytes(self, bytes_data, exclude=tuple(), disable=None, **kwargs):
if disable is not None:
deprecation_warning(Warnings.W014)
exclude = disable
deserializers = OrderedDict()
deserializers["meta.json"] = lambda ... | [
"Load state from a binary string.\n\n bytes_data (bytes): The data to load from.\n exclude (list): Names of components or serialization fields to exclude.\n RETURNS (Language): The `Language` object.\n\n DOCS: https://spacy.io/api/language#from_bytes\n "
] |
Please provide a description of the function:def restore(self):
current, self.nlp.pipeline = self.nlp.pipeline, self.original_pipeline
unexpected = [name for name, pipe in current if not self.nlp.has_pipe(name)]
if unexpected:
# Don't change the pipeline if we're raising an ... | [
"Restore the pipeline to its state when DisabledPipes was created."
] |
Please provide a description of the function:def get_loaded_rules(rules_paths):
for path in rules_paths:
if path.name != '__init__.py':
rule = Rule.from_path(path)
if rule.is_enabled:
yield rule | [
"Yields all available rules.\n\n :type rules_paths: [Path]\n :rtype: Iterable[Rule]\n\n "
] |
Please provide a description of the function:def get_rules_import_paths():
# Bundled rules:
yield Path(__file__).parent.joinpath('rules')
# Rules defined by user:
yield settings.user_dir.joinpath('rules')
# Packages with third-party rules:
for path in sys.path:
for contrib_module in... | [
"Yields all rules import paths.\n\n :rtype: Iterable[Path]\n\n "
] |
Please provide a description of the function:def get_rules():
paths = [rule_path for path in get_rules_import_paths()
for rule_path in sorted(path.glob('*.py'))]
return sorted(get_loaded_rules(paths),
key=lambda rule: rule.priority) | [
"Returns all enabled rules.\n\n :rtype: [Rule]\n\n "
] |
Please provide a description of the function:def organize_commands(corrected_commands):
try:
first_command = next(corrected_commands)
yield first_command
except StopIteration:
return
without_duplicates = {
command for command in sorted(
corrected_commands, k... | [
"Yields sorted commands without duplicates.\n\n :type corrected_commands: Iterable[thefuck.types.CorrectedCommand]\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n "
] |
Please provide a description of the function:def get_corrected_commands(command):
corrected_commands = (
corrected for rule in get_rules()
if rule.is_match(command)
for corrected in rule.get_corrected_commands(command))
return organize_commands(corrected_commands) | [
"Returns generator with sorted and unique corrected commands.\n\n :type command: thefuck.types.Command\n :rtype: Iterable[thefuck.types.CorrectedCommand]\n\n "
] |
Please provide a description of the function:def fix_command(known_args):
settings.init(known_args)
with logs.debug_time('Total'):
logs.debug(u'Run with settings: {}'.format(pformat(settings)))
raw_command = _get_raw_command(known_args)
try:
command = types.Command.from... | [
"Fixes previous command. Used when `thefuck` called without arguments."
] |
Please provide a description of the function:def get_output(script):
with logs.debug_time(u'Read output from external shell logger'):
commands = _get_last_n(const.SHELL_LOGGER_LIMIT)
for command in commands:
if command['command'] == script:
lines = _get_output_lines(... | [
"Gets command output from shell logger."
] |
Please provide a description of the function:def _get_history_lines(self):
history_file_name = self._get_history_file_name()
if os.path.isfile(history_file_name):
with io.open(history_file_name, 'r',
encoding='utf-8', errors='ignore') as history_file:
... | [
"Returns list of history entries."
] |
Please provide a description of the function:def split_command(self, command):
encoded = self.encode_utf8(command)
try:
splitted = [s.replace("??", "\\ ") for s in shlex.split(encoded.replace('\\ ', '??'))]
except ValueError:
splitted = encoded.split(' ')
... | [
"Split the command using shell-like syntax."
] |
Please provide a description of the function:def quote(self, s):
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | [
"Return a shell-escaped version of the string s."
] |
Please provide a description of the function:def info(self):
proc = Popen(['fish', '--version'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').split()[-1]
return u'Fish Shell {}'.format(version) | [
"Returns the name and version of the current shell"
] |
Please provide a description of the function:def _put_to_history(self, command_script):
history_file_name = self._get_history_file_name()
if os.path.isfile(history_file_name):
with open(history_file_name, 'a') as history:
entry = self._get_history_line(command_script... | [
"Puts command script to shell history."
] |
Please provide a description of the function:def _get_brew_commands(brew_path_prefix):
brew_cmd_path = brew_path_prefix + BREW_CMD_PATH
return [name[:-3] for name in os.listdir(brew_cmd_path)
if name.endswith(('.rb', '.sh'))] | [
"To get brew default commands on local environment"
] |
Please provide a description of the function:def _get_brew_tap_specific_commands(brew_path_prefix):
commands = []
brew_taps_path = brew_path_prefix + TAP_PATH
for user in _get_directory_names_only(brew_taps_path):
taps = _get_directory_names_only(brew_taps_path + '/%s' % user)
# Brew ... | [
"To get tap's specific commands\n https://github.com/Homebrew/homebrew/blob/master/Library/brew.rb#L115"
] |
Please provide a description of the function:def info(self):
proc = Popen(['zsh', '-c', 'echo $ZSH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').strip()
return u'ZSH {}'.format(version) | [
"Returns the name and version of the current shell"
] |
Please provide a description of the function:def git_support(fn, command):
# supports GitHub's `hub` command
# which is recommended to be used with `alias git=hub`
# but at this point, shell aliases have already been resolved
if not is_app(command, 'git', 'hub'):
return False
# perform... | [
"Resolves git aliases and supports testing for both git and hub."
] |
Please provide a description of the function:def read_actions():
while True:
key = get_key()
# Handle arrows, j/k (qwerty), and n/e (colemak)
if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'):
yield const.ACTION_PREVIOUS
elif key in (const.KEY_DOWN, const.KEY_CTR... | [
"Yields actions for pressed keys."
] |
Please provide a description of the function:def select_command(corrected_commands):
try:
selector = CommandSelector(corrected_commands)
except NoRuleMatched:
logs.failed('No fucks given' if get_alias() == 'fuck'
else 'Nothing found')
return
if not settings.... | [
"Returns:\n\n - the first command when confirmation disabled;\n - None when ctrl+c pressed;\n - selected command.\n\n :type corrected_commands: Iterable[thefuck.types.CorrectedCommand]\n :rtype: thefuck.types.CorrectedCommand | None\n\n "
] |
Please provide a description of the function:def _spawn(shell, master_read):
pid, master_fd = pty.fork()
if pid == pty.CHILD:
os.execlp(shell, shell)
try:
mode = tty.tcgetattr(pty.STDIN_FILENO)
tty.setraw(pty.STDIN_FILENO)
restore = True
except tty.error: # This... | [
"Create a spawned process.\n\n Modified version of pty.spawn with terminal size support.\n\n "
] |
Please provide a description of the function:def shell_logger(output):
if not os.environ.get('SHELL'):
logs.warn("Shell logger doesn't support your platform.")
sys.exit(1)
fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR)
os.write(fd, b'\x00' * const.LOG_SIZE_IN_BYTES)
buff... | [
"Logs shell output to the `output`.\n\n Works like unix script command with `-f` flag.\n\n "
] |
Please provide a description of the function:def get_output(script, expanded):
if shell_logger.is_available():
return shell_logger.get_output(script)
if settings.instant_mode:
return read_log.get_output(script)
else:
return rerun.get_output(script, expanded) | [
"Get output of the script.\n\n :param script: Console script.\n :type script: str\n :param expanded: Console script with expanded aliases.\n :type expanded: str\n :rtype: str\n\n "
] |
Please provide a description of the function:def _add_arguments(self):
self._parser.add_argument(
'-v', '--version',
action='store_true',
help="show program's version number and exit")
self._parser.add_argument(
'-a', '--alias',
nargs=... | [
"Adds arguments to parser."
] |
Please provide a description of the function:def _add_conflicting_arguments(self):
group = self._parser.add_mutually_exclusive_group()
group.add_argument(
'-y', '--yes', '--yeah',
action='store_true',
help='execute fixed command without confirmation')
... | [
"It's too dangerous to use `-y` and `-r` together."
] |
Please provide a description of the function:def _prepare_arguments(self, argv):
if ARGUMENT_PLACEHOLDER in argv:
index = argv.index(ARGUMENT_PLACEHOLDER)
return argv[index + 1:] + ['--'] + argv[:index]
elif argv and not argv[0].startswith('-') and argv[0] != '--':
... | [
"Prepares arguments by:\n\n - removing placeholder and moving arguments after it to beginning,\n we need this to distinguish arguments from `command` with ours;\n\n - adding `--` before `command`, so our parse would ignore arguments\n of `command`.\n\n "
] |
Please provide a description of the function:def get_scripts():
proc = Popen(['npm', 'run-script'], stdout=PIPE)
should_yeild = False
for line in proc.stdout.readlines():
line = line.decode()
if 'available via `npm run-script`:' in line:
should_yeild = True
conti... | [
"Get custom npm scripts."
] |
Please provide a description of the function:def init(self, args=None):
from .logs import exception
self._setup_user_dir()
self._init_settings_file()
try:
self.update(self._settings_from_file())
except Exception:
exception("Can't load settings f... | [
"Fills `settings` with values from `settings.py` and env."
] |
Please provide a description of the function:def _get_user_dir_path(self):
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
user_dir = Path(xdg_config_home, 'thefuck').expanduser()
legacy_user_dir = Path('~', '.thefuck').expanduser()
# For backward compatibility... | [
"Returns Path object representing the user config resource"
] |
Please provide a description of the function:def _setup_user_dir(self):
user_dir = self._get_user_dir_path()
rules_dir = user_dir.joinpath('rules')
if not rules_dir.is_dir():
rules_dir.mkdir(parents=True)
self.user_dir = user_dir | [
"Returns user config dir, create it when it doesn't exist."
] |
Please provide a description of the function:def _settings_from_file(self):
settings = load_source(
'settings', text_type(self.user_dir.joinpath('settings.py')))
return {key: getattr(settings, key)
for key in const.DEFAULT_SETTINGS.keys()
if hasattr(s... | [
"Loads settings from file."
] |
Please provide a description of the function:def _rules_from_env(self, val):
val = val.split(':')
if 'DEFAULT_RULES' in val:
val = const.DEFAULT_RULES + [rule for rule in val if rule != 'DEFAULT_RULES']
return val | [
"Transforms rules list from env-string to python."
] |
Please provide a description of the function:def _priority_from_env(self, val):
for part in val.split(':'):
try:
rule, priority = part.split('=')
yield rule, int(priority)
except ValueError:
continue | [
"Gets priority pairs from env."
] |
Please provide a description of the function:def _val_from_env(self, env, attr):
val = os.environ[env]
if attr in ('rules', 'exclude_rules'):
return self._rules_from_env(val)
elif attr == 'priority':
return dict(self._priority_from_env(val))
elif attr in ... | [
"Transforms env-strings to python."
] |
Please provide a description of the function:def _settings_from_env(self):
return {attr: self._val_from_env(env, attr)
for env, attr in const.ENV_TO_ATTR.items()
if env in os.environ} | [
"Loads settings from env."
] |
Please provide a description of the function:def _settings_from_args(self, args):
if not args:
return {}
from_args = {}
if args.yes:
from_args['require_confirmation'] = not args.yes
if args.debug:
from_args['debug'] = args.debug
if ar... | [
"Loads settings from args."
] |
Please provide a description of the function:def _get_destination(script_parts):
for part in script_parts:
if part not in {'ln', '-s', '--symbolic'} and os.path.exists(part):
return part | [
"When arguments order is wrong first argument will be destination."
] |
Please provide a description of the function:def sudo_support(fn, command):
if not command.script.startswith('sudo '):
return fn(command)
result = fn(command.update(script=command.script[5:]))
if result and isinstance(result, six.string_types):
return u'sudo {}'.format(result)
eli... | [
"Removes sudo before calling fn and adds it after."
] |
Please provide a description of the function:def _kill_process(proc):
try:
proc.kill()
except AccessDenied:
logs.debug(u'Rerun: process PID {} ({}) could not be terminated'.format(
proc.pid, proc.exe())) | [
"Tries to kill the process otherwise just logs a debug message, the\n process will be killed when thefuck terminates.\n\n :type proc: Process\n\n "
] |
Please provide a description of the function:def _wait_output(popen, is_slow):
proc = Process(popen.pid)
try:
proc.wait(settings.wait_slow_command if is_slow
else settings.wait_command)
return True
except TimeoutExpired:
for child in proc.children(recursive=Tru... | [
"Returns `True` if we can get output of the command in the\n `settings.wait_command` time.\n\n Command will be killed if it wasn't finished in the time.\n\n :type popen: Popen\n :rtype: bool\n\n "
] |
Please provide a description of the function:def get_output(script, expanded):
env = dict(os.environ)
env.update(settings.env)
is_slow = shlex.split(expanded) in settings.slow_commands
with logs.debug_time(u'Call: {}; with env: {}; is slow: '.format(
script, env, is_slow)):
res... | [
"Runs the script and obtains stdin/stderr.\n\n :type script: str\n :type expanded: str\n :rtype: str | None\n\n "
] |
Please provide a description of the function:def get_output(script):
if six.PY2:
logs.warn('Experimental instant mode is Python 3+ only')
return None
if 'THEFUCK_OUTPUT_LOG' not in os.environ:
logs.warn("Output log isn't specified")
return None
if const.USER_COMMAND_MA... | [
"Reads script output from log.\n\n :type script: str\n :rtype: str | None\n\n "
] |
Please provide a description of the function:def get_pkgfile(command):
try:
command = command.strip()
if command.startswith('sudo '):
command = command[5:]
command = command.split(" ")[0]
packages = subprocess.check_output(
['pkgfile', '-b', '-v', comm... | [
" Gets the packages that provide the given command using `pkgfile`.\n\n If the command is of the form `sudo foo`, searches for the `foo` command\n instead.\n "
] |
Please provide a description of the function:def _get_sub_dirs(parent):
return [child for child in os.listdir(parent) if os.path.isdir(os.path.join(parent, child))] | [
"Returns a list of the child directories of the given parent directory"
] |
Please provide a description of the function:def get_new_command(command):
dest = command.script_parts[1].split(os.sep)
if dest[-1] == '':
dest = dest[:-1]
if dest[0] == '':
cwd = os.sep
dest = dest[1:]
elif six.PY2:
cwd = os.getcwdu()
else:
cwd = os.get... | [
"\n Attempt to rebuild the path string by spellchecking the directories.\n If it fails (i.e. no directories are a close enough match), then it\n defaults to the rules of cd_mkdir.\n Change sensitivity by changing MAX_ALLOWED_DIFF. Default value is 0.6\n "
] |
Please provide a description of the function:def update(self, **kwargs):
kwargs.setdefault('script', self.script)
kwargs.setdefault('output', self.output)
return Command(**kwargs) | [
"Returns new command with replaced fields.\n\n :rtype: Command\n\n "
] |
Please provide a description of the function:def from_raw_script(cls, raw_script):
script = format_raw_script(raw_script)
if not script:
raise EmptyCommand
expanded = shell.from_shell(script)
output = get_output(script, expanded)
return cls(expanded, output) | [
"Creates instance of `Command` from a list of script parts.\n\n :type raw_script: [basestring]\n :rtype: Command\n :raises: EmptyCommand\n\n "
] |
Please provide a description of the function:def from_path(cls, path):
name = path.name[:-3]
with logs.debug_time(u'Importing rule: {};'.format(name)):
rule_module = load_source(name, str(path))
priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY)
return... | [
"Creates rule instance from path.\n\n :type path: pathlib.Path\n :rtype: Rule\n\n "
] |
Please provide a description of the function:def is_enabled(self):
if self.name in settings.exclude_rules:
return False
elif self.name in settings.rules:
return True
elif self.enabled_by_default and ALL_ENABLED in settings.rules:
return True
e... | [
"Returns `True` when rule enabled.\n\n :rtype: bool\n\n "
] |
Please provide a description of the function:def is_match(self, command):
if command.output is None and self.requires_output:
return False
try:
with logs.debug_time(u'Trying rule: {};'.format(self.name)):
if self.match(command):
retur... | [
"Returns `True` if rule matches the command.\n\n :type command: Command\n :rtype: bool\n\n "
] |
Please provide a description of the function:def get_corrected_commands(self, command):
new_commands = self.get_new_command(command)
if not isinstance(new_commands, list):
new_commands = (new_commands,)
for n, new_command in enumerate(new_commands):
yield Correct... | [
"Returns generator with corrected commands.\n\n :type command: Command\n :rtype: Iterable[CorrectedCommand]\n\n "
] |
Please provide a description of the function:def _get_script(self):
if settings.repeat:
repeat_fuck = '{} --repeat {}--force-command {}'.format(
get_alias(),
'--debug ' if settings.debug else '',
shell.quote(self.script))
return sh... | [
"Returns fixed commands script.\n\n If `settings.repeat` is `True`, appends command with second attempt\n of running fuck in case fixed command fails again.\n\n "
] |
Please provide a description of the function:def run(self, old_cmd):
if self.side_effect:
self.side_effect(old_cmd, self.script)
if settings.alter_history:
shell.put_to_history(self.script)
# This depends on correct setting of PYTHONIOENCODING by the alias:
... | [
"Runs command from rule for passed command.\n\n :type old_cmd: Command\n\n "
] |
Please provide a description of the function:def _get_shell_pid():
proc = Process(os.getpid())
try:
return proc.parent().pid
except TypeError:
return proc.parent.pid | [
"Returns parent process pid."
] |
Please provide a description of the function:def _record_first_run():
info = {'pid': _get_shell_pid(),
'time': time.time()}
mode = 'wb' if six.PY2 else 'w'
with _get_not_configured_usage_tracker_path().open(mode) as tracker:
json.dump(info, tracker) | [
"Records shell pid to tracker file."
] |
Please provide a description of the function:def _is_second_run():
tracker_path = _get_not_configured_usage_tracker_path()
if not tracker_path.exists():
return False
current_pid = _get_shell_pid()
with tracker_path.open('r') as tracker:
try:
info = json.load(tracker)
... | [
"Returns `True` when we know that `fuck` called second time."
] |
Please provide a description of the function:def _is_already_configured(configuration_details):
path = Path(configuration_details.path).expanduser()
with path.open('r') as shell_config:
return configuration_details.content in shell_config.read() | [
"Returns `True` when alias already in shell config."
] |
Please provide a description of the function:def _configure(configuration_details):
path = Path(configuration_details.path).expanduser()
with path.open('a') as shell_config:
shell_config.write(u'\n')
shell_config.write(configuration_details.content)
shell_config.write(u'\n') | [
"Adds alias to shell config."
] |
Please provide a description of the function:def main():
settings.init()
configuration_details = shell.how_to_configure()
if (
configuration_details and
configuration_details.can_configure_automatically
):
if _is_already_configured(configuration_details):
logs.al... | [
"Shows useful information about how-to configure alias on a first run\n and configure automatically on a second.\n\n It'll be only visible when user type fuck and when alias isn't configured.\n\n "
] |
Please provide a description of the function:def memoize(fn):
memo = {}
@wraps(fn)
def wrapper(*args, **kwargs):
if not memoize.disabled:
key = pickle.dumps((args, kwargs))
if key not in memo:
memo[key] = fn(*args, **kwargs)
value = memo[key]... | [
"Caches previous calls to the function."
] |
Please provide a description of the function:def default_settings(params):
def _default_settings(fn, command):
for k, w in params.items():
settings.setdefault(k, w)
return fn(command)
return decorator(_default_settings) | [
"Adds default values to settings if it not presented.\n\n Usage:\n\n @default_settings({'apt': '/usr/bin/apt'})\n def match(command):\n print(settings.apt)\n\n "
] |
Please provide a description of the function:def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True):
possibilities = list(possibilities)
try:
return difflib_get_close_matches(word, possibilities, 1, cutoff)[0]
except IndexError:
if fallback_to_first:
return... | [
"Returns closest match or just first from possibilities."
] |
Please provide a description of the function:def get_close_matches(word, possibilities, n=None, cutoff=0.6):
if n is None:
n = settings.num_close_matches
return difflib_get_close_matches(word, possibilities, n, cutoff) | [
"Overrides `difflib.get_close_match` to controle argument `n`."
] |
Please provide a description of the function:def replace_argument(script, from_, to):
replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to),
script, count=1)
if replaced_in_the_end != script:
return replaced_in_the_end
else:
re... | [
"Replaces command line argument."
] |
Please provide a description of the function:def replace_command(command, broken, matched):
new_cmds = get_close_matches(broken, matched, cutoff=0.1)
return [replace_argument(command.script, broken, new_cmd.strip())
for new_cmd in new_cmds] | [
"Helper for *_no_command rules."
] |
Please provide a description of the function:def is_app(command, *app_names, **kwargs):
at_least = kwargs.pop('at_least', 0)
if kwargs:
raise TypeError("got an unexpected keyword argument '{}'".format(kwargs.keys()))
if len(command.script_parts) > at_least:
return command.script_parts... | [
"Returns `True` if command is call to one of passed app names."
] |
Please provide a description of the function:def for_app(*app_names, **kwargs):
def _for_app(fn, command):
if is_app(command, *app_names, **kwargs):
return fn(command)
else:
return False
return decorator(_for_app) | [
"Specifies that matching script is for on of app names."
] |
Please provide a description of the function:def cache(*depends_on):
def cache_decorator(fn):
@memoize
@wraps(fn)
def wrapper(*args, **kwargs):
if cache.disabled:
return fn(*args, **kwargs)
else:
return _cache.get_value(fn, depends... | [
"Caches function result in temporary file.\n\n Cache will be expired when modification date of files from `depends_on`\n will be changed.\n\n Only functions should be wrapped in `cache`, not methods.\n\n "
] |
Please provide a description of the function:def format_raw_script(raw_script):
if six.PY2:
script = ' '.join(arg.decode('utf-8') for arg in raw_script)
else:
script = ' '.join(raw_script)
return script.strip() | [
"Creates single script from a list of script parts.\n\n :type raw_script: [basestring]\n :rtype: basestring\n\n "
] |
Please provide a description of the function:def get_action(self, brain_info: BrainInfo) -> ActionInfo:
if len(brain_info.agents) == 0:
return ActionInfo([], [], [], None, None)
run_out = self.evaluate(brain_info)
return ActionInfo(
action=run_out.get('action'),... | [
"\n Decides actions given observations information, and takes them in environment.\n :param brain_info: A dictionary of brain names and BrainInfo from environment.\n :return: an ActionInfo containing action, memories, values and an object\n to be passed to add experiences\n "
] |
Please provide a description of the function:def _execute_model(self, feed_dict, out_dict):
network_out = self.sess.run(list(out_dict.values()), feed_dict=feed_dict)
run_out = dict(zip(list(out_dict.keys()), network_out))
return run_out | [
"\n Executes model.\n :param feed_dict: Input dictionary mapping nodes to input data.\n :param out_dict: Output dictionary mapping names to nodes.\n :return: Dictionary mapping names to input data.\n "
] |
Please provide a description of the function:def get_current_step(self):
step = self.sess.run(self.model.global_step)
return step | [
"\n Gets current model step.\n :return: current model step.\n "
] |
Please provide a description of the function:def save_model(self, steps):
with self.graph.as_default():
last_checkpoint = self.model_path + '/model-' + str(steps) + '.cptk'
self.saver.save(self.sess, last_checkpoint)
tf.train.write_graph(self.graph, self.model_path,
... | [
"\n Saves the model\n :param steps: The number of steps the model was trained for\n :return:\n "
] |
Please provide a description of the function:def export_model(self):
with self.graph.as_default():
target_nodes = ','.join(self._process_graph())
ckpt = tf.train.get_checkpoint_state(self.model_path)
freeze_graph.freeze_graph(
input_graph=self.model_... | [
"\n Exports latest saved model to .nn format for Unity embedding.\n "
] |
Please provide a description of the function:def _process_graph(self):
all_nodes = [x.name for x in self.graph.as_graph_def().node]
nodes = [x for x in all_nodes if x in self.possible_output_nodes]
logger.info('List of nodes to export for brain :' + self.brain.brain_name)
for n ... | [
"\n Gets the list of the output nodes present in the graph for inference\n :return: list of node names\n "
] |
Please provide a description of the function:def reset_local_buffers(self):
agent_ids = list(self.keys())
for k in agent_ids:
self[k].reset_agent() | [
"\n Resets all the local local_buffers\n "
] |
Please provide a description of the function:def append_update_buffer(self, agent_id, key_list=None, batch_size=None, training_length=None):
if key_list is None:
key_list = self[agent_id].keys()
if not self[agent_id].check_length(key_list):
raise BufferException("The len... | [
"\n Appends the buffer of an agent to the update buffer.\n :param agent_id: The id of the agent which data will be appended\n :param key_list: The fields that must be added. If None: all fields will be appended.\n :param batch_size: The number of elements that must be appended. If None: ... |
Please provide a description of the function:def append_all_agent_batch_to_update_buffer(self, key_list=None, batch_size=None, training_length=None):
for agent_id in self.keys():
self.append_update_buffer(agent_id, key_list, batch_size, training_length) | [
"\n Appends the buffer of all agents to the update buffer.\n :param key_list: The fields that must be added. If None: all fields will be appended.\n :param batch_size: The number of elements that must be appended. If None: All of them will be.\n :param training_length: The length of the ... |
Please provide a description of the function:def run_training(sub_id: int, run_seed: int, run_options, process_queue):
# Docker Parameters
docker_target_name = (run_options['--docker-target-name']
if run_options['--docker-target-name'] != 'None' else None)
# General parameter... | [
"\n Launches training session.\n :param process_queue: Queue used to send signal back to main.\n :param sub_id: Unique id for training session.\n :param run_seed: Random seed used for training.\n :param run_options: Command line arguments for training.\n "
] |
Please provide a description of the function:def get_action(self, curr_info: BrainInfo) -> ActionInfo:
self.trainer_metrics.start_experience_collection_timer()
action = self.policy.get_action(curr_info)
self.trainer_metrics.end_experience_collection_timer()
return action | [
"\n Get an action using this trainer's current policy.\n :param curr_info: Current BrainInfo.\n :return: The ActionInfo given by the policy given the BrainInfo.\n "
] |
Please provide a description of the function:def write_summary(self, global_step, delta_train_start, lesson_num=0):
if global_step % self.trainer_parameters['summary_freq'] == 0 and global_step != 0:
is_training = "Training." if self.is_training and self.get_step <= self.get_max_steps else ... | [
"\n Saves training statistics to Tensorboard.\n :param delta_train_start: Time elapsed since training started.\n :param lesson_num: Current lesson number in curriculum.\n :param global_step: The number of steps the simulation has been going for\n "
] |
Please provide a description of the function:def write_tensorboard_text(self, key, input_dict):
try:
with tf.Session() as sess:
s_op = tf.summary.text(key, tf.convert_to_tensor(
([[str(x), str(input_dict[x])] for x in input_dict])))
s = se... | [
"\n Saves text to Tensorboard.\n Note: Only works on tensorflow r1.2 or above.\n :param key: The name of the text.\n :param input_dict: A dictionary that will be displayed in a table on Tensorboard.\n "
] |
Please provide a description of the function:def lesson_nums(self):
lesson_nums = {}
for brain_name, curriculum in self.brains_to_curriculums.items():
lesson_nums[brain_name] = curriculum.lesson_num
return lesson_nums | [
"A dict from brain name to the brain's curriculum's lesson number."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.