INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 resolution model ). May use ... | 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,
... |
Add the epoch number to the batch instances as a MetadataField. | 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 |
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 beginning. | 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... |
Breaks the dataset into memory - sized lists of instances which it yields up one at a time until it gets through a full epoch. | 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... |
If self. _maximum_samples_per_batch is specified then split the batch into smaller sub - batches if it exceeds the maximum size. | 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... |
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. | 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... |
This method should return one epoch worth of batches. | def _create_batches(self, instances: Iterable[Instance], shuffle: bool) -> Iterable[Batch]:
"""
This method should return one epoch worth of batches.
"""
raise NotImplementedError |
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: the message with ca... | 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.
... |
Context manager that captures the internal - module outputs of this predictor s model. The idea is that you could use it as follows: | 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:
... |
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_instance should be implemente... | 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 ... |
Instantiate a: class: Predictor from an archive path. | 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: 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. | 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... |
Compute Scaled Dot Product Attention | 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... |
Mask out subsequent positions. | 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 |
Helper: Construct a model from hyperparameters. | 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... |
Pass the input ( and mask ) through each layer in turn. | 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[... |
Apply residual connection to any sublayer with the same size. | 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))) |
Follow Figure 1 ( left ) for connections. | 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) |
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 scale i... | 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 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 initialized independently. | 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... |
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 | 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... |
Converts a Params object into an InitializerApplicator. The json should be formatted as follows:: | 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",
{
... |
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: | 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 JSON objects ( dicts ) here. This is useful when you are reading data from a demo. The expected format is:: | 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"... |
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 ). | 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... |
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 list of length one. | 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... |
Returns true if there is any cell in this column that can be split. | 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) |
Checks whether the cell should be split. We re just doing the same thing that SEMPRE did here. | 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 |
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. | 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... |
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. | 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 ... |
Return an Element from span ( list of spacy toks ) | 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))) |
Ensure single word predicate by adding before - predicate and after - predicate arguments. | 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 ... |
Return a conll representation of a given input Extraction. | 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 an integer tuple from textual representation of closed/ open 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 = []
... |
Construct an Element instance from regexp groups. | 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) |
Parse a raw element into text and indices ( integers ). | 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(';')... |
Given a list of extractions for a single sentence - convert it to conll representation. | 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.... |
Pad line to conform to ontonotes representation. | 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, '-',\
... |
Given a dictionary from sentence - > extractions return a corresponding CoNLL representation. | 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 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 aggregated data ... | 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... |
Parses a S3 Uri into a dictionary of the Bucket Key and VersionId | 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... |
Constructs a S3 URI string from given code dictionary | 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 Lambda Code or Content property from the SAM CodeUri or ContentUri property. This follows the current scheme for Lambda Functions and LayerVersions. | 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... |
Returns a list of policies from the resource properties. This method knows how to interpret and handle polymorphic nature of the policies property. | 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
... |
Is there policies data in this resource? | 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 \
... |
Returns the type of the given policy | 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 ... |
Is the given policy data a policy template? Policy templates is a dictionary with one key which is the name of the template. | 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
"""
... |
r Call shadow lambda to obtain current shadow state. | 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 Updates the thing shadow for the specified thing. | 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 Deletes the thing shadow for the specified thing. | 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 Publishes state information. | 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... |
Adds global properties to the resource if necessary. This method is a no - op if there are no global properties for this resource type | 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... |
Takes a SAM template as input and parses the Globals section | 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... |
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. | 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... |
Merges the two dictionaries together | 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... |
Returns the token type of the input. | 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... |
Is this a valid SAM template dictionary | 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... |
Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations. | 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 hotel. The price is fixed for a pair of location and roomType. | 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)):
... |
Performs dialog management and fulfillment for booking a hotel. | 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 car. | 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... |
Called when the user specifies an intent for this 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... |
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. | 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... |
If this source triggers a Lambda function whose execution role is auto - generated by SAM add the appropriate managed policy to this Role. | 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... |
Method to read default values for template parameters and merge with user supplied values. | 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
... |
Add pseudo parameter values: return: parameter values that have pseudo parameter in it | 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 this deployment preference to the collection | 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
... |
: return: only the logical id s for the deployment preferences in this collection which are 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] |
: param function_logical_id: logical_id of the function this deployment group belongs to: return: CodeDeployDeploymentGroup resource | 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... |
If we wanted to initialize the session to have some attributes we could add those here | 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... |
Sets the color in the session and prepares the speech to reply to the user. | 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... |
Called when the user specifies an intent for this skill | 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']
# ... |
Route the incoming request based on type ( LaunchRequest IntentRequest etc. ) The JSON body of the request is provided in the event parameter. | 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'])
"... |
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: | 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 and return a hash of data that can be used as suffix of logicalId | 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... |
Stable platform & language - independent stringification of a data with basic Python type. | 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... |
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. | 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"
... |
Returns the value of the reference for given logical_id at given property. Ex: MyFunction. Alias | 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... |
encrypt leverages KMS encrypt and base64 - encode encrypted blob | 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... |
Transforms the SAM defined Tags into the form CloudFormation is expecting. | 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
```
... |
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. | 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... |
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. | 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
... |
Returns True if this Swagger has the given path and optional method | 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 the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. | 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 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. | 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... |
Checks if an API Gateway integration is already present at the given path/ method | 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... |
Adds the path/ method combination to the Swagger if not already present | 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 aws_proxy APIGW integration to the given path + 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
... |
Wrap entire API path definition in a CloudFormation if condition. | 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]) |
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 to implement thems... | 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... |
Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. | 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... |
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. | 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 ... |
Add Authorizer definitions to the securityDefinitions part of Swagger. | 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... |
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 | 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... |
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. | 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... |
Add Gateway Response definitions to Swagger. | 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_... |
Returns a ** copy ** of the Swagger document as a dictionary. | 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... |
Checks if the input data is a Swagger document | 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 \
... |
Returns a lower case normalized version of HTTP Method. It also know how to handle API Gateway specific methods like ANY | 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... |
Hook method that runs before a template gets transformed. In this method we parse and process Globals section from the template ( if present ). | 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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.