id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,600 | dmlc/gluon-nlp | scripts/natural_language_inference/decomposable_attention.py | NLIModel.hybrid_forward | def hybrid_forward(self, F, sentence1, sentence2):
"""
Predict the relation of two sentences.
Parameters
----------
sentence1 : NDArray
Shape (batch_size, length)
sentence2 : NDArray
Shape (batch_size, length)
Returns
-------
... | python | def hybrid_forward(self, F, sentence1, sentence2):
"""
Predict the relation of two sentences.
Parameters
----------
sentence1 : NDArray
Shape (batch_size, length)
sentence2 : NDArray
Shape (batch_size, length)
Returns
-------
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"sentence1",
",",
"sentence2",
")",
":",
"feature1",
"=",
"self",
".",
"lin_proj",
"(",
"self",
".",
"word_emb",
"(",
"sentence1",
")",
")",
"feature2",
"=",
"self",
".",
"lin_proj",
"(",
"self",
"."... | Predict the relation of two sentences.
Parameters
----------
sentence1 : NDArray
Shape (batch_size, length)
sentence2 : NDArray
Shape (batch_size, length)
Returns
-------
pred : NDArray
Shape (batch_size, num_classes). num_cla... | [
"Predict",
"the",
"relation",
"of",
"two",
"sentences",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L55-L78 |
32,601 | dmlc/gluon-nlp | scripts/natural_language_inference/decomposable_attention.py | IntraSentenceAttention.hybrid_forward | def hybrid_forward(self, F, feature_a):
"""
Compute intra-sentence attention given embedded words.
Parameters
----------
feature_a : NDArray
Shape (batch_size, length, hidden_size)
Returns
-------
alpha : NDArray
Shape (batch_size... | python | def hybrid_forward(self, F, feature_a):
"""
Compute intra-sentence attention given embedded words.
Parameters
----------
feature_a : NDArray
Shape (batch_size, length, hidden_size)
Returns
-------
alpha : NDArray
Shape (batch_size... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"feature_a",
")",
":",
"tilde_a",
"=",
"self",
".",
"intra_attn_emb",
"(",
"feature_a",
")",
"e_matrix",
"=",
"F",
".",
"batch_dot",
"(",
"tilde_a",
",",
"tilde_a",
",",
"transpose_b",
"=",
"True",
")"... | Compute intra-sentence attention given embedded words.
Parameters
----------
feature_a : NDArray
Shape (batch_size, length, hidden_size)
Returns
-------
alpha : NDArray
Shape (batch_size, length, hidden_size) | [
"Compute",
"intra",
"-",
"sentence",
"attention",
"given",
"embedded",
"words",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L98-L115 |
32,602 | dmlc/gluon-nlp | scripts/natural_language_inference/decomposable_attention.py | DecomposableAttention.hybrid_forward | def hybrid_forward(self, F, a, b):
"""
Forward of Decomposable Attention layer
"""
# a.shape = [B, L1, H]
# b.shape = [B, L2, H]
# extract features
tilde_a = self.f(a) # shape = [B, L1, H]
tilde_b = self.f(b) # shape = [B, L2, H]
# attention
... | python | def hybrid_forward(self, F, a, b):
"""
Forward of Decomposable Attention layer
"""
# a.shape = [B, L1, H]
# b.shape = [B, L2, H]
# extract features
tilde_a = self.f(a) # shape = [B, L1, H]
tilde_b = self.f(b) # shape = [B, L2, H]
# attention
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"a",
",",
"b",
")",
":",
"# a.shape = [B, L1, H]",
"# b.shape = [B, L2, H]",
"# extract features",
"tilde_a",
"=",
"self",
".",
"f",
"(",
"a",
")",
"# shape = [B, L1, H]",
"tilde_b",
"=",
"self",
".",
"f",
... | Forward of Decomposable Attention layer | [
"Forward",
"of",
"Decomposable",
"Attention",
"layer"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/decomposable_attention.py#L144-L166 |
32,603 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | count_tokens | def count_tokens(tokens, to_lower=False, counter=None):
r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----... | python | def count_tokens(tokens, to_lower=False, counter=None):
r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----... | [
"def",
"count_tokens",
"(",
"tokens",
",",
"to_lower",
"=",
"False",
",",
"counter",
"=",
"None",
")",
":",
"if",
"to_lower",
":",
"tokens",
"=",
"[",
"t",
".",
"lower",
"(",
")",
"for",
"t",
"in",
"tokens",
"]",
"if",
"counter",
"is",
"None",
":",... | r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----------
tokens : list of str
A source list of tok... | [
"r",
"Counts",
"tokens",
"in",
"the",
"specified",
"string",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L92-L133 |
32,604 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | slice_sequence | def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0):
"""Slice a flat sequence of tokens into sequences tokens, with each
inner sequence's length equal to the specified `length`, taking into account the requested
sequence overlap.
Parameters
----------
sequence :... | python | def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0):
"""Slice a flat sequence of tokens into sequences tokens, with each
inner sequence's length equal to the specified `length`, taking into account the requested
sequence overlap.
Parameters
----------
sequence :... | [
"def",
"slice_sequence",
"(",
"sequence",
",",
"length",
",",
"pad_last",
"=",
"False",
",",
"pad_val",
"=",
"C",
".",
"PAD_TOKEN",
",",
"overlap",
"=",
"0",
")",
":",
"if",
"length",
"<=",
"overlap",
":",
"raise",
"ValueError",
"(",
"'length needs to be l... | Slice a flat sequence of tokens into sequences tokens, with each
inner sequence's length equal to the specified `length`, taking into account the requested
sequence overlap.
Parameters
----------
sequence : list of object
A flat list of tokens.
length : int
The length of each of... | [
"Slice",
"a",
"flat",
"sequence",
"of",
"tokens",
"into",
"sequences",
"tokens",
"with",
"each",
"inner",
"sequence",
"s",
"length",
"equal",
"to",
"the",
"specified",
"length",
"taking",
"into",
"account",
"the",
"requested",
"sequence",
"overlap",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L152-L187 |
32,605 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | _slice_pad_length | def _slice_pad_length(num_items, length, overlap=0):
"""Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap... | python | def _slice_pad_length(num_items, length, overlap=0):
"""Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap... | [
"def",
"_slice_pad_length",
"(",
"num_items",
",",
"length",
",",
"overlap",
"=",
"0",
")",
":",
"if",
"length",
"<=",
"overlap",
":",
"raise",
"ValueError",
"(",
"'length needs to be larger than overlap'",
")",
"step",
"=",
"length",
"-",
"overlap",
"span",
"... | Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap : int, default 0
The extra number of items in curre... | [
"Calculate",
"the",
"padding",
"length",
"needed",
"for",
"sliced",
"samples",
"in",
"order",
"not",
"to",
"discard",
"data",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L190-L217 |
32,606 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | train_valid_split | def train_valid_split(dataset, valid_ratio=0.05):
"""Split the dataset into training and validation sets.
Parameters
----------
dataset : list
A list of training samples.
valid_ratio : float, default 0.05
Proportion of training samples to use for validation set
range: [0, 1]... | python | def train_valid_split(dataset, valid_ratio=0.05):
"""Split the dataset into training and validation sets.
Parameters
----------
dataset : list
A list of training samples.
valid_ratio : float, default 0.05
Proportion of training samples to use for validation set
range: [0, 1]... | [
"def",
"train_valid_split",
"(",
"dataset",
",",
"valid_ratio",
"=",
"0.05",
")",
":",
"if",
"not",
"0.0",
"<=",
"valid_ratio",
"<=",
"1.0",
":",
"raise",
"ValueError",
"(",
"'valid_ratio should be in [0, 1]'",
")",
"num_train",
"=",
"len",
"(",
"dataset",
")"... | Split the dataset into training and validation sets.
Parameters
----------
dataset : list
A list of training samples.
valid_ratio : float, default 0.05
Proportion of training samples to use for validation set
range: [0, 1]
Returns
-------
train : SimpleDataset
v... | [
"Split",
"the",
"dataset",
"into",
"training",
"and",
"validation",
"sets",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L236-L262 |
32,607 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | _load_pretrained_vocab | def _load_pretrained_vocab(name, root=os.path.join(get_home_dir(), 'models'), cls=None):
"""Load the accompanying vocabulary object for pre-trained model.
Parameters
----------
name : str
Name of the vocabulary, usually the name of the dataset.
root : str, default '$MXNET_HOME/models'
... | python | def _load_pretrained_vocab(name, root=os.path.join(get_home_dir(), 'models'), cls=None):
"""Load the accompanying vocabulary object for pre-trained model.
Parameters
----------
name : str
Name of the vocabulary, usually the name of the dataset.
root : str, default '$MXNET_HOME/models'
... | [
"def",
"_load_pretrained_vocab",
"(",
"name",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'models'",
")",
",",
"cls",
"=",
"None",
")",
":",
"file_name",
"=",
"'{name}-{short_hash}'",
".",
"format",
"(",
"name",... | Load the accompanying vocabulary object for pre-trained model.
Parameters
----------
name : str
Name of the vocabulary, usually the name of the dataset.
root : str, default '$MXNET_HOME/models'
Location for keeping the model parameters.
MXNET_HOME defaults to '~/.mxnet'.
cls... | [
"Load",
"the",
"accompanying",
"vocabulary",
"object",
"for",
"pre",
"-",
"trained",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L271-L318 |
32,608 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | _extract_archive | def _extract_archive(file, target_dir):
"""Extract archive file
Parameters
----------
file : str
Absolute path of the archive file.
target_dir : str
Target directory of the archive to be uncompressed
"""
if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tg... | python | def _extract_archive(file, target_dir):
"""Extract archive file
Parameters
----------
file : str
Absolute path of the archive file.
target_dir : str
Target directory of the archive to be uncompressed
"""
if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tg... | [
"def",
"_extract_archive",
"(",
"file",
",",
"target_dir",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"'.gz'",
")",
"or",
"file",
".",
"endswith",
"(",
"'.tar'",
")",
"or",
"file",
".",
"endswith",
"(",
"'.tgz'",
")",
":",
"archive",
"=",
"tarfile",... | Extract archive file
Parameters
----------
file : str
Absolute path of the archive file.
target_dir : str
Target directory of the archive to be uncompressed | [
"Extract",
"archive",
"file"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L330-L348 |
32,609 | dmlc/gluon-nlp | src/gluonnlp/data/utils.py | Counter.discard | def discard(self, min_freq, unknown_token):
"""Discards tokens with frequency below min_frequency and represents them
as `unknown_token`.
Parameters
----------
min_freq: int
Tokens whose frequency is under min_freq is counted as `unknown_token` in
the Cou... | python | def discard(self, min_freq, unknown_token):
"""Discards tokens with frequency below min_frequency and represents them
as `unknown_token`.
Parameters
----------
min_freq: int
Tokens whose frequency is under min_freq is counted as `unknown_token` in
the Cou... | [
"def",
"discard",
"(",
"self",
",",
"min_freq",
",",
"unknown_token",
")",
":",
"freq",
"=",
"0",
"ret",
"=",
"Counter",
"(",
"{",
"}",
")",
"for",
"token",
",",
"count",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"count",
"<",
"min_freq",
... | Discards tokens with frequency below min_frequency and represents them
as `unknown_token`.
Parameters
----------
min_freq: int
Tokens whose frequency is under min_freq is counted as `unknown_token` in
the Counter returned.
unknown_token: str
T... | [
"Discards",
"tokens",
"with",
"frequency",
"below",
"min_frequency",
"and",
"represents",
"them",
"as",
"unknown_token",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/utils.py#L45-L75 |
32,610 | dmlc/gluon-nlp | src/gluonnlp/model/highway.py | Highway.hybrid_forward | def hybrid_forward(self, F, inputs, **kwargs):
# pylint: disable=unused-argument
r"""
Forward computation for highway layer
Parameters
----------
inputs: NDArray
The input tensor is of shape `(..., input_size)`.
Returns
----------
out... | python | def hybrid_forward(self, F, inputs, **kwargs):
# pylint: disable=unused-argument
r"""
Forward computation for highway layer
Parameters
----------
inputs: NDArray
The input tensor is of shape `(..., input_size)`.
Returns
----------
out... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"current_input",
"=",
"inputs",
"for",
"layer",
"in",
"self",
".",
"hnet",
":",
"projected_input",
"=",
"layer",
"(",
"curr... | r"""
Forward computation for highway layer
Parameters
----------
inputs: NDArray
The input tensor is of shape `(..., input_size)`.
Returns
----------
outputs: NDArray
The output tensor is of the same shape with input tensor `(..., input_s... | [
"r",
"Forward",
"computation",
"for",
"highway",
"layer"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/highway.py#L102-L126 |
32,611 | dmlc/gluon-nlp | scripts/natural_language_inference/preprocess.py | main | def main(args):
"""
Read tokens from the provided parse tree in the SNLI dataset.
Illegal examples are removed.
"""
examples = []
with open(args.input, 'r') as fin:
reader = csv.DictReader(fin, delimiter='\t')
for cols in reader:
s1 = read_tokens(cols['sentence1_parse... | python | def main(args):
"""
Read tokens from the provided parse tree in the SNLI dataset.
Illegal examples are removed.
"""
examples = []
with open(args.input, 'r') as fin:
reader = csv.DictReader(fin, delimiter='\t')
for cols in reader:
s1 = read_tokens(cols['sentence1_parse... | [
"def",
"main",
"(",
"args",
")",
":",
"examples",
"=",
"[",
"]",
"with",
"open",
"(",
"args",
".",
"input",
",",
"'r'",
")",
"as",
"fin",
":",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"fin",
",",
"delimiter",
"=",
"'\\t'",
")",
"for",
"cols"... | Read tokens from the provided parse tree in the SNLI dataset.
Illegal examples are removed. | [
"Read",
"tokens",
"from",
"the",
"provided",
"parse",
"tree",
"in",
"the",
"SNLI",
"dataset",
".",
"Illegal",
"examples",
"are",
"removed",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/natural_language_inference/preprocess.py#L42-L58 |
32,612 | dmlc/gluon-nlp | scripts/parsing/common/k_means.py | KMeans._recenter | def _recenter(self):
"""
one iteration of k-means
"""
for split_idx in range(len(self._splits)):
split = self._splits[split_idx]
len_idx = self._split2len_idx[split]
if split == self._splits[-1]:
continue
right_split = self.... | python | def _recenter(self):
"""
one iteration of k-means
"""
for split_idx in range(len(self._splits)):
split = self._splits[split_idx]
len_idx = self._split2len_idx[split]
if split == self._splits[-1]:
continue
right_split = self.... | [
"def",
"_recenter",
"(",
"self",
")",
":",
"for",
"split_idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_splits",
")",
")",
":",
"split",
"=",
"self",
".",
"_splits",
"[",
"split_idx",
"]",
"len_idx",
"=",
"self",
".",
"_split2len_idx",
"[",
"sp... | one iteration of k-means | [
"one",
"iteration",
"of",
"k",
"-",
"means"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L108-L145 |
32,613 | dmlc/gluon-nlp | scripts/parsing/common/k_means.py | KMeans._reindex | def _reindex(self):
"""
Index every sentence into a cluster
"""
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits):
self._len2split_idx.update(
dict(list(zip(list(range(last_split + 1, split)), [split_idx] ... | python | def _reindex(self):
"""
Index every sentence into a cluster
"""
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits):
self._len2split_idx.update(
dict(list(zip(list(range(last_split + 1, split)), [split_idx] ... | [
"def",
"_reindex",
"(",
"self",
")",
":",
"self",
".",
"_len2split_idx",
"=",
"{",
"}",
"last_split",
"=",
"-",
"1",
"for",
"split_idx",
",",
"split",
"in",
"enumerate",
"(",
"self",
".",
"_splits",
")",
":",
"self",
".",
"_len2split_idx",
".",
"update... | Index every sentence into a cluster | [
"Index",
"every",
"sentence",
"into",
"a",
"cluster"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/k_means.py#L147-L155 |
32,614 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | transform | def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True):
"""Transform instance to inputs for MLM and NSP."""
pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0]
input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
input_mask = [1] * len(input_ids)
segment_ids... | python | def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True):
"""Transform instance to inputs for MLM and NSP."""
pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0]
input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
input_mask = [1] * len(input_ids)
segment_ids... | [
"def",
"transform",
"(",
"instance",
",",
"tokenizer",
",",
"max_seq_length",
",",
"max_predictions_per_seq",
",",
"do_pad",
"=",
"True",
")",
":",
"pad",
"=",
"tokenizer",
".",
"convert_tokens_to_ids",
"(",
"[",
"'[PAD]'",
"]",
")",
"[",
"0",
"]",
"input_id... | Transform instance to inputs for MLM and NSP. | [
"Transform",
"instance",
"to",
"inputs",
"for",
"MLM",
"and",
"NSP",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L163-L208 |
32,615 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | write_to_files_np | def write_to_files_np(features, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
# pylint: disable=unused-argument
"""Write to numpy files from `TrainingInstance`s."""
next_sentence_labels = []
valid_lengths = []
assert len(output_files) == 1, 'numpy format o... | python | def write_to_files_np(features, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
# pylint: disable=unused-argument
"""Write to numpy files from `TrainingInstance`s."""
next_sentence_labels = []
valid_lengths = []
assert len(output_files) == 1, 'numpy format o... | [
"def",
"write_to_files_np",
"(",
"features",
",",
"tokenizer",
",",
"max_seq_length",
",",
"max_predictions_per_seq",
",",
"output_files",
")",
":",
"# pylint: disable=unused-argument",
"next_sentence_labels",
"=",
"[",
"]",
"valid_lengths",
"=",
"[",
"]",
"assert",
"... | Write to numpy files from `TrainingInstance`s. | [
"Write",
"to",
"numpy",
"files",
"from",
"TrainingInstance",
"s",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L218-L242 |
32,616 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | write_to_files_rec | def write_to_files_rec(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create IndexedRecordIO files from `TrainingInstance`s."""
writers = []
for output_file in output_files:
writers.append(
mx.recordio.MXIndexedRecordIO(
... | python | def write_to_files_rec(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
"""Create IndexedRecordIO files from `TrainingInstance`s."""
writers = []
for output_file in output_files:
writers.append(
mx.recordio.MXIndexedRecordIO(
... | [
"def",
"write_to_files_rec",
"(",
"instances",
",",
"tokenizer",
",",
"max_seq_length",
",",
"max_predictions_per_seq",
",",
"output_files",
")",
":",
"writers",
"=",
"[",
"]",
"for",
"output_file",
"in",
"output_files",
":",
"writers",
".",
"append",
"(",
"mx",... | Create IndexedRecordIO files from `TrainingInstance`s. | [
"Create",
"IndexedRecordIO",
"files",
"from",
"TrainingInstance",
"s",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L244-L266 |
32,617 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | create_training_instances | def create_training_instances(x):
"""Create `TrainingInstance`s from raw text."""
(input_files, out, tokenizer, max_seq_length, dupe_factor,
short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x
time_start = time.time()
logging.info('Processing %s', input_files)
all_documents = [[]]... | python | def create_training_instances(x):
"""Create `TrainingInstance`s from raw text."""
(input_files, out, tokenizer, max_seq_length, dupe_factor,
short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x
time_start = time.time()
logging.info('Processing %s', input_files)
all_documents = [[]]... | [
"def",
"create_training_instances",
"(",
"x",
")",
":",
"(",
"input_files",
",",
"out",
",",
"tokenizer",
",",
"max_seq_length",
",",
"dupe_factor",
",",
"short_seq_prob",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"rng",
")",
"=",
"x",
"time_st... | Create `TrainingInstance`s from raw text. | [
"Create",
"TrainingInstance",
"s",
"from",
"raw",
"text",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L269-L351 |
32,618 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | create_instances_from_document | def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates `TrainingInstance`s for a single document."""
document = all_documents[document_index]
# Account for [CLS], [SEP], [SEP]
... | python | def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates `TrainingInstance`s for a single document."""
document = all_documents[document_index]
# Account for [CLS], [SEP], [SEP]
... | [
"def",
"create_instances_from_document",
"(",
"all_documents",
",",
"document_index",
",",
"max_seq_length",
",",
"short_seq_prob",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"vocab_words",
",",
"rng",
")",
":",
"document",
"=",
"all_documents",
"[",
... | Creates `TrainingInstance`s for a single document. | [
"Creates",
"TrainingInstance",
"s",
"for",
"a",
"single",
"document",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L354-L472 |
32,619 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | create_masked_lm_predictions | def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective."""
cand_indexes = []
for (i, token) in enumerate(tokens):
if token in ['[CLS]', '[SEP]']:
continu... | python | def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective."""
cand_indexes = []
for (i, token) in enumerate(tokens):
if token in ['[CLS]', '[SEP]']:
continu... | [
"def",
"create_masked_lm_predictions",
"(",
"tokens",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"vocab_words",
",",
"rng",
")",
":",
"cand_indexes",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"token",
")",
"in",
"enumerate",
"(",
"tokens",
")",
"... | Creates the predictions for the masked LM objective. | [
"Creates",
"the",
"predictions",
"for",
"the",
"masked",
"LM",
"objective",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L479-L530 |
32,620 | dmlc/gluon-nlp | scripts/bert/create_pretraining_data.py | truncate_seq_pair | def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
"""Truncates a pair of sequences to a maximum sequence length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(... | python | def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
"""Truncates a pair of sequences to a maximum sequence length."""
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(... | [
"def",
"truncate_seq_pair",
"(",
"tokens_a",
",",
"tokens_b",
",",
"max_num_tokens",
",",
"rng",
")",
":",
"while",
"True",
":",
"total_length",
"=",
"len",
"(",
"tokens_a",
")",
"+",
"len",
"(",
"tokens_b",
")",
"if",
"total_length",
"<=",
"max_num_tokens",... | Truncates a pair of sequences to a maximum sequence length. | [
"Truncates",
"a",
"pair",
"of",
"sequences",
"to",
"a",
"maximum",
"sequence",
"length",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/create_pretraining_data.py#L533-L548 |
32,621 | dmlc/gluon-nlp | scripts/bert/utils.py | convert_vocab | def convert_vocab(vocab_file):
"""GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab."""
original_vocab = load_vocab(vocab_file)
token_to_idx = dict(original_vocab)
num_tokens = len(token_to_idx)
idx_to_token = [None] * len(original_vocab)
for word in original_vocab... | python | def convert_vocab(vocab_file):
"""GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab."""
original_vocab = load_vocab(vocab_file)
token_to_idx = dict(original_vocab)
num_tokens = len(token_to_idx)
idx_to_token = [None] * len(original_vocab)
for word in original_vocab... | [
"def",
"convert_vocab",
"(",
"vocab_file",
")",
":",
"original_vocab",
"=",
"load_vocab",
"(",
"vocab_file",
")",
"token_to_idx",
"=",
"dict",
"(",
"original_vocab",
")",
"num_tokens",
"=",
"len",
"(",
"token_to_idx",
")",
"idx_to_token",
"=",
"[",
"None",
"]"... | GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab. | [
"GluonNLP",
"specific",
"code",
"to",
"convert",
"the",
"original",
"vocabulary",
"to",
"nlp",
".",
"vocab",
".",
"BERTVocab",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L33-L83 |
32,622 | dmlc/gluon-nlp | scripts/bert/utils.py | read_tf_checkpoint | def read_tf_checkpoint(path):
"""read tensorflow checkpoint"""
from tensorflow.python import pywrap_tensorflow
tensors = {}
reader = pywrap_tensorflow.NewCheckpointReader(path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
tensor = reader.get_... | python | def read_tf_checkpoint(path):
"""read tensorflow checkpoint"""
from tensorflow.python import pywrap_tensorflow
tensors = {}
reader = pywrap_tensorflow.NewCheckpointReader(path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
tensor = reader.get_... | [
"def",
"read_tf_checkpoint",
"(",
"path",
")",
":",
"from",
"tensorflow",
".",
"python",
"import",
"pywrap_tensorflow",
"tensors",
"=",
"{",
"}",
"reader",
"=",
"pywrap_tensorflow",
".",
"NewCheckpointReader",
"(",
"path",
")",
"var_to_shape_map",
"=",
"reader",
... | read tensorflow checkpoint | [
"read",
"tensorflow",
"checkpoint"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L97-L106 |
32,623 | dmlc/gluon-nlp | scripts/bert/utils.py | profile | def profile(curr_step, start_step, end_step, profile_name='profile.json',
early_exit=True):
"""profile the program between [start_step, end_step)."""
if curr_step == start_step:
mx.nd.waitall()
mx.profiler.set_config(profile_memory=False, profile_symbolic=True,
... | python | def profile(curr_step, start_step, end_step, profile_name='profile.json',
early_exit=True):
"""profile the program between [start_step, end_step)."""
if curr_step == start_step:
mx.nd.waitall()
mx.profiler.set_config(profile_memory=False, profile_symbolic=True,
... | [
"def",
"profile",
"(",
"curr_step",
",",
"start_step",
",",
"end_step",
",",
"profile_name",
"=",
"'profile.json'",
",",
"early_exit",
"=",
"True",
")",
":",
"if",
"curr_step",
"==",
"start_step",
":",
"mx",
".",
"nd",
".",
"waitall",
"(",
")",
"mx",
"."... | profile the program between [start_step, end_step). | [
"profile",
"the",
"program",
"between",
"[",
"start_step",
"end_step",
")",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L108-L123 |
32,624 | dmlc/gluon-nlp | scripts/bert/utils.py | load_vocab | def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with io.open(vocab_file, 'r') as reader:
while True:
token = reader.readline()
if not token:
break
token = token.strip()
... | python | def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
index = 0
with io.open(vocab_file, 'r') as reader:
while True:
token = reader.readline()
if not token:
break
token = token.strip()
... | [
"def",
"load_vocab",
"(",
"vocab_file",
")",
":",
"vocab",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"index",
"=",
"0",
"with",
"io",
".",
"open",
"(",
"vocab_file",
",",
"'r'",
")",
"as",
"reader",
":",
"while",
"True",
":",
"token",
"=",
"r... | Loads a vocabulary file into a dictionary. | [
"Loads",
"a",
"vocabulary",
"file",
"into",
"a",
"dictionary",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/utils.py#L125-L137 |
32,625 | dmlc/gluon-nlp | src/gluonnlp/model/convolutional_encoder.py | ConvolutionalEncoder.hybrid_forward | def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
r"""
Forward computation for char_encoder
Parameters
----------
inputs: NDArray
The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.
mask: NDArray
... | python | def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
r"""
Forward computation for char_encoder
Parameters
----------
inputs: NDArray
The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.
mask: NDArray
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"mask",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"mask",
"is",
"not",
"None",
":",
"inputs",
"=",
"F",
".",
"broadcast_mul",
"(",
"inputs",
",",
"mask",
".",
"e... | r"""
Forward computation for char_encoder
Parameters
----------
inputs: NDArray
The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.
mask: NDArray
The mask applied to the input of shape `(seq_len, batch_size)`, the mask will
... | [
"r",
"Forward",
"computation",
"for",
"char_encoder"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/convolutional_encoder.py#L135-L166 |
32,626 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | _position_encoding_init | def _position_encoding_init(max_length, dim):
"""Init the sinusoid position encoding table """
position_enc = np.arange(max_length).reshape((-1, 1)) \
/ (np.power(10000, (2. / dim) * np.arange(dim).reshape((1, -1))))
# Apply the cosine to even columns and sin to odds.
position_enc[:, ... | python | def _position_encoding_init(max_length, dim):
"""Init the sinusoid position encoding table """
position_enc = np.arange(max_length).reshape((-1, 1)) \
/ (np.power(10000, (2. / dim) * np.arange(dim).reshape((1, -1))))
# Apply the cosine to even columns and sin to odds.
position_enc[:, ... | [
"def",
"_position_encoding_init",
"(",
"max_length",
",",
"dim",
")",
":",
"position_enc",
"=",
"np",
".",
"arange",
"(",
"max_length",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"/",
"(",
"np",
".",
"power",
"(",
"10000",
",",
"(... | Init the sinusoid position encoding table | [
"Init",
"the",
"sinusoid",
"position",
"encoding",
"table"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L46-L53 |
32,627 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | transformer_en_de_512 | def transformer_en_de_512(dataset_name=None, src_vocab=None, tgt_vocab=None, pretrained=False,
ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Transformer pretrained model.
Embedding size is 400, and hidden layer size is 1150.
Parameters
----------
... | python | def transformer_en_de_512(dataset_name=None, src_vocab=None, tgt_vocab=None, pretrained=False,
ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Transformer pretrained model.
Embedding size is 400, and hidden layer size is 1150.
Parameters
----------
... | [
"def",
"transformer_en_de_512",
"(",
"dataset_name",
"=",
"None",
",",
"src_vocab",
"=",
"None",
",",
"tgt_vocab",
"=",
"None",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | r"""Transformer pretrained model.
Embedding size is 400, and hidden layer size is 1150.
Parameters
----------
dataset_name : str or None, default None
src_vocab : gluonnlp.Vocab or None, default None
tgt_vocab : gluonnlp.Vocab or None, default None
pretrained : bool, default False
... | [
"r",
"Transformer",
"pretrained",
"model",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L1200-L1251 |
32,628 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | BasePositionwiseFFN._get_activation | def _get_activation(self, act):
"""Get activation block based on the name. """
if isinstance(act, str):
if act.lower() == 'gelu':
return GELU()
else:
return gluon.nn.Activation(act)
assert isinstance(act, gluon.Block)
return act | python | def _get_activation(self, act):
"""Get activation block based on the name. """
if isinstance(act, str):
if act.lower() == 'gelu':
return GELU()
else:
return gluon.nn.Activation(act)
assert isinstance(act, gluon.Block)
return act | [
"def",
"_get_activation",
"(",
"self",
",",
"act",
")",
":",
"if",
"isinstance",
"(",
"act",
",",
"str",
")",
":",
"if",
"act",
".",
"lower",
"(",
")",
"==",
"'gelu'",
":",
"return",
"GELU",
"(",
")",
"else",
":",
"return",
"gluon",
".",
"nn",
".... | Get activation block based on the name. | [
"Get",
"activation",
"block",
"based",
"on",
"the",
"name",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L116-L124 |
32,629 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | BasePositionwiseFFN.hybrid_forward | def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Position-wise encoding of the inputs.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
Returns
... | python | def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Position-wise encoding of the inputs.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
Returns
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
")",
":",
"# pylint: disable=arguments-differ",
"# pylint: disable=unused-argument",
"outputs",
"=",
"self",
".",
"ffn_1",
"(",
"inputs",
")",
"if",
"self",
".",
"activation",
":",
"outputs",
"=",
"s... | Position-wise encoding of the inputs.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
Returns
-------
outputs : Symbol or NDArray
Shape (batch_size, length, C_out) | [
"Position",
"-",
"wise",
"encoding",
"of",
"the",
"inputs",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L126-L149 |
32,630 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | BaseTransformerEncoderCell.hybrid_forward | def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask... | python | def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"mask",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"# pylint: disable=unused-argument",
"outputs",
",",
"attention_weights",
"=",
"self",
".",
"attention_cell",
"(",
"inputs",
",",... | Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask : Symbol or NDArray or None
Mask for inputs. Shape (batch_size, length, length)
Returns
-------
enc... | [
"Transformer",
"Encoder",
"Attention",
"Cell",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L236-L267 |
32,631 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | TransformerDecoderCell.hybrid_forward | def hybrid_forward(self, F, inputs, mem_value, mask=None, mem_mask=None): #pylint: disable=unused-argument
# pylint: disable=arguments-differ
"""Transformer Decoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, ... | python | def hybrid_forward(self, F, inputs, mem_value, mask=None, mem_mask=None): #pylint: disable=unused-argument
# pylint: disable=arguments-differ
"""Transformer Decoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, ... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"mem_value",
",",
"mask",
"=",
"None",
",",
"mem_mask",
"=",
"None",
")",
":",
"#pylint: disable=unused-argument",
"# pylint: disable=arguments-differ",
"outputs",
",",
"attention_in_outputs",
"=",... | Transformer Decoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mem_value : Symbol or NDArrays
Memory value, i.e. output of the encoder. Shape (batch_size, mem_length, C_in)
mask : Symb... | [
"Transformer",
"Decoder",
"Attention",
"Cell",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L778-L823 |
32,632 | dmlc/gluon-nlp | src/gluonnlp/model/transformer.py | ParallelTransformer.forward_backward | def forward_backward(self, x):
"""Perform forward and backward computation for a batch of src seq and dst seq"""
(src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x
with mx.autograd.record():
out, _ = self._model(src_seq, tgt_seq[:, :-1],
... | python | def forward_backward(self, x):
"""Perform forward and backward computation for a batch of src seq and dst seq"""
(src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x
with mx.autograd.record():
out, _ = self._model(src_seq, tgt_seq[:, :-1],
... | [
"def",
"forward_backward",
"(",
"self",
",",
"x",
")",
":",
"(",
"src_seq",
",",
"tgt_seq",
",",
"src_valid_length",
",",
"tgt_valid_length",
")",
",",
"batch_size",
"=",
"x",
"with",
"mx",
".",
"autograd",
".",
"record",
"(",
")",
":",
"out",
",",
"_"... | Perform forward and backward computation for a batch of src seq and dst seq | [
"Perform",
"forward",
"and",
"backward",
"computation",
"for",
"a",
"batch",
"of",
"src",
"seq",
"and",
"dst",
"seq"
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/transformer.py#L1274-L1284 |
32,633 | dmlc/gluon-nlp | src/gluonnlp/data/candidate_sampler.py | UnigramCandidateSampler.hybrid_forward | def hybrid_forward(self, F, candidates_like, prob, alias):
# pylint: disable=unused-argument
"""Draw samples from uniform distribution and return sampled candidates.
Parameters
----------
candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol
This input specifies the ... | python | def hybrid_forward(self, F, candidates_like, prob, alias):
# pylint: disable=unused-argument
"""Draw samples from uniform distribution and return sampled candidates.
Parameters
----------
candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol
This input specifies the ... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"candidates_like",
",",
"prob",
",",
"alias",
")",
":",
"# pylint: disable=unused-argument",
"flat_shape",
"=",
"functools",
".",
"reduce",
"(",
"operator",
".",
"mul",
",",
"self",
".",
"_shape",
")",
"id... | Draw samples from uniform distribution and return sampled candidates.
Parameters
----------
candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol
This input specifies the shape of the to be sampled candidates. #
TODO shape selection is not yet supported. Shape must be sp... | [
"Draw",
"samples",
"from",
"uniform",
"distribution",
"and",
"return",
"sampled",
"candidates",
"."
] | 4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/data/candidate_sampler.py#L105-L134 |
32,634 | Delgan/loguru | loguru/_logger.py | Logger.remove | def remove(self, handler_id=None):
"""Remove a previously added handler and stop sending logs to its sink.
Parameters
----------
handler_id : |int| or ``None``
The id of the sink to remove, as it was returned by the |add| method. If ``None``, all
handlers are rem... | python | def remove(self, handler_id=None):
"""Remove a previously added handler and stop sending logs to its sink.
Parameters
----------
handler_id : |int| or ``None``
The id of the sink to remove, as it was returned by the |add| method. If ``None``, all
handlers are rem... | [
"def",
"remove",
"(",
"self",
",",
"handler_id",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"handlers",
"=",
"self",
".",
"_handlers",
".",
"copy",
"(",
")",
"if",
"handler_id",
"is",
"None",
":",
"for",
"handler",
"in",
"handlers",
".... | Remove a previously added handler and stop sending logs to its sink.
Parameters
----------
handler_id : |int| or ``None``
The id of the sink to remove, as it was returned by the |add| method. If ``None``, all
handlers are removed. The pre-configured handler is guaranteed... | [
"Remove",
"a",
"previously",
"added",
"handler",
"and",
"stop",
"sending",
"logs",
"to",
"its",
"sink",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L845-L883 |
32,635 | Delgan/loguru | loguru/_logger.py | Logger.catch | def catch(
self,
exception=Exception,
*,
level="ERROR",
reraise=False,
message="An error has been caught in function '{record[function]}', "
"process '{record[process].name}' ({record[process].id}), "
"thread '{record[thread].name}' ({record[thread].id}):"... | python | def catch(
self,
exception=Exception,
*,
level="ERROR",
reraise=False,
message="An error has been caught in function '{record[function]}', "
"process '{record[process].name}' ({record[process].id}), "
"thread '{record[thread].name}' ({record[thread].id}):"... | [
"def",
"catch",
"(",
"self",
",",
"exception",
"=",
"Exception",
",",
"*",
",",
"level",
"=",
"\"ERROR\"",
",",
"reraise",
"=",
"False",
",",
"message",
"=",
"\"An error has been caught in function '{record[function]}', \"",
"\"process '{record[process].name}' ({record[pr... | Return a decorator to automatically log possibly caught error in wrapped function.
This is useful to ensure unexpected exceptions are logged, the entire program can be
wrapped by this method. This is also very useful to decorate |Thread.run| methods while
using threads to propagate errors to th... | [
"Return",
"a",
"decorator",
"to",
"automatically",
"log",
"possibly",
"caught",
"error",
"in",
"wrapped",
"function",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L885-L1011 |
32,636 | Delgan/loguru | loguru/_logger.py | Logger.opt | def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0):
r"""Parametrize a logging call to slightly change generated log message.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False`... | python | def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0):
r"""Parametrize a logging call to slightly change generated log message.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False`... | [
"def",
"opt",
"(",
"self",
",",
"*",
",",
"exception",
"=",
"None",
",",
"record",
"=",
"False",
",",
"lazy",
"=",
"False",
",",
"ansi",
"=",
"False",
",",
"raw",
"=",
"False",
",",
"depth",
"=",
"0",
")",
":",
"return",
"Logger",
"(",
"self",
... | r"""Parametrize a logging call to slightly change generated log message.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False``, the passed exception is formatted and added to the
log message. It could be an |Excep... | [
"r",
"Parametrize",
"a",
"logging",
"call",
"to",
"slightly",
"change",
"generated",
"log",
"message",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1013-L1079 |
32,637 | Delgan/loguru | loguru/_logger.py | Logger.bind | def bind(_self, **kwargs):
"""Bind attributes to the ``extra`` dict of each logged message record.
This is used to add custom context to each logging call.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the ``extra`` dict.
... | python | def bind(_self, **kwargs):
"""Bind attributes to the ``extra`` dict of each logged message record.
This is used to add custom context to each logging call.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the ``extra`` dict.
... | [
"def",
"bind",
"(",
"_self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Logger",
"(",
"{",
"*",
"*",
"_self",
".",
"_extra",
",",
"*",
"*",
"kwargs",
"}",
",",
"_self",
".",
"_exception",
",",
"_self",
".",
"_record",
",",
"_self",
".",
"_lazy... | Bind attributes to the ``extra`` dict of each logged message record.
This is used to add custom context to each logging call.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the ``extra`` dict.
Returns
-------
:c... | [
"Bind",
"attributes",
"to",
"the",
"extra",
"dict",
"of",
"each",
"logged",
"message",
"record",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1081-L1123 |
32,638 | Delgan/loguru | loguru/_logger.py | Logger.level | def level(self, name, no=None, color=None, icon=None):
"""Add, update or retrieve a logging level.
Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
level, you... | python | def level(self, name, no=None, color=None, icon=None):
"""Add, update or retrieve a logging level.
Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
level, you... | [
"def",
"level",
"(",
"self",
",",
"name",
",",
"no",
"=",
"None",
",",
"color",
"=",
"None",
",",
"icon",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid level name, it should ... | Add, update or retrieve a logging level.
Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
level, you should necessarily use its name, the severity number is not linke... | [
"Add",
"update",
"or",
"retrieve",
"a",
"logging",
"level",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1125-L1212 |
32,639 | Delgan/loguru | loguru/_logger.py | Logger.configure | def configure(self, *, handlers=None, levels=None, extra=None, activation=None):
"""Configure the core logger.
It should be noted that ``extra`` values set using this function are available across all
modules, so this is the best way to set overall default values.
Parameters
--... | python | def configure(self, *, handlers=None, levels=None, extra=None, activation=None):
"""Configure the core logger.
It should be noted that ``extra`` values set using this function are available across all
modules, so this is the best way to set overall default values.
Parameters
--... | [
"def",
"configure",
"(",
"self",
",",
"*",
",",
"handlers",
"=",
"None",
",",
"levels",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"if",
"handlers",
"is",
"not",
"None",
":",
"self",
".",
"remove",
"(",
")",
... | Configure the core logger.
It should be noted that ``extra`` values set using this function are available across all
modules, so this is the best way to set overall default values.
Parameters
----------
handlers : |list| of |dict|, optional
A list of each handler to... | [
"Configure",
"the",
"core",
"logger",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1255-L1330 |
32,640 | Delgan/loguru | loguru/_logger.py | Logger.parse | def parse(file, pattern, *, cast={}, chunk=2 ** 16):
"""
Parse raw logs and extract each entry as a |dict|.
The logging format has to be specified as the regex ``pattern``, it will then be
used to parse the ``file`` and retrieve each entries based on the named groups present
in ... | python | def parse(file, pattern, *, cast={}, chunk=2 ** 16):
"""
Parse raw logs and extract each entry as a |dict|.
The logging format has to be specified as the regex ``pattern``, it will then be
used to parse the ``file`` and retrieve each entries based on the named groups present
in ... | [
"def",
"parse",
"(",
"file",
",",
"pattern",
",",
"*",
",",
"cast",
"=",
"{",
"}",
",",
"chunk",
"=",
"2",
"**",
"16",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"(",
"str",
",",
"PathLike",
")",
")",
":",
"should_close",
"=",
"True",
"fil... | Parse raw logs and extract each entry as a |dict|.
The logging format has to be specified as the regex ``pattern``, it will then be
used to parse the ``file`` and retrieve each entries based on the named groups present
in the regex.
Parameters
----------
file : |str|, |... | [
"Parse",
"raw",
"logs",
"and",
"extract",
"each",
"entry",
"as",
"a",
"|dict|",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1359-L1450 |
32,641 | Delgan/loguru | loguru/_logger.py | Logger.start | def start(self, *args, **kwargs):
"""Deprecated function to |add| a new handler.
Warnings
--------
.. deprecated:: 0.2.2
``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
confusing name.
"""
warnings.warn(
... | python | def start(self, *args, **kwargs):
"""Deprecated function to |add| a new handler.
Warnings
--------
.. deprecated:: 0.2.2
``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
confusing name.
"""
warnings.warn(
... | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The 'start()' method is deprecated, please use 'add()' instead\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"add",
"(",
"*",
"args",
... | Deprecated function to |add| a new handler.
Warnings
--------
.. deprecated:: 0.2.2
``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
confusing name. | [
"Deprecated",
"function",
"to",
"|add|",
"a",
"new",
"handler",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1624-L1636 |
32,642 | Delgan/loguru | loguru/_logger.py | Logger.stop | def stop(self, *args, **kwargs):
"""Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name.
"""
warnings.wa... | python | def stop(self, *args, **kwargs):
"""Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name.
"""
warnings.wa... | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The 'stop()' method is deprecated, please use 'remove()' instead\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"remove",
"(",
"*",
"arg... | Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name. | [
"Deprecated",
"function",
"to",
"|remove|",
"an",
"existing",
"handler",
"."
] | 6571879c37904e3a18567e694d70651c6886b860 | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1638-L1650 |
32,643 | graphql-python/graphene-django | graphene_django/rest_framework/serializer_converter.py | convert_serializer_field | def convert_serializer_field(field, is_input=True):
"""
Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required
"""
graphql_type = get_graphene_type_from_serializer_field(field)
args = []
... | python | def convert_serializer_field(field, is_input=True):
"""
Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required
"""
graphql_type = get_graphene_type_from_serializer_field(field)
args = []
... | [
"def",
"convert_serializer_field",
"(",
"field",
",",
"is_input",
"=",
"True",
")",
":",
"graphql_type",
"=",
"get_graphene_type_from_serializer_field",
"(",
"field",
")",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"\"description\"",
":",
"field",
".",
"help_tex... | Converts a django rest frameworks field to a graphql field
and marks the field as required if we are creating an input type
and the field itself is required | [
"Converts",
"a",
"django",
"rest",
"frameworks",
"field",
"to",
"a",
"graphql",
"field",
"and",
"marks",
"the",
"field",
"as",
"required",
"if",
"we",
"are",
"creating",
"an",
"input",
"type",
"and",
"the",
"field",
"itself",
"is",
"required"
] | 20160113948b4167b61dbdaa477bb301227aac2e | https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/rest_framework/serializer_converter.py#L21-L56 |
32,644 | graphql-python/graphene-django | graphene_django/filter/filterset.py | custom_filterset_factory | def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta):
""" Create a filterset for the given model using the provided meta data
"""
meta.update({"model": model})
meta_class = type(str("Meta"), (object,), meta)
filterset = type(
str("%sFilterSet" % model._meta.object_name... | python | def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta):
""" Create a filterset for the given model using the provided meta data
"""
meta.update({"model": model})
meta_class = type(str("Meta"), (object,), meta)
filterset = type(
str("%sFilterSet" % model._meta.object_name... | [
"def",
"custom_filterset_factory",
"(",
"model",
",",
"filterset_base_class",
"=",
"FilterSet",
",",
"*",
"*",
"meta",
")",
":",
"meta",
".",
"update",
"(",
"{",
"\"model\"",
":",
"model",
"}",
")",
"meta_class",
"=",
"type",
"(",
"str",
"(",
"\"Meta\"",
... | Create a filterset for the given model using the provided meta data | [
"Create",
"a",
"filterset",
"for",
"the",
"given",
"model",
"using",
"the",
"provided",
"meta",
"data"
] | 20160113948b4167b61dbdaa477bb301227aac2e | https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/filter/filterset.py#L95-L105 |
32,645 | graphql-python/graphene-django | graphene_django/filter/filterset.py | GlobalIDFilter.filter | def filter(self, qs, value):
""" Convert the filter value to a primary key before filtering """
_id = None
if value is not None:
_, _id = from_global_id(value)
return super(GlobalIDFilter, self).filter(qs, _id) | python | def filter(self, qs, value):
""" Convert the filter value to a primary key before filtering """
_id = None
if value is not None:
_, _id = from_global_id(value)
return super(GlobalIDFilter, self).filter(qs, _id) | [
"def",
"filter",
"(",
"self",
",",
"qs",
",",
"value",
")",
":",
"_id",
"=",
"None",
"if",
"value",
"is",
"not",
"None",
":",
"_",
",",
"_id",
"=",
"from_global_id",
"(",
"value",
")",
"return",
"super",
"(",
"GlobalIDFilter",
",",
"self",
")",
"."... | Convert the filter value to a primary key before filtering | [
"Convert",
"the",
"filter",
"value",
"to",
"a",
"primary",
"key",
"before",
"filtering"
] | 20160113948b4167b61dbdaa477bb301227aac2e | https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/filter/filterset.py#L16-L21 |
32,646 | graphql-python/graphene-django | graphene_django/filter/utils.py | get_filtering_args_from_filterset | def get_filtering_args_from_filterset(filterset_class, type):
""" Inspect a FilterSet and produce the arguments to pass to
a Graphene Field. These arguments will be available to
filter against in the GraphQL
"""
from ..forms.converter import convert_form_field
args = {}
for name, fi... | python | def get_filtering_args_from_filterset(filterset_class, type):
""" Inspect a FilterSet and produce the arguments to pass to
a Graphene Field. These arguments will be available to
filter against in the GraphQL
"""
from ..forms.converter import convert_form_field
args = {}
for name, fi... | [
"def",
"get_filtering_args_from_filterset",
"(",
"filterset_class",
",",
"type",
")",
":",
"from",
".",
".",
"forms",
".",
"converter",
"import",
"convert_form_field",
"args",
"=",
"{",
"}",
"for",
"name",
",",
"filter_field",
"in",
"six",
".",
"iteritems",
"(... | Inspect a FilterSet and produce the arguments to pass to
a Graphene Field. These arguments will be available to
filter against in the GraphQL | [
"Inspect",
"a",
"FilterSet",
"and",
"produce",
"the",
"arguments",
"to",
"pass",
"to",
"a",
"Graphene",
"Field",
".",
"These",
"arguments",
"will",
"be",
"available",
"to",
"filter",
"against",
"in",
"the",
"GraphQL"
] | 20160113948b4167b61dbdaa477bb301227aac2e | https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/filter/utils.py#L6-L19 |
32,647 | confluentinc/confluent-kafka-python | confluent_kafka/admin/__init__.py | AdminClient._make_futures | def _make_futures(futmap_keys, class_check, make_result_fn):
"""
Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API.
"""
futmap = {}
for key in futmap_keys:
if class_check is not None and not... | python | def _make_futures(futmap_keys, class_check, make_result_fn):
"""
Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API.
"""
futmap = {}
for key in futmap_keys:
if class_check is not None and not... | [
"def",
"_make_futures",
"(",
"futmap_keys",
",",
"class_check",
",",
"make_result_fn",
")",
":",
"futmap",
"=",
"{",
"}",
"for",
"key",
"in",
"futmap_keys",
":",
"if",
"class_check",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"key",
",",
"class_... | Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API. | [
"Create",
"futures",
"and",
"a",
"futuremap",
"for",
"the",
"keys",
"in",
"futmap_keys",
"and",
"create",
"a",
"request",
"-",
"level",
"future",
"to",
"be",
"bassed",
"to",
"the",
"C",
"API",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/admin/__init__.py#L268-L290 |
32,648 | confluentinc/confluent-kafka-python | confluent_kafka/admin/__init__.py | AdminClient.create_topics | def create_topics(self, new_topics, **kwargs):
"""
Create new topics in cluster.
The future result() value is None.
:param list(NewTopic) new_topics: New topics to be created.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlli... | python | def create_topics(self, new_topics, **kwargs):
"""
Create new topics in cluster.
The future result() value is None.
:param list(NewTopic) new_topics: New topics to be created.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlli... | [
"def",
"create_topics",
"(",
"self",
",",
"new_topics",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
",",
"futmap",
"=",
"AdminClient",
".",
"_make_futures",
"(",
"[",
"x",
".",
"topic",
"for",
"x",
"in",
"new_topics",
"]",
",",
"None",
",",
"AdminClient",
... | Create new topics in cluster.
The future result() value is None.
:param list(NewTopic) new_topics: New topics to be created.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the CreateTopics request will block
o... | [
"Create",
"new",
"topics",
"in",
"cluster",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/admin/__init__.py#L292-L323 |
32,649 | confluentinc/confluent-kafka-python | confluent_kafka/admin/__init__.py | AdminClient.delete_topics | def delete_topics(self, topics, **kwargs):
"""
Delete topics.
The future result() value is None.
:param list(str) topics: Topics to mark for deletion.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the DeleteTop... | python | def delete_topics(self, topics, **kwargs):
"""
Delete topics.
The future result() value is None.
:param list(str) topics: Topics to mark for deletion.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the DeleteTop... | [
"def",
"delete_topics",
"(",
"self",
",",
"topics",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
",",
"futmap",
"=",
"AdminClient",
".",
"_make_futures",
"(",
"topics",
",",
"None",
",",
"AdminClient",
".",
"_make_topics_result",
")",
"super",
"(",
"AdminClient... | Delete topics.
The future result() value is None.
:param list(str) topics: Topics to mark for deletion.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the DeleteTopics request will block
on the broker waiting ... | [
"Delete",
"topics",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/admin/__init__.py#L325-L353 |
32,650 | confluentinc/confluent-kafka-python | confluent_kafka/admin/__init__.py | AdminClient.create_partitions | def create_partitions(self, new_partitions, **kwargs):
"""
Create additional partitions for the given topics.
The future result() value is None.
:param list(NewPartitions) new_partitions: New partitions to be created.
:param float operation_timeout: Set broker's operation timeo... | python | def create_partitions(self, new_partitions, **kwargs):
"""
Create additional partitions for the given topics.
The future result() value is None.
:param list(NewPartitions) new_partitions: New partitions to be created.
:param float operation_timeout: Set broker's operation timeo... | [
"def",
"create_partitions",
"(",
"self",
",",
"new_partitions",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
",",
"futmap",
"=",
"AdminClient",
".",
"_make_futures",
"(",
"[",
"x",
".",
"topic",
"for",
"x",
"in",
"new_partitions",
"]",
",",
"None",
",",
"Ad... | Create additional partitions for the given topics.
The future result() value is None.
:param list(NewPartitions) new_partitions: New partitions to be created.
:param float operation_timeout: Set broker's operation timeout in seconds,
controlling how long the CreatePartitions ... | [
"Create",
"additional",
"partitions",
"for",
"the",
"given",
"topics",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/admin/__init__.py#L355-L386 |
32,651 | confluentinc/confluent-kafka-python | confluent_kafka/admin/__init__.py | AdminClient.describe_configs | def describe_configs(self, resources, **kwargs):
"""
Get configuration for the specified resources.
The future result() value is a dict(<configname, ConfigEntry>).
:warning: Multiple resources and resource types may be requested,
but at most one resource of type RESOU... | python | def describe_configs(self, resources, **kwargs):
"""
Get configuration for the specified resources.
The future result() value is a dict(<configname, ConfigEntry>).
:warning: Multiple resources and resource types may be requested,
but at most one resource of type RESOU... | [
"def",
"describe_configs",
"(",
"self",
",",
"resources",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
",",
"futmap",
"=",
"AdminClient",
".",
"_make_futures",
"(",
"resources",
",",
"ConfigResource",
",",
"AdminClient",
".",
"_make_resource_result",
")",
"super",
... | Get configuration for the specified resources.
The future result() value is a dict(<configname, ConfigEntry>).
:warning: Multiple resources and resource types may be requested,
but at most one resource of type RESOURCE_BROKER is allowed
per call since these resource... | [
"Get",
"configuration",
"for",
"the",
"specified",
"resources",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/admin/__init__.py#L388-L419 |
32,652 | confluentinc/confluent-kafka-python | confluent_kafka/avro/load.py | loads | def loads(schema_str):
""" Parse a schema given a schema string """
try:
if sys.version_info[0] < 3:
return schema.parse(schema_str)
else:
return schema.Parse(schema_str)
except schema.SchemaParseException as e:
raise ClientError("Schema parse failed: %s" % (s... | python | def loads(schema_str):
""" Parse a schema given a schema string """
try:
if sys.version_info[0] < 3:
return schema.parse(schema_str)
else:
return schema.Parse(schema_str)
except schema.SchemaParseException as e:
raise ClientError("Schema parse failed: %s" % (s... | [
"def",
"loads",
"(",
"schema_str",
")",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"return",
"schema",
".",
"parse",
"(",
"schema_str",
")",
"else",
":",
"return",
"schema",
".",
"Parse",
"(",
"schema_str",
")",
... | Parse a schema given a schema string | [
"Parse",
"a",
"schema",
"given",
"a",
"schema",
"string"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/avro/load.py#L23-L31 |
32,653 | confluentinc/confluent-kafka-python | confluent_kafka/avro/__init__.py | AvroProducer.produce | def produce(self, **kwargs):
"""
Asynchronously sends message to Kafka by encoding with specified or default avro schema.
:param str topic: topic name
:param object value: An object to serialize
:param str value_schema: Avro schema for value
:param ob... | python | def produce(self, **kwargs):
"""
Asynchronously sends message to Kafka by encoding with specified or default avro schema.
:param str topic: topic name
:param object value: An object to serialize
:param str value_schema: Avro schema for value
:param ob... | [
"def",
"produce",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# get schemas from kwargs if defined",
"key_schema",
"=",
"kwargs",
".",
"pop",
"(",
"'key_schema'",
",",
"self",
".",
"_key_schema",
")",
"value_schema",
"=",
"kwargs",
".",
"pop",
"(",
"'v... | Asynchronously sends message to Kafka by encoding with specified or default avro schema.
:param str topic: topic name
:param object value: An object to serialize
:param str value_schema: Avro schema for value
:param object key: An object to serialize
:param s... | [
"Asynchronously",
"sends",
"message",
"to",
"Kafka",
"by",
"encoding",
"with",
"specified",
"or",
"default",
"avro",
"schema",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/avro/__init__.py#L53-L90 |
32,654 | confluentinc/confluent-kafka-python | confluent_kafka/avro/__init__.py | AvroConsumer.poll | def poll(self, timeout=None):
"""
This is an overriden method from confluent_kafka.Consumer class. This handles message
deserialization using avro schema
:param float timeout: Poll timeout in seconds (default: indefinite)
:returns: message object with deserialized key and value ... | python | def poll(self, timeout=None):
"""
This is an overriden method from confluent_kafka.Consumer class. This handles message
deserialization using avro schema
:param float timeout: Poll timeout in seconds (default: indefinite)
:returns: message object with deserialized key and value ... | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"-",
"1",
"message",
"=",
"super",
"(",
"AvroConsumer",
",",
"self",
")",
".",
"poll",
"(",
"timeout",
")",
"if",
"message",
"is"... | This is an overriden method from confluent_kafka.Consumer class. This handles message
deserialization using avro schema
:param float timeout: Poll timeout in seconds (default: indefinite)
:returns: message object with deserialized key and value as dict objects
:rtype: Message | [
"This",
"is",
"an",
"overriden",
"method",
"from",
"confluent_kafka",
".",
"Consumer",
"class",
".",
"This",
"handles",
"message",
"deserialization",
"using",
"avro",
"schema"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/avro/__init__.py#L128-L157 |
32,655 | confluentinc/confluent-kafka-python | confluent_kafka/avro/serializer/message_serializer.py | MessageSerializer.encode_record_with_schema | def encode_record_with_schema(self, topic, schema, record, is_key=False):
"""
Given a parsed avro schema, encode a record for the given topic. The
record is expected to be a dictionary.
The schema is registered with the subject of 'topic-value'
:param str topic: Topic name
... | python | def encode_record_with_schema(self, topic, schema, record, is_key=False):
"""
Given a parsed avro schema, encode a record for the given topic. The
record is expected to be a dictionary.
The schema is registered with the subject of 'topic-value'
:param str topic: Topic name
... | [
"def",
"encode_record_with_schema",
"(",
"self",
",",
"topic",
",",
"schema",
",",
"record",
",",
"is_key",
"=",
"False",
")",
":",
"serialize_err",
"=",
"KeySerializerError",
"if",
"is_key",
"else",
"ValueSerializerError",
"subject_suffix",
"=",
"(",
"'-key'",
... | Given a parsed avro schema, encode a record for the given topic. The
record is expected to be a dictionary.
The schema is registered with the subject of 'topic-value'
:param str topic: Topic name
:param schema schema: Avro Schema
:param dict record: An object to serialize
... | [
"Given",
"a",
"parsed",
"avro",
"schema",
"encode",
"a",
"record",
"for",
"the",
"given",
"topic",
".",
"The",
"record",
"is",
"expected",
"to",
"be",
"a",
"dictionary",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/avro/serializer/message_serializer.py#L86-L113 |
32,656 | confluentinc/confluent-kafka-python | examples/adminapi.py | example_alter_configs | def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... | python | def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... | [
"def",
"example_alter_configs",
"(",
"a",
",",
"args",
")",
":",
"resources",
"=",
"[",
"]",
"for",
"restype",
",",
"resname",
",",
"configs",
"in",
"zip",
"(",
"args",
"[",
"0",
":",
":",
"3",
"]",
",",
"args",
"[",
"1",
":",
":",
"3",
"]",
",... | Alter configs atomically, replacing non-specified
configuration properties with their default values. | [
"Alter",
"configs",
"atomically",
"replacing",
"non",
"-",
"specified",
"configuration",
"properties",
"with",
"their",
"default",
"values",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L120-L140 |
32,657 | confluentinc/confluent-kafka-python | examples/adminapi.py | example_delta_alter_configs | def example_delta_alter_configs(a, args):
"""
The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration ... | python | def example_delta_alter_configs(a, args):
"""
The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration ... | [
"def",
"example_delta_alter_configs",
"(",
"a",
",",
"args",
")",
":",
"# Convert supplied config to resources.",
"# We can reuse the same resources both for describe_configs and",
"# alter_configs.",
"resources",
"=",
"[",
"]",
"for",
"restype",
",",
"resname",
",",
"configs... | The AlterConfigs Kafka API requires all configuration to be passed,
any left out configuration properties will revert to their default settings.
This example shows how to just modify the supplied configuration entries
by first reading the configuration from the broker, updating the supplied
configurati... | [
"The",
"AlterConfigs",
"Kafka",
"API",
"requires",
"all",
"configuration",
"to",
"be",
"passed",
"any",
"left",
"out",
"configuration",
"properties",
"will",
"revert",
"to",
"their",
"default",
"settings",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L143-L232 |
32,658 | confluentinc/confluent-kafka-python | examples/adminapi.py | example_list | def example_list(a, args):
""" list topics and cluster metadata """
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "broke... | python | def example_list(a, args):
""" list topics and cluster metadata """
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "broke... | [
"def",
"example_list",
"(",
"a",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"what",
"=",
"\"all\"",
"else",
":",
"what",
"=",
"args",
"[",
"0",
"]",
"md",
"=",
"a",
".",
"list_topics",
"(",
"timeout",
"=",
"10",
")",
... | list topics and cluster metadata | [
"list",
"topics",
"and",
"cluster",
"metadata"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/adminapi.py#L235-L274 |
32,659 | confluentinc/confluent-kafka-python | confluent_kafka/__init__.py | _resolve_plugins | def _resolve_plugins(plugins):
""" Resolve embedded plugins from the wheel's library directory.
For internal module use only.
:param str plugins: The plugin.library.paths value
"""
import os
from sys import platform
# Location of __init__.py and the embedded library directory
... | python | def _resolve_plugins(plugins):
""" Resolve embedded plugins from the wheel's library directory.
For internal module use only.
:param str plugins: The plugin.library.paths value
"""
import os
from sys import platform
# Location of __init__.py and the embedded library directory
... | [
"def",
"_resolve_plugins",
"(",
"plugins",
")",
":",
"import",
"os",
"from",
"sys",
"import",
"platform",
"# Location of __init__.py and the embedded library directory",
"basedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"if",
"platform",
"in",... | Resolve embedded plugins from the wheel's library directory.
For internal module use only.
:param str plugins: The plugin.library.paths value | [
"Resolve",
"embedded",
"plugins",
"from",
"the",
"wheel",
"s",
"library",
"directory",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/confluent_kafka/__init__.py#L47-L102 |
32,660 | confluentinc/confluent-kafka-python | examples/avro-cli.py | on_delivery | def on_delivery(err, msg, obj):
"""
Handle delivery reports served from producer.poll.
This callback takes an extra argument, obj.
This allows the original contents to be included for debugging purposes.
"""
if err is not None:
print('Message {} delivery failed for user {} wi... | python | def on_delivery(err, msg, obj):
"""
Handle delivery reports served from producer.poll.
This callback takes an extra argument, obj.
This allows the original contents to be included for debugging purposes.
"""
if err is not None:
print('Message {} delivery failed for user {} wi... | [
"def",
"on_delivery",
"(",
"err",
",",
"msg",
",",
"obj",
")",
":",
"if",
"err",
"is",
"not",
"None",
":",
"print",
"(",
"'Message {} delivery failed for user {} with error {}'",
".",
"format",
"(",
"obj",
".",
"id",
",",
"obj",
".",
"name",
",",
"err",
... | Handle delivery reports served from producer.poll.
This callback takes an extra argument, obj.
This allows the original contents to be included for debugging purposes. | [
"Handle",
"delivery",
"reports",
"served",
"from",
"producer",
".",
"poll",
".",
"This",
"callback",
"takes",
"an",
"extra",
"argument",
"obj",
".",
"This",
"allows",
"the",
"original",
"contents",
"to",
"be",
"included",
"for",
"debugging",
"purposes",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/avro-cli.py#L68-L79 |
32,661 | confluentinc/confluent-kafka-python | examples/avro-cli.py | produce | def produce(topic, conf):
"""
Produce User records
"""
from confluent_kafka.avro import AvroProducer
producer = AvroProducer(conf, default_value_schema=record_schema)
print("Producing user records to topic {}. ^c to exit.".format(topic))
while True:
# Instantiate new User, pop... | python | def produce(topic, conf):
"""
Produce User records
"""
from confluent_kafka.avro import AvroProducer
producer = AvroProducer(conf, default_value_schema=record_schema)
print("Producing user records to topic {}. ^c to exit.".format(topic))
while True:
# Instantiate new User, pop... | [
"def",
"produce",
"(",
"topic",
",",
"conf",
")",
":",
"from",
"confluent_kafka",
".",
"avro",
"import",
"AvroProducer",
"producer",
"=",
"AvroProducer",
"(",
"conf",
",",
"default_value_schema",
"=",
"record_schema",
")",
"print",
"(",
"\"Producing user records t... | Produce User records | [
"Produce",
"User",
"records"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/avro-cli.py#L82-L113 |
32,662 | confluentinc/confluent-kafka-python | examples/avro-cli.py | consume | def consume(topic, conf):
"""
Consume User records
"""
from confluent_kafka.avro import AvroConsumer
from confluent_kafka.avro.serializer import SerializerError
print("Consuming user records from topic {} with group {}. ^c to exit.".format(topic, conf["group.id"]))
c = AvroConsumer(con... | python | def consume(topic, conf):
"""
Consume User records
"""
from confluent_kafka.avro import AvroConsumer
from confluent_kafka.avro.serializer import SerializerError
print("Consuming user records from topic {} with group {}. ^c to exit.".format(topic, conf["group.id"]))
c = AvroConsumer(con... | [
"def",
"consume",
"(",
"topic",
",",
"conf",
")",
":",
"from",
"confluent_kafka",
".",
"avro",
"import",
"AvroConsumer",
"from",
"confluent_kafka",
".",
"avro",
".",
"serializer",
"import",
"SerializerError",
"print",
"(",
"\"Consuming user records from topic {} with ... | Consume User records | [
"Consume",
"User",
"records"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/examples/avro-cli.py#L116-L151 |
32,663 | confluentinc/confluent-kafka-python | tools/download-s3.py | Artifact.download | def download(self, dirpath):
""" Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. """
if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0:
return
print('Downloading %s -> %s' % (self.path, self.... | python | def download(self, dirpath):
""" Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. """
if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0:
return
print('Downloading %s -> %s' % (self.path, self.... | [
"def",
"download",
"(",
"self",
",",
"dirpath",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"lpath",
")",
"and",
"os",
".",
"path",
".",
"getsize",
"(",
"self",
".",
"lpath",
")",
">",
"0",
":",
"return",
"print",
"(",
"... | Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. | [
"Download",
"artifact",
"from",
"S3",
"and",
"store",
"in",
"dirpath",
"directory",
".",
"If",
"the",
"artifact",
"is",
"already",
"downloaded",
"nothing",
"is",
"done",
"."
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/tools/download-s3.py#L46-L54 |
32,664 | confluentinc/confluent-kafka-python | tools/download-s3.py | Artifacts.collect_s3 | def collect_s3(self):
""" Collect and download build-artifacts from S3 based on git reference """
print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket))
self.s3 = boto3.resource('s3')
self.s3_bucket = self.s3.Bucket(s3_bucket)
self.s3.meta.... | python | def collect_s3(self):
""" Collect and download build-artifacts from S3 based on git reference """
print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket))
self.s3 = boto3.resource('s3')
self.s3_bucket = self.s3.Bucket(s3_bucket)
self.s3.meta.... | [
"def",
"collect_s3",
"(",
"self",
")",
":",
"print",
"(",
"'Collecting artifacts matching tag/sha %s from S3 bucket %s'",
"%",
"(",
"self",
".",
"gitref",
",",
"s3_bucket",
")",
")",
"self",
".",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
"self",
... | Collect and download build-artifacts from S3 based on git reference | [
"Collect",
"and",
"download",
"build",
"-",
"artifacts",
"from",
"S3",
"based",
"on",
"git",
"reference"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/tools/download-s3.py#L104-L114 |
32,665 | confluentinc/confluent-kafka-python | tools/download-s3.py | Artifacts.collect_local | def collect_local(self, path):
""" Collect artifacts from a local directory possibly previously
collected from s3 """
for f in os.listdir(path):
lpath = os.path.join(path, f)
if not os.path.isfile(lpath):
continue
Artifact(self, lpath) | python | def collect_local(self, path):
""" Collect artifacts from a local directory possibly previously
collected from s3 """
for f in os.listdir(path):
lpath = os.path.join(path, f)
if not os.path.isfile(lpath):
continue
Artifact(self, lpath) | [
"def",
"collect_local",
"(",
"self",
",",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"lpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
... | Collect artifacts from a local directory possibly previously
collected from s3 | [
"Collect",
"artifacts",
"from",
"a",
"local",
"directory",
"possibly",
"previously",
"collected",
"from",
"s3"
] | 5a8aeb741609e61eaccafff2a67fa494dd549e8b | https://github.com/confluentinc/confluent-kafka-python/blob/5a8aeb741609e61eaccafff2a67fa494dd549e8b/tools/download-s3.py#L116-L123 |
32,666 | saltstack/salt | salt/modules/ddns.py | delete_host | def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53,
**kwargs):
'''
Delete the forward and reverse records for a host.
Returns true if any records are deleted.
CLI Example:
.. code-block:: bash
salt ns1 ddns.delete_host example.com host1
'''
fqd... | python | def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53,
**kwargs):
'''
Delete the forward and reverse records for a host.
Returns true if any records are deleted.
CLI Example:
.. code-block:: bash
salt ns1 ddns.delete_host example.com host1
'''
fqd... | [
"def",
"delete_host",
"(",
"zone",
",",
"name",
",",
"nameserver",
"=",
"'127.0.0.1'",
",",
"timeout",
"=",
"5",
",",
"port",
"=",
"53",
",",
"*",
"*",
"kwargs",
")",
":",
"fqdn",
"=",
"'{0}.{1}'",
".",
"format",
"(",
"name",
",",
"zone",
")",
"req... | Delete the forward and reverse records for a host.
Returns true if any records are deleted.
CLI Example:
.. code-block:: bash
salt ns1 ddns.delete_host example.com host1 | [
"Delete",
"the",
"forward",
"and",
"reverse",
"records",
"for",
"a",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L112-L151 |
32,667 | saltstack/salt | salt/modules/ddns.py | update | def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5,
replace=False, port=53, **kwargs):
'''
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, fir... | python | def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5,
replace=False, port=53, **kwargs):
'''
Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, fir... | [
"def",
"update",
"(",
"zone",
",",
"name",
",",
"ttl",
",",
"rdtype",
",",
"data",
",",
"nameserver",
"=",
"'127.0.0.1'",
",",
"timeout",
"=",
"5",
",",
"replace",
"=",
"False",
",",
"port",
"=",
"53",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"... | Add, replace, or update a DNS record.
nameserver must be an IP address and the minion running this module
must have update privileges on that server.
If replace is true, first deletes all records for this name and type.
CLI Example:
.. code-block:: bash
salt ns1 ddns.update example.com ho... | [
"Add",
"replace",
"or",
"update",
"a",
"DNS",
"record",
".",
"nameserver",
"must",
"be",
"an",
"IP",
"address",
"and",
"the",
"minion",
"running",
"this",
"module",
"must",
"have",
"update",
"privileges",
"on",
"that",
"server",
".",
"If",
"replace",
"is",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L154-L205 |
32,668 | saltstack/salt | salt/modules/ansiblegate.py | help | def help(module=None, *args):
'''
Display help on Ansible standard module.
:param module:
:return:
'''
if not module:
raise CommandExecutionError('Please tell me what module you want to have helped with. '
'Or call "ansible.list" to know what is avail... | python | def help(module=None, *args):
'''
Display help on Ansible standard module.
:param module:
:return:
'''
if not module:
raise CommandExecutionError('Please tell me what module you want to have helped with. '
'Or call "ansible.list" to know what is avail... | [
"def",
"help",
"(",
"module",
"=",
"None",
",",
"*",
"args",
")",
":",
"if",
"not",
"module",
":",
"raise",
"CommandExecutionError",
"(",
"'Please tell me what module you want to have helped with. '",
"'Or call \"ansible.list\" to know what is available.'",
")",
"try",
":... | Display help on Ansible standard module.
:param module:
:return: | [
"Display",
"help",
"on",
"Ansible",
"standard",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L237-L273 |
32,669 | saltstack/salt | salt/modules/ansiblegate.py | AnsibleModuleResolver.load_module | def load_module(self, module):
'''
Introspect Ansible module.
:param module:
:return:
'''
m_ref = self._modules_map.get(module)
if m_ref is None:
raise LoaderError('Module "{0}" was not found'.format(module))
mod = importlib.import_module('ans... | python | def load_module(self, module):
'''
Introspect Ansible module.
:param module:
:return:
'''
m_ref = self._modules_map.get(module)
if m_ref is None:
raise LoaderError('Module "{0}" was not found'.format(module))
mod = importlib.import_module('ans... | [
"def",
"load_module",
"(",
"self",
",",
"module",
")",
":",
"m_ref",
"=",
"self",
".",
"_modules_map",
".",
"get",
"(",
"module",
")",
"if",
"m_ref",
"is",
"None",
":",
"raise",
"LoaderError",
"(",
"'Module \"{0}\" was not found'",
".",
"format",
"(",
"mod... | Introspect Ansible module.
:param module:
:return: | [
"Introspect",
"Ansible",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ansiblegate.py#L94-L107 |
32,670 | saltstack/salt | salt/modules/file.py | __clean_tmp | def __clean_tmp(sfn):
'''
Clean out a template temp file
'''
if sfn.startswith(os.path.join(tempfile.gettempdir(),
salt.utils.files.TEMPFILE_PREFIX)):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
... | python | def __clean_tmp(sfn):
'''
Clean out a template temp file
'''
if sfn.startswith(os.path.join(tempfile.gettempdir(),
salt.utils.files.TEMPFILE_PREFIX)):
# Don't remove if it exists in file_roots (any saltenv)
all_roots = itertools.chain.from_iterable(
... | [
"def",
"__clean_tmp",
"(",
"sfn",
")",
":",
"if",
"sfn",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"salt",
".",
"utils",
".",
"files",
".",
"TEMPFILE_PREFIX",
")",
")",
":",
"# Don't re... | Clean out a template temp file | [
"Clean",
"out",
"a",
"template",
"temp",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L88-L100 |
32,671 | saltstack/salt | salt/modules/file.py | _binary_replace | def _binary_replace(old, new):
'''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should... | python | def _binary_replace(old, new):
'''
This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should... | [
"def",
"_binary_replace",
"(",
"old",
",",
"new",
")",
":",
"old_isbin",
"=",
"not",
"__utils__",
"[",
"'files.is_text'",
"]",
"(",
"old",
")",
"new_isbin",
"=",
"not",
"__utils__",
"[",
"'files.is_text'",
"]",
"(",
"new",
")",
"if",
"any",
"(",
"(",
"... | This function does NOT do any diffing, it just checks the old and new files
to see if either is binary, and provides an appropriate string noting the
difference between the two files. If neither file is binary, an empty
string is returned.
This function should only be run AFTER it has been determined t... | [
"This",
"function",
"does",
"NOT",
"do",
"any",
"diffing",
"it",
"just",
"checks",
"the",
"old",
"and",
"new",
"files",
"to",
"see",
"if",
"either",
"is",
"binary",
"and",
"provides",
"an",
"appropriate",
"string",
"noting",
"the",
"difference",
"between",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L112-L131 |
32,672 | saltstack/salt | salt/modules/file.py | lchown | def lchown(path, user, group):
'''
Chown a file, pass the file the desired user and group without following
symlinks.
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/pass... | python | def lchown(path, user, group):
'''
Chown a file, pass the file the desired user and group without following
symlinks.
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/pass... | [
"def",
"lchown",
"(",
"path",
",",
"user",
",",
"group",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"uid",
"=",
"user_to_uid",
"(",
"user",
")",
"gid",
"=",
"group_to_gid",
"(",
"group",
")",
"err",
"=",
"''",
... | Chown a file, pass the file the desired user and group without following
symlinks.
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/passwd root root | [
"Chown",
"a",
"file",
"pass",
"the",
"file",
"the",
"desired",
"user",
"and",
"group",
"without",
"following",
"symlinks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L399-L435 |
32,673 | saltstack/salt | salt/modules/file.py | check_hash | def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versioncha... | python | def check_hash(path, file_hash):
'''
Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versioncha... | [
"def",
"check_hash",
"(",
"path",
",",
"file_hash",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"isinstance",
"(",
"file_hash",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"SaltInvocationError",
"("... | Check if a file matches the given hash string
Returns ``True`` if the hash matches, otherwise ``False``.
path
Path to a file local to the minion.
hash
The hash to check against the file specified in the ``path`` argument.
.. versionchanged:: 2016.11.4
For this and newer ... | [
"Check",
"if",
"a",
"file",
"matches",
"the",
"given",
"hash",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L851-L905 |
32,674 | saltstack/salt | salt/modules/file.py | _sed_esc | def _sed_esc(string, escape_all=False):
'''
Escape single quotes and forward slashes
'''
special_chars = "^.[$()|*+?{"
string = string.replace("'", "'\"'\"'").replace("/", "\\/")
if escape_all is True:
for char in special_chars:
string = string.replace(char, "\\" + char)
... | python | def _sed_esc(string, escape_all=False):
'''
Escape single quotes and forward slashes
'''
special_chars = "^.[$()|*+?{"
string = string.replace("'", "'\"'\"'").replace("/", "\\/")
if escape_all is True:
for char in special_chars:
string = string.replace(char, "\\" + char)
... | [
"def",
"_sed_esc",
"(",
"string",
",",
"escape_all",
"=",
"False",
")",
":",
"special_chars",
"=",
"\"^.[$()|*+?{\"",
"string",
"=",
"string",
".",
"replace",
"(",
"\"'\"",
",",
"\"'\\\"'\\\"'\"",
")",
".",
"replace",
"(",
"\"/\"",
",",
"\"\\\\/\"",
")",
"... | Escape single quotes and forward slashes | [
"Escape",
"single",
"quotes",
"and",
"forward",
"slashes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1037-L1046 |
32,675 | saltstack/salt | salt/modules/file.py | _psed | def _psed(text,
before,
after,
limit,
flags):
'''
Does the actual work for file.psed, so that single lines can be passed in
'''
atext = text
if limit:
limit = re.compile(limit)
comps = text.split(limit)
atext = ''.join(comps[1:])
c... | python | def _psed(text,
before,
after,
limit,
flags):
'''
Does the actual work for file.psed, so that single lines can be passed in
'''
atext = text
if limit:
limit = re.compile(limit)
comps = text.split(limit)
atext = ''.join(comps[1:])
c... | [
"def",
"_psed",
"(",
"text",
",",
"before",
",",
"after",
",",
"limit",
",",
"flags",
")",
":",
"atext",
"=",
"text",
"if",
"limit",
":",
"limit",
"=",
"re",
".",
"compile",
"(",
"limit",
")",
"comps",
"=",
"text",
".",
"split",
"(",
"limit",
")"... | Does the actual work for file.psed, so that single lines can be passed in | [
"Does",
"the",
"actual",
"work",
"for",
"file",
".",
"psed",
"so",
"that",
"single",
"lines",
"can",
"be",
"passed",
"in"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1291-L1317 |
32,676 | saltstack/salt | salt/modules/file.py | _get_flags | def _get_flags(flags):
'''
Return an integer appropriate for use as a flag for the re module from a
list of human-readable strings
.. code-block:: python
>>> _get_flags(['MULTILINE', 'IGNORECASE'])
10
>>> _get_flags('MULTILINE')
8
>>> _get_flags(2)
2
... | python | def _get_flags(flags):
'''
Return an integer appropriate for use as a flag for the re module from a
list of human-readable strings
.. code-block:: python
>>> _get_flags(['MULTILINE', 'IGNORECASE'])
10
>>> _get_flags('MULTILINE')
8
>>> _get_flags(2)
2
... | [
"def",
"_get_flags",
"(",
"flags",
")",
":",
"if",
"isinstance",
"(",
"flags",
",",
"six",
".",
"string_types",
")",
":",
"flags",
"=",
"[",
"flags",
"]",
"if",
"isinstance",
"(",
"flags",
",",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"flags",... | Return an integer appropriate for use as a flag for the re module from a
list of human-readable strings
.. code-block:: python
>>> _get_flags(['MULTILINE', 'IGNORECASE'])
10
>>> _get_flags('MULTILINE')
8
>>> _get_flags(2)
2 | [
"Return",
"an",
"integer",
"appropriate",
"for",
"use",
"as",
"a",
"flag",
"for",
"the",
"re",
"module",
"from",
"a",
"list",
"of",
"human",
"-",
"readable",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1581-L1617 |
32,677 | saltstack/salt | salt/modules/file.py | _add_flags | def _add_flags(flags, new_flags):
'''
Combine ``flags`` and ``new_flags``
'''
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return flags | new_flags | python | def _add_flags(flags, new_flags):
'''
Combine ``flags`` and ``new_flags``
'''
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return flags | new_flags | [
"def",
"_add_flags",
"(",
"flags",
",",
"new_flags",
")",
":",
"flags",
"=",
"_get_flags",
"(",
"flags",
")",
"new_flags",
"=",
"_get_flags",
"(",
"new_flags",
")",
"return",
"flags",
"|",
"new_flags"
] | Combine ``flags`` and ``new_flags`` | [
"Combine",
"flags",
"and",
"new_flags"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1620-L1626 |
32,678 | saltstack/salt | salt/modules/file.py | _starts_till | def _starts_till(src, probe, strip_comments=True):
'''
Returns True if src and probe at least matches at the beginning till some point.
'''
def _strip_comments(txt):
'''
Strip possible comments.
Usually comments are one or two symbols at the beginning of the line, separated with ... | python | def _starts_till(src, probe, strip_comments=True):
'''
Returns True if src and probe at least matches at the beginning till some point.
'''
def _strip_comments(txt):
'''
Strip possible comments.
Usually comments are one or two symbols at the beginning of the line, separated with ... | [
"def",
"_starts_till",
"(",
"src",
",",
"probe",
",",
"strip_comments",
"=",
"True",
")",
":",
"def",
"_strip_comments",
"(",
"txt",
")",
":",
"'''\n Strip possible comments.\n Usually comments are one or two symbols at the beginning of the line, separated with spac... | Returns True if src and probe at least matches at the beginning till some point. | [
"Returns",
"True",
"if",
"src",
"and",
"probe",
"at",
"least",
"matches",
"at",
"the",
"beginning",
"till",
"some",
"point",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1683-L1721 |
32,679 | saltstack/salt | salt/modules/file.py | _regex_to_static | def _regex_to_static(src, regex):
'''
Expand regular expression to static match.
'''
if not src or not regex:
return None
try:
compiled = re.compile(regex, re.DOTALL)
src = [line for line in src if compiled.search(line) or line.count(regex)]
except Exception as ex:
... | python | def _regex_to_static(src, regex):
'''
Expand regular expression to static match.
'''
if not src or not regex:
return None
try:
compiled = re.compile(regex, re.DOTALL)
src = [line for line in src if compiled.search(line) or line.count(regex)]
except Exception as ex:
... | [
"def",
"_regex_to_static",
"(",
"src",
",",
"regex",
")",
":",
"if",
"not",
"src",
"or",
"not",
"regex",
":",
"return",
"None",
"try",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"regex",
",",
"re",
".",
"DOTALL",
")",
"src",
"=",
"[",
"line",... | Expand regular expression to static match. | [
"Expand",
"regular",
"expression",
"to",
"static",
"match",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1724-L1737 |
32,680 | saltstack/salt | salt/modules/file.py | _assert_occurrence | def _assert_occurrence(probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = len(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
else:
... | python | def _assert_occurrence(probe, target, amount=1):
'''
Raise an exception, if there are different amount of specified occurrences in src.
'''
occ = len(probe)
if occ > amount:
msg = 'more than'
elif occ < amount:
msg = 'less than'
elif not occ:
msg = 'no'
else:
... | [
"def",
"_assert_occurrence",
"(",
"probe",
",",
"target",
",",
"amount",
"=",
"1",
")",
":",
"occ",
"=",
"len",
"(",
"probe",
")",
"if",
"occ",
">",
"amount",
":",
"msg",
"=",
"'more than'",
"elif",
"occ",
"<",
"amount",
":",
"msg",
"=",
"'less than'... | Raise an exception, if there are different amount of specified occurrences in src. | [
"Raise",
"an",
"exception",
"if",
"there",
"are",
"different",
"amount",
"of",
"specified",
"occurrences",
"in",
"src",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1740-L1757 |
32,681 | saltstack/salt | salt/modules/file.py | _set_line_indent | def _set_line_indent(src, line, indent):
'''
Indent the line with the source line.
'''
if not indent:
return line
idt = []
for c in src:
if c not in ['\t', ' ']:
break
idt.append(c)
return ''.join(idt) + line.lstrip() | python | def _set_line_indent(src, line, indent):
'''
Indent the line with the source line.
'''
if not indent:
return line
idt = []
for c in src:
if c not in ['\t', ' ']:
break
idt.append(c)
return ''.join(idt) + line.lstrip() | [
"def",
"_set_line_indent",
"(",
"src",
",",
"line",
",",
"indent",
")",
":",
"if",
"not",
"indent",
":",
"return",
"line",
"idt",
"=",
"[",
"]",
"for",
"c",
"in",
"src",
":",
"if",
"c",
"not",
"in",
"[",
"'\\t'",
",",
"' '",
"]",
":",
"break",
... | Indent the line with the source line. | [
"Indent",
"the",
"line",
"with",
"the",
"source",
"line",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1760-L1773 |
32,682 | saltstack/salt | salt/modules/file.py | _set_line_eol | def _set_line_eol(src, line):
'''
Add line ending
'''
line_ending = _get_eol(src) or os.linesep
return line.rstrip() + line_ending | python | def _set_line_eol(src, line):
'''
Add line ending
'''
line_ending = _get_eol(src) or os.linesep
return line.rstrip() + line_ending | [
"def",
"_set_line_eol",
"(",
"src",
",",
"line",
")",
":",
"line_ending",
"=",
"_get_eol",
"(",
"src",
")",
"or",
"os",
".",
"linesep",
"return",
"line",
".",
"rstrip",
"(",
")",
"+",
"line_ending"
] | Add line ending | [
"Add",
"line",
"ending"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1781-L1786 |
32,683 | saltstack/salt | salt/modules/file.py | rename | def rename(src, dst):
'''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must b... | python | def rename(src, dst):
'''
Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst
'''
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError('File path must b... | [
"def",
"rename",
"(",
"src",
",",
"dst",
")",
":",
"src",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"src",
")",
"dst",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dst",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"src",
... | Rename a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.rename /path/to/src /path/to/dst | [
"Rename",
"a",
"file",
"or",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3449-L3472 |
32,684 | saltstack/salt | salt/modules/file.py | copy | def copy(src, dst, recurse=False, remove_existing=False):
'''
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on ... | python | def copy(src, dst, recurse=False, remove_existing=False):
'''
Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on ... | [
"def",
"copy",
"(",
"src",
",",
"dst",
",",
"recurse",
"=",
"False",
",",
"remove_existing",
"=",
"False",
")",
":",
"src",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"src",
")",
"dst",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dst",
... | Copy a file or directory from source to dst
In order to copy a directory, the recurse flag is required, and
will by default overwrite files in the destination with the same path,
and retain all other existing files. (similar to cp -r on unix)
remove_existing will remove all files in the target directo... | [
"Copy",
"a",
"file",
"or",
"directory",
"from",
"source",
"to",
"dst"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3475-L3536 |
32,685 | saltstack/salt | salt/modules/file.py | stats | def stats(path, hash_type=None, follow_symlinks=True):
'''
Return a dict containing the stats for a given file
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd
'''
path = os.path.expanduser(path)
ret = {}
if not os.path.exists(path):
try:
... | python | def stats(path, hash_type=None, follow_symlinks=True):
'''
Return a dict containing the stats for a given file
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd
'''
path = os.path.expanduser(path)
ret = {}
if not os.path.exists(path):
try:
... | [
"def",
"stats",
"(",
"path",
",",
"hash_type",
"=",
"None",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"ret",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"... | Return a dict containing the stats for a given file
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd | [
"Return",
"a",
"dict",
"containing",
"the",
"stats",
"for",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3702-L3760 |
32,686 | saltstack/salt | salt/modules/file.py | remove | def remove(path, **kwargs):
'''
Remove the named file. If a directory is supplied, it will be recursively
deleted.
CLI Example:
.. code-block:: bash
salt '*' file.remove /tmp/foo
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError... | python | def remove(path, **kwargs):
'''
Remove the named file. If a directory is supplied, it will be recursively
deleted.
CLI Example:
.. code-block:: bash
salt '*' file.remove /tmp/foo
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError... | [
"def",
"remove",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'File p... | Remove the named file. If a directory is supplied, it will be recursively
deleted.
CLI Example:
.. code-block:: bash
salt '*' file.remove /tmp/foo | [
"Remove",
"the",
"named",
"file",
".",
"If",
"a",
"directory",
"is",
"supplied",
"it",
"will",
"be",
"recursively",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3790-L3817 |
32,687 | saltstack/salt | salt/modules/file.py | restorecon | def restorecon(path, recursive=False):
'''
Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', pat... | python | def restorecon(path, recursive=False):
'''
Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys
'''
if recursive:
cmd = ['restorecon', '-FR', path]
else:
cmd = ['restorecon', '-F', pat... | [
"def",
"restorecon",
"(",
"path",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"recursive",
":",
"cmd",
"=",
"[",
"'restorecon'",
",",
"'-FR'",
",",
"path",
"]",
"else",
":",
"cmd",
"=",
"[",
"'restorecon'",
",",
"'-F'",
",",
"path",
"]",
"return"... | Reset the SELinux context on a given path
CLI Example:
.. code-block:: bash
salt '*' file.restorecon /home/user/.ssh/authorized_keys | [
"Reset",
"the",
"SELinux",
"context",
"on",
"a",
"given",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3866-L3880 |
32,688 | saltstack/salt | salt/modules/file.py | get_selinux_context | def get_selinux_context(path):
'''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).g... | python | def get_selinux_context(path):
'''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).g... | [
"def",
"get_selinux_context",
"(",
"path",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"'ls'",
",",
"'-Z'",
",",
"path",
"]",
",",
"python_shell",
"=",
"False",
")",
"try",
":",
"ret",
"=",
"re",
".",
"search",
"(",
"r'\\w+:\\w... | Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts | [
"Get",
"an",
"SELinux",
"context",
"from",
"a",
"given",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L3883-L3902 |
32,689 | saltstack/salt | salt/modules/file.py | apply_template_on_contents | def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
'''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variabl... | python | def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
'''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variabl... | [
"def",
"apply_template_on_contents",
"(",
"contents",
",",
"template",
",",
"context",
",",
"defaults",
",",
"saltenv",
")",
":",
"if",
"template",
"in",
"salt",
".",
"utils",
".",
"templates",
".",
"TEMPLATE_REGISTRY",
":",
"context_dict",
"=",
"defaults",
"i... | Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
CLI Example:
.. code-block:: bash
... | [
"Return",
"the",
"contents",
"after",
"applying",
"the",
"templating",
"engine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L4065-L4122 |
32,690 | saltstack/salt | salt/modules/file.py | check_managed | def check_managed(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
seuser=None,
serole=None,
... | python | def check_managed(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
seuser=None,
serole=None,
... | [
"def",
"check_managed",
"(",
"name",
",",
"source",
",",
"source_hash",
",",
"source_hash_name",
",",
"user",
",",
"group",
",",
"mode",
",",
"attrs",
",",
"template",
",",
"context",
",",
"defaults",
",",
"saltenv",
",",
"contents",
"=",
"None",
",",
"s... | Check to see what changes need to be made for a file
CLI Example:
.. code-block:: bash
salt '*' file.check_managed /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '755' jinja True None None base | [
"Check",
"to",
"see",
"what",
"changes",
"need",
"to",
"be",
"made",
"for",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L4860-L4933 |
32,691 | saltstack/salt | salt/modules/file.py | check_managed_changes | def check_managed_changes(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
keep_mode=False,
seuse... | python | def check_managed_changes(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
keep_mode=False,
seuse... | [
"def",
"check_managed_changes",
"(",
"name",
",",
"source",
",",
"source_hash",
",",
"source_hash_name",
",",
"user",
",",
"group",
",",
"mode",
",",
"attrs",
",",
"template",
",",
"context",
",",
"defaults",
",",
"saltenv",
",",
"contents",
"=",
"None",
"... | Return a dictionary of what changes need to be made for a file
.. versionchanged:: Neon
selinux attributes added
CLI Example:
.. code-block:: bash
salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '... | [
"Return",
"a",
"dictionary",
"of",
"what",
"changes",
"need",
"to",
"be",
"made",
"for",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L4936-L5014 |
32,692 | saltstack/salt | salt/modules/file.py | get_diff | def get_diff(file1,
file2,
saltenv='base',
show_filenames=True,
show_changes=True,
template=False,
source_hash_file1=None,
source_hash_file2=None):
'''
Return unified diff of two files
file1
The first file to... | python | def get_diff(file1,
file2,
saltenv='base',
show_filenames=True,
show_changes=True,
template=False,
source_hash_file1=None,
source_hash_file2=None):
'''
Return unified diff of two files
file1
The first file to... | [
"def",
"get_diff",
"(",
"file1",
",",
"file2",
",",
"saltenv",
"=",
"'base'",
",",
"show_filenames",
"=",
"True",
",",
"show_changes",
"=",
"True",
",",
"template",
"=",
"False",
",",
"source_hash_file1",
"=",
"None",
",",
"source_hash_file2",
"=",
"None",
... | Return unified diff of two files
file1
The first file to feed into the diff utility
.. versionchanged:: 2018.3.0
Can now be either a local or remote file. In earlier releases,
thuis had to be a file local to the minion.
file2
The second file to feed into the di... | [
"Return",
"unified",
"diff",
"of",
"two",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L5205-L5327 |
32,693 | saltstack/salt | salt/modules/file.py | mkdir | def mkdir(dir_path,
user=None,
group=None,
mode=None):
'''
Ensure that a directory is available.
CLI Example:
.. code-block:: bash
salt '*' file.mkdir /opt/jetty/context
'''
dir_path = os.path.expanduser(dir_path)
directory = os.path.normpath(dir_pat... | python | def mkdir(dir_path,
user=None,
group=None,
mode=None):
'''
Ensure that a directory is available.
CLI Example:
.. code-block:: bash
salt '*' file.mkdir /opt/jetty/context
'''
dir_path = os.path.expanduser(dir_path)
directory = os.path.normpath(dir_pat... | [
"def",
"mkdir",
"(",
"dir_path",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"dir_path",
")",
"directory",
"=",
"os",
".",
"path",
".",
"normpa... | Ensure that a directory is available.
CLI Example:
.. code-block:: bash
salt '*' file.mkdir /opt/jetty/context | [
"Ensure",
"that",
"a",
"directory",
"is",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L5850-L5873 |
32,694 | saltstack/salt | salt/modules/file.py | makedirs_ | def makedirs_(path,
user=None,
group=None,
mode=None):
'''
Ensure that the directory containing this path is available.
.. note::
The path must end with a trailing slash otherwise the directory/directories
will be created up to the parent directory... | python | def makedirs_(path,
user=None,
group=None,
mode=None):
'''
Ensure that the directory containing this path is available.
.. note::
The path must end with a trailing slash otherwise the directory/directories
will be created up to the parent directory... | [
"def",
"makedirs_",
"(",
"path",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"mode",
":",
"mode",
"=",
"salt",
".",
"utils",
... | Ensure that the directory containing this path is available.
.. note::
The path must end with a trailing slash otherwise the directory/directories
will be created up to the parent directory. For example if path is
``/opt/code``, then it would be treated as ``/opt/`` but if the path
... | [
"Ensure",
"that",
"the",
"directory",
"containing",
"this",
"path",
"is",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L5876-L5939 |
32,695 | saltstack/salt | salt/modules/file.py | makedirs_perms | def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
'''
Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code
... | python | def makedirs_perms(name,
user=None,
group=None,
mode='0755'):
'''
Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code
... | [
"def",
"makedirs_perms",
"(",
"name",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"'0755'",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"path",
"=",
"os",
".",
"path",
"head",
",",
"ta... | Taken and modified from os.makedirs to set user, group and mode for each
directory created.
CLI Example:
.. code-block:: bash
salt '*' file.makedirs_perms /opt/code | [
"Taken",
"and",
"modified",
"from",
"os",
".",
"makedirs",
"to",
"set",
"user",
"group",
"and",
"mode",
"for",
"each",
"directory",
"created",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L5942-L5976 |
32,696 | saltstack/salt | salt/modules/file.py | is_chrdev | def is_chrdev(name):
'''
Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
... | python | def is_chrdev(name):
'''
Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
... | [
"def",
"is_chrdev",
"(",
"name",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"stat_structure",
"=",
"None",
"try",
":",
"stat_structure",
"=",
"os",
".",
"stat",
"(",
"name",
")",
"except",
"OSError",
"as",
"exc",
"... | Check if a file exists and is a character device.
CLI Example:
.. code-block:: bash
salt '*' file.is_chrdev /dev/chr | [
"Check",
"if",
"a",
"file",
"exists",
"and",
"is",
"a",
"character",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L6000-L6021 |
32,697 | saltstack/salt | salt/modules/file.py | is_blkdev | def is_blkdev(name):
'''
Check if a file exists and is a block device.
CLI Example:
.. code-block:: bash
salt '*' file.is_blkdev /dev/blk
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if... | python | def is_blkdev(name):
'''
Check if a file exists and is a block device.
CLI Example:
.. code-block:: bash
salt '*' file.is_blkdev /dev/blk
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if... | [
"def",
"is_blkdev",
"(",
"name",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"stat_structure",
"=",
"None",
"try",
":",
"stat_structure",
"=",
"os",
".",
"stat",
"(",
"name",
")",
"except",
"OSError",
"as",
"exc",
"... | Check if a file exists and is a block device.
CLI Example:
.. code-block:: bash
salt '*' file.is_blkdev /dev/blk | [
"Check",
"if",
"a",
"file",
"exists",
"and",
"is",
"a",
"block",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L6075-L6096 |
32,698 | saltstack/salt | salt/modules/file.py | is_fifo | def is_fifo(name):
'''
Check if a file exists and is a FIFO.
CLI Example:
.. code-block:: bash
salt '*' file.is_fifo /dev/fifo
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno ... | python | def is_fifo(name):
'''
Check if a file exists and is a FIFO.
CLI Example:
.. code-block:: bash
salt '*' file.is_fifo /dev/fifo
'''
name = os.path.expanduser(name)
stat_structure = None
try:
stat_structure = os.stat(name)
except OSError as exc:
if exc.errno ... | [
"def",
"is_fifo",
"(",
"name",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"stat_structure",
"=",
"None",
"try",
":",
"stat_structure",
"=",
"os",
".",
"stat",
"(",
"name",
")",
"except",
"OSError",
"as",
"exc",
":"... | Check if a file exists and is a FIFO.
CLI Example:
.. code-block:: bash
salt '*' file.is_fifo /dev/fifo | [
"Check",
"if",
"a",
"file",
"exists",
"and",
"is",
"a",
"FIFO",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L6150-L6171 |
32,699 | saltstack/salt | salt/modules/file.py | grep | def grep(path,
pattern,
*opts):
'''
Grep for a string in the specified file
.. note::
This function's return value is slated for refinement in future
versions of Salt
path
Path to the file to be searched
.. note::
Globbing is supported (i.... | python | def grep(path,
pattern,
*opts):
'''
Grep for a string in the specified file
.. note::
This function's return value is slated for refinement in future
versions of Salt
path
Path to the file to be searched
.. note::
Globbing is supported (i.... | [
"def",
"grep",
"(",
"path",
",",
"pattern",
",",
"*",
"opts",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"# Backup the path in case the glob returns nothing",
"_path",
"=",
"path",
"path",
"=",
"glob",
".",
"glob",
"(",
... | Grep for a string in the specified file
.. note::
This function's return value is slated for refinement in future
versions of Salt
path
Path to the file to be searched
.. note::
Globbing is supported (i.e. ``/var/log/foo/*.log``, but if globbing
is bein... | [
"Grep",
"for",
"a",
"string",
"in",
"the",
"specified",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L6503-L6577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.