INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 ``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 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...
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:: [ ["parameter_regex_match1", { "type": "normal" "mean": 0.01 "std": 0.1 }...
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: Nation Olympics Medals USA 1896 8 China 1932 ...
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:: {"question": [token1, token2, ...], "columns": [column1, column2, ...], "cells": [[row1_cell1, row1_cell2, ...], [ro...
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"). We also handle y...
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 li...
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 a...
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 :return: a BodyS3Location dict or None if not an S3 Uri :rtype: dict
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 :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
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. :param dict or string location_uri: s3 location dict or string :param string logical_id: logical_id of the resource calling this functio...
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. Policies can be one of the following: * Managed policy name: string * List of managed policy names: list of strings * ...
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? :param dict resource_properties: Properties of the resource :return: True if we can process this resource. False, otherwise
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 :param string or dict policy: Policy data :return PolicyTypes: Type of the given policy. None, if type could not be inferred
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. :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 """ ...
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``) -...
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. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. * *payload* (``bytes or seekable file-like object``) -- [REQUIRED] The state informa...
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. :Keyword Arguments: * *thingName* (``string``) -- [REQUIRED] The name of the thing. :returns: (``dict``) -- The output from the DeleteThingShadow operation * *payload* (``bytes``)...
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. :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
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 :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...
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 :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...
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. :param global_value: Global value to be merged :param local_value: Local value to be merged :return: Merged result
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 :param global_dict: Global dictionary to be merged :param local_dict: Local dictionary to be merged :return: New merged dictionary with values shallow copied
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. :param input: Input whose type is to be determined :return TOKENS: 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 :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
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. 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
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. 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
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. :param dict kwargs: a dict containing the execution role generated for the function :returns: a list of vanilla CloudForm...
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. :param model.iam.IAMROle role: the execution role generated for the function
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. Example: If the template contains the following parameters defined Parameters: Param1: Type: String Default: default_value Param2: ...
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 :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...
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: logicalId changes *if and only if* either the `prefix` or `data_obj` changes Internally we simply use a SHA...
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 :return: Hash of data if it was present :rtype string
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. 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 ...
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. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaF...
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 :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...
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 More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
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. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dicti...
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. This implementation is borrowed from AWS CLI https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaul...
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. :param dict template_dict: Dictionary of the SAM template :return: Nothing
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 :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document
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. :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 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...
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 :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present
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 :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary
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. :param string path: Path name :param string method: HTTP Method :param string integration_uri: URI for the integration.
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 ...
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. 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...
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. :param string path: Path to generate AllowMethods val...
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. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.
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 :param string path: Path name :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the ...
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. :param string path: Path name :param string method_name: Method name :param d...
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. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.
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. :return dict: Dictionary containing the Swagger document
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 :param dict data: Data to be validated :return: True, if data is a Swagger
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" 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
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). :param dict template_dict: SAM template as a dictionary
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: ...
Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise :rtype: callable
def is_type(valid_type): """Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwis...
Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True its input is an list of valid items,...
def list_of(validate_item): """Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True i...
Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in the dict :param callable validate_item: the va...
def dict_of(validate_key, validate_item): """Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in t...
Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError otherwise :rtype: call...
def one_of(*validators): """Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError ...
With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Dictionary containing policy statement :raises InvalidPa...
def to_statement(self, parameter_values): """ With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Di...
Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are missing. :raises InvalidParameterValues: When parameter values is not ...
def missing_parameter_values(self, parameter_values): """ Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are miss...
Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the JSON Schema validation. :return Template: Instance of this clas...
def from_dict(template_name, template_values_dict): """ Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the...
Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already regis...
def register(self, plugin): """ Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins....
Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise
def _get(self, plugin_name): """ Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise """ for p in self._plugins: if p.name == pl...
Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event to act upon :return: Nothing :raises ValueE...
def act(self, event, *args, **kwargs): """ Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event ...
:param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return:
def from_dict(cls, logical_id, deployment_preference_dict): """ :param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return: """ enabled = deployment_preferen...
decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html
def decrypt(message): '''decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html ''' try: ret = kms.decrypt( CiphertextBlob=base64.decodestring(message)) dec...
Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object.
def lambda_handler(event, context): '''Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object. ''' #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event bucket = event['Records'][0]['s3']['bucket']['name'] k...
Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message to prepend :param str end: the separator to a...
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message...
Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Call out to the OAuth provider 2. Decode a JWT token inline 3. Lookup in a self-managed DB
def lambda_handler(event, context): # incoming token value token = event['authorizationToken'] print("Method ARN: " + event['methodArn']) ''' Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Ca...