partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Pruner.forward
Extracts the top-k scoring items with respect to the scorer. We additionally return the indices of the top-k in their original order, not ordered by score, so that downstream components can rely on the original ordering (e.g., for knowing what spans are valid antecedents in a coreference resolut...
allennlp/modules/pruner.py
def forward(self, # pylint: disable=arguments-differ embeddings: torch.FloatTensor, mask: torch.LongTensor, num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor, ...
def forward(self, # pylint: disable=arguments-differ embeddings: torch.FloatTensor, mask: torch.LongTensor, num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor, ...
[ "Extracts", "the", "top", "-", "k", "scoring", "items", "with", "respect", "to", "the", "scorer", ".", "We", "additionally", "return", "the", "indices", "of", "the", "top", "-", "k", "in", "their", "original", "order", "not", "ordered", "by", "score", "s...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/pruner.py#L25-L131
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "embeddings", ":", "torch", ".", "FloatTensor", ",", "mask", ":", "torch", ".", "LongTensor", ",", "num_items_to_keep", ":", "Union", "[", "int", ",", "torch", ".", "LongTensor", "]", ")...
648a36f77db7e45784c047176074f98534c76636
train
add_epoch_number
Add the epoch number to the batch instances as a MetadataField.
allennlp/data/iterators/data_iterator.py
def add_epoch_number(batch: Batch, epoch: int) -> Batch: """ Add the epoch number to the batch instances as a MetadataField. """ for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
def add_epoch_number(batch: Batch, epoch: int) -> Batch: """ Add the epoch number to the batch instances as a MetadataField. """ for instance in batch.instances: instance.fields['epoch_num'] = MetadataField(epoch) return batch
[ "Add", "the", "epoch", "number", "to", "the", "batch", "instances", "as", "a", "MetadataField", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L22-L28
[ "def", "add_epoch_number", "(", "batch", ":", "Batch", ",", "epoch", ":", "int", ")", "->", "Batch", ":", "for", "instance", "in", "batch", ".", "instances", ":", "instance", ".", "fields", "[", "'epoch_num'", "]", "=", "MetadataField", "(", "epoch", ")"...
648a36f77db7e45784c047176074f98534c76636
train
DataIterator._take_instances
Take the next `max_instances` instances from the given dataset. If `max_instances` is `None`, then just take all instances from the dataset. If `max_instances` is not `None`, each call resumes where the previous one left off, and when you get to the end of the dataset you start again from the be...
allennlp/data/iterators/data_iterator.py
def _take_instances(self, instances: Iterable[Instance], max_instances: Optional[int] = None) -> Iterator[Instance]: """ Take the next `max_instances` instances from the given dataset. If `max_instances` is `None`, then just take all instances from...
def _take_instances(self, instances: Iterable[Instance], max_instances: Optional[int] = None) -> Iterator[Instance]: """ Take the next `max_instances` instances from the given dataset. If `max_instances` is `None`, then just take all instances from...
[ "Take", "the", "next", "max_instances", "instances", "from", "the", "given", "dataset", ".", "If", "max_instances", "is", "None", "then", "just", "take", "all", "instances", "from", "the", "dataset", ".", "If", "max_instances", "is", "not", "None", "each", "...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L163-L192
[ "def", "_take_instances", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ",", "max_instances", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Iterator", "[", "Instance", "]", ":", "# If max_instances isn't specified, just itera...
648a36f77db7e45784c047176074f98534c76636
train
DataIterator._memory_sized_lists
Breaks the dataset into "memory-sized" lists of instances, which it yields up one at a time until it gets through a full epoch. For example, if the dataset is already an in-memory list, and each epoch represents one pass through the dataset, it just yields back the dataset. Whereas if t...
allennlp/data/iterators/data_iterator.py
def _memory_sized_lists(self, instances: Iterable[Instance]) -> Iterable[List[Instance]]: """ Breaks the dataset into "memory-sized" lists of instances, which it yields up one at a time until it gets through a full epoch. For example, if the dataset is alread...
def _memory_sized_lists(self, instances: Iterable[Instance]) -> Iterable[List[Instance]]: """ Breaks the dataset into "memory-sized" lists of instances, which it yields up one at a time until it gets through a full epoch. For example, if the dataset is alread...
[ "Breaks", "the", "dataset", "into", "memory", "-", "sized", "lists", "of", "instances", "which", "it", "yields", "up", "one", "at", "a", "time", "until", "it", "gets", "through", "a", "full", "epoch", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L194-L228
[ "def", "_memory_sized_lists", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ")", "->", "Iterable", "[", "List", "[", "Instance", "]", "]", ":", "lazy", "=", "is_lazy", "(", "instances", ")", "# Get an iterator over the next epoch worth of...
648a36f77db7e45784c047176074f98534c76636
train
DataIterator._ensure_batch_is_sufficiently_small
If self._maximum_samples_per_batch is specified, then split the batch into smaller sub-batches if it exceeds the maximum size. Parameters ---------- batch_instances : ``Iterable[Instance]`` A candidate batch. excess : ``Deque[Instance]`` Instances that we...
allennlp/data/iterators/data_iterator.py
def _ensure_batch_is_sufficiently_small( self, batch_instances: Iterable[Instance], excess: Deque[Instance]) -> List[List[Instance]]: """ If self._maximum_samples_per_batch is specified, then split the batch into smaller sub-batches if it exceeds the maximum s...
def _ensure_batch_is_sufficiently_small( self, batch_instances: Iterable[Instance], excess: Deque[Instance]) -> List[List[Instance]]: """ If self._maximum_samples_per_batch is specified, then split the batch into smaller sub-batches if it exceeds the maximum s...
[ "If", "self", ".", "_maximum_samples_per_batch", "is", "specified", "then", "split", "the", "batch", "into", "smaller", "sub", "-", "batches", "if", "it", "exceeds", "the", "maximum", "size", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L230-L297
[ "def", "_ensure_batch_is_sufficiently_small", "(", "self", ",", "batch_instances", ":", "Iterable", "[", "Instance", "]", ",", "excess", ":", "Deque", "[", "Instance", "]", ")", "->", "List", "[", "List", "[", "Instance", "]", "]", ":", "if", "self", ".", ...
648a36f77db7e45784c047176074f98534c76636
train
DataIterator.get_num_batches
Returns the number of batches that ``dataset`` will be split into; if you want to track progress through the batch with the generator produced by ``__call__``, this could be useful.
allennlp/data/iterators/data_iterator.py
def get_num_batches(self, instances: Iterable[Instance]) -> int: """ Returns the number of batches that ``dataset`` will be split into; if you want to track progress through the batch with the generator produced by ``__call__``, this could be useful. """ if is_lazy(instan...
def get_num_batches(self, instances: Iterable[Instance]) -> int: """ Returns the number of batches that ``dataset`` will be split into; if you want to track progress through the batch with the generator produced by ``__call__``, this could be useful. """ if is_lazy(instan...
[ "Returns", "the", "number", "of", "batches", "that", "dataset", "will", "be", "split", "into", ";", "if", "you", "want", "to", "track", "progress", "through", "the", "batch", "with", "the", "generator", "produced", "by", "__call__", "this", "could", "be", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L299-L312
[ "def", "get_num_batches", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ")", "->", "int", ":", "if", "is_lazy", "(", "instances", ")", "and", "self", ".", "_instances_per_epoch", "is", "None", ":", "# Unable to compute num batches, so jus...
648a36f77db7e45784c047176074f98534c76636
train
DataIterator._create_batches
This method should return one epoch worth of batches.
allennlp/data/iterators/data_iterator.py
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: """ This method should return one epoch worth of batches. """ raise NotImplementedError
def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]: """ This method should return one epoch worth of batches. """ raise NotImplementedError
[ "This", "method", "should", "return", "one", "epoch", "worth", "of", "batches", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/iterators/data_iterator.py#L314-L318
[ "def", "_create_batches", "(", "self", ",", "instances", ":", "Iterable", "[", "Instance", "]", ",", "shuffle", ":", "bool", ")", "->", "Iterable", "[", "Batch", "]", ":", "raise", "NotImplementedError" ]
648a36f77db7e45784c047176074f98534c76636
train
replace_cr_with_newline
TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. :param message: the message to permute :return: t...
allennlp/common/tee_logger.py
def replace_cr_with_newline(message: str): """ TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. ...
def replace_cr_with_newline(message: str): """ TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. ...
[ "TQDM", "and", "requests", "use", "carriage", "returns", "to", "get", "the", "training", "line", "to", "update", "for", "each", "batch", "without", "adding", "more", "lines", "to", "the", "terminal", "output", ".", "Displaying", "those", "in", "a", "file", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/tee_logger.py#L8-L20
[ "def", "replace_cr_with_newline", "(", "message", ":", "str", ")", ":", "if", "'\\r'", "in", "message", ":", "message", "=", "message", ".", "replace", "(", "'\\r'", ",", "''", ")", "if", "not", "message", "or", "message", "[", "-", "1", "]", "!=", "...
648a36f77db7e45784c047176074f98534c76636
train
Predictor.capture_model_internals
Context manager that captures the internal-module outputs of this predictor's model. The idea is that you could use it as follows: .. code-block:: python with predictor.capture_model_internals() as internals: outputs = predictor.predict_json(inputs) return {**o...
allennlp/predictors/predictor.py
def capture_model_internals(self) -> Iterator[dict]: """ Context manager that captures the internal-module outputs of this predictor's model. The idea is that you could use it as follows: .. code-block:: python with predictor.capture_model_internals() as internals: ...
def capture_model_internals(self) -> Iterator[dict]: """ Context manager that captures the internal-module outputs of this predictor's model. The idea is that you could use it as follows: .. code-block:: python with predictor.capture_model_internals() as internals: ...
[ "Context", "manager", "that", "captures", "the", "internal", "-", "module", "outputs", "of", "this", "predictor", "s", "model", ".", "The", "idea", "is", "that", "you", "could", "use", "it", "as", "follows", ":" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L61-L92
[ "def", "capture_model_internals", "(", "self", ")", "->", "Iterator", "[", "dict", "]", ":", "results", "=", "{", "}", "hooks", "=", "[", "]", "# First we'll register hooks to add the outputs of each module to the results dict.", "def", "add_output", "(", "idx", ":", ...
648a36f77db7e45784c047176074f98534c76636
train
Predictor._batch_json_to_instances
Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted by :func:`predict_json`. In order to use this method for batch prediction, :func:`_json_to_ins...
allennlp/predictors/predictor.py
def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]: """ Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted ...
def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]: """ Converts a list of JSON objects into a list of :class:`~allennlp.data.instance.Instance`s. By default, this expects that a "batch" consists of a list of JSON blobs which would individually be predicted ...
[ "Converts", "a", "list", "of", "JSON", "objects", "into", "a", "list", "of", ":", "class", ":", "~allennlp", ".", "data", ".", "instance", ".", "Instance", "s", ".", "By", "default", "this", "expects", "that", "a", "batch", "consists", "of", "a", "list...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L114-L126
[ "def", "_batch_json_to_instances", "(", "self", ",", "json_dicts", ":", "List", "[", "JsonDict", "]", ")", "->", "List", "[", "Instance", "]", ":", "instances", "=", "[", "]", "for", "json_dict", "in", "json_dicts", ":", "instances", ".", "append", "(", ...
648a36f77db7e45784c047176074f98534c76636
train
Predictor.from_path
Instantiate a :class:`Predictor` from an archive path. If you need more detailed configuration options, such as running the predictor on the GPU, please use `from_archive`. Parameters ---------- archive_path The path to the archive. Returns ------- A Pr...
allennlp/predictors/predictor.py
def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor': """ Instantiate a :class:`Predictor` from an archive path. If you need more detailed configuration options, such as running the predictor on the GPU, please use `from_archive`. Parameters ...
def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor': """ Instantiate a :class:`Predictor` from an archive path. If you need more detailed configuration options, such as running the predictor on the GPU, please use `from_archive`. Parameters ...
[ "Instantiate", "a", ":", "class", ":", "Predictor", "from", "an", "archive", "path", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L129-L144
[ "def", "from_path", "(", "cls", ",", "archive_path", ":", "str", ",", "predictor_name", ":", "str", "=", "None", ")", "->", "'Predictor'", ":", "return", "Predictor", ".", "from_archive", "(", "load_archive", "(", "archive_path", ")", ",", "predictor_name", ...
648a36f77db7e45784c047176074f98534c76636
train
Predictor.from_archive
Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the default one for the model will be used.
allennlp/predictors/predictor.py
def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor': """ Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the default...
def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor': """ Instantiate a :class:`Predictor` from an :class:`~allennlp.models.archival.Archive`; that is, from the result of training a model. Optionally specify which `Predictor` subclass; otherwise, the default...
[ "Instantiate", "a", ":", "class", ":", "Predictor", "from", "an", ":", "class", ":", "~allennlp", ".", "models", ".", "archival", ".", "Archive", ";", "that", "is", "from", "the", "result", "of", "training", "a", "model", ".", "Optionally", "specify", "w...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/predictors/predictor.py#L147-L169
[ "def", "from_archive", "(", "cls", ",", "archive", ":", "Archive", ",", "predictor_name", ":", "str", "=", "None", ")", "->", "'Predictor'", ":", "# Duplicate the config so that the config inside the archive doesn't get consumed", "config", "=", "archive", ".", "config"...
648a36f77db7e45784c047176074f98534c76636
train
attention
Compute 'Scaled Dot Product Attention
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]: """Compute 'Scaled Dot Product Attention'""" d_k = query.size(-1) scores = torch.matmu...
def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]: """Compute 'Scaled Dot Product Attention'""" d_k = query.size(-1) scores = torch.matmu...
[ "Compute", "Scaled", "Dot", "Product", "Attention" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L24-L37
[ "def", "attention", "(", "query", ":", "torch", ".", "Tensor", ",", "key", ":", "torch", ".", "Tensor", ",", "value", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", "=", "None", ",", "dropout", ":", "Callable", "=", "None", ...
648a36f77db7e45784c047176074f98534c76636
train
subsequent_mask
Mask out subsequent positions.
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor: """Mask out subsequent positions.""" mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0) return mask
def subsequent_mask(size: int, device: str = 'cpu') -> torch.Tensor: """Mask out subsequent positions.""" mask = torch.tril(torch.ones(size, size, device=device, dtype=torch.int32)).unsqueeze(0) return mask
[ "Mask", "out", "subsequent", "positions", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L40-L43
[ "def", "subsequent_mask", "(", "size", ":", "int", ",", "device", ":", "str", "=", "'cpu'", ")", "->", "torch", ".", "Tensor", ":", "mask", "=", "torch", ".", "tril", "(", "torch", ".", "ones", "(", "size", ",", "size", ",", "device", "=", "device"...
648a36f77db7e45784c047176074f98534c76636
train
make_model
Helper: Construct a model from hyperparameters.
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def make_model(num_layers: int = 6, input_size: int = 512, # Attention size hidden_size: int = 2048, # FF layer size heads: int = 8, dropout: float = 0.1, return_all_layers: bool = False) -> TransformerEncoder: """Helper: Construct a model...
def make_model(num_layers: int = 6, input_size: int = 512, # Attention size hidden_size: int = 2048, # FF layer size heads: int = 8, dropout: float = 0.1, return_all_layers: bool = False) -> TransformerEncoder: """Helper: Construct a model...
[ "Helper", ":", "Construct", "a", "model", "from", "hyperparameters", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L175-L192
[ "def", "make_model", "(", "num_layers", ":", "int", "=", "6", ",", "input_size", ":", "int", "=", "512", ",", "# Attention size", "hidden_size", ":", "int", "=", "2048", ",", "# FF layer size", "heads", ":", "int", "=", "8", ",", "dropout", ":", "float",...
648a36f77db7e45784c047176074f98534c76636
train
TransformerEncoder.forward
Pass the input (and mask) through each layer in turn.
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def forward(self, x, mask): """Pass the input (and mask) through each layer in turn.""" all_layers = [] for layer in self.layers: x = layer(x, mask) if self.return_all_layers: all_layers.append(x) if self.return_all_layers: all_layers[...
def forward(self, x, mask): """Pass the input (and mask) through each layer in turn.""" all_layers = [] for layer in self.layers: x = layer(x, mask) if self.return_all_layers: all_layers.append(x) if self.return_all_layers: all_layers[...
[ "Pass", "the", "input", "(", "and", "mask", ")", "through", "each", "layer", "in", "turn", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L89-L100
[ "def", "forward", "(", "self", ",", "x", ",", "mask", ")", ":", "all_layers", "=", "[", "]", "for", "layer", "in", "self", ".", "layers", ":", "x", "=", "layer", "(", "x", ",", "mask", ")", "if", "self", ".", "return_all_layers", ":", "all_layers",...
648a36f77db7e45784c047176074f98534c76636
train
SublayerConnection.forward
Apply residual connection to any sublayer with the same size.
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor: """Apply residual connection to any sublayer with the same size.""" return x + self.dropout(sublayer(self.norm(x)))
def forward(self, x: torch.Tensor, sublayer: Callable[[torch.Tensor], torch.Tensor]) -> torch.Tensor: """Apply residual connection to any sublayer with the same size.""" return x + self.dropout(sublayer(self.norm(x)))
[ "Apply", "residual", "connection", "to", "any", "sublayer", "with", "the", "same", "size", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L114-L116
[ "def", "forward", "(", "self", ",", "x", ":", "torch", ".", "Tensor", ",", "sublayer", ":", "Callable", "[", "[", "torch", ".", "Tensor", "]", ",", "torch", ".", "Tensor", "]", ")", "->", "torch", ".", "Tensor", ":", "return", "x", "+", "self", "...
648a36f77db7e45784c047176074f98534c76636
train
EncoderLayer.forward
Follow Figure 1 (left) for connections.
allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """Follow Figure 1 (left) for connections.""" x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward)
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """Follow Figure 1 (left) for connections.""" x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward)
[ "Follow", "Figure", "1", "(", "left", ")", "for", "connections", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/seq2seq_encoders/bidirectional_language_model_transformer.py#L133-L136
[ "def", "forward", "(", "self", ",", "x", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "x", "=", "self", ".", "sublayer", "[", "0", "]", "(", "x", ",", "lambda", "x", ":", "self",...
648a36f77db7e45784c047176074f98534c76636
train
uniform_unit_scaling
An initaliser which preserves output variance for approximately gaussian distributed inputs. This boils down to initialising layers using a uniform distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)``, where ``dim[0]`` is equal to the input dimension of the parameter and the ``s...
allennlp/nn/initializers.py
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"): """ An initaliser which preserves output variance for approximately gaussian distributed inputs. This boils down to initialising layers using a uniform distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * s...
def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"): """ An initaliser which preserves output variance for approximately gaussian distributed inputs. This boils down to initialising layers using a uniform distribution in the range ``(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * s...
[ "An", "initaliser", "which", "preserves", "output", "variance", "for", "approximately", "gaussian", "distributed", "inputs", ".", "This", "boils", "down", "to", "initialising", "layers", "using", "a", "uniform", "distribution", "in", "the", "range", "(", "-", "s...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L58-L95
[ "def", "uniform_unit_scaling", "(", "tensor", ":", "torch", ".", "Tensor", ",", "nonlinearity", ":", "str", "=", "\"linear\"", ")", ":", "size", "=", "1.", "# Estimate the input size. This won't work perfectly,", "# but it covers almost all use cases where this initialiser", ...
648a36f77db7e45784c047176074f98534c76636
train
block_orthogonal
An initializer which allows initializing model parameters in "blocks". This is helpful in the case of recurrent models which use multiple gates applied to linear projections, which can be computed efficiently if they are concatenated together. However, they are separate parameters which should be initialize...
allennlp/nn/initializers.py
def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None: """ An initializer which allows initializing model parameters in "blocks". This is helpful in the case of recurrent models which use multiple gates applied to linear proje...
def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None: """ An initializer which allows initializing model parameters in "blocks". This is helpful in the case of recurrent models which use multiple gates applied to linear proje...
[ "An", "initializer", "which", "allows", "initializing", "model", "parameters", "in", "blocks", ".", "This", "is", "helpful", "in", "the", "case", "of", "recurrent", "models", "which", "use", "multiple", "gates", "applied", "to", "linear", "projections", "which",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L98-L138
[ "def", "block_orthogonal", "(", "tensor", ":", "torch", ".", "Tensor", ",", "split_sizes", ":", "List", "[", "int", "]", ",", "gain", ":", "float", "=", "1.0", ")", "->", "None", ":", "data", "=", "tensor", ".", "data", "sizes", "=", "list", "(", "...
648a36f77db7e45784c047176074f98534c76636
train
lstm_hidden_bias
Initialize the biases of the forget gate to 1, and all other gates to 0, following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures
allennlp/nn/initializers.py
def lstm_hidden_bias(tensor: torch.Tensor) -> None: """ Initialize the biases of the forget gate to 1, and all other gates to 0, following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures """ # gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size) tensor.data.zer...
def lstm_hidden_bias(tensor: torch.Tensor) -> None: """ Initialize the biases of the forget gate to 1, and all other gates to 0, following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures """ # gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size) tensor.data.zer...
[ "Initialize", "the", "biases", "of", "the", "forget", "gate", "to", "1", "and", "all", "other", "gates", "to", "0", "following", "Jozefowicz", "et", "al", ".", "An", "Empirical", "Exploration", "of", "Recurrent", "Network", "Architectures" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L144-L152
[ "def", "lstm_hidden_bias", "(", "tensor", ":", "torch", ".", "Tensor", ")", "->", "None", ":", "# gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)", "tensor", ".", "data", ".", "zero_", "(", ")", "hidden_size", "=", "tensor", ".", "shape", "[", "0", "]",...
648a36f77db7e45784c047176074f98534c76636
train
InitializerApplicator.from_params
Converts a Params object into an InitializerApplicator. The json should be formatted as follows:: [ ["parameter_regex_match1", { "type": "normal" "mean": 0.01 "std": 0.1 }...
allennlp/nn/initializers.py
def from_params(cls, params: List[Tuple[str, Params]] = None) -> "InitializerApplicator": """ Converts a Params object into an InitializerApplicator. The json should be formatted as follows:: [ ["parameter_regex_match1", { ...
def from_params(cls, params: List[Tuple[str, Params]] = None) -> "InitializerApplicator": """ Converts a Params object into an InitializerApplicator. The json should be formatted as follows:: [ ["parameter_regex_match1", { ...
[ "Converts", "a", "Params", "object", "into", "an", "InitializerApplicator", ".", "The", "json", "should", "be", "formatted", "as", "follows", "::" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/nn/initializers.py#L317-L353
[ "def", "from_params", "(", "cls", ",", "params", ":", "List", "[", "Tuple", "[", "str", ",", "Params", "]", "]", "=", "None", ")", "->", "\"InitializerApplicator\"", ":", "# pylint: disable=arguments-differ", "params", "=", "params", "or", "[", "]", "is_prev...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph.read_from_file
We read tables formatted as TSV files here. We assume the first line in the file is a tab separated list of column headers, and all subsequent lines are content rows. For example if the TSV file is: Nation Olympics Medals USA 1896 8 China 1932 ...
allennlp/semparse/contexts/table_question_knowledge_graph.py
def read_from_file(cls, filename: str, question: List[Token]) -> 'TableQuestionKnowledgeGraph': """ We read tables formatted as TSV files here. We assume the first line in the file is a tab separated list of column headers, and all subsequent lines are content rows. For example if the TS...
def read_from_file(cls, filename: str, question: List[Token]) -> 'TableQuestionKnowledgeGraph': """ We read tables formatted as TSV files here. We assume the first line in the file is a tab separated list of column headers, and all subsequent lines are content rows. For example if the TS...
[ "We", "read", "tables", "formatted", "as", "TSV", "files", "here", ".", "We", "assume", "the", "first", "line", "in", "the", "file", "is", "a", "tab", "separated", "list", "of", "column", "headers", "and", "all", "subsequent", "lines", "are", "content", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L101-L114
[ "def", "read_from_file", "(", "cls", ",", "filename", ":", "str", ",", "question", ":", "List", "[", "Token", "]", ")", "->", "'TableQuestionKnowledgeGraph'", ":", "return", "cls", ".", "read_from_lines", "(", "open", "(", "filename", ")", ".", "readlines", ...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph.read_from_json
We read tables formatted as JSON objects (dicts) here. This is useful when you are reading data from a demo. The expected format is:: {"question": [token1, token2, ...], "columns": [column1, column2, ...], "cells": [[row1_cell1, row1_cell2, ...], [ro...
allennlp/semparse/contexts/table_question_knowledge_graph.py
def read_from_json(cls, json_object: Dict[str, Any]) -> 'TableQuestionKnowledgeGraph': """ We read tables formatted as JSON objects (dicts) here. This is useful when you are reading data from a demo. The expected format is:: {"question": [token1, token2, ...], "columns"...
def read_from_json(cls, json_object: Dict[str, Any]) -> 'TableQuestionKnowledgeGraph': """ We read tables formatted as JSON objects (dicts) here. This is useful when you are reading data from a demo. The expected format is:: {"question": [token1, token2, ...], "columns"...
[ "We", "read", "tables", "formatted", "as", "JSON", "objects", "(", "dicts", ")", "here", ".", "This", "is", "useful", "when", "you", "are", "reading", "data", "from", "a", "demo", ".", "The", "expected", "format", "is", "::" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L129-L203
[ "def", "read_from_json", "(", "cls", ",", "json_object", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "'TableQuestionKnowledgeGraph'", ":", "entity_text", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", "neighbors", ":", "DefaultDict", "...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph._get_numbers_from_tokens
Finds numbers in the input tokens and returns them as strings. We do some simple heuristic number recognition, finding ordinals and cardinals expressed as text ("one", "first", etc.), as well as numerals ("7th", "3rd"), months (mapping "july" to 7), and units ("1ghz"). We also handle y...
allennlp/semparse/contexts/table_question_knowledge_graph.py
def _get_numbers_from_tokens(tokens: List[Token]) -> List[Tuple[str, str]]: """ Finds numbers in the input tokens and returns them as strings. We do some simple heuristic number recognition, finding ordinals and cardinals expressed as text ("one", "first", etc.), as well as numerals ("7...
def _get_numbers_from_tokens(tokens: List[Token]) -> List[Tuple[str, str]]: """ Finds numbers in the input tokens and returns them as strings. We do some simple heuristic number recognition, finding ordinals and cardinals expressed as text ("one", "first", etc.), as well as numerals ("7...
[ "Finds", "numbers", "in", "the", "input", "tokens", "and", "returns", "them", "as", "strings", ".", "We", "do", "some", "simple", "heuristic", "number", "recognition", "finding", "ordinals", "and", "cardinals", "expressed", "as", "text", "(", "one", "first", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L246-L306
[ "def", "_get_numbers_from_tokens", "(", "tokens", ":", "List", "[", "Token", "]", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "numbers", "=", "[", "]", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":"...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph._get_cell_parts
Splits a cell into parts and returns the parts of the cell. We return a list of ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and ``entity_text`` is the text of the cell corresponding to that part. For many cells, there is only one "part", and we return a li...
allennlp/semparse/contexts/table_question_knowledge_graph.py
def _get_cell_parts(cls, cell_text: str) -> List[Tuple[str, str]]: """ Splits a cell into parts and returns the parts of the cell. We return a list of ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and ``entity_text`` is the text of the cell correspond...
def _get_cell_parts(cls, cell_text: str) -> List[Tuple[str, str]]: """ Splits a cell into parts and returns the parts of the cell. We return a list of ``(entity_name, entity_text)``, where ``entity_name`` is ``fb:part.[something]``, and ``entity_text`` is the text of the cell correspond...
[ "Splits", "a", "cell", "into", "parts", "and", "returns", "the", "parts", "of", "the", "cell", ".", "We", "return", "a", "list", "of", "(", "entity_name", "entity_text", ")", "where", "entity_name", "is", "fb", ":", "part", ".", "[", "something", "]", ...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L310-L326
[ "def", "_get_cell_parts", "(", "cls", ",", "cell_text", ":", "str", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "parts", "=", "[", "]", "for", "part_text", "in", "cls", ".", "cell_part_regex", ".", "split", "(", "cell_text...
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph._should_split_column_cells
Returns true if there is any cell in this column that can be split.
allennlp/semparse/contexts/table_question_knowledge_graph.py
def _should_split_column_cells(cls, column_cells: List[str]) -> bool: """ Returns true if there is any cell in this column that can be split. """ return any(cls._should_split_cell(cell_text) for cell_text in column_cells)
def _should_split_column_cells(cls, column_cells: List[str]) -> bool: """ Returns true if there is any cell in this column that can be split. """ return any(cls._should_split_cell(cell_text) for cell_text in column_cells)
[ "Returns", "true", "if", "there", "is", "any", "cell", "in", "this", "column", "that", "can", "be", "split", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L329-L333
[ "def", "_should_split_column_cells", "(", "cls", ",", "column_cells", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "return", "any", "(", "cls", ".", "_should_split_cell", "(", "cell_text", ")", "for", "cell_text", "in", "column_cells", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph._should_split_cell
Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here.
allennlp/semparse/contexts/table_question_knowledge_graph.py
def _should_split_cell(cls, cell_text: str) -> bool: """ Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here. """ if ', ' in cell_text or '\n' in cell_text or '/' in cell_text: return True return False
def _should_split_cell(cls, cell_text: str) -> bool: """ Checks whether the cell should be split. We're just doing the same thing that SEMPRE did here. """ if ', ' in cell_text or '\n' in cell_text or '/' in cell_text: return True return False
[ "Checks", "whether", "the", "cell", "should", "be", "split", ".", "We", "re", "just", "doing", "the", "same", "thing", "that", "SEMPRE", "did", "here", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L336-L343
[ "def", "_should_split_cell", "(", "cls", ",", "cell_text", ":", "str", ")", "->", "bool", ":", "if", "', '", "in", "cell_text", "or", "'\\n'", "in", "cell_text", "or", "'/'", "in", "cell_text", ":", "return", "True", "return", "False" ]
648a36f77db7e45784c047176074f98534c76636
train
TableQuestionKnowledgeGraph.get_linked_agenda_items
Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learning to search parser.
allennlp/semparse/contexts/table_question_knowledge_graph.py
def get_linked_agenda_items(self) -> List[str]: """ Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learni...
def get_linked_agenda_items(self) -> List[str]: """ Returns entities that can be linked to spans in the question, that should be in the agenda, for training a coverage based semantic parser. This method essentially does a heuristic entity linking, to provide weak supervision for a learni...
[ "Returns", "entities", "that", "can", "be", "linked", "to", "spans", "in", "the", "question", "that", "should", "be", "in", "the", "agenda", "for", "training", "a", "coverage", "based", "semantic", "parser", ".", "This", "method", "essentially", "does", "a",...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L345-L358
[ "def", "get_linked_agenda_items", "(", "self", ")", "->", "List", "[", "str", "]", ":", "agenda_items", ":", "List", "[", "str", "]", "=", "[", "]", "for", "entity", "in", "self", ".", "_get_longest_span_matching_entities", "(", ")", ":", "agenda_items", "...
648a36f77db7e45784c047176074f98534c76636
train
main
inp_fn: str, required. Path to file from which to read Open IE extractions in Open IE4's format. domain: str, required. Domain to be used when writing CoNLL format. out_fn: str, required. Path to file to which to write the CoNLL format Open IE extractions.
scripts/convert_openie_to_conll.py
def main(inp_fn: str, domain: str, out_fn: str) -> None: """ inp_fn: str, required. Path to file from which to read Open IE extractions in Open IE4's format. domain: str, required. Domain to be used when writing CoNLL format. out_fn: str, required. Path to file to ...
def main(inp_fn: str, domain: str, out_fn: str) -> None: """ inp_fn: str, required. Path to file from which to read Open IE extractions in Open IE4's format. domain: str, required. Domain to be used when writing CoNLL format. out_fn: str, required. Path to file to ...
[ "inp_fn", ":", "str", "required", ".", "Path", "to", "file", "from", "which", "to", "read", "Open", "IE", "extractions", "in", "Open", "IE4", "s", "format", ".", "domain", ":", "str", "required", ".", "Domain", "to", "be", "used", "when", "writing", "C...
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L35-L52
[ "def", "main", "(", "inp_fn", ":", "str", ",", "domain", ":", "str", ",", "out_fn", ":", "str", ")", "->", "None", ":", "with", "open", "(", "out_fn", ",", "'w'", ")", "as", "fout", ":", "for", "sent_ls", "in", "read", "(", "inp_fn", ")", ":", ...
648a36f77db7e45784c047176074f98534c76636
train
element_from_span
Return an Element from span (list of spacy toks)
scripts/convert_openie_to_conll.py
def element_from_span(span: List[int], span_type: str) -> Element: """ Return an Element from span (list of spacy toks) """ return Element(span_type, [span[0].idx, span[-1].idx + len(span[-1])], ' '.join(map(str, span)))
def element_from_span(span: List[int], span_type: str) -> Element: """ Return an Element from span (list of spacy toks) """ return Element(span_type, [span[0].idx, span[-1].idx + len(span[-1])], ' '.join(map(str, span)))
[ "Return", "an", "Element", "from", "span", "(", "list", "of", "spacy", "toks", ")" ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L69-L77
[ "def", "element_from_span", "(", "span", ":", "List", "[", "int", "]", ",", "span_type", ":", "str", ")", "->", "Element", ":", "return", "Element", "(", "span_type", ",", "[", "span", "[", "0", "]", ".", "idx", ",", "span", "[", "-", "1", "]", "...
648a36f77db7e45784c047176074f98534c76636
train
split_predicate
Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments.
scripts/convert_openie_to_conll.py
def split_predicate(ex: Extraction) -> Extraction: """ Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments. """ rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \ : char_to_word_index(ex.rel.span[1], ex.sent) + 1] if ...
def split_predicate(ex: Extraction) -> Extraction: """ Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments. """ rel_toks = ex.toks[char_to_word_index(ex.rel.span[0], ex.sent) \ : char_to_word_index(ex.rel.span[1], ex.sent) + 1] if ...
[ "Ensure", "single", "word", "predicate", "by", "adding", "before", "-", "predicate", "and", "after", "-", "predicate", "arguments", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L79-L109
[ "def", "split_predicate", "(", "ex", ":", "Extraction", ")", "->", "Extraction", ":", "rel_toks", "=", "ex", ".", "toks", "[", "char_to_word_index", "(", "ex", ".", "rel", ".", "span", "[", "0", "]", ",", "ex", ".", "sent", ")", ":", "char_to_word_inde...
648a36f77db7e45784c047176074f98534c76636
train
extraction_to_conll
Return a conll representation of a given input Extraction.
scripts/convert_openie_to_conll.py
def extraction_to_conll(ex: Extraction) -> List[str]: """ Return a conll representation of a given input Extraction. """ ex = split_predicate(ex) toks = ex.sent.split(' ') ret = ['*'] * len(toks) args = [ex.arg1] + ex.args2 rels_and_args = [("ARG{}".format(arg_ind), arg) ...
def extraction_to_conll(ex: Extraction) -> List[str]: """ Return a conll representation of a given input Extraction. """ ex = split_predicate(ex) toks = ex.sent.split(' ') ret = ['*'] * len(toks) args = [ex.arg1] + ex.args2 rels_and_args = [("ARG{}".format(arg_ind), arg) ...
[ "Return", "a", "conll", "representation", "of", "a", "given", "input", "Extraction", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L111-L133
[ "def", "extraction_to_conll", "(", "ex", ":", "Extraction", ")", "->", "List", "[", "str", "]", ":", "ex", "=", "split_predicate", "(", "ex", ")", "toks", "=", "ex", ".", "sent", ".", "split", "(", "' '", ")", "ret", "=", "[", "'*'", "]", "*", "l...
648a36f77db7e45784c047176074f98534c76636
train
interpret_span
Return an integer tuple from textual representation of closed / open spans.
scripts/convert_openie_to_conll.py
def interpret_span(text_spans: str) -> List[int]: """ Return an integer tuple from textual representation of closed / open spans. """ m = regex.match("^(?:(?:([\(\[]\d+, \d+[\)\]])|({\d+}))[,]?\s*)+$", text_spans) spans = m.captures(1) + m.captures(2) int_spans = [] ...
def interpret_span(text_spans: str) -> List[int]: """ Return an integer tuple from textual representation of closed / open spans. """ m = regex.match("^(?:(?:([\(\[]\d+, \d+[\)\]])|({\d+}))[,]?\s*)+$", text_spans) spans = m.captures(1) + m.captures(2) int_spans = [] ...
[ "Return", "an", "integer", "tuple", "from", "textual", "representation", "of", "closed", "/", "open", "spans", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L135-L175
[ "def", "interpret_span", "(", "text_spans", ":", "str", ")", "->", "List", "[", "int", "]", ":", "m", "=", "regex", ".", "match", "(", "\"^(?:(?:([\\(\\[]\\d+, \\d+[\\)\\]])|({\\d+}))[,]?\\s*)+$\"", ",", "text_spans", ")", "spans", "=", "m", ".", "captures", "...
648a36f77db7e45784c047176074f98534c76636
train
interpret_element
Construct an Element instance from regexp groups.
scripts/convert_openie_to_conll.py
def interpret_element(element_type: str, text: str, span: str) -> Element: """ Construct an Element instance from regexp groups. """ return Element(element_type, interpret_span(span), text)
def interpret_element(element_type: str, text: str, span: str) -> Element: """ Construct an Element instance from regexp groups. """ return Element(element_type, interpret_span(span), text)
[ "Construct", "an", "Element", "instance", "from", "regexp", "groups", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L177-L184
[ "def", "interpret_element", "(", "element_type", ":", "str", ",", "text", ":", "str", ",", "span", ":", "str", ")", "->", "Element", ":", "return", "Element", "(", "element_type", ",", "interpret_span", "(", "span", ")", ",", "text", ")" ]
648a36f77db7e45784c047176074f98534c76636
train
parse_element
Parse a raw element into text and indices (integers).
scripts/convert_openie_to_conll.py
def parse_element(raw_element: str) -> List[Element]: """ Parse a raw element into text and indices (integers). """ elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$", elem.lstrip().rstrip()) for elem in raw_element.split(';')...
def parse_element(raw_element: str) -> List[Element]: """ Parse a raw element into text and indices (integers). """ elements = [regex.match("^(([a-zA-Z]+)\(([^;]+),List\(([^;]*)\)\))$", elem.lstrip().rstrip()) for elem in raw_element.split(';')...
[ "Parse", "a", "raw", "element", "into", "text", "and", "indices", "(", "integers", ")", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L186-L196
[ "def", "parse_element", "(", "raw_element", ":", "str", ")", "->", "List", "[", "Element", "]", ":", "elements", "=", "[", "regex", ".", "match", "(", "\"^(([a-zA-Z]+)\\(([^;]+),List\\(([^;]*)\\)\\))$\"", ",", "elem", ".", "lstrip", "(", ")", ".", "rstrip", ...
648a36f77db7e45784c047176074f98534c76636
train
convert_sent_to_conll
Given a list of extractions for a single sentence - convert it to conll representation.
scripts/convert_openie_to_conll.py
def convert_sent_to_conll(sent_ls: List[Extraction]): """ Given a list of extractions for a single sentence - convert it to conll representation. """ # Sanity check - make sure all extractions are on the same sentence assert(len(set([ex.sent for ex in sent_ls])) == 1) toks = sent_ls[0].sent....
def convert_sent_to_conll(sent_ls: List[Extraction]): """ Given a list of extractions for a single sentence - convert it to conll representation. """ # Sanity check - make sure all extractions are on the same sentence assert(len(set([ex.sent for ex in sent_ls])) == 1) toks = sent_ls[0].sent....
[ "Given", "a", "list", "of", "extractions", "for", "a", "single", "sentence", "-", "convert", "it", "to", "conll", "representation", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L237-L249
[ "def", "convert_sent_to_conll", "(", "sent_ls", ":", "List", "[", "Extraction", "]", ")", ":", "# Sanity check - make sure all extractions are on the same sentence", "assert", "(", "len", "(", "set", "(", "[", "ex", ".", "sent", "for", "ex", "in", "sent_ls", "]", ...
648a36f77db7e45784c047176074f98534c76636
train
pad_line_to_ontonotes
Pad line to conform to ontonotes representation.
scripts/convert_openie_to_conll.py
def pad_line_to_ontonotes(line, domain) -> List[str]: """ Pad line to conform to ontonotes representation. """ word_ind, word = line[ : 2] pos = 'XX' oie_tags = line[2 : ] line_num = 0 parse = "-" lemma = "-" return [domain, line_num, word_ind, word, pos, parse, lemma, '-',\ ...
def pad_line_to_ontonotes(line, domain) -> List[str]: """ Pad line to conform to ontonotes representation. """ word_ind, word = line[ : 2] pos = 'XX' oie_tags = line[2 : ] line_num = 0 parse = "-" lemma = "-" return [domain, line_num, word_ind, word, pos, parse, lemma, '-',\ ...
[ "Pad", "line", "to", "conform", "to", "ontonotes", "representation", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L252-L263
[ "def", "pad_line_to_ontonotes", "(", "line", ",", "domain", ")", "->", "List", "[", "str", "]", ":", "word_ind", ",", "word", "=", "line", "[", ":", "2", "]", "pos", "=", "'XX'", "oie_tags", "=", "line", "[", "2", ":", "]", "line_num", "=", "0", ...
648a36f77db7e45784c047176074f98534c76636
train
convert_sent_dict_to_conll
Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation.
scripts/convert_openie_to_conll.py
def convert_sent_dict_to_conll(sent_dic, domain) -> str: """ Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation. """ return '\n\n'.join(['\n'.join(['\t'.join(map(str, pad_line_to_ontonotes(line, domain))) for line in conver...
def convert_sent_dict_to_conll(sent_dic, domain) -> str: """ Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation. """ return '\n\n'.join(['\n'.join(['\t'.join(map(str, pad_line_to_ontonotes(line, domain))) for line in conver...
[ "Given", "a", "dictionary", "from", "sentence", "-", ">", "extractions", "return", "a", "corresponding", "CoNLL", "representation", "." ]
allenai/allennlp
python
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L265-L273
[ "def", "convert_sent_dict_to_conll", "(", "sent_dic", ",", "domain", ")", "->", "str", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "'\\n'", ".", "join", "(", "[", "'\\t'", ".", "join", "(", "map", "(", "str", ",", "pad_line_to_ontonotes", "(", "lin...
648a36f77db7e45784c047176074f98534c76636
train
deaggregate_record
Given a Kinesis record data that is decoded, deaggregate if it was packed using the Kinesis Producer Library into individual records. This method will be a no-op for any records that are not aggregated (but will still return them). decoded_data - the base64 decoded data that comprises either the KPL a...
examples/apps/kinesis-analytics-process-kpl-record/aws_kinesis_agg/deaggregator.py
def deaggregate_record(decoded_data): '''Given a Kinesis record data that is decoded, deaggregate if it was packed using the Kinesis Producer Library into individual records. This method will be a no-op for any records that are not aggregated (but will still return them). decoded_data - the base64...
def deaggregate_record(decoded_data): '''Given a Kinesis record data that is decoded, deaggregate if it was packed using the Kinesis Producer Library into individual records. This method will be a no-op for any records that are not aggregated (but will still return them). decoded_data - the base64...
[ "Given", "a", "Kinesis", "record", "data", "that", "is", "decoded", "deaggregate", "if", "it", "was", "packed", "using", "the", "Kinesis", "Producer", "Library", "into", "individual", "records", ".", "This", "method", "will", "be", "a", "no", "-", "op", "f...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/kinesis-analytics-process-kpl-record/aws_kinesis_agg/deaggregator.py#L26-L72
[ "def", "deaggregate_record", "(", "decoded_data", ")", ":", "is_aggregated", "=", "True", "#Verify the magic header", "data_magic", "=", "None", "if", "(", "len", "(", "decoded_data", ")", ">=", "len", "(", "aws_kinesis_agg", ".", "MAGIC", ")", ")", ":", "data...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
parse_s3_uri
Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId :return: a BodyS3Location dict or None if not an S3 Uri :rtype: dict
samtranslator/model/s3_utils/uri_parser.py
def parse_s3_uri(uri): """Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId :return: a BodyS3Location dict or None if not an S3 Uri :rtype: dict """ if not isinstance(uri, string_types): return None url = urlparse(uri) query = parse_qs(url.query) if url.schem...
def parse_s3_uri(uri): """Parses a S3 Uri into a dictionary of the Bucket, Key, and VersionId :return: a BodyS3Location dict or None if not an S3 Uri :rtype: dict """ if not isinstance(uri, string_types): return None url = urlparse(uri) query = parse_qs(url.query) if url.schem...
[ "Parses", "a", "S3", "Uri", "into", "a", "dictionary", "of", "the", "Bucket", "Key", "and", "VersionId" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L6-L27
[ "def", "parse_s3_uri", "(", "uri", ")", ":", "if", "not", "isinstance", "(", "uri", ",", "string_types", ")", ":", "return", "None", "url", "=", "urlparse", "(", "uri", ")", "query", "=", "parse_qs", "(", "url", ".", "query", ")", "if", "url", ".", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
to_s3_uri
Constructs a S3 URI string from given code dictionary :param dict code_dict: Dictionary containing Lambda function Code S3 location of the form {S3Bucket, S3Key, S3ObjectVersion} :return: S3 URI of form s3://bucket/key?versionId=version :rtype string
samtranslator/model/s3_utils/uri_parser.py
def to_s3_uri(code_dict): """Constructs a S3 URI string from given code dictionary :param dict code_dict: Dictionary containing Lambda function Code S3 location of the form {S3Bucket, S3Key, S3ObjectVersion} :return: S3 URI of form s3://bucket/key?versionId=version :rtype stri...
def to_s3_uri(code_dict): """Constructs a S3 URI string from given code dictionary :param dict code_dict: Dictionary containing Lambda function Code S3 location of the form {S3Bucket, S3Key, S3ObjectVersion} :return: S3 URI of form s3://bucket/key?versionId=version :rtype stri...
[ "Constructs", "a", "S3", "URI", "string", "from", "given", "code", "dictionary" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L30-L48
[ "def", "to_s3_uri", "(", "code_dict", ")", ":", "try", ":", "uri", "=", "\"s3://{bucket}/{key}\"", ".", "format", "(", "bucket", "=", "code_dict", "[", "\"S3Bucket\"", "]", ",", "key", "=", "code_dict", "[", "\"S3Key\"", "]", ")", "version", "=", "code_dic...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
construct_s3_location_object
Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property. This follows the current scheme for Lambda Functions and LayerVersions. :param dict or string location_uri: s3 location dict or string :param string logical_id: logical_id of the resource calling this functio...
samtranslator/model/s3_utils/uri_parser.py
def construct_s3_location_object(location_uri, logical_id, property_name): """Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property. This follows the current scheme for Lambda Functions and LayerVersions. :param dict or string location_uri: s3 location dict or st...
def construct_s3_location_object(location_uri, logical_id, property_name): """Constructs a Lambda `Code` or `Content` property, from the SAM `CodeUri` or `ContentUri` property. This follows the current scheme for Lambda Functions and LayerVersions. :param dict or string location_uri: s3 location dict or st...
[ "Constructs", "a", "Lambda", "Code", "or", "Content", "property", "from", "the", "SAM", "CodeUri", "or", "ContentUri", "property", ".", "This", "follows", "the", "current", "scheme", "for", "Lambda", "Functions", "and", "LayerVersions", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L51-L86
[ "def", "construct_s3_location_object", "(", "location_uri", ",", "logical_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "location_uri", ",", "dict", ")", ":", "if", "not", "location_uri", ".", "get", "(", "\"Bucket\"", ")", "or", "not", "locati...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
FunctionPolicies._get_policies
Returns a list of policies from the resource properties. This method knows how to interpret and handle polymorphic nature of the policies property. Policies can be one of the following: * Managed policy name: string * List of managed policy names: list of strings * ...
samtranslator/model/function_policies.py
def _get_policies(self, resource_properties): """ Returns a list of policies from the resource properties. This method knows how to interpret and handle polymorphic nature of the policies property. Policies can be one of the following: * Managed policy name: string ...
def _get_policies(self, resource_properties): """ Returns a list of policies from the resource properties. This method knows how to interpret and handle polymorphic nature of the policies property. Policies can be one of the following: * Managed policy name: string ...
[ "Returns", "a", "list", "of", "policies", "from", "the", "resource", "properties", ".", "This", "method", "knows", "how", "to", "interpret", "and", "handle", "polymorphic", "nature", "of", "the", "policies", "property", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L55-L94
[ "def", "_get_policies", "(", "self", ",", "resource_properties", ")", ":", "policies", "=", "None", "if", "self", ".", "_contains_policies", "(", "resource_properties", ")", ":", "policies", "=", "resource_properties", "[", "self", ".", "POLICIES_PROPERTY_NAME", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
FunctionPolicies._contains_policies
Is there policies data in this resource? :param dict resource_properties: Properties of the resource :return: True if we can process this resource. False, otherwise
samtranslator/model/function_policies.py
def _contains_policies(self, resource_properties): """ Is there policies data in this resource? :param dict resource_properties: Properties of the resource :return: True if we can process this resource. False, otherwise """ return resource_properties is not None \ ...
def _contains_policies(self, resource_properties): """ Is there policies data in this resource? :param dict resource_properties: Properties of the resource :return: True if we can process this resource. False, otherwise """ return resource_properties is not None \ ...
[ "Is", "there", "policies", "data", "in", "this", "resource?" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L96-L105
[ "def", "_contains_policies", "(", "self", ",", "resource_properties", ")", ":", "return", "resource_properties", "is", "not", "None", "and", "isinstance", "(", "resource_properties", ",", "dict", ")", "and", "self", ".", "POLICIES_PROPERTY_NAME", "in", "resource_pro...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
FunctionPolicies._get_type
Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred
samtranslator/model/function_policies.py
def _get_type(self, policy): """ Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred """ # Must handle intrinsic functions. Policy could be a primitive type or ...
def _get_type(self, policy): """ Returns the type of the given policy :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred """ # Must handle intrinsic functions. Policy could be a primitive type or ...
[ "Returns", "the", "type", "of", "the", "given", "policy" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L107-L130
[ "def", "_get_type", "(", "self", ",", "policy", ")", ":", "# Must handle intrinsic functions. Policy could be a primitive type or an intrinsic function", "# Managed policies are either string or an intrinsic function that resolves to a string", "if", "isinstance", "(", "policy", ",", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
FunctionPolicies._is_policy_template
Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name of the template. :param dict policy: Policy data :return: True, if this is a policy template. False if it is not
samtranslator/model/function_policies.py
def _is_policy_template(self, policy): """ Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name of the template. :param dict policy: Policy data :return: True, if this is a policy template. False if it is not """ ...
def _is_policy_template(self, policy): """ Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name of the template. :param dict policy: Policy data :return: True, if this is a policy template. False if it is not """ ...
[ "Is", "the", "given", "policy", "data", "a", "policy", "template?", "Policy", "templates", "is", "a", "dictionary", "with", "one", "key", "which", "is", "the", "name", "of", "the", "template", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L132-L144
[ "def", "_is_policy_template", "(", "self", ",", "policy", ")", ":", "return", "self", ".", "_policy_template_processor", "is", "not", "None", "and", "isinstance", "(", "policy", ",", "dict", ")", "and", "len", "(", "policy", ")", "==", "1", "and", "self", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Client.get_thing_shadow
r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the GetThingShadow operation * *payload* (``bytes``) -...
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
def get_thing_shadow(self, **kwargs): r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the GetThingShadow o...
def get_thing_shadow(self, **kwargs): r""" Call shadow lambda to obtain current shadow state. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the GetThingShadow o...
[ "r", "Call", "shadow", "lambda", "to", "obtain", "current", "shadow", "state", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L28-L45
[ "def", "get_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'get'"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Client.update_thing_shadow
r""" Updates the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. * *payload* (``bytes or seekable file-like object``) -- [REQUIRED] The state informa...
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
def update_thing_shadow(self, **kwargs): r""" Updates the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. * *payload* (``bytes or seekable file-like object``) -- ...
def update_thing_shadow(self, **kwargs): r""" Updates the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. * *payload* (``bytes or seekable file-like object``) -- ...
[ "r", "Updates", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L47-L67
[ "def", "update_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "self", ".", "_get_required_parameter", "(", "'payload'",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Client.delete_thing_shadow
r""" Deletes the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the DeleteThingShadow operation * *payload* (``bytes``)...
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
def delete_thing_shadow(self, **kwargs): r""" Deletes the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the DeleteThingSha...
def delete_thing_shadow(self, **kwargs): r""" Deletes the thing shadow for the specified thing. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the DeleteThingSha...
[ "r", "Deletes", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L69-L86
[ "def", "delete_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'de...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Client.publish
r""" Publishes state information. :Keyword Arguments: * *topic* (``string``) -- [REQUIRED] The name of the MQTT topic. * *payload* (``bytes or seekable file-like object``) -- The state information, in JSON format. :returns: None
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
def publish(self, **kwargs): r""" Publishes state information. :Keyword Arguments: * *topic* (``string``) -- [REQUIRED] The name of the MQTT topic. * *payload* (``bytes or seekable file-like object``) -- The state information, in...
def publish(self, **kwargs): r""" Publishes state information. :Keyword Arguments: * *topic* (``string``) -- [REQUIRED] The name of the MQTT topic. * *payload* (``bytes or seekable file-like object``) -- The state information, in...
[ "r", "Publishes", "state", "information", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L88-L120
[ "def", "publish", "(", "self", ",", "*", "*", "kwargs", ")", ":", "topic", "=", "self", ".", "_get_required_parameter", "(", "'topic'", ",", "*", "*", "kwargs", ")", "# payload is an optional parameter", "payload", "=", "kwargs", ".", "get", "(", "'payload'"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Globals.merge
Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties for this resource type :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function) :param dict resource_properties: Properties of the resource that need to be mer...
samtranslator/plugins/globals/globals.py
def merge(self, resource_type, resource_properties): """ Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties for this resource type :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function) :param...
def merge(self, resource_type, resource_properties): """ Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties for this resource type :param string resource_type: Type of the resource (Ex: AWS::Serverless::Function) :param...
[ "Adds", "global", "properties", "to", "the", "resource", "if", "necessary", ".", "This", "method", "is", "a", "no", "-", "op", "if", "there", "are", "no", "global", "properties", "for", "this", "resource", "type" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L80-L96
[ "def", "merge", "(", "self", ",", "resource_type", ",", "resource_properties", ")", ":", "if", "resource_type", "not", "in", "self", ".", "template_globals", ":", "# Nothing to do. Return the template unmodified", "return", "resource_properties", "global_props", "=", "s...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Globals._parse
Takes a SAM template as input and parses the Globals section :param globals_dict: Dictionary representation of the Globals section :return: Processed globals dictionary which can be used to quickly identify properties to merge :raises: InvalidResourceException if the input contains properties t...
samtranslator/plugins/globals/globals.py
def _parse(self, globals_dict): """ Takes a SAM template as input and parses the Globals section :param globals_dict: Dictionary representation of the Globals section :return: Processed globals dictionary which can be used to quickly identify properties to merge :raises: Invalid...
def _parse(self, globals_dict): """ Takes a SAM template as input and parses the Globals section :param globals_dict: Dictionary representation of the Globals section :return: Processed globals dictionary which can be used to quickly identify properties to merge :raises: Invalid...
[ "Takes", "a", "SAM", "template", "as", "input", "and", "parses", "the", "Globals", "section" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L110-L149
[ "def", "_parse", "(", "self", ",", "globals_dict", ")", ":", "globals", "=", "{", "}", "if", "not", "isinstance", "(", "globals_dict", ",", "dict", ")", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"It must be a non-empt...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
GlobalProperties._do_merge
Actually perform the merge operation for the given inputs. This method is used as part of the recursion. Therefore input values can be of any type. So is the output. :param global_value: Global value to be merged :param local_value: Local value to be merged :return: Merged result
samtranslator/plugins/globals/globals.py
def _do_merge(self, global_value, local_value): """ Actually perform the merge operation for the given inputs. This method is used as part of the recursion. Therefore input values can be of any type. So is the output. :param global_value: Global value to be merged :param local_v...
def _do_merge(self, global_value, local_value): """ Actually perform the merge operation for the given inputs. This method is used as part of the recursion. Therefore input values can be of any type. So is the output. :param global_value: Global value to be merged :param local_v...
[ "Actually", "perform", "the", "merge", "operation", "for", "the", "given", "inputs", ".", "This", "method", "is", "used", "as", "part", "of", "the", "recursion", ".", "Therefore", "input", "values", "can", "be", "of", "any", "type", ".", "So", "is", "the...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L286-L314
[ "def", "_do_merge", "(", "self", ",", "global_value", ",", "local_value", ")", ":", "token_global", "=", "self", ".", "_token_of", "(", "global_value", ")", "token_local", "=", "self", ".", "_token_of", "(", "local_value", ")", "# The following statements codify t...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
GlobalProperties._merge_dict
Merges the two dictionaries together :param global_dict: Global dictionary to be merged :param local_dict: Local dictionary to be merged :return: New merged dictionary with values shallow copied
samtranslator/plugins/globals/globals.py
def _merge_dict(self, global_dict, local_dict): """ Merges the two dictionaries together :param global_dict: Global dictionary to be merged :param local_dict: Local dictionary to be merged :return: New merged dictionary with values shallow copied """ # Local has...
def _merge_dict(self, global_dict, local_dict): """ Merges the two dictionaries together :param global_dict: Global dictionary to be merged :param local_dict: Local dictionary to be merged :return: New merged dictionary with values shallow copied """ # Local has...
[ "Merges", "the", "two", "dictionaries", "together" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L327-L349
[ "def", "_merge_dict", "(", "self", ",", "global_dict", ",", "local_dict", ")", ":", "# Local has higher priority than global. So iterate over local dict and merge into global if keys are overridden", "global_dict", "=", "global_dict", ".", "copy", "(", ")", "for", "key", "in"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
GlobalProperties._token_of
Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input
samtranslator/plugins/globals/globals.py
def _token_of(self, input): """ Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input """ if isinstance(input, dict): # Intrinsic functions are always dicts if is_intrinsi...
def _token_of(self, input): """ Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input """ if isinstance(input, dict): # Intrinsic functions are always dicts if is_intrinsi...
[ "Returns", "the", "token", "type", "of", "the", "input", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L362-L384
[ "def", "_token_of", "(", "self", ",", "input", ")", ":", "if", "isinstance", "(", "input", ",", "dict", ")", ":", "# Intrinsic functions are always dicts", "if", "is_intrinsics", "(", "input", ")", ":", "# Intrinsic functions are handled *exactly* like a primitive type ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamTemplateValidator.validate
Is this a valid SAM template dictionary :param dict template_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing SAM template :return: Empty string if there are no validation errors in template
samtranslator/validator/validator.py
def validate(template_dict, schema=None): """ Is this a valid SAM template dictionary :param dict template_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing SAM template :return: Empty string if there are no validation errors...
def validate(template_dict, schema=None): """ Is this a valid SAM template dictionary :param dict template_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing SAM template :return: Empty string if there are no validation errors...
[ "Is", "this", "a", "valid", "SAM", "template", "dictionary" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/validator/validator.py#L12-L35
[ "def", "validate", "(", "template_dict", ",", "schema", "=", "None", ")", ":", "if", "not", "schema", ":", "schema", "=", "SamTemplateValidator", ".", "_read_schema", "(", ")", "validation_errors", "=", "\"\"", "try", ":", "jsonschema", ".", "validate", "(",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
generate_car_price
Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations.
examples/apps/lex-book-trip-python/lambda_function.py
def generate_car_price(location, days, age, car_type): """ Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations. """ car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury'] base_location_cost ...
def generate_car_price(location, days, age, car_type): """ Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations. """ car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury'] base_location_cost ...
[ "Generates", "a", "number", "within", "a", "reasonable", "range", "that", "might", "be", "expected", "for", "a", "flight", ".", "The", "price", "is", "fixed", "for", "a", "given", "pair", "of", "locations", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L97-L113
[ "def", "generate_car_price", "(", "location", ",", "days", ",", "age", ",", "car_type", ")", ":", "car_types", "=", "[", "'economy'", ",", "'standard'", ",", "'midsize'", ",", "'full size'", ",", "'minivan'", ",", "'luxury'", "]", "base_location_cost", "=", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
generate_hotel_price
Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType.
examples/apps/lex-book-trip-python/lambda_function.py
def generate_hotel_price(location, nights, room_type): """ Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType. """ room_types = ['queen', 'king', 'deluxe'] cost_of_living = 0 for i in range(len(location)): ...
def generate_hotel_price(location, nights, room_type): """ Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType. """ room_types = ['queen', 'king', 'deluxe'] cost_of_living = 0 for i in range(len(location)): ...
[ "Generates", "a", "number", "within", "a", "reasonable", "range", "that", "might", "be", "expected", "for", "a", "hotel", ".", "The", "price", "is", "fixed", "for", "a", "pair", "of", "location", "and", "roomType", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L116-L127
[ "def", "generate_hotel_price", "(", "location", ",", "nights", ",", "room_type", ")", ":", "room_types", "=", "[", "'queen'", ",", "'king'", ",", "'deluxe'", "]", "cost_of_living", "=", "0", "for", "i", "in", "range", "(", "len", "(", "location", ")", ")...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
book_hotel
Performs dialog management and fulfillment for booking a hotel. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be used to guide conversation
examples/apps/lex-book-trip-python/lambda_function.py
def book_hotel(intent_request): """ Performs dialog management and fulfillment for booking a hotel. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be...
def book_hotel(intent_request): """ Performs dialog management and fulfillment for booking a hotel. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be...
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "hotel", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L261-L330
[ "def", "book_hotel", "(", "intent_request", ")", ":", "location", "=", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Location'", "]", ")", "checkin_date", "=", "try_ex", "(", "lambda", ":", "intent_r...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
book_car
Performs dialog management and fulfillment for booking a car. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be used to guide conversation
examples/apps/lex-book-trip-python/lambda_function.py
def book_car(intent_request): """ Performs dialog management and fulfillment for booking a car. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be use...
def book_car(intent_request): """ Performs dialog management and fulfillment for booking a car. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be use...
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "car", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L333-L484
[ "def", "book_car", "(", "intent_request", ")", ":", "slots", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "pickup_city", "=", "slots", "[", "'PickUpCity'", "]", "pickup_date", "=", "slots", "[", "'PickUpDate'", "]", "return_date", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
dispatch
Called when the user specifies an intent for this bot.
examples/apps/lex-book-trip-python/lambda_function.py
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "bot", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L490-L505
[ "def", "dispatch", "(", "intent_request", ")", ":", "logger", ".", "debug", "(", "'dispatch userId={}, intentName={}'", ".", "format", "(", "intent_request", "[", "'userId'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ")", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
PullEventSource.to_cloudformation
Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed policy to the function's execution role, if such a role is provided. :param dict kwargs: a dict containing the execution role generated for the function :returns: a list of vanilla CloudForm...
samtranslator/model/eventsources/pull.py
def to_cloudformation(self, **kwargs): """Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed policy to the function's execution role, if such a role is provided. :param dict kwargs: a dict containing the execution role generated for the func...
def to_cloudformation(self, **kwargs): """Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed policy to the function's execution role, if such a role is provided. :param dict kwargs: a dict containing the execution role generated for the func...
[ "Returns", "the", "Lambda", "EventSourceMapping", "to", "which", "this", "pull", "event", "corresponds", ".", "Adds", "the", "appropriate", "managed", "policy", "to", "the", "function", "s", "execution", "role", "if", "such", "a", "role", "is", "provided", "."...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L30-L73
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "resources...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
PullEventSource._link_policy
If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the appropriate managed policy to this Role. :param model.iam.IAMROle role: the execution role generated for the function
samtranslator/model/eventsources/pull.py
def _link_policy(self, role): """If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the appropriate managed policy to this Role. :param model.iam.IAMROle role: the execution role generated for the function """ policy_arn = self.get_polic...
def _link_policy(self, role): """If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the appropriate managed policy to this Role. :param model.iam.IAMROle role: the execution role generated for the function """ policy_arn = self.get_polic...
[ "If", "this", "source", "triggers", "a", "Lambda", "function", "whose", "execution", "role", "is", "auto", "-", "generated", "by", "SAM", "add", "the", "appropriate", "managed", "policy", "to", "this", "Role", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L75-L83
[ "def", "_link_policy", "(", "self", ",", "role", ")", ":", "policy_arn", "=", "self", ".", "get_policy_arn", "(", ")", "if", "role", "is", "not", "None", "and", "policy_arn", "not", "in", "role", ".", "ManagedPolicyArns", ":", "role", ".", "ManagedPolicyAr...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamParameterValues.add_default_parameter_values
Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String Default: default_value Param2: ...
samtranslator/sdk/parameter.py
def add_default_parameter_values(self, sam_template): """ Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String ...
def add_default_parameter_values(self, sam_template): """ Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String ...
[ "Method", "to", "read", "default", "values", "for", "template", "parameters", "and", "merge", "with", "user", "supplied", "values", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L19-L59
[ "def", "add_default_parameter_values", "(", "self", ",", "sam_template", ")", ":", "parameter_definition", "=", "sam_template", ".", "get", "(", "\"Parameters\"", ",", "None", ")", "if", "not", "parameter_definition", "or", "not", "isinstance", "(", "parameter_defin...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamParameterValues.add_pseudo_parameter_values
Add pseudo parameter values :return: parameter values that have pseudo parameter in it
samtranslator/sdk/parameter.py
def add_pseudo_parameter_values(self): """ Add pseudo parameter values :return: parameter values that have pseudo parameter in it """ if 'AWS::Region' not in self.parameter_values: self.parameter_values['AWS::Region'] = boto3.session.Session().region_name
def add_pseudo_parameter_values(self): """ Add pseudo parameter values :return: parameter values that have pseudo parameter in it """ if 'AWS::Region' not in self.parameter_values: self.parameter_values['AWS::Region'] = boto3.session.Session().region_name
[ "Add", "pseudo", "parameter", "values", ":", "return", ":", "parameter", "values", "that", "have", "pseudo", "parameter", "in", "it" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L61-L67
[ "def", "add_pseudo_parameter_values", "(", "self", ")", ":", "if", "'AWS::Region'", "not", "in", "self", ".", "parameter_values", ":", "self", ".", "parameter_values", "[", "'AWS::Region'", "]", "=", "boto3", ".", "session", ".", "Session", "(", ")", ".", "r...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
DeploymentPreferenceCollection.add
Add this deployment preference to the collection :raise ValueError if an existing logical id already exists in the _resource_preferences :param logical_id: logical id of the resource where this deployment preference applies :param deployment_preference_dict: the input SAM template deployment pr...
samtranslator/model/preferences/deployment_preference_collection.py
def add(self, logical_id, deployment_preference_dict): """ Add this deployment preference to the collection :raise ValueError if an existing logical id already exists in the _resource_preferences :param logical_id: logical id of the resource where this deployment preference applies ...
def add(self, logical_id, deployment_preference_dict): """ Add this deployment preference to the collection :raise ValueError if an existing logical id already exists in the _resource_preferences :param logical_id: logical id of the resource where this deployment preference applies ...
[ "Add", "this", "deployment", "preference", "to", "the", "collection" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L32-L44
[ "def", "add", "(", "self", ",", "logical_id", ",", "deployment_preference_dict", ")", ":", "if", "logical_id", "in", "self", ".", "_resource_preferences", ":", "raise", "ValueError", "(", "\"logical_id {logical_id} previously added to this deployment_preference_collection\"",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
DeploymentPreferenceCollection.enabled_logical_ids
:return: only the logical id's for the deployment preferences in this collection which are enabled
samtranslator/model/preferences/deployment_preference_collection.py
def enabled_logical_ids(self): """ :return: only the logical id's for the deployment preferences in this collection which are enabled """ return [logical_id for logical_id, preference in self._resource_preferences.items() if preference.enabled]
def enabled_logical_ids(self): """ :return: only the logical id's for the deployment preferences in this collection which are enabled """ return [logical_id for logical_id, preference in self._resource_preferences.items() if preference.enabled]
[ ":", "return", ":", "only", "the", "logical", "id", "s", "for", "the", "deployment", "preferences", "in", "this", "collection", "which", "are", "enabled" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L66-L70
[ "def", "enabled_logical_ids", "(", "self", ")", ":", "return", "[", "logical_id", "for", "logical_id", ",", "preference", "in", "self", ".", "_resource_preferences", ".", "items", "(", ")", "if", "preference", ".", "enabled", "]" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
DeploymentPreferenceCollection.deployment_group
:param function_logical_id: logical_id of the function this deployment group belongs to :return: CodeDeployDeploymentGroup resource
samtranslator/model/preferences/deployment_preference_collection.py
def deployment_group(self, function_logical_id): """ :param function_logical_id: logical_id of the function this deployment group belongs to :return: CodeDeployDeploymentGroup resource """ deployment_preference = self.get(function_logical_id) deployment_group = CodeDeplo...
def deployment_group(self, function_logical_id): """ :param function_logical_id: logical_id of the function this deployment group belongs to :return: CodeDeployDeploymentGroup resource """ deployment_preference = self.get(function_logical_id) deployment_group = CodeDeplo...
[ ":", "param", "function_logical_id", ":", "logical_id", "of", "the", "function", "this", "deployment", "group", "belongs", "to", ":", "return", ":", "CodeDeployDeploymentGroup", "resource" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L93-L121
[ "def", "deployment_group", "(", "self", ",", "function_logical_id", ")", ":", "deployment_preference", "=", "self", ".", "get", "(", "function_logical_id", ")", "deployment_group", "=", "CodeDeployDeploymentGroup", "(", "self", ".", "deployment_group_logical_id", "(", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
get_welcome_response
If we wanted to initialize the session to have some attributes we could add those here
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "Welcome to the Alexa Skills Kit sample. " \ "Please tell me your favorite color by sayin...
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "Welcome to the Alexa Skills Kit sample. " \ "Please tell me your favorite color by sayin...
[ "If", "we", "wanted", "to", "initialize", "the", "session", "to", "have", "some", "attributes", "we", "could", "add", "those", "here" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L46-L62
[ "def", "get_welcome_response", "(", ")", ":", "session_attributes", "=", "{", "}", "card_title", "=", "\"Welcome\"", "speech_output", "=", "\"Welcome to the Alexa Skills Kit sample. \"", "\"Please tell me your favorite color by saying, \"", "\"my favorite color is red\"", "# If the...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
set_color_in_session
Sets the color in the session and prepares the speech to reply to the user.
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
def set_color_in_session(intent, session): """ Sets the color in the session and prepares the speech to reply to the user. """ card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['va...
def set_color_in_session(intent, session): """ Sets the color in the session and prepares the speech to reply to the user. """ card_title = intent['name'] session_attributes = {} should_end_session = False if 'Color' in intent['slots']: favorite_color = intent['slots']['Color']['va...
[ "Sets", "the", "color", "in", "the", "session", "and", "prepares", "the", "speech", "to", "reply", "to", "the", "user", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L79-L104
[ "def", "set_color_in_session", "(", "intent", ",", "session", ")", ":", "card_title", "=", "intent", "[", "'name'", "]", "session_attributes", "=", "{", "}", "should_end_session", "=", "False", "if", "'Color'", "in", "intent", "[", "'slots'", "]", ":", "favo...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
on_intent
Called when the user specifies an intent for this skill
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # ...
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # ...
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "skill" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L148-L167
[ "def", "on_intent", "(", "intent_request", ",", "session", ")", ":", "print", "(", "\"on_intent requestId=\"", "+", "intent_request", "[", "'requestId'", "]", "+", "\", sessionId=\"", "+", "session", "[", "'sessionId'", "]", ")", "intent", "=", "intent_request", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
lambda_handler
Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter.
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) "...
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) "...
[ "Route", "the", "incoming", "request", "based", "on", "type", "(", "LaunchRequest", "IntentRequest", "etc", ".", ")", "The", "JSON", "body", "of", "the", "request", "is", "provided", "in", "the", "event", "parameter", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L182-L207
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "print", "(", "\"event.session.application.applicationId=\"", "+", "event", "[", "'session'", "]", "[", "'application'", "]", "[", "'applicationId'", "]", ")", "\"\"\"\n Uncomment this if statement and ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
LogicalIdGenerator.gen
Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is deterministic and stable based on input prefix & data object. In other words: logicalId changes *if and only if* either the `prefix` or `data_obj` changes Internally we simply use a SHA...
samtranslator/translator/logical_id_generator.py
def gen(self): """ Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is deterministic and stable based on input prefix & data object. In other words: logicalId changes *if and only if* either the `prefix` or `data_obj` changes ...
def gen(self): """ Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is deterministic and stable based on input prefix & data object. In other words: logicalId changes *if and only if* either the `prefix` or `data_obj` changes ...
[ "Generate", "stable", "LogicalIds", "based", "on", "the", "prefix", "and", "given", "data", ".", "This", "method", "ensures", "that", "the", "logicalId", "is", "deterministic", "and", "stable", "based", "on", "input", "prefix", "&", "data", "object", ".", "I...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L28-L47
[ "def", "gen", "(", "self", ")", ":", "data_hash", "=", "self", ".", "get_hash", "(", ")", "return", "\"{prefix}{hash}\"", ".", "format", "(", "prefix", "=", "self", ".", "_prefix", ",", "hash", "=", "data_hash", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
LogicalIdGenerator.get_hash
Generate and return a hash of data that can be used as suffix of logicalId :return: Hash of data if it was present :rtype string
samtranslator/translator/logical_id_generator.py
def get_hash(self, length=HASH_LENGTH): """ Generate and return a hash of data that can be used as suffix of logicalId :return: Hash of data if it was present :rtype string """ data_hash = "" if not self.data_str: return data_hash encoded_da...
def get_hash(self, length=HASH_LENGTH): """ Generate and return a hash of data that can be used as suffix of logicalId :return: Hash of data if it was present :rtype string """ data_hash = "" if not self.data_str: return data_hash encoded_da...
[ "Generate", "and", "return", "a", "hash", "of", "data", "that", "can", "be", "used", "as", "suffix", "of", "logicalId" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L49-L72
[ "def", "get_hash", "(", "self", ",", "length", "=", "HASH_LENGTH", ")", ":", "data_hash", "=", "\"\"", "if", "not", "self", ".", "data_str", ":", "return", "data_hash", "encoded_data_str", "=", "self", ".", "data_str", "if", "sys", ".", "version_info", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
LogicalIdGenerator._stringify
Stable, platform & language-independent stringification of a data with basic Python type. We use JSON to dump a string instead of `str()` method in order to be language independent. :param data: Data to be stringified. If this is one of JSON native types like string, dict, array etc, it will ...
samtranslator/translator/logical_id_generator.py
def _stringify(self, data): """ Stable, platform & language-independent stringification of a data with basic Python type. We use JSON to dump a string instead of `str()` method in order to be language independent. :param data: Data to be stringified. If this is one of JSON native types...
def _stringify(self, data): """ Stable, platform & language-independent stringification of a data with basic Python type. We use JSON to dump a string instead of `str()` method in order to be language independent. :param data: Data to be stringified. If this is one of JSON native types...
[ "Stable", "platform", "&", "language", "-", "independent", "stringification", "of", "a", "data", "with", "basic", "Python", "type", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L74-L90
[ "def", "_stringify", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "string_types", ")", ":", "return", "data", "# Get the most compact dictionary (separators) and sort the keys recursively to get a stable output", "return", "json", ".", "dumps"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SupportedResourceReferences.add
Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaF...
samtranslator/intrinsics/resource_refs.py
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" ...
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" ...
[ "Add", "the", "information", "that", "resource", "with", "given", "logical_id", "supports", "the", "given", "property", "and", "that", "a", "reference", "to", "logical_id", ".", "property", "resolves", "to", "given", "value", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L17-L44
[ "def", "add", "(", "self", ",", "logical_id", ",", "property", ",", "value", ")", ":", "if", "not", "logical_id", "or", "not", "property", ":", "raise", "ValueError", "(", "\"LogicalId and property must be a non-empty string\"", ")", "if", "not", "value", "or", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SupportedResourceReferences.get
Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all properties :return: Value of this property if present...
samtranslator/intrinsics/resource_refs.py
def get(self, logical_id, property): """ Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all prop...
def get(self, logical_id, property): """ Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all prop...
[ "Returns", "the", "value", "of", "the", "reference", "for", "given", "logical_id", "at", "given", "property", ".", "Ex", ":", "MyFunction", ".", "Alias" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L46-L60
[ "def", "get", "(", "self", ",", "logical_id", ",", "property", ")", ":", "# By defaulting to empty dictionary, we can handle the case where logical_id is not in map without if statements", "prop_values", "=", "self", ".", "get_all", "(", "logical_id", ")", "if", "prop_values"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
encrypt
encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
examples/2016-10-31/encryption_proxy/src/encryption.py
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.en...
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.en...
[ "encrypt", "leverages", "KMS", "encrypt", "and", "base64", "-", "encode", "encrypted", "blob" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/2016-10-31/encryption_proxy/src/encryption.py#L16-L29
[ "def", "encrypt", "(", "key", ",", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "encrypt", "(", "KeyId", "=", "key", ",", "Plaintext", "=", "message", ")", "encrypted_data", "=", "base64", ".", "encodestring", "(", "ret", ".", "get", "(",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
get_tag_list
Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dicti...
samtranslator/model/tags/resource_tagging.py
def get_tag_list(resource_tag_dict): """ Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` ...
def get_tag_list(resource_tag_dict): """ Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` ...
[ "Transforms", "the", "SAM", "defined", "Tags", "into", "the", "form", "CloudFormation", "is", "expecting", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/tags/resource_tagging.py#L7-L36
[ "def", "get_tag_list", "(", "resource_tag_dict", ")", ":", "tag_list", "=", "[", "]", "if", "resource_tag_dict", "is", "None", ":", "return", "tag_list", "for", "tag_key", ",", "tag_value", "in", "resource_tag_dict", ".", "items", "(", ")", ":", "tag", "=", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
ArnGenerator.get_partition_name
Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaul...
samtranslator/translator/arn_generator.py
def get_partition_name(cls, region=None): """ Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aw...
def get_partition_name(cls, region=None): """ Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aw...
[ "Gets", "the", "name", "of", "the", "partition", "given", "the", "region", "name", ".", "If", "region", "name", "is", "not", "provided", "this", "method", "will", "use", "Boto3", "to", "get", "name", "of", "the", "region", "where", "this", "code", "is", ...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/arn_generator.py#L33-L56
[ "def", "get_partition_name", "(", "cls", ",", "region", "=", "None", ")", ":", "if", "region", "is", "None", ":", "# Use Boto3 to get the region where code is running. This uses Boto's regular region resolution", "# mechanism, starting from AWS_DEFAULT_REGION environment variable.", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
DefaultDefinitionBodyPlugin.on_before_transform_template
Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing
samtranslator/plugins/api/default_definition_body_plugin.py
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template ...
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template ...
[ "Hook", "method", "that", "gets", "called", "before", "the", "SAM", "template", "is", "processed", ".", "The", "template", "has", "passed", "the", "validation", "and", "is", "guaranteed", "to", "contain", "a", "non", "-", "empty", "Resources", "section", "."...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/default_definition_body_plugin.py#L22-L37
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "template", "=", "SamTemplate", "(", "template_dict", ")", "for", "logicalId", ",", "api", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Api", ".", "value", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.has_path
Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document
samtranslator/swagger/swagger.py
def has_path(self, path, method=None): """ Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document """ method = self._normali...
def has_path(self, path, method=None): """ Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document """ method = self._normali...
[ "Returns", "True", "if", "this", "Swagger", "has", "the", "given", "path", "and", "optional", "method" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L46-L60
[ "def", "has_path", "(", "self", ",", "path", ",", "method", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "path_dict_exists", "=", "path_dict", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.method_has_integration
Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations
samtranslator/swagger/swagger.py
def method_has_integration(self, method): """ Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations ...
def method_has_integration(self, method): """ Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations ...
[ "Returns", "true", "if", "the", "given", "method", "contains", "a", "valid", "method", "definition", ".", "This", "uses", "the", "get_method_contents", "function", "to", "handle", "conditionals", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L62-L73
[ "def", "method_has_integration", "(", "self", ",", "method", ")", ":", "for", "method_definition", "in", "self", ".", "get_method_contents", "(", "method", ")", ":", "if", "self", ".", "method_definition_has_integration", "(", "method_definition", ")", ":", "retur...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.get_method_contents
Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dictionary :return: list of swagger component dictionari...
samtranslator/swagger/swagger.py
def get_method_contents(self, method): """ Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dicti...
def get_method_contents(self, method): """ Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dicti...
[ "Returns", "the", "swagger", "contents", "of", "the", "given", "method", ".", "This", "checks", "to", "see", "if", "a", "conditional", "block", "has", "been", "used", "inside", "of", "the", "method", "and", "if", "so", "returns", "the", "method", "contents...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L86-L97
[ "def", "get_method_contents", "(", "self", ",", "method", ")", ":", "if", "self", ".", "_CONDITIONAL_IF", "in", "method", ":", "return", "method", "[", "self", ".", "_CONDITIONAL_IF", "]", "[", "1", ":", "]", "return", "[", "method", "]" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.has_integration
Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present
samtranslator/swagger/swagger.py
def has_integration(self, path, method): """ Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present """ metho...
def has_integration(self, path, method): """ Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present """ metho...
[ "Checks", "if", "an", "API", "Gateway", "integration", "is", "already", "present", "at", "the", "given", "path", "/", "method" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L99-L112
[ "def", "has_integration", "(", "self", ",", "path", ",", "method", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "return", "self", ".", "has_path", "(", "p...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_path
Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary
samtranslator/swagger/swagger.py
def add_path(self, path, method=None): """ Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary """ method...
def add_path(self, path, method=None): """ Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary """ method...
[ "Adds", "the", "path", "/", "method", "combination", "to", "the", "Swagger", "if", "not", "already", "present" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L114-L135
[ "def", "add_path", "(", "self", ",", "path", ",", "method", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "paths", ".", "setdefault", "(", "path", ",", "{", "}", ")", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_lambda_integration
Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method :param string integration_uri: URI for the integration.
samtranslator/swagger/swagger.py
def add_lambda_integration(self, path, method, integration_uri, method_auth_config=None, api_auth_config=None, condition=None): """ Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method ...
def add_lambda_integration(self, path, method, integration_uri, method_auth_config=None, api_auth_config=None, condition=None): """ Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method ...
[ "Adds", "aws_proxy", "APIGW", "integration", "to", "the", "given", "path", "+", "method", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L137-L179
[ "def", "add_lambda_integration", "(", "self", ",", "path", ",", "method", ",", "integration_uri", ",", "method_auth_config", "=", "None", ",", "api_auth_config", "=", "None", ",", "condition", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_meth...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.make_path_conditional
Wrap entire API path definition in a CloudFormation if condition.
samtranslator/swagger/swagger.py
def make_path_conditional(self, path, condition): """ Wrap entire API path definition in a CloudFormation if condition. """ self.paths[path] = make_conditional(condition, self.paths[path])
def make_path_conditional(self, path, condition): """ Wrap entire API path definition in a CloudFormation if condition. """ self.paths[path] = make_conditional(condition, self.paths[path])
[ "Wrap", "entire", "API", "path", "definition", "in", "a", "CloudFormation", "if", "condition", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L181-L185
[ "def", "make_path_conditional", "(", "self", ",", "path", ",", "condition", ")", ":", "self", ".", "paths", "[", "path", "]", "=", "make_conditional", "(", "condition", ",", "self", ".", "paths", "[", "path", "]", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_cors
Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers into the actual response returned from Lambda function. This is something customers have ...
samtranslator/swagger/swagger.py
def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Si...
def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Si...
[ "Add", "CORS", "configuration", "to", "this", "path", ".", "Specifically", "we", "will", "add", "a", "OPTIONS", "response", "config", "to", "the", "Swagger", "that", "will", "return", "headers", "required", "for", "CORS", ".", "Since", "SAM", "uses", "aws_pr...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L205-L254
[ "def", "add_cors", "(", "self", ",", "path", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "# Skip if Options is already present", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor._options_method_response_for_cors
Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippet is taken from public documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string/dict a...
samtranslator/swagger/swagger.py
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippe...
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippe...
[ "Returns", "a", "Swagger", "snippet", "containing", "configuration", "for", "OPTIONS", "HTTP", "Method", "to", "configure", "CORS", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L256-L343
[ "def", "_options_method_response_for_cors", "(", "self", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "ALLOW_ORIGIN", "=", "\"Access-...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor._make_cors_allowed_methods_for_path
Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned as result. :param string path: Path to generate AllowMethods val...
samtranslator/swagger/swagger.py
def _make_cors_allowed_methods_for_path(self, path): """ Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned ...
def _make_cors_allowed_methods_for_path(self, path): """ Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned ...
[ "Creates", "the", "value", "for", "Access", "-", "Control", "-", "Allow", "-", "Methods", "header", "for", "given", "path", ".", "All", "HTTP", "methods", "defined", "for", "this", "path", "will", "be", "included", "in", "the", "result", ".", "If", "the"...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L345-L384
[ "def", "_make_cors_allowed_methods_for_path", "(", "self", ",", "path", ")", ":", "# https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html", "all_http_methods", "=", "[", "\"OPTIONS\"", ",", "\"GET\"", ",", "\"HEAD\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_authorizers
Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.
samtranslator/swagger/swagger.py
def add_authorizers(self, authorizers): """ Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions. """ self.security_definitions = self.security_definitions or...
def add_authorizers(self, authorizers): """ Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions. """ self.security_definitions = self.security_definitions or...
[ "Add", "Authorizer", "definitions", "to", "the", "securityDefinitions", "part", "of", "Swagger", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L386-L395
[ "def", "add_authorizers", "(", "self", ",", "authorizers", ")", ":", "self", ".", "security_definitions", "=", "self", ".", "security_definitions", "or", "{", "}", "for", "authorizer_name", ",", "authorizer", "in", "authorizers", ".", "items", "(", ")", ":", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.set_path_default_authorizer
Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the ...
samtranslator/swagger/swagger.py
def set_path_default_authorizer(self, path, default_authorizer, authorizers): """ Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param strin...
def set_path_default_authorizer(self, path, default_authorizer, authorizers): """ Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param strin...
[ "Sets", "the", "DefaultAuthorizer", "for", "each", "method", "on", "this", "path", ".", "The", "DefaultAuthorizer", "won", "t", "be", "set", "if", "an", "Authorizer", "was", "defined", "at", "the", "Function", "/", "Path", "/", "Method", "level" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L397-L409
[ "def", "set_path_default_authorizer", "(", "self", ",", "path", ",", "default_authorizer", ",", "authorizers", ")", ":", "for", "method_name", ",", "method", "in", "self", ".", "get_path", "(", "path", ")", ".", "items", "(", ")", ":", "self", ".", "set_me...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_auth_to_method
Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param d...
samtranslator/swagger/swagger.py
def add_auth_to_method(self, path, method_name, auth, api): """ Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string...
def add_auth_to_method(self, path, method_name, auth, api): """ Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string...
[ "Adds", "auth", "settings", "for", "this", "path", "/", "method", ".", "Auth", "settings", "currently", "consist", "solely", "of", "Authorizers", "but", "this", "method", "will", "eventually", "include", "setting", "other", "auth", "settings", "such", "as", "A...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L411-L429
[ "def", "add_auth_to_method", "(", "self", ",", "path", ",", "method_name", ",", "auth", ",", "api", ")", ":", "method_authorizer", "=", "auth", "and", "auth", ".", "get", "(", "'Authorizer'", ")", "if", "method_authorizer", ":", "api_auth", "=", "api", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.add_gateway_responses
Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.
samtranslator/swagger/swagger.py
def add_gateway_responses(self, gateway_responses): """ Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated. """ self.gateway_responses = self.gateway_responses or {} for response_...
def add_gateway_responses(self, gateway_responses): """ Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated. """ self.gateway_responses = self.gateway_responses or {} for response_...
[ "Add", "Gateway", "Response", "definitions", "to", "Swagger", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L516-L525
[ "def", "add_gateway_responses", "(", "self", ",", "gateway_responses", ")", ":", "self", ".", "gateway_responses", "=", "self", ".", "gateway_responses", "or", "{", "}", "for", "response_type", ",", "response", "in", "gateway_responses", ".", "items", "(", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.swagger
Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document
samtranslator/swagger/swagger.py
def swagger(self): """ Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document """ # Make sure any changes to the paths are reflected back in output self._doc["paths"] = self.paths if self.security_de...
def swagger(self): """ Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document """ # Make sure any changes to the paths are reflected back in output self._doc["paths"] = self.paths if self.security_de...
[ "Returns", "a", "**", "copy", "**", "of", "the", "Swagger", "document", "as", "a", "dictionary", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L528-L543
[ "def", "swagger", "(", "self", ")", ":", "# Make sure any changes to the paths are reflected back in output", "self", ".", "_doc", "[", "\"paths\"", "]", "=", "self", ".", "paths", "if", "self", ".", "security_definitions", ":", "self", ".", "_doc", "[", "\"securi...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor.is_valid
Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger
samtranslator/swagger/swagger.py
def is_valid(data): """ Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger """ return bool(data) and \ isinstance(data, dict) and \ bool(data.get("swagger")) and \ ...
def is_valid(data): """ Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger """ return bool(data) and \ isinstance(data, dict) and \ bool(data.get("swagger")) and \ ...
[ "Checks", "if", "the", "input", "data", "is", "a", "Swagger", "document" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L546-L556
[ "def", "is_valid", "(", "data", ")", ":", "return", "bool", "(", "data", ")", "and", "isinstance", "(", "data", ",", "dict", ")", "and", "bool", "(", "data", ".", "get", "(", "\"swagger\"", ")", ")", "and", "isinstance", "(", "data", ".", "get", "(...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SwaggerEditor._normalize_method_name
Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP Method :return string: Normalized method name
samtranslator/swagger/swagger.py
def _normalize_method_name(method): """ Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP M...
def _normalize_method_name(method): """ Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP M...
[ "Returns", "a", "lower", "case", "normalized", "version", "of", "HTTP", "Method", ".", "It", "also", "know", "how", "to", "handle", "API", "Gateway", "specific", "methods", "like", "ANY" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L576-L593
[ "def", "_normalize_method_name", "(", "method", ")", ":", "if", "not", "method", "or", "not", "isinstance", "(", "method", ",", "string_types", ")", ":", "return", "method", "method", "=", "method", ".", "lower", "(", ")", "if", "method", "==", "'any'", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
GlobalsPlugin.on_before_transform_template
Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary
samtranslator/plugins/globals/globals_plugin.py
def on_before_transform_template(self, template_dict): """ Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary """ try: ...
def on_before_transform_template(self, template_dict): """ Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary """ try: ...
[ "Hook", "method", "that", "runs", "before", "a", "template", "gets", "transformed", ".", "In", "this", "method", "we", "parse", "and", "process", "Globals", "section", "from", "the", "template", "(", "if", "present", ")", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals_plugin.py#L20-L40
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "try", ":", "global_section", "=", "Globals", "(", "template_dict", ")", "except", "InvalidGlobalsSectionException", "as", "ex", ":", "raise", "InvalidDocumentException", "(", "[", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd