repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
facebookresearch/fastText | python/fastText/FastText.py | _FastText.get_line | def get_line(self, text, on_unicode_error='strict'):
"""
Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default).
"""
def check(entry):
if entry.find('\n') != -1:
raise ValueError(
... | python | def get_line(self, text, on_unicode_error='strict'):
"""
Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default).
"""
def check(entry):
if entry.find('\n') != -1:
raise ValueError(
... | [
"def",
"get_line",
"(",
"self",
",",
"text",
",",
"on_unicode_error",
"=",
"'strict'",
")",
":",
"def",
"check",
"(",
"entry",
")",
":",
"if",
"entry",
".",
"find",
"(",
"'\\n'",
")",
"!=",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"get_line process... | Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default). | [
"Split",
"a",
"line",
"of",
"text",
"into",
"words",
"and",
"labels",
".",
"Labels",
"must",
"start",
"with",
"the",
"prefix",
"used",
"to",
"create",
"the",
"model",
"(",
"__label__",
"by",
"default",
")",
"."
] | 6dd2e11b5fe82854c4529d2a58d699b2cb182b1b | https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L194-L213 | train |
facebookresearch/fastText | python/fastText/FastText.py | _FastText.quantize | def quantize(
self,
input=None,
qout=False,
cutoff=0,
retrain=False,
epoch=None,
lr=None,
thread=None,
verbose=None,
dsub=2,
qnorm=False
):
"""
Quantize the model reducing the size of the model and
it's m... | python | def quantize(
self,
input=None,
qout=False,
cutoff=0,
retrain=False,
epoch=None,
lr=None,
thread=None,
verbose=None,
dsub=2,
qnorm=False
):
"""
Quantize the model reducing the size of the model and
it's m... | [
"def",
"quantize",
"(",
"self",
",",
"input",
"=",
"None",
",",
"qout",
"=",
"False",
",",
"cutoff",
"=",
"0",
",",
"retrain",
"=",
"False",
",",
"epoch",
"=",
"None",
",",
"lr",
"=",
"None",
",",
"thread",
"=",
"None",
",",
"verbose",
"=",
"None... | Quantize the model reducing the size of the model and
it's memory footprint. | [
"Quantize",
"the",
"model",
"reducing",
"the",
"size",
"of",
"the",
"model",
"and",
"it",
"s",
"memory",
"footprint",
"."
] | 6dd2e11b5fe82854c4529d2a58d699b2cb182b1b | https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L234-L267 | train |
allenai/allennlp | allennlp/modules/stacked_bidirectional_lstm.py | StackedBidirectionalLstm.forward | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
) -> Tuple[PackedSequence, Tuple[torch.Tensor, torch.Tensor]]:
"""
Parameters
----------
inputs :... | python | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
) -> Tuple[PackedSequence, Tuple[torch.Tensor, torch.Tensor]]:
"""
Parameters
----------
inputs :... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"PackedSequence",
",",
"initial_state",
":",
"Optional",
"[",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch",
".",
"Tensor",
"]",
"]",
"=",
"None",
")",
"->",
"Tuple... | Parameters
----------
inputs : ``PackedSequence``, required.
A batch first ``PackedSequence`` to run the stacked LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the initial hidden state and memo... | [
"Parameters",
"----------",
"inputs",
":",
"PackedSequence",
"required",
".",
"A",
"batch",
"first",
"PackedSequence",
"to",
"run",
"the",
"stacked",
"LSTM",
"over",
".",
"initial_state",
":",
"Tuple",
"[",
"torch",
".",
"Tensor",
"torch",
".",
"Tensor",
"]",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/stacked_bidirectional_lstm.py#L78-L134 | train |
allenai/allennlp | allennlp/nn/regularizers/regularizer_applicator.py | RegularizerApplicator.from_params | def from_params(cls, params: Iterable[Tuple[str, Params]] = ()) -> Optional['RegularizerApplicator']:
"""
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each ... | python | def from_params(cls, params: Iterable[Tuple[str, Params]] = ()) -> Optional['RegularizerApplicator']:
"""
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each ... | [
"def",
"from_params",
"(",
"cls",
",",
"params",
":",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Params",
"]",
"]",
"=",
"(",
")",
")",
"->",
"Optional",
"[",
"'RegularizerApplicator'",
"]",
":",
"if",
"not",
"params",
":",
"return",
"None",
"instanti... | Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each parameter receives the penalty corresponding to the first regex
that matches its name (which may be no regex and h... | [
"Converts",
"a",
"List",
"of",
"pairs",
"(",
"regex",
"params",
")",
"into",
"an",
"RegularizerApplicator",
".",
"This",
"list",
"should",
"look",
"like"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/regularizers/regularizer_applicator.py#L45-L81 | train |
allenai/allennlp | allennlp/common/registrable.py | Registrable.list_available | def list_available(cls) -> List[str]:
"""List default first if it exists"""
keys = list(Registrable._registry[cls].keys())
default = cls.default_implementation
if default is None:
return keys
elif default not in keys:
message = "Default implementation %s ... | python | def list_available(cls) -> List[str]:
"""List default first if it exists"""
keys = list(Registrable._registry[cls].keys())
default = cls.default_implementation
if default is None:
return keys
elif default not in keys:
message = "Default implementation %s ... | [
"def",
"list_available",
"(",
"cls",
")",
"->",
"List",
"[",
"str",
"]",
":",
"keys",
"=",
"list",
"(",
"Registrable",
".",
"_registry",
"[",
"cls",
"]",
".",
"keys",
"(",
")",
")",
"default",
"=",
"cls",
".",
"default_implementation",
"if",
"default",... | List default first if it exists | [
"List",
"default",
"first",
"if",
"it",
"exists"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/registrable.py#L62-L73 | train |
allenai/allennlp | allennlp/common/util.py | sanitize | def sanitize(x: Any) -> Any: # pylint: disable=invalid-name,too-many-return-statements
"""
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON.
"""
if isinstance(x, (str, float, int, bool)):
# x is already serializable
return x
elif... | python | def sanitize(x: Any) -> Any: # pylint: disable=invalid-name,too-many-return-statements
"""
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON.
"""
if isinstance(x, (str, float, int, bool)):
# x is already serializable
return x
elif... | [
"def",
"sanitize",
"(",
"x",
":",
"Any",
")",
"->",
"Any",
":",
"# pylint: disable=invalid-name,too-many-return-statements",
"if",
"isinstance",
"(",
"x",
",",
"(",
"str",
",",
"float",
",",
"int",
",",
"bool",
")",
")",
":",
"# x is already serializable",
"re... | Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON. | [
"Sanitize",
"turns",
"PyTorch",
"and",
"Numpy",
"types",
"into",
"basic",
"Python",
"types",
"so",
"they",
"can",
"be",
"serialized",
"into",
"JSON",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L48-L81 | train |
allenai/allennlp | allennlp/common/util.py | group_by_count | def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]:
"""
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the
list at the end if the list is not divisable by ``count``.
For example:
>>> group_by_count([1, 2, 3, 4, 5, 6... | python | def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]:
"""
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the
list at the end if the list is not divisable by ``count``.
For example:
>>> group_by_count([1, 2, 3, 4, 5, 6... | [
"def",
"group_by_count",
"(",
"iterable",
":",
"List",
"[",
"Any",
"]",
",",
"count",
":",
"int",
",",
"default_value",
":",
"Any",
")",
"->",
"List",
"[",
"List",
"[",
"Any",
"]",
"]",
":",
"return",
"[",
"list",
"(",
"l",
")",
"for",
"l",
"in",... | Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the
list at the end if the list is not divisable by ``count``.
For example:
>>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0)
[[1, 2, 3], [4, 5, 6], [7, 0, 0]]
This is a short method, but it's complicated and ... | [
"Takes",
"a",
"list",
"and",
"groups",
"it",
"into",
"sublists",
"of",
"size",
"count",
"using",
"default_value",
"to",
"pad",
"the",
"list",
"at",
"the",
"end",
"if",
"the",
"list",
"is",
"not",
"divisable",
"by",
"count",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L83-L95 | train |
allenai/allennlp | allennlp/common/util.py | lazy_groups_of | def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]:
"""
Takes an iterator and batches the individual instances into lists of the
specified size. The last list may be smaller if there are instances left over.
"""
return iter(lambda: list(islice(iterator, 0, group_size)), ... | python | def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]:
"""
Takes an iterator and batches the individual instances into lists of the
specified size. The last list may be smaller if there are instances left over.
"""
return iter(lambda: list(islice(iterator, 0, group_size)), ... | [
"def",
"lazy_groups_of",
"(",
"iterator",
":",
"Iterator",
"[",
"A",
"]",
",",
"group_size",
":",
"int",
")",
"->",
"Iterator",
"[",
"List",
"[",
"A",
"]",
"]",
":",
"return",
"iter",
"(",
"lambda",
":",
"list",
"(",
"islice",
"(",
"iterator",
",",
... | Takes an iterator and batches the individual instances into lists of the
specified size. The last list may be smaller if there are instances left over. | [
"Takes",
"an",
"iterator",
"and",
"batches",
"the",
"individual",
"instances",
"into",
"lists",
"of",
"the",
"specified",
"size",
".",
"The",
"last",
"list",
"may",
"be",
"smaller",
"if",
"there",
"are",
"instances",
"left",
"over",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L99-L104 | train |
allenai/allennlp | allennlp/common/util.py | pad_sequence_to_length | def pad_sequence_to_length(sequence: List,
desired_length: int,
default_value: Callable[[], Any] = lambda: 0,
padding_on_right: bool = True) -> List:
"""
Take a list of objects and pads it to the desired length, returning the padde... | python | def pad_sequence_to_length(sequence: List,
desired_length: int,
default_value: Callable[[], Any] = lambda: 0,
padding_on_right: bool = True) -> List:
"""
Take a list of objects and pads it to the desired length, returning the padde... | [
"def",
"pad_sequence_to_length",
"(",
"sequence",
":",
"List",
",",
"desired_length",
":",
"int",
",",
"default_value",
":",
"Callable",
"[",
"[",
"]",
",",
"Any",
"]",
"=",
"lambda",
":",
"0",
",",
"padding_on_right",
":",
"bool",
"=",
"True",
")",
"->"... | Take a list of objects and pads it to the desired length, returning the padded list. The
original list is not modified.
Parameters
----------
sequence : List
A list of objects to be padded.
desired_length : int
Maximum length of each sequence. Longer sequences are truncated to thi... | [
"Take",
"a",
"list",
"of",
"objects",
"and",
"pads",
"it",
"to",
"the",
"desired",
"length",
"returning",
"the",
"padded",
"list",
".",
"The",
"original",
"list",
"is",
"not",
"modified",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L106-L147 | train |
allenai/allennlp | allennlp/common/util.py | add_noise_to_dict_values | def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]:
"""
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary.
"""
new... | python | def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]:
"""
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary.
"""
new... | [
"def",
"add_noise_to_dict_values",
"(",
"dictionary",
":",
"Dict",
"[",
"A",
",",
"float",
"]",
",",
"noise_param",
":",
"float",
")",
"->",
"Dict",
"[",
"A",
",",
"float",
"]",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"dicti... | Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary. | [
"Returns",
"a",
"new",
"dictionary",
"with",
"noise",
"added",
"to",
"every",
"key",
"in",
"dictionary",
".",
"The",
"noise",
"is",
"uniformly",
"distributed",
"within",
"noise_param",
"percent",
"of",
"the",
"value",
"for",
"every",
"value",
"in",
"the",
"d... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L150-L161 | train |
allenai/allennlp | allennlp/common/util.py | namespace_match | def namespace_match(pattern: str, namespace: str):
"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == '*' and namespace.endswith(patt... | python | def namespace_match(pattern: str, namespace: str):
"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == '*' and namespace.endswith(patt... | [
"def",
"namespace_match",
"(",
"pattern",
":",
"str",
",",
"namespace",
":",
"str",
")",
":",
"if",
"pattern",
"[",
"0",
"]",
"==",
"'*'",
"and",
"namespace",
".",
"endswith",
"(",
"pattern",
"[",
"1",
":",
"]",
")",
":",
"return",
"True",
"elif",
... | Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``. | [
"Matches",
"a",
"namespace",
"pattern",
"against",
"a",
"namespace",
"string",
".",
"For",
"example",
"*",
"tags",
"matches",
"passage_tags",
"and",
"question_tags",
"and",
"tokens",
"matches",
"tokens",
"but",
"not",
"stemmed_tokens",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L164-L174 | train |
allenai/allennlp | allennlp/common/util.py | prepare_environment | def prepare_environment(params: Params):
"""
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
yo... | python | def prepare_environment(params: Params):
"""
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
yo... | [
"def",
"prepare_environment",
"(",
"params",
":",
"Params",
")",
":",
"seed",
"=",
"params",
".",
"pop_int",
"(",
"\"random_seed\"",
",",
"13370",
")",
"numpy_seed",
"=",
"params",
".",
"pop_int",
"(",
"\"numpy_seed\"",
",",
"1337",
")",
"torch_seed",
"=",
... | Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
your experiments should be reasonably reproducible. If ... | [
"Sets",
"random",
"seeds",
"for",
"reproducible",
"experiments",
".",
"This",
"may",
"not",
"work",
"as",
"expected",
"if",
"you",
"use",
"this",
"from",
"within",
"a",
"python",
"project",
"in",
"which",
"you",
"have",
"already",
"imported",
"Pytorch",
".",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L177-L206 | train |
allenai/allennlp | allennlp/common/util.py | prepare_global_logging | def prepare_global_logging(serialization_dir: str, file_friendly_logging: bool) -> logging.FileHandler:
"""
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval... | python | def prepare_global_logging(serialization_dir: str, file_friendly_logging: bool) -> logging.FileHandler:
"""
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval... | [
"def",
"prepare_global_logging",
"(",
"serialization_dir",
":",
"str",
",",
"file_friendly_logging",
":",
"bool",
")",
"->",
"logging",
".",
"FileHandler",
":",
"# If we don't have a terminal as stdout,",
"# force tqdm to be nicer.",
"if",
"not",
"sys",
".",
"stdout",
"... | This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval frequency for the Tqdm progress bar.
Note that this function does not set the logging level, which is set in `... | [
"This",
"function",
"configures",
"3",
"global",
"logging",
"attributes",
"-",
"streaming",
"stdout",
"and",
"stderr",
"to",
"a",
"file",
"as",
"well",
"as",
"the",
"terminal",
"setting",
"the",
"formatting",
"for",
"the",
"python",
"logging",
"library",
"and"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L208-L250 | train |
allenai/allennlp | allennlp/common/util.py | cleanup_global_logging | def cleanup_global_logging(stdout_handler: logging.FileHandler) -> None:
"""
This function closes any open file handles and logs set up by `prepare_global_logging`.
Parameters
----------
stdout_handler : ``logging.FileHandler``, required.
The file handler returned from `prepare_global_loggi... | python | def cleanup_global_logging(stdout_handler: logging.FileHandler) -> None:
"""
This function closes any open file handles and logs set up by `prepare_global_logging`.
Parameters
----------
stdout_handler : ``logging.FileHandler``, required.
The file handler returned from `prepare_global_loggi... | [
"def",
"cleanup_global_logging",
"(",
"stdout_handler",
":",
"logging",
".",
"FileHandler",
")",
"->",
"None",
":",
"stdout_handler",
".",
"close",
"(",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"removeHandler",
"(",
"stdout_handler",
")",
"if",
"isinst... | This function closes any open file handles and logs set up by `prepare_global_logging`.
Parameters
----------
stdout_handler : ``logging.FileHandler``, required.
The file handler returned from `prepare_global_logging`, attached to the global logger. | [
"This",
"function",
"closes",
"any",
"open",
"file",
"handles",
"and",
"logs",
"set",
"up",
"by",
"prepare_global_logging",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L252-L267 | train |
allenai/allennlp | allennlp/common/util.py | get_spacy_model | def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
"""
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded... | python | def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
"""
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded... | [
"def",
"get_spacy_model",
"(",
"spacy_model_name",
":",
"str",
",",
"pos_tags",
":",
"bool",
",",
"parse",
":",
"bool",
",",
"ner",
":",
"bool",
")",
"->",
"SpacyModelType",
":",
"options",
"=",
"(",
"spacy_model_name",
",",
"pos_tags",
",",
"parse",
",",
... | In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded once. | [
"In",
"order",
"to",
"avoid",
"loading",
"spacy",
"models",
"a",
"whole",
"bunch",
"of",
"times",
"we",
"ll",
"save",
"references",
"to",
"them",
"keyed",
"by",
"the",
"options",
"we",
"used",
"to",
"create",
"the",
"spacy",
"model",
"so",
"any",
"partic... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L272-L306 | train |
allenai/allennlp | allennlp/common/util.py | import_submodules | def import_submodules(package_name: str) -> None:
"""
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
"""
importlib.invalidate_caches()
... | python | def import_submodules(package_name: str) -> None:
"""
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
"""
importlib.invalidate_caches()
... | [
"def",
"import_submodules",
"(",
"package_name",
":",
"str",
")",
"->",
"None",
":",
"importlib",
".",
"invalidate_caches",
"(",
")",
"# For some reason, python doesn't always add this by default to your path, but you pretty much",
"# always want it when using `--include-package`. A... | Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered. | [
"Import",
"all",
"submodules",
"under",
"the",
"given",
"package",
".",
"Primarily",
"useful",
"so",
"that",
"people",
"using",
"AllenNLP",
"as",
"a",
"library",
"can",
"specify",
"their",
"own",
"custom",
"packages",
"and",
"have",
"their",
"custom",
"classes... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L308-L334 | train |
allenai/allennlp | allennlp/common/util.py | peak_memory_mb | def peak_memory_mb() -> float:
"""
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise.
"""
if resource is Non... | python | def peak_memory_mb() -> float:
"""
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise.
"""
if resource is Non... | [
"def",
"peak_memory_mb",
"(",
")",
"->",
"float",
":",
"if",
"resource",
"is",
"None",
"or",
"sys",
".",
"platform",
"not",
"in",
"(",
"'linux'",
",",
"'darwin'",
")",
":",
"return",
"0.0",
"# TODO(joelgrus): For whatever, our pinned version 0.521 of mypy does not l... | Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise. | [
"Get",
"peak",
"memory",
"usage",
"for",
"this",
"process",
"as",
"measured",
"by",
"max",
"-",
"resident",
"-",
"set",
"size",
":"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L337-L360 | train |
allenai/allennlp | allennlp/common/util.py | gpu_memory_mb | def gpu_memory_mb() -> Dict[int, int]:
"""
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Re... | python | def gpu_memory_mb() -> Dict[int, int]:
"""
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Re... | [
"def",
"gpu_memory_mb",
"(",
")",
"->",
"Dict",
"[",
"int",
",",
"int",
"]",
":",
"# pylint: disable=bare-except",
"try",
":",
"result",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'nvidia-smi'",
",",
"'--query-gpu=memory.used'",
",",
"'--format=csv,nounits... | Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Returns an empty ``dict`` if GPUs are not available. | [
"Get",
"the",
"current",
"GPU",
"memory",
"usage",
".",
"Based",
"on",
"https",
":",
"//",
"discuss",
".",
"pytorch",
".",
"org",
"/",
"t",
"/",
"access",
"-",
"gpu",
"-",
"memory",
"-",
"usage",
"-",
"in",
"-",
"pytorch",
"/",
"3192",
"/",
"4"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L362-L388 | train |
allenai/allennlp | allennlp/common/util.py | ensure_list | def ensure_list(iterable: Iterable[A]) -> List[A]:
"""
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
"""
if isinstance(iterable, list):
return iterable
else:
return list(iterable) | python | def ensure_list(iterable: Iterable[A]) -> List[A]:
"""
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
"""
if isinstance(iterable, list):
return iterable
else:
return list(iterable) | [
"def",
"ensure_list",
"(",
"iterable",
":",
"Iterable",
"[",
"A",
"]",
")",
"->",
"List",
"[",
"A",
"]",
":",
"if",
"isinstance",
"(",
"iterable",
",",
"list",
")",
":",
"return",
"iterable",
"else",
":",
"return",
"list",
"(",
"iterable",
")"
] | An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy. | [
"An",
"Iterable",
"may",
"be",
"a",
"list",
"or",
"a",
"generator",
".",
"This",
"ensures",
"we",
"get",
"a",
"list",
"without",
"making",
"an",
"unnecessary",
"copy",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L391-L399 | train |
allenai/allennlp | allennlp/state_machines/states/checklist_statelet.py | ChecklistStatelet.update | def update(self, action: torch.Tensor) -> 'ChecklistStatelet':
"""
Takes an action index, updates checklist and returns an updated state.
"""
checklist_addition = (self.terminal_actions == action).float()
new_checklist = self.checklist + checklist_addition
new_checklist_s... | python | def update(self, action: torch.Tensor) -> 'ChecklistStatelet':
"""
Takes an action index, updates checklist and returns an updated state.
"""
checklist_addition = (self.terminal_actions == action).float()
new_checklist = self.checklist + checklist_addition
new_checklist_s... | [
"def",
"update",
"(",
"self",
",",
"action",
":",
"torch",
".",
"Tensor",
")",
"->",
"'ChecklistStatelet'",
":",
"checklist_addition",
"=",
"(",
"self",
".",
"terminal_actions",
"==",
"action",
")",
".",
"float",
"(",
")",
"new_checklist",
"=",
"self",
"."... | Takes an action index, updates checklist and returns an updated state. | [
"Takes",
"an",
"action",
"index",
"updates",
"checklist",
"and",
"returns",
"an",
"updated",
"state",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/checklist_statelet.py#L57-L68 | train |
allenai/allennlp | allennlp/semparse/worlds/wikitables_world.py | WikiTablesWorld._remove_action_from_type | def _remove_action_from_type(valid_actions: Dict[str, List[str]],
type_: str,
filter_function: Callable[[str], bool]) -> None:
"""
Finds the production rule matching the filter function in the given type's valid action
list, and r... | python | def _remove_action_from_type(valid_actions: Dict[str, List[str]],
type_: str,
filter_function: Callable[[str], bool]) -> None:
"""
Finds the production rule matching the filter function in the given type's valid action
list, and r... | [
"def",
"_remove_action_from_type",
"(",
"valid_actions",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"type_",
":",
"str",
",",
"filter_function",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"bool",
"]",
")",
"->",
"None",
":",
"a... | Finds the production rule matching the filter function in the given type's valid action
list, and removes it. If there is more than one matching function, we crash. | [
"Finds",
"the",
"production",
"rule",
"matching",
"the",
"filter",
"function",
"in",
"the",
"given",
"type",
"s",
"valid",
"action",
"list",
"and",
"removes",
"it",
".",
"If",
"there",
"is",
"more",
"than",
"one",
"matching",
"function",
"we",
"crash",
"."... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/wikitables_world.py#L124-L134 | train |
allenai/allennlp | allennlp/modules/lstm_cell_with_projection.py | LstmCellWithProjection.forward | def forward(self, # pylint: disable=arguments-differ
inputs: torch.FloatTensor,
batch_lengths: List[int],
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : ``torch.FloatTensor``, require... | python | def forward(self, # pylint: disable=arguments-differ
inputs: torch.FloatTensor,
batch_lengths: List[int],
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : ``torch.FloatTensor``, require... | [
"def",
"forward",
"(",
"self",
",",
"# pylint: disable=arguments-differ",
"inputs",
":",
"torch",
".",
"FloatTensor",
",",
"batch_lengths",
":",
"List",
"[",
"int",
"]",
",",
"initial_state",
":",
"Optional",
"[",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"... | Parameters
----------
inputs : ``torch.FloatTensor``, required.
A tensor of shape (batch_size, num_timesteps, input_size)
to apply the LSTM over.
batch_lengths : ``List[int]``, required.
A list of length batch_size containing the lengths of the sequences in ba... | [
"Parameters",
"----------",
"inputs",
":",
"torch",
".",
"FloatTensor",
"required",
".",
"A",
"tensor",
"of",
"shape",
"(",
"batch_size",
"num_timesteps",
"input_size",
")",
"to",
"apply",
"the",
"LSTM",
"over",
".",
"batch_lengths",
":",
"List",
"[",
"int",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/lstm_cell_with_projection.py#L93-L230 | train |
allenai/allennlp | doc/conf.py | linkcode_resolve | def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262
"""
if domain != 'py':
return None
modname = info['module... | python | def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262
"""
if domain != 'py':
return None
modname = info['module... | [
"def",
"linkcode_resolve",
"(",
"domain",
",",
"info",
")",
":",
"if",
"domain",
"!=",
"'py'",
":",
"return",
"None",
"modname",
"=",
"info",
"[",
"'module'",
"]",
"fullname",
"=",
"info",
"[",
"'fullname'",
"]",
"submod",
"=",
"sys",
".",
"modules",
"... | Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262 | [
"Determine",
"the",
"URL",
"corresponding",
"to",
"Python",
"object",
"This",
"code",
"is",
"from",
"https",
":",
"//",
"github",
".",
"com",
"/",
"numpy",
"/",
"numpy",
"/",
"blob",
"/",
"master",
"/",
"doc",
"/",
"source",
"/",
"conf",
".",
"py#L290"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/doc/conf.py#L199-L241 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._get_initial_rnn_and_grammar_state | def _get_initial_rnn_and_grammar_state(self,
question: Dict[str, torch.LongTensor],
table: Dict[str, torch.LongTensor],
world: List[WikiTablesWorld],
... | python | def _get_initial_rnn_and_grammar_state(self,
question: Dict[str, torch.LongTensor],
table: Dict[str, torch.LongTensor],
world: List[WikiTablesWorld],
... | [
"def",
"_get_initial_rnn_and_grammar_state",
"(",
"self",
",",
"question",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"LongTensor",
"]",
",",
"table",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"LongTensor",
"]",
",",
"world",
":",
"List",
"[",
"WikiTa... | Encodes the question and table, computes a linking between the two, and constructs an
initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the
decoder.
We take ``outputs`` as a parameter here and `modify` it, adding things that we want to
visualize in a demo. | [
"Encodes",
"the",
"question",
"and",
"table",
"computes",
"a",
"linking",
"between",
"the",
"two",
"and",
"constructs",
"an",
"initial",
"RnnStatelet",
"and",
"LambdaGrammarStatelet",
"for",
"each",
"batch",
"instance",
"to",
"pass",
"to",
"the",
"decoder",
"."
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L140-L296 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._get_neighbor_indices | def _get_neighbor_indices(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> torch.LongTensor:
"""
This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purpo... | python | def _get_neighbor_indices(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> torch.LongTensor:
"""
This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purpo... | [
"def",
"_get_neighbor_indices",
"(",
"worlds",
":",
"List",
"[",
"WikiTablesWorld",
"]",
",",
"num_entities",
":",
"int",
",",
"tensor",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"LongTensor",
":",
"num_neighbors",
"=",
"0",
"for",
"world",
"in... | This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purposes.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
num_entities : ``int``
tensor : ``torch.Tensor``
Used for copying the constructed li... | [
"This",
"method",
"returns",
"the",
"indices",
"of",
"each",
"entity",
"s",
"neighbors",
".",
"A",
"tensor",
"is",
"accepted",
"as",
"a",
"parameter",
"for",
"copying",
"purposes",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L299-L341 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._get_type_vector | def _get_type_vector(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]:
"""
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition,... | python | def _get_type_vector(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]:
"""
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition,... | [
"def",
"_get_type_vector",
"(",
"worlds",
":",
"List",
"[",
"WikiTablesWorld",
"]",
",",
"num_entities",
":",
"int",
",",
"tensor",
":",
"torch",
".",
"Tensor",
")",
"->",
"Tuple",
"[",
"torch",
".",
"LongTensor",
",",
"Dict",
"[",
"int",
",",
"int",
"... | Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition, a map from a flattened entity index to type is returned to combine
entity type operations into one method.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
n... | [
"Produces",
"a",
"tensor",
"with",
"shape",
"(",
"batch_size",
"num_entities",
")",
"that",
"encodes",
"each",
"entity",
"s",
"type",
".",
"In",
"addition",
"a",
"map",
"from",
"a",
"flattened",
"entity",
"index",
"to",
"type",
"is",
"returned",
"to",
"com... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L344-L390 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._get_linking_probabilities | def _get_linking_probabilities(self,
worlds: List[WikiTablesWorld],
linking_scores: torch.FloatTensor,
question_mask: torch.LongTensor,
entity_type_dict: Dict[int, int]) -> torch.F... | python | def _get_linking_probabilities(self,
worlds: List[WikiTablesWorld],
linking_scores: torch.FloatTensor,
question_mask: torch.LongTensor,
entity_type_dict: Dict[int, int]) -> torch.F... | [
"def",
"_get_linking_probabilities",
"(",
"self",
",",
"worlds",
":",
"List",
"[",
"WikiTablesWorld",
"]",
",",
"linking_scores",
":",
"torch",
".",
"FloatTensor",
",",
"question_mask",
":",
"torch",
".",
"LongTensor",
",",
"entity_type_dict",
":",
"Dict",
"[",
... | Produces the probability of an entity given a question word and type. The logic below
separates the entities by type since the softmax normalization term sums over entities
of a single type.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
linking_scores : ``torc... | [
"Produces",
"the",
"probability",
"of",
"an",
"entity",
"given",
"a",
"question",
"word",
"and",
"type",
".",
"The",
"logic",
"below",
"separates",
"the",
"entities",
"by",
"type",
"since",
"the",
"softmax",
"normalization",
"term",
"sums",
"over",
"entities",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L392-L472 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser.get_metrics | def get_metrics(self, reset: bool = False) -> Dict[str, float]:
"""
We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
... | python | def get_metrics(self, reset: bool = False) -> Dict[str, float]:
"""
We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
... | [
"def",
"get_metrics",
"(",
"self",
",",
"reset",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
":",
"return",
"{",
"'dpd_acc'",
":",
"self",
".",
"_action_sequence_accuracy",
".",
"get_metric",
"(",
"reset",
")",
",",
"'d... | We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
on denotation accuracy for the set of examples where we actually have DPD outp... | [
"We",
"track",
"three",
"metrics",
"here",
":"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L486-L511 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._create_grammar_state | def _create_grammar_state(self,
world: WikiTablesWorld,
possible_actions: List[ProductionRule],
linking_scores: torch.Tensor,
entity_types: torch.Tensor) -> LambdaGrammarStatelet:
"""
... | python | def _create_grammar_state(self,
world: WikiTablesWorld,
possible_actions: List[ProductionRule],
linking_scores: torch.Tensor,
entity_types: torch.Tensor) -> LambdaGrammarStatelet:
"""
... | [
"def",
"_create_grammar_state",
"(",
"self",
",",
"world",
":",
"WikiTablesWorld",
",",
"possible_actions",
":",
"List",
"[",
"ProductionRule",
"]",
",",
"linking_scores",
":",
"torch",
".",
"Tensor",
",",
"entity_types",
":",
"torch",
".",
"Tensor",
")",
"->"... | This method creates the LambdaGrammarStatelet object that's used for decoding. Part of
creating that is creating the `valid_actions` dictionary, which contains embedded
representations of all of the valid actions. So, we create that here as well.
The way we represent the valid expansions is a... | [
"This",
"method",
"creates",
"the",
"LambdaGrammarStatelet",
"object",
"that",
"s",
"used",
"for",
"decoding",
".",
"Part",
"of",
"creating",
"that",
"is",
"creating",
"the",
"valid_actions",
"dictionary",
"which",
"contains",
"embedded",
"representations",
"of",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L513-L620 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser._compute_validation_outputs | def _compute_validation_outputs(self,
actions: List[List[ProductionRule]],
best_final_states: Mapping[int, Sequence[GrammarBasedState]],
world: List[WikiTablesWorld],
example_l... | python | def _compute_validation_outputs(self,
actions: List[List[ProductionRule]],
best_final_states: Mapping[int, Sequence[GrammarBasedState]],
world: List[WikiTablesWorld],
example_l... | [
"def",
"_compute_validation_outputs",
"(",
"self",
",",
"actions",
":",
"List",
"[",
"List",
"[",
"ProductionRule",
"]",
"]",
",",
"best_final_states",
":",
"Mapping",
"[",
"int",
",",
"Sequence",
"[",
"GrammarBasedState",
"]",
"]",
",",
"world",
":",
"List"... | Does common things for validation time: computing logical form accuracy (which is expensive
and unnecessary during training), adding visualization info to the output dictionary, etc.
This doesn't return anything; instead it `modifies` the given ``outputs`` dictionary, and
calls metrics on ``sel... | [
"Does",
"common",
"things",
"for",
"validation",
"time",
":",
"computing",
"logical",
"form",
"accuracy",
"(",
"which",
"is",
"expensive",
"and",
"unnecessary",
"during",
"training",
")",
"adding",
"visualization",
"info",
"to",
"the",
"output",
"dictionary",
"e... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L622-L673 | train |
allenai/allennlp | allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py | WikiTablesSemanticParser.decode | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder... | python | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder... | [
"def",
"decode",
"(",
"self",
",",
"output_dict",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"action_mapping",
"=",
"output_dict",
"[",
"'action_mapping'",
"]",
"best... | This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder", where that decoder logic lives in the ``TransitionFunction``.
This method trims the output ... | [
"This",
"method",
"overrides",
"Model",
".",
"decode",
"which",
"gets",
"called",
"after",
"Model",
".",
"forward",
"at",
"test",
"time",
"to",
"finalize",
"predictions",
".",
"This",
"is",
"(",
"confusingly",
")",
"a",
"separate",
"notion",
"from",
"the",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L676-L708 | train |
allenai/allennlp | allennlp/state_machines/transition_functions/linking_coverage_transition_function.py | LinkingCoverageTransitionFunction._get_linked_logits_addition | def _get_linked_logits_addition(checklist_state: ChecklistStatelet,
action_ids: List[int],
action_logits: torch.Tensor) -> torch.Tensor:
"""
Gets the logits of desired terminal actions yet to be produced by the decoder, and
... | python | def _get_linked_logits_addition(checklist_state: ChecklistStatelet,
action_ids: List[int],
action_logits: torch.Tensor) -> torch.Tensor:
"""
Gets the logits of desired terminal actions yet to be produced by the decoder, and
... | [
"def",
"_get_linked_logits_addition",
"(",
"checklist_state",
":",
"ChecklistStatelet",
",",
"action_ids",
":",
"List",
"[",
"int",
"]",
",",
"action_logits",
":",
"torch",
".",
"Tensor",
")",
"->",
"torch",
".",
"Tensor",
":",
"# Our basic approach here will be to ... | Gets the logits of desired terminal actions yet to be produced by the decoder, and
returns them for the decoder to add to the prior action logits, biasing the model towards
predicting missing linked actions. | [
"Gets",
"the",
"logits",
"of",
"desired",
"terminal",
"actions",
"yet",
"to",
"be",
"produced",
"by",
"the",
"decoder",
"and",
"returns",
"them",
"for",
"the",
"decoder",
"to",
"add",
"to",
"the",
"prior",
"action",
"logits",
"biasing",
"the",
"model",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/linking_coverage_transition_function.py#L161-L196 | train |
allenai/allennlp | allennlp/state_machines/transition_functions/basic_transition_function.py | BasicTransitionFunction.attend_on_question | def attend_on_question(self,
query: torch.Tensor,
encoder_outputs: torch.Tensor,
encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a query (which is typically the decoder hidden state), comp... | python | def attend_on_question(self,
query: torch.Tensor,
encoder_outputs: torch.Tensor,
encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a query (which is typically the decoder hidden state), comp... | [
"def",
"attend_on_question",
"(",
"self",
",",
"query",
":",
"torch",
".",
"Tensor",
",",
"encoder_outputs",
":",
"torch",
".",
"Tensor",
",",
"encoder_output_mask",
":",
"torch",
".",
"Tensor",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch"... | Given a query (which is typically the decoder hidden state), compute an attention over the
output of the question encoder, and return a weighted sum of the question representations
given this attention. We also return the attention weights themselves.
This is a simple computation, but we have ... | [
"Given",
"a",
"query",
"(",
"which",
"is",
"typically",
"the",
"decoder",
"hidden",
"state",
")",
"compute",
"an",
"attention",
"over",
"the",
"output",
"of",
"the",
"question",
"encoder",
"and",
"return",
"a",
"weighted",
"sum",
"of",
"the",
"question",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/basic_transition_function.py#L393-L412 | train |
allenai/allennlp | allennlp/semparse/action_space_walker.py | ActionSpaceWalker._walk | def _walk(self) -> None:
"""
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
"""
# Buffer of NTs to expand, previous actions
incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
s... | python | def _walk(self) -> None:
"""
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
"""
# Buffer of NTs to expand, previous actions
incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
s... | [
"def",
"_walk",
"(",
"self",
")",
"->",
"None",
":",
"# Buffer of NTs to expand, previous actions",
"incomplete_paths",
"=",
"[",
"(",
"[",
"str",
"(",
"type_",
")",
"]",
",",
"[",
"f\"{START_SYMBOL} -> {type_}\"",
"]",
")",
"for",
"type_",
"in",
"self",
".",
... | Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. | [
"Walk",
"over",
"action",
"space",
"to",
"collect",
"completed",
"paths",
"of",
"at",
"most",
"self",
".",
"_max_path_length",
"steps",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/action_space_walker.py#L35-L101 | train |
allenai/allennlp | allennlp/data/dataset.py | Batch._check_types | def _check_types(self) -> None:
"""
Check that all the instances have the same types.
"""
all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__
for k, v in x.fields.items()}
... | python | def _check_types(self) -> None:
"""
Check that all the instances have the same types.
"""
all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__
for k, v in x.fields.items()}
... | [
"def",
"_check_types",
"(",
"self",
")",
"->",
"None",
":",
"all_instance_fields_and_types",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"[",
"{",
"k",
":",
"v",
".",
"__class__",
".",
"__name__",
"for",
"k",
",",
"v",
"in",
"x... | Check that all the instances have the same types. | [
"Check",
"that",
"all",
"the",
"instances",
"have",
"the",
"same",
"types",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L35-L44 | train |
allenai/allennlp | allennlp/data/dataset.py | Batch.get_padding_lengths | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and ... | python | def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and ... | [
"def",
"get_padding_lengths",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"padding_lengths",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"defaultdict",
"(",
"dict"... | Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and find the max values for each (field_name,
padding_key) pair, returning t... | [
"Gets",
"the",
"maximum",
"padding",
"lengths",
"from",
"all",
"Instances",
"in",
"this",
"batch",
".",
"Each",
"Instance",
"has",
"multiple",
"Fields",
"and",
"each",
"Field",
"could",
"have",
"multiple",
"things",
"that",
"need",
"padding",
".",
"We",
"loo... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L46-L69 | train |
allenai/allennlp | allennlp/data/dataset.py | Batch.as_tensor_dict | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None,
verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
# This complex return type is actually predefined elsewhere as a DataArray,
# but we can't use it b... | python | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None,
verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
# This complex return type is actually predefined elsewhere as a DataArray,
# but we can't use it b... | [
"def",
"as_tensor_dict",
"(",
"self",
",",
"padding_lengths",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"None",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"Union",
"[",
"torch",... | This method converts this ``Batch`` into a set of pytorch Tensors that can be passed
through a model. In order for the tensors to be valid tensors, all ``Instances`` in this
batch need to be padded to the same lengths wherever padding is necessary, so we do that
first, then we combine all of th... | [
"This",
"method",
"converts",
"this",
"Batch",
"into",
"a",
"set",
"of",
"pytorch",
"Tensors",
"that",
"can",
"be",
"passed",
"through",
"a",
"model",
".",
"In",
"order",
"for",
"the",
"tensors",
"to",
"be",
"valid",
"tensors",
"all",
"Instances",
"in",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L71-L148 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | get_strings_from_utterance | def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
Based on the current utterance, return a dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to.
"""
string_linking_scores: Dict[str, List[i... | python | def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]:
"""
Based on the current utterance, return a dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to.
"""
string_linking_scores: Dict[str, List[i... | [
"def",
"get_strings_from_utterance",
"(",
"tokenized_utterance",
":",
"List",
"[",
"Token",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"int",
"]",
"]",
":",
"string_linking_scores",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"int",
"]",
"]",
... | Based on the current utterance, return a dictionary where the keys are the strings in
the database that map to lists of the token indices that they are linked to. | [
"Based",
"on",
"the",
"current",
"utterance",
"return",
"a",
"dictionary",
"where",
"the",
"keys",
"are",
"the",
"strings",
"in",
"the",
"database",
"that",
"map",
"to",
"lists",
"of",
"the",
"token",
"indices",
"that",
"they",
"are",
"linked",
"to",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L15-L42 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld._update_grammar | def _update_grammar(self):
"""
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we ... | python | def _update_grammar(self):
"""
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we ... | [
"def",
"_update_grammar",
"(",
"self",
")",
":",
"# This will give us a shallow copy. We have to be careful here because the ``Grammar`` object",
"# contains ``Expression`` objects that have tuples containing the members of that expression.",
"# We have to create new sub-expression objects so that o... | We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we don't have to create
a new grammar from... | [
"We",
"create",
"a",
"new",
"Grammar",
"object",
"from",
"the",
"one",
"in",
"AtisSqlTableContext",
"that",
"also",
"has",
"the",
"new",
"entities",
"that",
"are",
"extracted",
"from",
"the",
"utterance",
".",
"Stitching",
"together",
"the",
"expressions",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L83-L183 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld._update_expression_reference | def _update_expression_reference(self, # pylint: disable=no-self-use
grammar: Grammar,
parent_expression_nonterminal: str,
child_expression_nonterminal: str) -> None:
"""
When we add a new expr... | python | def _update_expression_reference(self, # pylint: disable=no-self-use
grammar: Grammar,
parent_expression_nonterminal: str,
child_expression_nonterminal: str) -> None:
"""
When we add a new expr... | [
"def",
"_update_expression_reference",
"(",
"self",
",",
"# pylint: disable=no-self-use",
"grammar",
":",
"Grammar",
",",
"parent_expression_nonterminal",
":",
"str",
",",
"child_expression_nonterminal",
":",
"str",
")",
"->",
"None",
":",
"grammar",
"[",
"parent_expres... | When we add a new expression, there may be other expressions that refer to
it, and we need to update those to point to the new expression. | [
"When",
"we",
"add",
"a",
"new",
"expression",
"there",
"may",
"be",
"other",
"expressions",
"that",
"refer",
"to",
"it",
"and",
"we",
"need",
"to",
"update",
"those",
"to",
"point",
"to",
"the",
"new",
"expression",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L198-L209 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld._get_sequence_with_spacing | def _get_sequence_with_spacing(self, # pylint: disable=no-self-use
new_grammar,
expressions: List[Expression],
name: str = '') -> Sequence:
"""
This is a helper method for generating sequences, since... | python | def _get_sequence_with_spacing(self, # pylint: disable=no-self-use
new_grammar,
expressions: List[Expression],
name: str = '') -> Sequence:
"""
This is a helper method for generating sequences, since... | [
"def",
"_get_sequence_with_spacing",
"(",
"self",
",",
"# pylint: disable=no-self-use",
"new_grammar",
",",
"expressions",
":",
"List",
"[",
"Expression",
"]",
",",
"name",
":",
"str",
"=",
"''",
")",
"->",
"Sequence",
":",
"expressions",
"=",
"[",
"subexpressio... | This is a helper method for generating sequences, since we often want a list of expressions
with whitespaces between them. | [
"This",
"is",
"a",
"helper",
"method",
"for",
"generating",
"sequences",
"since",
"we",
"often",
"want",
"a",
"list",
"of",
"expressions",
"with",
"whitespaces",
"between",
"them",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L211-L222 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld.add_to_number_linking_scores | def add_to_number_linking_scores(self,
all_numbers: Set[str],
number_linking_scores: Dict[str, Tuple[str, str, List[int]]],
get_number_linking_dict: Callable[[str, List[Token]],
... | python | def add_to_number_linking_scores(self,
all_numbers: Set[str],
number_linking_scores: Dict[str, Tuple[str, str, List[int]]],
get_number_linking_dict: Callable[[str, List[Token]],
... | [
"def",
"add_to_number_linking_scores",
"(",
"self",
",",
"all_numbers",
":",
"Set",
"[",
"str",
"]",
",",
"number_linking_scores",
":",
"Dict",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"List",
"[",
"int",
"]",
"]",
"]",
",",
"get_number_lin... | This is a helper method for adding different types of numbers (eg. starting time ranges) as entities.
We first go through all utterances in the interaction and find the numbers of a certain type and add
them to the set ``all_numbers``, which is initialized with default values. We want to add all numbers... | [
"This",
"is",
"a",
"helper",
"method",
"for",
"adding",
"different",
"types",
"of",
"numbers",
"(",
"eg",
".",
"starting",
"time",
"ranges",
")",
"as",
"entities",
".",
"We",
"first",
"go",
"through",
"all",
"utterances",
"in",
"the",
"interaction",
"and",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L274-L302 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld._get_linked_entities | def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]:
"""
This method gets entities from the current utterance finds which tokens they are linked to.
The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these
entities later ... | python | def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]:
"""
This method gets entities from the current utterance finds which tokens they are linked to.
The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these
entities later ... | [
"def",
"_get_linked_entities",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
",",
"List",
"[",
"int",
"]",
"]",
"]",
"]",
":",
"current_tokenized_utterance",
"=",
"[",
"]",
"if",
"not",
"... | This method gets entities from the current utterance finds which tokens they are linked to.
The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these
entities later for updating the valid actions and the grammar. | [
"This",
"method",
"gets",
"entities",
"from",
"the",
"current",
"utterance",
"finds",
"which",
"tokens",
"they",
"are",
"linked",
"to",
".",
"The",
"entities",
"are",
"divided",
"into",
"two",
"main",
"groups",
"numbers",
"and",
"strings",
".",
"We",
"rely",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L305-L381 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld.all_possible_actions | def all_possible_actions(self) -> List[str]:
"""
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side]
"""
all_actions = set()
for _, action_list in self.valid_actions.items():
for action in action_list... | python | def all_possible_actions(self) -> List[str]:
"""
Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side]
"""
all_actions = set()
for _, action_list in self.valid_actions.items():
for action in action_list... | [
"def",
"all_possible_actions",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"all_actions",
"=",
"set",
"(",
")",
"for",
"_",
",",
"action_list",
"in",
"self",
".",
"valid_actions",
".",
"items",
"(",
")",
":",
"for",
"action",
"in",
"action_li... | Return a sorted list of strings representing all possible actions
of the form: nonterminal -> [right_hand_side] | [
"Return",
"a",
"sorted",
"list",
"of",
"strings",
"representing",
"all",
"possible",
"actions",
"of",
"the",
"form",
":",
"nonterminal",
"-",
">",
"[",
"right_hand_side",
"]"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L413-L422 | train |
allenai/allennlp | allennlp/semparse/worlds/atis_world.py | AtisWorld._flatten_entities | def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]:
"""
When we first get the entities and the linking scores in ``_get_linked_entities``
we represent as dictionaries for easier updates to the grammar and valid actions.
In this method, we flatten them for the model so that th... | python | def _flatten_entities(self) -> Tuple[List[str], numpy.ndarray]:
"""
When we first get the entities and the linking scores in ``_get_linked_entities``
we represent as dictionaries for easier updates to the grammar and valid actions.
In this method, we flatten them for the model so that th... | [
"def",
"_flatten_entities",
"(",
"self",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"numpy",
".",
"ndarray",
"]",
":",
"entities",
"=",
"[",
"]",
"linking_scores",
"=",
"[",
"]",
"for",
"entity",
"in",
"sorted",
"(",
"self",
".",
"linked_... | When we first get the entities and the linking scores in ``_get_linked_entities``
we represent as dictionaries for easier updates to the grammar and valid actions.
In this method, we flatten them for the model so that the entities are represented as
a list, and the linking scores are a 2D numpy ... | [
"When",
"we",
"first",
"get",
"the",
"entities",
"and",
"the",
"linking",
"scores",
"in",
"_get_linked_entities",
"we",
"represent",
"as",
"dictionaries",
"for",
"easier",
"updates",
"to",
"the",
"grammar",
"and",
"valid",
"actions",
".",
"In",
"this",
"method... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L424-L441 | train |
allenai/allennlp | allennlp/service/config_explorer.py | make_app | def make_app(include_packages: Sequence[str] = ()) -> Flask:
"""
Creates a Flask app that serves up a simple configuration wizard.
"""
# Load modules
for package_name in include_packages:
import_submodules(package_name)
app = Flask(__name__) # pylint: disable=invalid-name
@app.err... | python | def make_app(include_packages: Sequence[str] = ()) -> Flask:
"""
Creates a Flask app that serves up a simple configuration wizard.
"""
# Load modules
for package_name in include_packages:
import_submodules(package_name)
app = Flask(__name__) # pylint: disable=invalid-name
@app.err... | [
"def",
"make_app",
"(",
"include_packages",
":",
"Sequence",
"[",
"str",
"]",
"=",
"(",
")",
")",
"->",
"Flask",
":",
"# Load modules",
"for",
"package_name",
"in",
"include_packages",
":",
"import_submodules",
"(",
"package_name",
")",
"app",
"=",
"Flask",
... | Creates a Flask app that serves up a simple configuration wizard. | [
"Creates",
"a",
"Flask",
"app",
"that",
"serves",
"up",
"a",
"simple",
"configuration",
"wizard",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/config_explorer.py#L31-L105 | train |
allenai/allennlp | allennlp/commands/train.py | train_model_from_args | def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
train_model_from_file(args.param_path,
args.serialization_dir,
args.overrides,
args.file_friendl... | python | def train_model_from_args(args: argparse.Namespace):
"""
Just converts from an ``argparse.Namespace`` object to string paths.
"""
train_model_from_file(args.param_path,
args.serialization_dir,
args.overrides,
args.file_friendl... | [
"def",
"train_model_from_args",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
":",
"train_model_from_file",
"(",
"args",
".",
"param_path",
",",
"args",
".",
"serialization_dir",
",",
"args",
".",
"overrides",
",",
"args",
".",
"file_friendly_logging",
",... | Just converts from an ``argparse.Namespace`` object to string paths. | [
"Just",
"converts",
"from",
"an",
"argparse",
".",
"Namespace",
"object",
"to",
"string",
"paths",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L105-L116 | train |
allenai/allennlp | allennlp/commands/train.py | train_model_from_file | def train_model_from_file(parameter_filename: str,
serialization_dir: str,
overrides: str = "",
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
... | python | def train_model_from_file(parameter_filename: str,
serialization_dir: str,
overrides: str = "",
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
... | [
"def",
"train_model_from_file",
"(",
"parameter_filename",
":",
"str",
",",
"serialization_dir",
":",
"str",
",",
"overrides",
":",
"str",
"=",
"\"\"",
",",
"file_friendly_logging",
":",
"bool",
"=",
"False",
",",
"recover",
":",
"bool",
"=",
"False",
",",
"... | A wrapper around :func:`train_model` which loads the params from a file.
Parameters
----------
parameter_filename : ``str``
A json parameter file specifying an AllenNLP experiment.
serialization_dir : ``str``
The directory in which to save results and logs. We just pass this along to
... | [
"A",
"wrapper",
"around",
":",
"func",
":",
"train_model",
"which",
"loads",
"the",
"params",
"from",
"a",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L119-L160 | train |
allenai/allennlp | allennlp/commands/train.py | train_model | def train_model(params: Params,
serialization_dir: str,
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
cache_directory: str = None,
cache_prefix: str = None) -> Model:
"""
Trains the... | python | def train_model(params: Params,
serialization_dir: str,
file_friendly_logging: bool = False,
recover: bool = False,
force: bool = False,
cache_directory: str = None,
cache_prefix: str = None) -> Model:
"""
Trains the... | [
"def",
"train_model",
"(",
"params",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"file_friendly_logging",
":",
"bool",
"=",
"False",
",",
"recover",
":",
"bool",
"=",
"False",
",",
"force",
":",
"bool",
"=",
"False",
",",
"cache_directory",
"... | Trains the model specified in the given :class:`Params` object, using the data and training
parameters also specified in that object, and saves the results in ``serialization_dir``.
Parameters
----------
params : ``Params``
A parameter object specifying an AllenNLP Experiment.
serialization... | [
"Trains",
"the",
"model",
"specified",
"in",
"the",
"given",
":",
"class",
":",
"Params",
"object",
"using",
"the",
"data",
"and",
"training",
"parameters",
"also",
"specified",
"in",
"that",
"object",
"and",
"saves",
"the",
"results",
"in",
"serialization_dir... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/train.py#L163-L269 | train |
allenai/allennlp | allennlp/training/metrics/fbeta_measure.py | _prf_divide | def _prf_divide(numerator, denominator):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero.
"""
result = numerator / denominator
mask = denominator == 0.0
if not mask.any():
return result
# remove nan
result[mask] ... | python | def _prf_divide(numerator, denominator):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero.
"""
result = numerator / denominator
mask = denominator == 0.0
if not mask.any():
return result
# remove nan
result[mask] ... | [
"def",
"_prf_divide",
"(",
"numerator",
",",
"denominator",
")",
":",
"result",
"=",
"numerator",
"/",
"denominator",
"mask",
"=",
"denominator",
"==",
"0.0",
"if",
"not",
"mask",
".",
"any",
"(",
")",
":",
"return",
"result",
"# remove nan",
"result",
"["... | Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero. | [
"Performs",
"division",
"and",
"handles",
"divide",
"-",
"by",
"-",
"zero",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/fbeta_measure.py#L231-L243 | train |
allenai/allennlp | tutorials/tagger/basic_pytorch.py | load_data | def load_data(file_path: str) -> Tuple[List[str], List[str]]:
"""
One sentence per line, formatted like
The###DET dog###NN ate###V the###DET apple###NN
Returns a list of pairs (tokenized_sentence, tags)
"""
data = []
with open(file_path) as f:
for line in f:
pairs ... | python | def load_data(file_path: str) -> Tuple[List[str], List[str]]:
"""
One sentence per line, formatted like
The###DET dog###NN ate###V the###DET apple###NN
Returns a list of pairs (tokenized_sentence, tags)
"""
data = []
with open(file_path) as f:
for line in f:
pairs ... | [
"def",
"load_data",
"(",
"file_path",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"data",
"=",
"[",
"]",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
... | One sentence per line, formatted like
The###DET dog###NN ate###V the###DET apple###NN
Returns a list of pairs (tokenized_sentence, tags) | [
"One",
"sentence",
"per",
"line",
"formatted",
"like"
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/tutorials/tagger/basic_pytorch.py#L23-L39 | train |
allenai/allennlp | allennlp/data/vocabulary.py | pop_max_vocab_size | def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]:
"""
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.
max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).
But it could also be a string representing an int (in the case... | python | def pop_max_vocab_size(params: Params) -> Union[int, Dict[str, int]]:
"""
max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.
max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).
But it could also be a string representing an int (in the case... | [
"def",
"pop_max_vocab_size",
"(",
"params",
":",
"Params",
")",
"->",
"Union",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"size",
"=",
"params",
".",
"pop",
"(",
"\"max_vocab_size\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"s... | max_vocab_size limits the size of the vocabulary, not including the @@UNKNOWN@@ token.
max_vocab_size is allowed to be either an int or a Dict[str, int] (or nothing).
But it could also be a string representing an int (in the case of environment variable
substitution). So we need some complex logic to handl... | [
"max_vocab_size",
"limits",
"the",
"size",
"of",
"the",
"vocabulary",
"not",
"including",
"the",
"@@UNKNOWN@@",
"token",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L117-L134 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.save_to_files | def save_to_files(self, directory: str) -> None:
"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
... | python | def save_to_files(self, directory: str) -> None:
"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
... | [
"def",
"save_to_files",
"(",
"self",
",",
"directory",
":",
"str",
")",
"->",
"None",
":",
"os",
".",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"if",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"logging",
".",
"warning",
... | Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary. | [
"Persist",
"this",
"Vocabulary",
"to",
"files",
"so",
"it",
"can",
"be",
"reloaded",
"later",
".",
"Each",
"namespace",
"corresponds",
"to",
"one",
"file",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L270-L294 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.from_files | def from_files(cls, directory: str) -> 'Vocabulary':
"""
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
"""
logger.info("Loading token d... | python | def from_files(cls, directory: str) -> 'Vocabulary':
"""
Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary.
"""
logger.info("Loading token d... | [
"def",
"from_files",
"(",
"cls",
",",
"directory",
":",
"str",
")",
"->",
"'Vocabulary'",
":",
"logger",
".",
"info",
"(",
"\"Loading token dictionary from %s.\"",
",",
"directory",
")",
"with",
"codecs",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"... | Loads a ``Vocabulary`` that was serialized using ``save_to_files``.
Parameters
----------
directory : ``str``
The directory containing the serialized vocabulary. | [
"Loads",
"a",
"Vocabulary",
"that",
"was",
"serialized",
"using",
"save_to_files",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L297-L326 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.set_from_file | def set_from_file(self,
filename: str,
is_padded: bool = True,
oov_token: str = DEFAULT_OOV_TOKEN,
namespace: str = "tokens"):
"""
If you already have a vocabulary file for a trained model somewhere, and you really w... | python | def set_from_file(self,
filename: str,
is_padded: bool = True,
oov_token: str = DEFAULT_OOV_TOKEN,
namespace: str = "tokens"):
"""
If you already have a vocabulary file for a trained model somewhere, and you really w... | [
"def",
"set_from_file",
"(",
"self",
",",
"filename",
":",
"str",
",",
"is_padded",
":",
"bool",
"=",
"True",
",",
"oov_token",
":",
"str",
"=",
"DEFAULT_OOV_TOKEN",
",",
"namespace",
":",
"str",
"=",
"\"tokens\"",
")",
":",
"if",
"is_padded",
":",
"self... | If you already have a vocabulary file for a trained model somewhere, and you really want to
use that vocabulary file instead of just setting the vocabulary from a dataset, for
whatever reason, you can do that with this method. You must specify the namespace to use,
and we assume that you want t... | [
"If",
"you",
"already",
"have",
"a",
"vocabulary",
"file",
"for",
"a",
"trained",
"model",
"somewhere",
"and",
"you",
"really",
"want",
"to",
"use",
"that",
"vocabulary",
"file",
"instead",
"of",
"just",
"setting",
"the",
"vocabulary",
"from",
"a",
"dataset"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L328-L378 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.from_instances | def from_instances(cls,
instances: Iterable['adi.Instance'],
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
... | python | def from_instances(cls,
instances: Iterable['adi.Instance'],
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
... | [
"def",
"from_instances",
"(",
"cls",
",",
"instances",
":",
"Iterable",
"[",
"'adi.Instance'",
"]",
",",
"min_count",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"max_vocab_size",
":",
"Union",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
... | Constructs a vocabulary given a collection of `Instances` and some parameters.
We count all of the vocabulary items in the instances, then pass those counts
and the other parameters, to :func:`__init__`. See that method for a description
of what the other parameters do. | [
"Constructs",
"a",
"vocabulary",
"given",
"a",
"collection",
"of",
"Instances",
"and",
"some",
"parameters",
".",
"We",
"count",
"all",
"of",
"the",
"vocabulary",
"items",
"in",
"the",
"instances",
"then",
"pass",
"those",
"counts",
"and",
"the",
"other",
"p... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L381-L408 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.from_params | def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore
"""
There are two possible ways to build a vocabulary; from a
collection of instances, using :func:`Vocabulary.from_instances`, or
from a pre-saved vocabulary, using :func:`Vocabulary.from_f... | python | def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore
"""
There are two possible ways to build a vocabulary; from a
collection of instances, using :func:`Vocabulary.from_instances`, or
from a pre-saved vocabulary, using :func:`Vocabulary.from_f... | [
"def",
"from_params",
"(",
"cls",
",",
"params",
":",
"Params",
",",
"instances",
":",
"Iterable",
"[",
"'adi.Instance'",
"]",
"=",
"None",
")",
":",
"# type: ignore",
"# pylint: disable=arguments-differ",
"# Vocabulary is ``Registrable`` so that you can configure a custom ... | There are two possible ways to build a vocabulary; from a
collection of instances, using :func:`Vocabulary.from_instances`, or
from a pre-saved vocabulary, using :func:`Vocabulary.from_files`.
You can also extend pre-saved vocabulary with collection of instances
using this method. This m... | [
"There",
"are",
"two",
"possible",
"ways",
"to",
"build",
"a",
"vocabulary",
";",
"from",
"a",
"collection",
"of",
"instances",
"using",
":",
"func",
":",
"Vocabulary",
".",
"from_instances",
"or",
"from",
"a",
"pre",
"-",
"saved",
"vocabulary",
"using",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L412-L487 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary._extend | def _extend(self,
counter: Dict[str, Dict[str, int]] = None,
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
pretrained_files: Option... | python | def _extend(self,
counter: Dict[str, Dict[str, int]] = None,
min_count: Dict[str, int] = None,
max_vocab_size: Union[int, Dict[str, int]] = None,
non_padded_namespaces: Iterable[str] = DEFAULT_NON_PADDED_NAMESPACES,
pretrained_files: Option... | [
"def",
"_extend",
"(",
"self",
",",
"counter",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"None",
",",
"min_count",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"max_vocab_size",
":",
"Union",
"[",... | This method can be used for extending already generated vocabulary.
It takes same parameters as Vocabulary initializer. The token2index
and indextotoken mappings of calling vocabulary will be retained.
It is an inplace operation so None will be returned. | [
"This",
"method",
"can",
"be",
"used",
"for",
"extending",
"already",
"generated",
"vocabulary",
".",
"It",
"takes",
"same",
"parameters",
"as",
"Vocabulary",
"initializer",
".",
"The",
"token2index",
"and",
"indextotoken",
"mappings",
"of",
"calling",
"vocabulary... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L489-L567 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.extend_from_instances | def extend_from_instances(self,
params: Params,
instances: Iterable['adi.Instance'] = ()) -> None:
"""
Extends an already generated vocabulary using a collection of instances.
"""
min_count = params.pop("min_count", None)
... | python | def extend_from_instances(self,
params: Params,
instances: Iterable['adi.Instance'] = ()) -> None:
"""
Extends an already generated vocabulary using a collection of instances.
"""
min_count = params.pop("min_count", None)
... | [
"def",
"extend_from_instances",
"(",
"self",
",",
"params",
":",
"Params",
",",
"instances",
":",
"Iterable",
"[",
"'adi.Instance'",
"]",
"=",
"(",
")",
")",
"->",
"None",
":",
"min_count",
"=",
"params",
".",
"pop",
"(",
"\"min_count\"",
",",
"None",
")... | Extends an already generated vocabulary using a collection of instances. | [
"Extends",
"an",
"already",
"generated",
"vocabulary",
"using",
"a",
"collection",
"of",
"instances",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L569-L595 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.is_padded | def is_padded(self, namespace: str) -> bool:
"""
Returns whether or not there are padding and OOV tokens added to the given namespace.
"""
return self._index_to_token[namespace][0] == self._padding_token | python | def is_padded(self, namespace: str) -> bool:
"""
Returns whether or not there are padding and OOV tokens added to the given namespace.
"""
return self._index_to_token[namespace][0] == self._padding_token | [
"def",
"is_padded",
"(",
"self",
",",
"namespace",
":",
"str",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_index_to_token",
"[",
"namespace",
"]",
"[",
"0",
"]",
"==",
"self",
".",
"_padding_token"
] | Returns whether or not there are padding and OOV tokens added to the given namespace. | [
"Returns",
"whether",
"or",
"not",
"there",
"are",
"padding",
"and",
"OOV",
"tokens",
"added",
"to",
"the",
"given",
"namespace",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L597-L601 | train |
allenai/allennlp | allennlp/data/vocabulary.py | Vocabulary.add_token_to_namespace | def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int:
"""
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token.
"""
if not isinstance(token, str):
raise ValueError("Vocabulary tokens must be... | python | def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int:
"""
Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token.
"""
if not isinstance(token, str):
raise ValueError("Vocabulary tokens must be... | [
"def",
"add_token_to_namespace",
"(",
"self",
",",
"token",
":",
"str",
",",
"namespace",
":",
"str",
"=",
"'tokens'",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"Vocabulary tokens mu... | Adds ``token`` to the index, if it is not already present. Either way, we return the index of
the token. | [
"Adds",
"token",
"to",
"the",
"index",
"if",
"it",
"is",
"not",
"already",
"present",
".",
"Either",
"way",
"we",
"return",
"the",
"index",
"of",
"the",
"token",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L603-L617 | train |
allenai/allennlp | allennlp/models/model.py | Model.get_regularization_penalty | def get_regularization_penalty(self) -> Union[float, torch.Tensor]:
"""
Computes the regularization penalty for the model.
Returns 0 if the model was not configured to use regularization.
"""
if self._regularizer is None:
return 0.0
else:
return se... | python | def get_regularization_penalty(self) -> Union[float, torch.Tensor]:
"""
Computes the regularization penalty for the model.
Returns 0 if the model was not configured to use regularization.
"""
if self._regularizer is None:
return 0.0
else:
return se... | [
"def",
"get_regularization_penalty",
"(",
"self",
")",
"->",
"Union",
"[",
"float",
",",
"torch",
".",
"Tensor",
"]",
":",
"if",
"self",
".",
"_regularizer",
"is",
"None",
":",
"return",
"0.0",
"else",
":",
"return",
"self",
".",
"_regularizer",
"(",
"se... | Computes the regularization penalty for the model.
Returns 0 if the model was not configured to use regularization. | [
"Computes",
"the",
"regularization",
"penalty",
"for",
"the",
"model",
".",
"Returns",
"0",
"if",
"the",
"model",
"was",
"not",
"configured",
"to",
"use",
"regularization",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L58-L66 | train |
allenai/allennlp | allennlp/models/model.py | Model.forward_on_instance | def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]:
"""
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
through :func:`self.forwar... | python | def forward_on_instance(self, instance: Instance) -> Dict[str, numpy.ndarray]:
"""
Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
through :func:`self.forwar... | [
"def",
"forward_on_instance",
"(",
"self",
",",
"instance",
":",
"Instance",
")",
"->",
"Dict",
"[",
"str",
",",
"numpy",
".",
"ndarray",
"]",
":",
"return",
"self",
".",
"forward_on_instances",
"(",
"[",
"instance",
"]",
")",
"[",
"0",
"]"
] | Takes an :class:`~allennlp.data.instance.Instance`, which typically has raw text in it,
converts that text into arrays using this model's :class:`Vocabulary`, passes those arrays
through :func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
and returns the result. Bef... | [
"Takes",
"an",
":",
"class",
":",
"~allennlp",
".",
"data",
".",
"instance",
".",
"Instance",
"which",
"typically",
"has",
"raw",
"text",
"in",
"it",
"converts",
"that",
"text",
"into",
"arrays",
"using",
"this",
"model",
"s",
":",
"class",
":",
"Vocabul... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L116-L124 | train |
allenai/allennlp | allennlp/models/model.py | Model.forward_on_instances | def forward_on_instances(self,
instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
"""
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:f... | python | def forward_on_instances(self,
instances: List[Instance]) -> List[Dict[str, numpy.ndarray]]:
"""
Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:f... | [
"def",
"forward_on_instances",
"(",
"self",
",",
"instances",
":",
"List",
"[",
"Instance",
"]",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"numpy",
".",
"ndarray",
"]",
"]",
":",
"batch_size",
"=",
"len",
"(",
"instances",
")",
"with",
"torch",
... | Takes a list of :class:`~allennlp.data.instance.Instance`s, converts that text into
arrays using this model's :class:`Vocabulary`, passes those arrays through
:func:`self.forward()` and :func:`self.decode()` (which by default does nothing)
and returns the result. Before returning the result, w... | [
"Takes",
"a",
"list",
"of",
":",
"class",
":",
"~allennlp",
".",
"data",
".",
"instance",
".",
"Instance",
"s",
"converts",
"that",
"text",
"into",
"arrays",
"using",
"this",
"model",
"s",
":",
"class",
":",
"Vocabulary",
"passes",
"those",
"arrays",
"th... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L126-L172 | train |
allenai/allennlp | allennlp/models/model.py | Model.decode | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
Takes the result of :func:`forward` and runs inference / decoding / whatever
post-processing you need to do your model. The intent is that ``model.forward()`` should
produce potentials or probabilitie... | python | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
Takes the result of :func:`forward` and runs inference / decoding / whatever
post-processing you need to do your model. The intent is that ``model.forward()`` should
produce potentials or probabilitie... | [
"def",
"decode",
"(",
"self",
",",
"output_dict",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"# pylint: disable=no-self-use",
"return",
"output_dict"
] | Takes the result of :func:`forward` and runs inference / decoding / whatever
post-processing you need to do your model. The intent is that ``model.forward()`` should
produce potentials or probabilities, and then ``model.decode()`` can take those results and
run some kind of beam search or const... | [
"Takes",
"the",
"result",
"of",
":",
"func",
":",
"forward",
"and",
"runs",
"inference",
"/",
"decoding",
"/",
"whatever",
"post",
"-",
"processing",
"you",
"need",
"to",
"do",
"your",
"model",
".",
"The",
"intent",
"is",
"that",
"model",
".",
"forward",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L174-L189 | train |
allenai/allennlp | allennlp/models/model.py | Model._get_prediction_device | def _get_prediction_device(self) -> int:
"""
This method checks the device of the model parameters to determine the cuda_device
this model should be run on for predictions. If there are no parameters, it returns -1.
Returns
-------
The cuda device this model should run ... | python | def _get_prediction_device(self) -> int:
"""
This method checks the device of the model parameters to determine the cuda_device
this model should be run on for predictions. If there are no parameters, it returns -1.
Returns
-------
The cuda device this model should run ... | [
"def",
"_get_prediction_device",
"(",
"self",
")",
"->",
"int",
":",
"devices",
"=",
"{",
"util",
".",
"get_device_of",
"(",
"param",
")",
"for",
"param",
"in",
"self",
".",
"parameters",
"(",
")",
"}",
"if",
"len",
"(",
"devices",
")",
">",
"1",
":"... | This method checks the device of the model parameters to determine the cuda_device
this model should be run on for predictions. If there are no parameters, it returns -1.
Returns
-------
The cuda device this model should run on for predictions. | [
"This",
"method",
"checks",
"the",
"device",
"of",
"the",
"model",
"parameters",
"to",
"determine",
"the",
"cuda_device",
"this",
"model",
"should",
"be",
"run",
"on",
"for",
"predictions",
".",
"If",
"there",
"are",
"no",
"parameters",
"it",
"returns",
"-",... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L206-L223 | train |
allenai/allennlp | allennlp/models/model.py | Model._maybe_warn_for_unseparable_batches | def _maybe_warn_for_unseparable_batches(self, output_key: str):
"""
This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch. This is controlled
by a class attribute ``_warn_for_unseperable_... | python | def _maybe_warn_for_unseparable_batches(self, output_key: str):
"""
This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch. This is controlled
by a class attribute ``_warn_for_unseperable_... | [
"def",
"_maybe_warn_for_unseparable_batches",
"(",
"self",
",",
"output_key",
":",
"str",
")",
":",
"if",
"output_key",
"not",
"in",
"self",
".",
"_warn_for_unseparable_batches",
":",
"logger",
".",
"warning",
"(",
"f\"Encountered the {output_key} key in the model's retur... | This method warns once if a user implements a model which returns a dictionary with
values which we are unable to split back up into elements of the batch. This is controlled
by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose
otherwise. | [
"This",
"method",
"warns",
"once",
"if",
"a",
"user",
"implements",
"a",
"model",
"which",
"returns",
"a",
"dictionary",
"with",
"values",
"which",
"we",
"are",
"unable",
"to",
"split",
"back",
"up",
"into",
"elements",
"of",
"the",
"batch",
".",
"This",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L225-L237 | train |
allenai/allennlp | allennlp/models/model.py | Model._load | def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
"""
... | python | def _load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
"""
... | [
"def",
"_load",
"(",
"cls",
",",
"config",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"weights_file",
":",
"str",
"=",
"None",
",",
"cuda_device",
":",
"int",
"=",
"-",
"1",
")",
"->",
"'Model'",
":",
"weights_file",
"=",
"weights_file",
... | Instantiates an already-trained model, based on the experiment
configuration and some optional overrides. | [
"Instantiates",
"an",
"already",
"-",
"trained",
"model",
"based",
"on",
"the",
"experiment",
"configuration",
"and",
"some",
"optional",
"overrides",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L240-L285 | train |
allenai/allennlp | allennlp/models/model.py | Model.load | def load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters... | python | def load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters... | [
"def",
"load",
"(",
"cls",
",",
"config",
":",
"Params",
",",
"serialization_dir",
":",
"str",
",",
"weights_file",
":",
"str",
"=",
"None",
",",
"cuda_device",
":",
"int",
"=",
"-",
"1",
")",
"->",
"'Model'",
":",
"# Peak at the class of the model.",
"mod... | Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters
----------
config: Params
The configuration that was used to train the model. It should definitely
have a `model` section, and should probably hav... | [
"Instantiates",
"an",
"already",
"-",
"trained",
"model",
"based",
"on",
"the",
"experiment",
"configuration",
"and",
"some",
"optional",
"overrides",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L288-L327 | train |
allenai/allennlp | allennlp/models/model.py | Model.extend_embedder_vocab | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with... | python | def extend_embedder_vocab(self, embedding_sources_mapping: Dict[str, str] = None) -> None:
"""
Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with... | [
"def",
"extend_embedder_vocab",
"(",
"self",
",",
"embedding_sources_mapping",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"# self.named_modules() gives all sub-modules (including nested children)",
"# The path nesting is already separated b... | Iterates through all embedding modules in the model and assures it can embed
with the extended vocab. This is required in fine-tuning or transfer learning
scenarios where model was trained with original vocabulary but during
fine-tuning/tranfer-learning, it will have it work with extended vocabu... | [
"Iterates",
"through",
"all",
"embedding",
"modules",
"in",
"the",
"model",
"and",
"assures",
"it",
"can",
"embed",
"with",
"the",
"extended",
"vocab",
".",
"This",
"is",
"required",
"in",
"fine",
"-",
"tuning",
"or",
"transfer",
"learning",
"scenarios",
"wh... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L329-L354 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.get_agenda | def get_agenda(self,
conservative: bool = False):
"""
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
conf... | python | def get_agenda(self,
conservative: bool = False):
"""
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
conf... | [
"def",
"get_agenda",
"(",
"self",
",",
"conservative",
":",
"bool",
"=",
"False",
")",
":",
"agenda_items",
"=",
"[",
"]",
"question_tokens",
"=",
"[",
"token",
".",
"text",
"for",
"token",
"in",
"self",
".",
"table_context",
".",
"question_tokens",
"]",
... | Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
confidence lexical matches. You'll need this if you are going to use this agenda to
... | [
"Returns",
"an",
"agenda",
"that",
"can",
"be",
"used",
"guide",
"search",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L145-L321 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.evaluate_logical_form | def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool:
"""
Takes a logical form, and the list of target values as strings from the original lisp
string, and returns True iff the logical form executes to the target list, using the
official WikiTableQuestions e... | python | def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool:
"""
Takes a logical form, and the list of target values as strings from the original lisp
string, and returns True iff the logical form executes to the target list, using the
official WikiTableQuestions e... | [
"def",
"evaluate_logical_form",
"(",
"self",
",",
"logical_form",
":",
"str",
",",
"target_list",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"normalized_target_list",
"=",
"[",
"TableQuestionContext",
".",
"normalize_string",
"(",
"value",
")",
"for... | Takes a logical form, and the list of target values as strings from the original lisp
string, and returns True iff the logical form executes to the target list, using the
official WikiTableQuestions evaluation script. | [
"Takes",
"a",
"logical",
"form",
"and",
"the",
"list",
"of",
"target",
"values",
"as",
"strings",
"from",
"the",
"original",
"lisp",
"string",
"and",
"returns",
"True",
"iff",
"the",
"logical",
"form",
"executes",
"to",
"the",
"target",
"list",
"using",
"t... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L323-L342 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.select_string | def select_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Select function takes a list of rows and a column name and returns a list of strings as
in cells.
"""
return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None] | python | def select_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Select function takes a list of rows and a column name and returns a list of strings as
in cells.
"""
return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None] | [
"def",
"select_string",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"StringColumn",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"str",
"(",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
")",
"f... | Select function takes a list of rows and a column name and returns a list of strings as
in cells. | [
"Select",
"function",
"takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"name",
"and",
"returns",
"a",
"list",
"of",
"strings",
"as",
"in",
"cells",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L354-L359 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.select_number | def select_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None.
"""
numbers: List[float] = []
... | python | def select_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None.
"""
numbers: List[float] = []
... | [
"def",
"select_number",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"numbers",
":",
"List",
"[",
"float",
"]",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"cell_value",
"... | Select function takes a row (as a list) and a column name and returns the number in that
column. If multiple rows are given, will return the first number that is not None. | [
"Select",
"function",
"takes",
"a",
"row",
"(",
"as",
"a",
"list",
")",
"and",
"a",
"column",
"name",
"and",
"returns",
"the",
"number",
"in",
"that",
"column",
".",
"If",
"multiple",
"rows",
"are",
"given",
"will",
"return",
"the",
"first",
"number",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L362-L373 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.select_date | def select_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Select function takes a row as a list and a column name and returns the date in that column.
"""
dates: List[Date] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... | python | def select_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Select function takes a row as a list and a column name and returns the date in that column.
"""
dates: List[Date] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... | [
"def",
"select_date",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"DateColumn",
")",
"->",
"Date",
":",
"dates",
":",
"List",
"[",
"Date",
"]",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"cell_value",
"=",
"ro... | Select function takes a row as a list and a column name and returns the date in that column. | [
"Select",
"function",
"takes",
"a",
"row",
"as",
"a",
"list",
"and",
"a",
"column",
"name",
"and",
"returns",
"the",
"date",
"in",
"that",
"column",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L376-L386 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.same_as | def same_as(self, rows: List[Row], column: Column) -> List[Row]:
"""
Takes a row and a column and returns a list of rows from the full set of rows that contain
the same value under the given column as the given row.
"""
cell_value = rows[0].values[column.name]
return_list... | python | def same_as(self, rows: List[Row], column: Column) -> List[Row]:
"""
Takes a row and a column and returns a list of rows from the full set of rows that contain
the same value under the given column as the given row.
"""
cell_value = rows[0].values[column.name]
return_list... | [
"def",
"same_as",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"Column",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"cell_value",
"=",
"rows",
"[",
"0",
"]",
".",
"values",
"[",
"column",
".",
"name",
"]",
"return_lis... | Takes a row and a column and returns a list of rows from the full set of rows that contain
the same value under the given column as the given row. | [
"Takes",
"a",
"row",
"and",
"a",
"column",
"and",
"returns",
"a",
"list",
"of",
"rows",
"from",
"the",
"full",
"set",
"of",
"rows",
"that",
"contain",
"the",
"same",
"value",
"under",
"the",
"given",
"column",
"as",
"the",
"given",
"row",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L389-L399 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.date | def date(self, year: Number, month: Number, day: Number) -> Date:
"""
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order.
"""
return Date(year, month, day) | python | def date(self, year: Number, month: Number, day: Number) -> Date:
"""
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order.
"""
return Date(year, month, day) | [
"def",
"date",
"(",
"self",
",",
"year",
":",
"Number",
",",
"month",
":",
"Number",
",",
"day",
":",
"Number",
")",
"->",
"Date",
":",
"return",
"Date",
"(",
"year",
",",
"month",
",",
"day",
")"
] | Takes three numbers and returns a ``Date`` object whose year, month, and day are the three
numbers in that order. | [
"Takes",
"three",
"numbers",
"and",
"returns",
"a",
"Date",
"object",
"whose",
"year",
"month",
"and",
"day",
"are",
"the",
"three",
"numbers",
"in",
"that",
"order",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L402-L407 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.first | def first(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the first one in that
list.
"""
if not rows:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... | python | def first(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the first one in that
list.
"""
if not rows:
logger.warning("Trying to get first row from an empty list")
return []
return [rows[0]... | [
"def",
"first",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"logger",
".",
"warning",
"(",
"\"Trying to get first row from an empty list\"",
")",
"return",
"[",
"]",
"return",... | Takes an expression that evaluates to a list of rows, and returns the first one in that
list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"list",
"of",
"rows",
"and",
"returns",
"the",
"first",
"one",
"in",
"that",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L410-L418 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.last | def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] | python | def last(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a list of rows, and returns the last one in that
list.
"""
if not rows:
logger.warning("Trying to get last row from an empty list")
return []
return [rows[-1]] | [
"def",
"last",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"logger",
".",
"warning",
"(",
"\"Trying to get last row from an empty list\"",
")",
"return",
"[",
"]",
"return",
... | Takes an expression that evaluates to a list of rows, and returns the last one in that
list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"list",
"of",
"rows",
"and",
"returns",
"the",
"last",
"one",
"in",
"that",
"list",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L421-L429 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.previous | def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... | python | def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... | [
"def",
"previous",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"input_row_index",
"=",
"self",
".",
"_get_row_index",
"(",
"rows",
"[",
"0",
"]",
"... | Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"single",
"row",
"and",
"returns",
"the",
"row",
"that",
"occurs",
"before",
"the",
"input",
"row",
"in",
"the",
"original",
"set",
"of",
"rows",
".",
"If",
"the",
"input",
"row",
"happens",
"t... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L432-L443 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.next | def next(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list.
"""
if not row... | python | def next(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list.
"""
if not row... | [
"def",
"next",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"input_row_index",
"=",
"self",
".",
"_get_row_index",
"(",
"rows",
"[",
"0",
"]",
")",
... | Takes an expression that evaluates to a single row, and returns the row that occurs after
the input row in the original set of rows. If the input row happens to be the last row, we
will return an empty list. | [
"Takes",
"an",
"expression",
"that",
"evaluates",
"to",
"a",
"single",
"row",
"and",
"returns",
"the",
"row",
"that",
"occurs",
"after",
"the",
"input",
"row",
"in",
"the",
"original",
"set",
"of",
"rows",
".",
"If",
"the",
"input",
"row",
"happens",
"to... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L446-L457 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.mode_string | def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Takes a list of rows and a column and returns the most frequent values (one or more) under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if no... | python | def mode_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Takes a list of rows and a column and returns the most frequent values (one or more) under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if no... | [
"def",
"mode_string",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"StringColumn",
")",
"->",
"List",
"[",
"str",
"]",
":",
"most_frequent_list",
"=",
"self",
".",
"_get_most_frequent_values",
"(",
"rows",
",",
"column",
")... | Takes a list of rows and a column and returns the most frequent values (one or more) under
that column in those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"most",
"frequent",
"values",
"(",
"one",
"or",
"more",
")",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L464-L474 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.mode_number | def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... | python | def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... | [
"def",
"mode_number",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"most_frequent_list",
"=",
"self",
".",
"_get_most_frequent_values",
"(",
"rows",
",",
"column",
")",
"if",
"not",
... | Takes a list of rows and a column and returns the most frequent value under
that column in those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"most",
"frequent",
"value",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L477-L488 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.mode_date | def mode_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
... | python | def mode_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
... | [
"def",
"mode_date",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"DateColumn",
")",
"->",
"Date",
":",
"most_frequent_list",
"=",
"self",
".",
"_get_most_frequent_values",
"(",
"rows",
",",
"column",
")",
"if",
"not",
"most... | Takes a list of rows and a column and returns the most frequent value under
that column in those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"most",
"frequent",
"value",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L491-L502 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.argmax | def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict... | python | def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict... | [
"def",
"argmax",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"ComparableColumn",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"value_row_pairs",
"=",
"[",
"(",
"row",
".",
... | Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"name",
"and",
"returns",
"a",
"list",
"containing",
"a",
"single",
"row",
"(",
"dict",
"from",
"columns",
"to",
"cells",
")",
"that",
"has",
"the",
"maximum",
"numerical",
"value",
"in",
"the",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L507-L520 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.argmin | def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to b... | python | def argmin(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to b... | [
"def",
"argmin",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"ComparableColumn",
")",
"->",
"List",
"[",
"Row",
"]",
":",
"if",
"not",
"rows",
":",
"return",
"[",
"]",
"value_row_pairs",
"=",
"[",
"(",
"row",
".",
... | Takes a list of rows and a column and returns a list containing a single row (dict from
columns to cells) that has the minimum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"a",
"list",
"containing",
"a",
"single",
"row",
"(",
"dict",
"from",
"columns",
"to",
"cells",
")",
"that",
"has",
"the",
"minimum",
"numerical",
"value",
"in",
"the",
"given",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L522-L535 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.max_date | def max_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return Dat... | python | def max_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return Dat... | [
"def",
"max_date",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"DateColumn",
")",
"->",
"Date",
":",
"cell_values",
"=",
"[",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
"for",
"row",
"in",
"rows",
"]",
... | Takes a list of rows and a column and returns the max of the values under that column in
those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"max",
"of",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L676-L686 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.max_number | def max_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
retu... | python | def max_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the max of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
retu... | [
"def",
"max_number",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"cell_values",
"=",
"[",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
"for",
"row",
"in",
"rows",
"... | Takes a list of rows and a column and returns the max of the values under that column in
those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"max",
"of",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L703-L713 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.average | def average(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the mean of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... | python | def average(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the mean of the values under that column in
those rows.
"""
cell_values = [row.values[column.name] for row in rows]
if not cell_values:
return... | [
"def",
"average",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"cell_values",
"=",
"[",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
"for",
"row",
"in",
"rows",
"]",... | Takes a list of rows and a column and returns the mean of the values under that column in
those rows. | [
"Takes",
"a",
"list",
"of",
"rows",
"and",
"a",
"column",
"and",
"returns",
"the",
"mean",
"of",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L737-L745 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage.diff | def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number:
"""
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... | python | def diff(self, first_row: List[Row], second_row: List[Row], column: NumberColumn) -> Number:
"""
Takes a two rows and a number column and returns the difference between the values under
that column in those two rows.
"""
if not first_row or not second_row:
return 0.0 ... | [
"def",
"diff",
"(",
"self",
",",
"first_row",
":",
"List",
"[",
"Row",
"]",
",",
"second_row",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"NumberColumn",
")",
"->",
"Number",
":",
"if",
"not",
"first_row",
"or",
"not",
"second_row",
":",
"retu... | Takes a two rows and a number column and returns the difference between the values under
that column in those two rows. | [
"Takes",
"a",
"two",
"rows",
"and",
"a",
"number",
"column",
"and",
"returns",
"the",
"difference",
"between",
"the",
"values",
"under",
"that",
"column",
"in",
"those",
"two",
"rows",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L747-L759 | train |
allenai/allennlp | allennlp/semparse/domain_languages/wikitables_language.py | WikiTablesLanguage._get_row_index | def _get_row_index(self, row: Row) -> int:
"""
Takes a row and returns its index in the full list of rows. If the row does not occur in the
table (which should never happen because this function will only be called with a row that
is the result of applying one or more functions on the ta... | python | def _get_row_index(self, row: Row) -> int:
"""
Takes a row and returns its index in the full list of rows. If the row does not occur in the
table (which should never happen because this function will only be called with a row that
is the result of applying one or more functions on the ta... | [
"def",
"_get_row_index",
"(",
"self",
",",
"row",
":",
"Row",
")",
"->",
"int",
":",
"row_index",
"=",
"-",
"1",
"for",
"index",
",",
"table_row",
"in",
"enumerate",
"(",
"self",
".",
"table_data",
")",
":",
"if",
"table_row",
".",
"values",
"==",
"r... | Takes a row and returns its index in the full list of rows. If the row does not occur in the
table (which should never happen because this function will only be called with a row that
is the result of applying one or more functions on the table rows), the method returns -1. | [
"Takes",
"a",
"row",
"and",
"returns",
"its",
"index",
"in",
"the",
"full",
"list",
"of",
"rows",
".",
"If",
"the",
"row",
"does",
"not",
"occur",
"in",
"the",
"table",
"(",
"which",
"should",
"never",
"happen",
"because",
"this",
"function",
"will",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L785-L796 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.is_terminal | def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | python | def is_terminal(self, symbol: str) -> bool:
"""
This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol.
"""
... | [
"def",
"is_terminal",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"bool",
":",
"# We special-case 'lambda' here because it behaves weirdly in action sequences.",
"return",
"(",
"symbol",
"in",
"self",
".",
"global_name_mapping",
"or",
"symbol",
"in",
"self",
".... | This function will be called on nodes of a logical form tree, which are either non-terminal
symbols that can be expanded or terminal symbols that must be leaf nodes. Returns ``True``
if the given symbol is a terminal symbol. | [
"This",
"function",
"will",
"be",
"called",
"on",
"nodes",
"of",
"a",
"logical",
"form",
"tree",
"which",
"are",
"either",
"non",
"-",
"terminal",
"symbols",
"that",
"can",
"be",
"expanded",
"or",
"terminal",
"symbols",
"that",
"must",
"be",
"leaf",
"nodes... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L76-L85 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_paths_to_root | def get_paths_to_root(self,
action: str,
max_path_length: int = 20,
beam_size: int = 30,
max_num_paths: int = 10) -> List[List[str]]:
"""
For a given action, returns at most ``max_num_paths`` paths to... | python | def get_paths_to_root(self,
action: str,
max_path_length: int = 20,
beam_size: int = 30,
max_num_paths: int = 10) -> List[List[str]]:
"""
For a given action, returns at most ``max_num_paths`` paths to... | [
"def",
"get_paths_to_root",
"(",
"self",
",",
"action",
":",
"str",
",",
"max_path_length",
":",
"int",
"=",
"20",
",",
"beam_size",
":",
"int",
"=",
"30",
",",
"max_num_paths",
":",
"int",
"=",
"10",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
... | For a given action, returns at most ``max_num_paths`` paths to the root (production with
``START_SYMBOL``) that are not longer than ``max_path_length``. | [
"For",
"a",
"given",
"action",
"returns",
"at",
"most",
"max_num_paths",
"paths",
"to",
"the",
"root",
"(",
"production",
"with",
"START_SYMBOL",
")",
"that",
"are",
"not",
"longer",
"than",
"max_path_length",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L98-L140 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_multi_match_mapping | def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... | python | def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... | [
"def",
"get_multi_match_mapping",
"(",
"self",
")",
"->",
"Dict",
"[",
"Type",
",",
"List",
"[",
"Type",
"]",
"]",
":",
"if",
"self",
".",
"_multi_match_mapping",
"is",
"None",
":",
"self",
".",
"_multi_match_mapping",
"=",
"{",
"}",
"basic_types",
"=",
... | Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches. | [
"Returns",
"a",
"mapping",
"from",
"each",
"MultiMatchNamedBasicType",
"to",
"all",
"the",
"NamedBasicTypes",
"that",
"it",
"matches",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L184-L204 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.parse_logical_form | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... | python | def parse_logical_form(self,
logical_form: str,
remove_var_function: bool = True) -> Expression:
"""
Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
l... | [
"def",
"parse_logical_form",
"(",
"self",
",",
"logical_form",
":",
"str",
",",
"remove_var_function",
":",
"bool",
"=",
"True",
")",
"->",
"Expression",
":",
"if",
"not",
"logical_form",
".",
"startswith",
"(",
"\"(\"",
")",
":",
"logical_form",
"=",
"f\"({... | Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression.
Parameters
----------
logical_form : ``str``
Logical form to parse
remove_var_function : ``bool`` (optional)
``var`` is a special function that some languages use... | [
"Takes",
"a",
"logical",
"form",
"as",
"a",
"string",
"maps",
"its",
"tokens",
"using",
"the",
"mapping",
"and",
"returns",
"a",
"parsed",
"expression",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L206-L235 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_action_sequence | def get_action_sequence(self, expression: Expression) -> List[str]:
"""
Returns the sequence of actions (as strings) that resulted in the given expression.
"""
# Starting with the type of the whole expression
return self._get_transitions(expression,
... | python | def get_action_sequence(self, expression: Expression) -> List[str]:
"""
Returns the sequence of actions (as strings) that resulted in the given expression.
"""
# Starting with the type of the whole expression
return self._get_transitions(expression,
... | [
"def",
"get_action_sequence",
"(",
"self",
",",
"expression",
":",
"Expression",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# Starting with the type of the whole expression",
"return",
"self",
".",
"_get_transitions",
"(",
"expression",
",",
"[",
"f\"{types.START_TYPE}... | Returns the sequence of actions (as strings) that resulted in the given expression. | [
"Returns",
"the",
"sequence",
"of",
"actions",
"(",
"as",
"strings",
")",
"that",
"resulted",
"in",
"the",
"given",
"expression",
"."
] | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L237-L243 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World.get_logical_form | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions ... | python | def get_logical_form(self,
action_sequence: List[str],
add_var_function: bool = True) -> str:
"""
Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions ... | [
"def",
"get_logical_form",
"(",
"self",
",",
"action_sequence",
":",
"List",
"[",
"str",
"]",
",",
"add_var_function",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# Basic outline: we assume that the bracketing that we get in the RHS of each action is the",
"# correc... | Takes an action sequence and constructs a logical form from it. This is useful if you want
to get a logical form from a decoded sequence of actions generated by a transition based
semantic parser.
Parameters
----------
action_sequence : ``List[str]``
The sequence of ... | [
"Takes",
"an",
"action",
"sequence",
"and",
"constructs",
"a",
"logical",
"form",
"from",
"it",
".",
"This",
"is",
"useful",
"if",
"you",
"want",
"to",
"get",
"a",
"logical",
"form",
"from",
"a",
"decoded",
"sequence",
"of",
"actions",
"generated",
"by",
... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L245-L285 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World._construct_node_from_actions | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]],
add_var_function: bool) -> List[List[str]]:
"""
Given a current node in the logical form tree, and... | python | def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]],
add_var_function: bool) -> List[List[str]]:
"""
Given a current node in the logical form tree, and... | [
"def",
"_construct_node_from_actions",
"(",
"self",
",",
"current_node",
":",
"Tree",
",",
"remaining_actions",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"add_var_function",
":",
"bool",
")",
"->",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
":... | Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, we could get a node with type ``c``, and an action sequence that begin... | [
"Given",
"a",
"current",
"node",
"in",
"the",
"logical",
"form",
"tree",
"and",
"a",
"list",
"of",
"actions",
"in",
"an",
"action",
"sequence",
"this",
"method",
"fills",
"in",
"the",
"children",
"of",
"the",
"current",
"node",
"from",
"the",
"action",
"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L287-L349 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World._infer_num_arguments | def _infer_num_arguments(cls, type_signature: str) -> int:
"""
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3
"""
if no... | python | def _infer_num_arguments(cls, type_signature: str) -> int:
"""
Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3
"""
if no... | [
"def",
"_infer_num_arguments",
"(",
"cls",
",",
"type_signature",
":",
"str",
")",
"->",
"int",
":",
"if",
"not",
"\"<\"",
"in",
"type_signature",
":",
"return",
"0",
"# We need to find the return type from the signature. We do that by removing the outer most",
"# angular b... | Takes a type signature and infers the number of arguments the corresponding function takes.
Examples:
e -> 0
<r,e> -> 1
<e,<e,t>> -> 2
<b,<<b,#1>,<#1,b>>> -> 3 | [
"Takes",
"a",
"type",
"signature",
"and",
"infers",
"the",
"number",
"of",
"arguments",
"the",
"corresponding",
"function",
"takes",
".",
"Examples",
":",
"e",
"-",
">",
"0",
"<r",
"e",
">",
"-",
">",
"1",
"<e",
"<e",
"t",
">>",
"-",
">",
"2",
"<b"... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L352-L380 | train |
allenai/allennlp | allennlp/semparse/worlds/world.py | World._process_nested_expression | def _process_nested_expression(self, nested_expression) -> str:
"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_li... | python | def _process_nested_expression(self, nested_expression) -> str:
"""
``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand.
"""
expression_is_li... | [
"def",
"_process_nested_expression",
"(",
"self",
",",
"nested_expression",
")",
"->",
"str",
":",
"expression_is_list",
"=",
"isinstance",
"(",
"nested_expression",
",",
"list",
")",
"expression_size",
"=",
"len",
"(",
"nested_expression",
")",
"if",
"expression_is... | ``nested_expression`` is the result of parsing a logical form in Lisp format.
We process it recursively and return a string in the format that NLTK's ``LogicParser``
would understand. | [
"nested_expression",
"is",
"the",
"result",
"of",
"parsing",
"a",
"logical",
"form",
"in",
"Lisp",
"format",
".",
"We",
"process",
"it",
"recursively",
"and",
"return",
"a",
"string",
"in",
"the",
"format",
"that",
"NLTK",
"s",
"LogicParser",
"would",
"under... | 648a36f77db7e45784c047176074f98534c76636 | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/world.py#L382-L408 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.