id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
23,200
allenai/allennlp
allennlp/semparse/contexts/table_question_knowledge_graph.py
TableQuestionKnowledgeGraph.get_linked_agenda_items
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 learning to search parser. """ agenda_items: List[str] = [] for entity in self._get_longest_span_matching_entities(): agenda_items.append(entity) # If the entity is a cell, we need to add the column to the agenda as well, # because the answer most likely involves getting the row with the cell. if 'fb:cell' in entity: agenda_items.append(self.neighbors[entity][0]) return agenda_items
python
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 learning to search parser. """ agenda_items: List[str] = [] for entity in self._get_longest_span_matching_entities(): agenda_items.append(entity) # If the entity is a cell, we need to add the column to the agenda as well, # because the answer most likely involves getting the row with the cell. if 'fb:cell' in entity: agenda_items.append(self.neighbors[entity][0]) return agenda_items
[ "def", "get_linked_agenda_items", "(", "self", ")", "->", "List", "[", "str", "]", ":", "agenda_items", ":", "List", "[", "str", "]", "=", "[", "]", "for", "entity", "in", "self", ".", "_get_longest_span_matching_entities", "(", ")", ":", "agenda_items", ".", "append", "(", "entity", ")", "# If the entity is a cell, we need to add the column to the agenda as well,", "# because the answer most likely involves getting the row with the cell.", "if", "'fb:cell'", "in", "entity", ":", "agenda_items", ".", "append", "(", "self", ".", "neighbors", "[", "entity", "]", "[", "0", "]", ")", "return", "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.
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/table_question_knowledge_graph.py#L345-L358
23,201
allenai/allennlp
scripts/convert_openie_to_conll.py
split_predicate
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 not rel_toks: return ex verb_inds = [tok_ind for (tok_ind, tok) in enumerate(rel_toks) if tok.tag_.startswith('VB')] last_verb_ind = verb_inds[-1] if verb_inds \ else (len(rel_toks) - 1) rel_parts = [element_from_span([rel_toks[last_verb_ind]], 'V')] before_verb = rel_toks[ : last_verb_ind] after_verb = rel_toks[last_verb_ind + 1 : ] if before_verb: rel_parts.append(element_from_span(before_verb, "BV")) if after_verb: rel_parts.append(element_from_span(after_verb, "AV")) return Extraction(ex.sent, ex.toks, ex.arg1, rel_parts, ex.args2, ex.confidence)
python
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 not rel_toks: return ex verb_inds = [tok_ind for (tok_ind, tok) in enumerate(rel_toks) if tok.tag_.startswith('VB')] last_verb_ind = verb_inds[-1] if verb_inds \ else (len(rel_toks) - 1) rel_parts = [element_from_span([rel_toks[last_verb_ind]], 'V')] before_verb = rel_toks[ : last_verb_ind] after_verb = rel_toks[last_verb_ind + 1 : ] if before_verb: rel_parts.append(element_from_span(before_verb, "BV")) if after_verb: rel_parts.append(element_from_span(after_verb, "AV")) return Extraction(ex.sent, ex.toks, ex.arg1, rel_parts, ex.args2, ex.confidence)
[ "def", "split_predicate", "(", "ex", ":", "Extraction", ")", "->", "Extraction", ":", "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", "not", "rel_toks", ":", "return", "ex", "verb_inds", "=", "[", "tok_ind", "for", "(", "tok_ind", ",", "tok", ")", "in", "enumerate", "(", "rel_toks", ")", "if", "tok", ".", "tag_", ".", "startswith", "(", "'VB'", ")", "]", "last_verb_ind", "=", "verb_inds", "[", "-", "1", "]", "if", "verb_inds", "else", "(", "len", "(", "rel_toks", ")", "-", "1", ")", "rel_parts", "=", "[", "element_from_span", "(", "[", "rel_toks", "[", "last_verb_ind", "]", "]", ",", "'V'", ")", "]", "before_verb", "=", "rel_toks", "[", ":", "last_verb_ind", "]", "after_verb", "=", "rel_toks", "[", "last_verb_ind", "+", "1", ":", "]", "if", "before_verb", ":", "rel_parts", ".", "append", "(", "element_from_span", "(", "before_verb", ",", "\"BV\"", ")", ")", "if", "after_verb", ":", "rel_parts", ".", "append", "(", "element_from_span", "(", "after_verb", ",", "\"AV\"", ")", ")", "return", "Extraction", "(", "ex", ".", "sent", ",", "ex", ".", "toks", ",", "ex", ".", "arg1", ",", "rel_parts", ",", "ex", ".", "args2", ",", "ex", ".", "confidence", ")" ]
Ensure single word predicate by adding "before-predicate" and "after-predicate" arguments.
[ "Ensure", "single", "word", "predicate", "by", "adding", "before", "-", "predicate", "and", "after", "-", "predicate", "arguments", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L79-L109
23,202
allenai/allennlp
scripts/convert_openie_to_conll.py
extraction_to_conll
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) for arg_ind, arg in enumerate(args)] + \ [(rel_part.elem_type, rel_part) for rel_part in ex.rel] for rel, arg in rels_and_args: # Add brackets cur_start_ind = char_to_word_index(arg.span[0], ex.sent) cur_end_ind = char_to_word_index(arg.span[1], ex.sent) ret[cur_start_ind] = "({}{}".format(rel, ret[cur_start_ind]) ret[cur_end_ind] += ')' return ret
python
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) for arg_ind, arg in enumerate(args)] + \ [(rel_part.elem_type, rel_part) for rel_part in ex.rel] for rel, arg in rels_and_args: # Add brackets cur_start_ind = char_to_word_index(arg.span[0], ex.sent) cur_end_ind = char_to_word_index(arg.span[1], ex.sent) ret[cur_start_ind] = "({}{}".format(rel, ret[cur_start_ind]) ret[cur_end_ind] += ')' return ret
[ "def", "extraction_to_conll", "(", "ex", ":", "Extraction", ")", "->", "List", "[", "str", "]", ":", "ex", "=", "split_predicate", "(", "ex", ")", "toks", "=", "ex", ".", "sent", ".", "split", "(", "' '", ")", "ret", "=", "[", "'*'", "]", "*", "len", "(", "toks", ")", "args", "=", "[", "ex", ".", "arg1", "]", "+", "ex", ".", "args2", "rels_and_args", "=", "[", "(", "\"ARG{}\"", ".", "format", "(", "arg_ind", ")", ",", "arg", ")", "for", "arg_ind", ",", "arg", "in", "enumerate", "(", "args", ")", "]", "+", "[", "(", "rel_part", ".", "elem_type", ",", "rel_part", ")", "for", "rel_part", "in", "ex", ".", "rel", "]", "for", "rel", ",", "arg", "in", "rels_and_args", ":", "# Add brackets", "cur_start_ind", "=", "char_to_word_index", "(", "arg", ".", "span", "[", "0", "]", ",", "ex", ".", "sent", ")", "cur_end_ind", "=", "char_to_word_index", "(", "arg", ".", "span", "[", "1", "]", ",", "ex", ".", "sent", ")", "ret", "[", "cur_start_ind", "]", "=", "\"({}{}\"", ".", "format", "(", "rel", ",", "ret", "[", "cur_start_ind", "]", ")", "ret", "[", "cur_end_ind", "]", "+=", "')'", "return", "ret" ]
Return a conll representation of a given input Extraction.
[ "Return", "a", "conll", "representation", "of", "a", "given", "input", "Extraction", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L111-L133
23,203
allenai/allennlp
scripts/convert_openie_to_conll.py
interpret_element
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)
python
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", ":", "return", "Element", "(", "element_type", ",", "interpret_span", "(", "span", ")", ",", "text", ")" ]
Construct an Element instance from regexp groups.
[ "Construct", "an", "Element", "instance", "from", "regexp", "groups", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L177-L184
23,204
allenai/allennlp
scripts/convert_openie_to_conll.py
convert_sent_to_conll
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.split(' ') return safe_zip(*[range(len(toks)), toks] + \ [extraction_to_conll(ex) for ex in sent_ls])
python
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.split(' ') return safe_zip(*[range(len(toks)), toks] + \ [extraction_to_conll(ex) for ex in sent_ls])
[ "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", "]", ")", ")", "==", "1", ")", "toks", "=", "sent_ls", "[", "0", "]", ".", "sent", ".", "split", "(", "' '", ")", "return", "safe_zip", "(", "*", "[", "range", "(", "len", "(", "toks", ")", ")", ",", "toks", "]", "+", "[", "extraction_to_conll", "(", "ex", ")", "for", "ex", "in", "sent_ls", "]", ")" ]
Given a list of extractions for a single sentence - convert it to conll representation.
[ "Given", "a", "list", "of", "extractions", "for", "a", "single", "sentence", "-", "convert", "it", "to", "conll", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L237-L249
23,205
allenai/allennlp
scripts/convert_openie_to_conll.py
pad_line_to_ontonotes
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, '-',\ '-', '-', '*'] + list(oie_tags) + ['-', ]
python
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, '-',\ '-', '-', '*'] + list(oie_tags) + ['-', ]
[ "def", "pad_line_to_ontonotes", "(", "line", ",", "domain", ")", "->", "List", "[", "str", "]", ":", "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", ",", "'-'", ",", "'-'", ",", "'-'", ",", "'*'", "]", "+", "list", "(", "oie_tags", ")", "+", "[", "'-'", ",", "]" ]
Pad line to conform to ontonotes representation.
[ "Pad", "line", "to", "conform", "to", "ontonotes", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L252-L263
23,206
allenai/allennlp
scripts/convert_openie_to_conll.py
convert_sent_dict_to_conll
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 convert_sent_to_conll(sent_ls)]) for sent_ls in sent_dic.iteritems()])
python
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 convert_sent_to_conll(sent_ls)]) for sent_ls in sent_dic.iteritems()])
[ "def", "convert_sent_dict_to_conll", "(", "sent_dic", ",", "domain", ")", "->", "str", ":", "return", "'\\n\\n'", ".", "join", "(", "[", "'\\n'", ".", "join", "(", "[", "'\\t'", ".", "join", "(", "map", "(", "str", ",", "pad_line_to_ontonotes", "(", "line", ",", "domain", ")", ")", ")", "for", "line", "in", "convert_sent_to_conll", "(", "sent_ls", ")", "]", ")", "for", "sent_ls", "in", "sent_dic", ".", "iteritems", "(", ")", "]", ")" ]
Given a dictionary from sentence -> extractions, return a corresponding CoNLL representation.
[ "Given", "a", "dictionary", "from", "sentence", "-", ">", "extractions", "return", "a", "corresponding", "CoNLL", "representation", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/convert_openie_to_conll.py#L265-L273
23,207
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
parse_s3_uri
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.scheme == 's3' and url.netloc and url.path: s3_pointer = { 'Bucket': url.netloc, 'Key': url.path.lstrip('/') } if 'versionId' in query and len(query['versionId']) == 1: s3_pointer['Version'] = query['versionId'][0] return s3_pointer else: return None
python
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.scheme == 's3' and url.netloc and url.path: s3_pointer = { 'Bucket': url.netloc, 'Key': url.path.lstrip('/') } if 'versionId' in query and len(query['versionId']) == 1: s3_pointer['Version'] = query['versionId'][0] return s3_pointer else: return None
[ "def", "parse_s3_uri", "(", "uri", ")", ":", "if", "not", "isinstance", "(", "uri", ",", "string_types", ")", ":", "return", "None", "url", "=", "urlparse", "(", "uri", ")", "query", "=", "parse_qs", "(", "url", ".", "query", ")", "if", "url", ".", "scheme", "==", "'s3'", "and", "url", ".", "netloc", "and", "url", ".", "path", ":", "s3_pointer", "=", "{", "'Bucket'", ":", "url", ".", "netloc", ",", "'Key'", ":", "url", ".", "path", ".", "lstrip", "(", "'/'", ")", "}", "if", "'versionId'", "in", "query", "and", "len", "(", "query", "[", "'versionId'", "]", ")", "==", "1", ":", "s3_pointer", "[", "'Version'", "]", "=", "query", "[", "'versionId'", "]", "[", "0", "]", "return", "s3_pointer", "else", ":", "return", "None" ]
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
[ "Parses", "a", "S3", "Uri", "into", "a", "dictionary", "of", "the", "Bucket", "Key", "and", "VersionId" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L6-L27
23,208
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
to_s3_uri
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 string """ try: uri = "s3://{bucket}/{key}".format(bucket=code_dict["S3Bucket"], key=code_dict["S3Key"]) version = code_dict.get("S3ObjectVersion", None) except (TypeError, AttributeError): raise TypeError("Code location should be a dictionary") if version: uri += "?versionId=" + version return uri
python
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 string """ try: uri = "s3://{bucket}/{key}".format(bucket=code_dict["S3Bucket"], key=code_dict["S3Key"]) version = code_dict.get("S3ObjectVersion", None) except (TypeError, AttributeError): raise TypeError("Code location should be a dictionary") if version: uri += "?versionId=" + version return uri
[ "def", "to_s3_uri", "(", "code_dict", ")", ":", "try", ":", "uri", "=", "\"s3://{bucket}/{key}\"", ".", "format", "(", "bucket", "=", "code_dict", "[", "\"S3Bucket\"", "]", ",", "key", "=", "code_dict", "[", "\"S3Key\"", "]", ")", "version", "=", "code_dict", ".", "get", "(", "\"S3ObjectVersion\"", ",", "None", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "raise", "TypeError", "(", "\"Code location should be a dictionary\"", ")", "if", "version", ":", "uri", "+=", "\"?versionId=\"", "+", "version", "return", "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
[ "Constructs", "a", "S3", "URI", "string", "from", "given", "code", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L30-L48
23,209
awslabs/serverless-application-model
samtranslator/model/s3_utils/uri_parser.py
construct_s3_location_object
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 string :param string logical_id: logical_id of the resource calling this function :param string property_name: name of the property which is used as an input to this function. :returns: a Code dict, containing the S3 Bucket, Key, and Version of the Lambda layer code :rtype: dict """ if isinstance(location_uri, dict): if not location_uri.get("Bucket") or not location_uri.get("Key"): # location_uri is a dictionary but does not contain Bucket or Key property raise InvalidResourceException(logical_id, "'{}' requires Bucket and Key properties to be " "specified".format(property_name)) s3_pointer = location_uri else: # location_uri is NOT a dictionary. Parse it as a string s3_pointer = parse_s3_uri(location_uri) if s3_pointer is None: raise InvalidResourceException(logical_id, '\'{}\' is not a valid S3 Uri of the form ' '"s3://bucket/key" with optional versionId query ' 'parameter.'.format(property_name)) code = { 'S3Bucket': s3_pointer['Bucket'], 'S3Key': s3_pointer['Key'] } if 'Version' in s3_pointer: code['S3ObjectVersion'] = s3_pointer['Version'] return code
python
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 string :param string logical_id: logical_id of the resource calling this function :param string property_name: name of the property which is used as an input to this function. :returns: a Code dict, containing the S3 Bucket, Key, and Version of the Lambda layer code :rtype: dict """ if isinstance(location_uri, dict): if not location_uri.get("Bucket") or not location_uri.get("Key"): # location_uri is a dictionary but does not contain Bucket or Key property raise InvalidResourceException(logical_id, "'{}' requires Bucket and Key properties to be " "specified".format(property_name)) s3_pointer = location_uri else: # location_uri is NOT a dictionary. Parse it as a string s3_pointer = parse_s3_uri(location_uri) if s3_pointer is None: raise InvalidResourceException(logical_id, '\'{}\' is not a valid S3 Uri of the form ' '"s3://bucket/key" with optional versionId query ' 'parameter.'.format(property_name)) code = { 'S3Bucket': s3_pointer['Bucket'], 'S3Key': s3_pointer['Key'] } if 'Version' in s3_pointer: code['S3ObjectVersion'] = s3_pointer['Version'] return code
[ "def", "construct_s3_location_object", "(", "location_uri", ",", "logical_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "location_uri", ",", "dict", ")", ":", "if", "not", "location_uri", ".", "get", "(", "\"Bucket\"", ")", "or", "not", "location_uri", ".", "get", "(", "\"Key\"", ")", ":", "# location_uri is a dictionary but does not contain Bucket or Key property", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"'{}' requires Bucket and Key properties to be \"", "\"specified\"", ".", "format", "(", "property_name", ")", ")", "s3_pointer", "=", "location_uri", "else", ":", "# location_uri is NOT a dictionary. Parse it as a string", "s3_pointer", "=", "parse_s3_uri", "(", "location_uri", ")", "if", "s3_pointer", "is", "None", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "'\\'{}\\' is not a valid S3 Uri of the form '", "'\"s3://bucket/key\" with optional versionId query '", "'parameter.'", ".", "format", "(", "property_name", ")", ")", "code", "=", "{", "'S3Bucket'", ":", "s3_pointer", "[", "'Bucket'", "]", ",", "'S3Key'", ":", "s3_pointer", "[", "'Key'", "]", "}", "if", "'Version'", "in", "s3_pointer", ":", "code", "[", "'S3ObjectVersion'", "]", "=", "s3_pointer", "[", "'Version'", "]", "return", "code" ]
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 function :param string property_name: name of the property which is used as an input to this function. :returns: a Code dict, containing the S3 Bucket, Key, and Version of the Lambda layer code :rtype: dict
[ "Constructs", "a", "Lambda", "Code", "or", "Content", "property", "from", "the", "SAM", "CodeUri", "or", "ContentUri", "property", ".", "This", "follows", "the", "current", "scheme", "for", "Lambda", "Functions", "and", "LayerVersions", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L51-L86
23,210
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._get_policies
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 * List of managed policy names: list of strings * IAM Policy document: dict containing Statement key * List of IAM Policy documents: list of IAM Policy Document * Policy Template: dict with only one key where key is in list of supported policy template names * List of Policy Templates: list of Policy Template :param dict resource_properties: Dictionary of resource properties containing the policies property. It is assumed that this is already a dictionary and contains policies key. :return list of PolicyEntry: List of policies, where each item is an instance of named tuple `PolicyEntry` """ policies = None if self._contains_policies(resource_properties): policies = resource_properties[self.POLICIES_PROPERTY_NAME] if not policies: # Policies is None or empty return [] if not isinstance(policies, list): # Just a single entry. Make it into a list of convenience policies = [policies] result = [] for policy in policies: policy_type = self._get_type(policy) entry = PolicyEntry(data=policy, type=policy_type) result.append(entry) return result
python
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 * List of managed policy names: list of strings * IAM Policy document: dict containing Statement key * List of IAM Policy documents: list of IAM Policy Document * Policy Template: dict with only one key where key is in list of supported policy template names * List of Policy Templates: list of Policy Template :param dict resource_properties: Dictionary of resource properties containing the policies property. It is assumed that this is already a dictionary and contains policies key. :return list of PolicyEntry: List of policies, where each item is an instance of named tuple `PolicyEntry` """ policies = None if self._contains_policies(resource_properties): policies = resource_properties[self.POLICIES_PROPERTY_NAME] if not policies: # Policies is None or empty return [] if not isinstance(policies, list): # Just a single entry. Make it into a list of convenience policies = [policies] result = [] for policy in policies: policy_type = self._get_type(policy) entry = PolicyEntry(data=policy, type=policy_type) result.append(entry) return result
[ "def", "_get_policies", "(", "self", ",", "resource_properties", ")", ":", "policies", "=", "None", "if", "self", ".", "_contains_policies", "(", "resource_properties", ")", ":", "policies", "=", "resource_properties", "[", "self", ".", "POLICIES_PROPERTY_NAME", "]", "if", "not", "policies", ":", "# Policies is None or empty", "return", "[", "]", "if", "not", "isinstance", "(", "policies", ",", "list", ")", ":", "# Just a single entry. Make it into a list of convenience", "policies", "=", "[", "policies", "]", "result", "=", "[", "]", "for", "policy", "in", "policies", ":", "policy_type", "=", "self", ".", "_get_type", "(", "policy", ")", "entry", "=", "PolicyEntry", "(", "data", "=", "policy", ",", "type", "=", "policy_type", ")", "result", ".", "append", "(", "entry", ")", "return", "result" ]
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 * IAM Policy document: dict containing Statement key * List of IAM Policy documents: list of IAM Policy Document * Policy Template: dict with only one key where key is in list of supported policy template names * List of Policy Templates: list of Policy Template :param dict resource_properties: Dictionary of resource properties containing the policies property. It is assumed that this is already a dictionary and contains policies key. :return list of PolicyEntry: List of policies, where each item is an instance of named tuple `PolicyEntry`
[ "Returns", "a", "list", "of", "policies", "from", "the", "resource", "properties", ".", "This", "method", "knows", "how", "to", "interpret", "and", "handle", "polymorphic", "nature", "of", "the", "policies", "property", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L55-L94
23,211
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._contains_policies
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 \ and isinstance(resource_properties, dict) \ and self.POLICIES_PROPERTY_NAME in resource_properties
python
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 \ and isinstance(resource_properties, dict) \ and self.POLICIES_PROPERTY_NAME in resource_properties
[ "def", "_contains_policies", "(", "self", ",", "resource_properties", ")", ":", "return", "resource_properties", "is", "not", "None", "and", "isinstance", "(", "resource_properties", ",", "dict", ")", "and", "self", ".", "POLICIES_PROPERTY_NAME", "in", "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
[ "Is", "there", "policies", "data", "in", "this", "resource?" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L96-L105
23,212
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._get_type
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 an intrinsic function # Managed policies are either string or an intrinsic function that resolves to a string if isinstance(policy, string_types) or is_instrinsic(policy): return PolicyTypes.MANAGED_POLICY # Policy statement is a dictionary with the key "Statement" in it if isinstance(policy, dict) and "Statement" in policy: return PolicyTypes.POLICY_STATEMENT # This could be a policy template then. if self._is_policy_template(policy): return PolicyTypes.POLICY_TEMPLATE # Nothing matches. Don't take opinions on how to handle it. Instead just set the appropriate type. return PolicyTypes.UNKNOWN
python
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 an intrinsic function # Managed policies are either string or an intrinsic function that resolves to a string if isinstance(policy, string_types) or is_instrinsic(policy): return PolicyTypes.MANAGED_POLICY # Policy statement is a dictionary with the key "Statement" in it if isinstance(policy, dict) and "Statement" in policy: return PolicyTypes.POLICY_STATEMENT # This could be a policy template then. if self._is_policy_template(policy): return PolicyTypes.POLICY_TEMPLATE # Nothing matches. Don't take opinions on how to handle it. Instead just set the appropriate type. return PolicyTypes.UNKNOWN
[ "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", ",", "string_types", ")", "or", "is_instrinsic", "(", "policy", ")", ":", "return", "PolicyTypes", ".", "MANAGED_POLICY", "# Policy statement is a dictionary with the key \"Statement\" in it", "if", "isinstance", "(", "policy", ",", "dict", ")", "and", "\"Statement\"", "in", "policy", ":", "return", "PolicyTypes", ".", "POLICY_STATEMENT", "# This could be a policy template then.", "if", "self", ".", "_is_policy_template", "(", "policy", ")", ":", "return", "PolicyTypes", ".", "POLICY_TEMPLATE", "# Nothing matches. Don't take opinions on how to handle it. Instead just set the appropriate type.", "return", "PolicyTypes", ".", "UNKNOWN" ]
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
[ "Returns", "the", "type", "of", "the", "given", "policy" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L107-L130
23,213
awslabs/serverless-application-model
samtranslator/model/function_policies.py
FunctionPolicies._is_policy_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 """ return self._policy_template_processor is not None and \ isinstance(policy, dict) and \ len(policy) == 1 and \ self._policy_template_processor.has(list(policy.keys())[0]) is True
python
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 """ return self._policy_template_processor is not None and \ isinstance(policy, dict) and \ len(policy) == 1 and \ self._policy_template_processor.has(list(policy.keys())[0]) is True
[ "def", "_is_policy_template", "(", "self", ",", "policy", ")", ":", "return", "self", ".", "_policy_template_processor", "is", "not", "None", "and", "isinstance", "(", "policy", ",", "dict", ")", "and", "len", "(", "policy", ")", "==", "1", "and", "self", ".", "_policy_template_processor", ".", "has", "(", "list", "(", "policy", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "is", "True" ]
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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/function_policies.py#L132-L144
23,214
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.get_thing_shadow
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 operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('get', thing_name, payload)
python
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 operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('get', thing_name, payload)
[ "def", "get_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'get'", ",", "thing_name", ",", "payload", ")" ]
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``) -- The state information, in JSON format.
[ "r", "Call", "shadow", "lambda", "to", "obtain", "current", "shadow", "state", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L28-L45
23,215
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.update_thing_shadow
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``) -- [REQUIRED] The state information, in JSON format. :returns: (``dict``) -- The output from the UpdateThingShadow operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = self._get_required_parameter('payload', **kwargs) return self._shadow_op('update', thing_name, payload)
python
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``) -- [REQUIRED] The state information, in JSON format. :returns: (``dict``) -- The output from the UpdateThingShadow operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = self._get_required_parameter('payload', **kwargs) return self._shadow_op('update', thing_name, payload)
[ "def", "update_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "self", ".", "_get_required_parameter", "(", "'payload'", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_shadow_op", "(", "'update'", ",", "thing_name", ",", "payload", ")" ]
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 information, in JSON format. :returns: (``dict``) -- The output from the UpdateThingShadow operation * *payload* (``bytes``) -- The state information, in JSON format.
[ "r", "Updates", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L47-L67
23,216
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.delete_thing_shadow
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 DeleteThingShadow operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('delete', thing_name, payload)
python
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 DeleteThingShadow operation * *payload* (``bytes``) -- The state information, in JSON format. """ thing_name = self._get_required_parameter('thingName', **kwargs) payload = b'' return self._shadow_op('delete', thing_name, payload)
[ "def", "delete_thing_shadow", "(", "self", ",", "*", "*", "kwargs", ")", ":", "thing_name", "=", "self", ".", "_get_required_parameter", "(", "'thingName'", ",", "*", "*", "kwargs", ")", "payload", "=", "b''", "return", "self", ".", "_shadow_op", "(", "'delete'", ",", "thing_name", ",", "payload", ")" ]
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``) -- The state information, in JSON format.
[ "r", "Deletes", "the", "thing", "shadow", "for", "the", "specified", "thing", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L69-L86
23,217
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py
Client.publish
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 JSON format. :returns: None """ topic = self._get_required_parameter('topic', **kwargs) # payload is an optional parameter payload = kwargs.get('payload', b'') function_arn = ROUTER_FUNCTION_ARN client_context = { 'custom': { 'source': MY_FUNCTION_ARN, 'subject': topic } } customer_logger.info('Publishing message on topic "{}" with Payload "{}"'.format(topic, payload)) self.lambda_client._invoke_internal( function_arn, payload, base64.b64encode(json.dumps(client_context).encode()) )
python
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 JSON format. :returns: None """ topic = self._get_required_parameter('topic', **kwargs) # payload is an optional parameter payload = kwargs.get('payload', b'') function_arn = ROUTER_FUNCTION_ARN client_context = { 'custom': { 'source': MY_FUNCTION_ARN, 'subject': topic } } customer_logger.info('Publishing message on topic "{}" with Payload "{}"'.format(topic, payload)) self.lambda_client._invoke_internal( function_arn, payload, base64.b64encode(json.dumps(client_context).encode()) )
[ "def", "publish", "(", "self", ",", "*", "*", "kwargs", ")", ":", "topic", "=", "self", ".", "_get_required_parameter", "(", "'topic'", ",", "*", "*", "kwargs", ")", "# payload is an optional parameter", "payload", "=", "kwargs", ".", "get", "(", "'payload'", ",", "b''", ")", "function_arn", "=", "ROUTER_FUNCTION_ARN", "client_context", "=", "{", "'custom'", ":", "{", "'source'", ":", "MY_FUNCTION_ARN", ",", "'subject'", ":", "topic", "}", "}", "customer_logger", ".", "info", "(", "'Publishing message on topic \"{}\" with Payload \"{}\"'", ".", "format", "(", "topic", ",", "payload", ")", ")", "self", ".", "lambda_client", ".", "_invoke_internal", "(", "function_arn", ",", "payload", ",", "base64", ".", "b64encode", "(", "json", ".", "dumps", "(", "client_context", ")", ".", "encode", "(", ")", ")", ")" ]
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
[ "r", "Publishes", "state", "information", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/IoTDataPlane.py#L88-L120
23,218
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
Globals.merge
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 dict resource_properties: Properties of the resource that need to be merged :return dict: Merged properties of the resource """ if resource_type not in self.template_globals: # Nothing to do. Return the template unmodified return resource_properties global_props = self.template_globals[resource_type] return global_props.merge(resource_properties)
python
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 dict resource_properties: Properties of the resource that need to be merged :return dict: Merged properties of the resource """ if resource_type not in self.template_globals: # Nothing to do. Return the template unmodified return resource_properties global_props = self.template_globals[resource_type] return global_props.merge(resource_properties)
[ "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", "=", "self", ".", "template_globals", "[", "resource_type", "]", "return", "global_props", ".", "merge", "(", "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 dict resource_properties: Properties of the resource that need to be merged :return dict: Merged properties of the resource
[ "Adds", "global", "properties", "to", "the", "resource", "if", "necessary", ".", "This", "method", "is", "a", "no", "-", "op", "if", "there", "are", "no", "global", "properties", "for", "this", "resource", "type" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L80-L96
23,219
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
Globals._parse
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: InvalidResourceException if the input contains properties that we don't support """ globals = {} if not isinstance(globals_dict, dict): raise InvalidGlobalsSectionException(self._KEYWORD, "It must be a non-empty dictionary".format(self._KEYWORD)) for section_name, properties in globals_dict.items(): resource_type = self._make_resource_type(section_name) if resource_type not in self.supported_properties: raise InvalidGlobalsSectionException(self._KEYWORD, "'{section}' is not supported. " "Must be one of the following values - {supported}" .format(section=section_name, supported=self.supported_resource_section_names)) if not isinstance(properties, dict): raise InvalidGlobalsSectionException(self._KEYWORD, "Value of ${section} must be a dictionary") for key, value in properties.items(): supported = self.supported_properties[resource_type] if key not in supported: raise InvalidGlobalsSectionException(self._KEYWORD, "'{key}' is not a supported property of '{section}'. " "Must be one of the following values - {supported}" .format(key=key, section=section_name, supported=supported)) # Store all Global properties in a map with key being the AWS::Serverless::* resource type globals[resource_type] = GlobalProperties(properties) return globals
python
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: InvalidResourceException if the input contains properties that we don't support """ globals = {} if not isinstance(globals_dict, dict): raise InvalidGlobalsSectionException(self._KEYWORD, "It must be a non-empty dictionary".format(self._KEYWORD)) for section_name, properties in globals_dict.items(): resource_type = self._make_resource_type(section_name) if resource_type not in self.supported_properties: raise InvalidGlobalsSectionException(self._KEYWORD, "'{section}' is not supported. " "Must be one of the following values - {supported}" .format(section=section_name, supported=self.supported_resource_section_names)) if not isinstance(properties, dict): raise InvalidGlobalsSectionException(self._KEYWORD, "Value of ${section} must be a dictionary") for key, value in properties.items(): supported = self.supported_properties[resource_type] if key not in supported: raise InvalidGlobalsSectionException(self._KEYWORD, "'{key}' is not a supported property of '{section}'. " "Must be one of the following values - {supported}" .format(key=key, section=section_name, supported=supported)) # Store all Global properties in a map with key being the AWS::Serverless::* resource type globals[resource_type] = GlobalProperties(properties) return globals
[ "def", "_parse", "(", "self", ",", "globals_dict", ")", ":", "globals", "=", "{", "}", "if", "not", "isinstance", "(", "globals_dict", ",", "dict", ")", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"It must be a non-empty dictionary\"", ".", "format", "(", "self", ".", "_KEYWORD", ")", ")", "for", "section_name", ",", "properties", "in", "globals_dict", ".", "items", "(", ")", ":", "resource_type", "=", "self", ".", "_make_resource_type", "(", "section_name", ")", "if", "resource_type", "not", "in", "self", ".", "supported_properties", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"'{section}' is not supported. \"", "\"Must be one of the following values - {supported}\"", ".", "format", "(", "section", "=", "section_name", ",", "supported", "=", "self", ".", "supported_resource_section_names", ")", ")", "if", "not", "isinstance", "(", "properties", ",", "dict", ")", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"Value of ${section} must be a dictionary\"", ")", "for", "key", ",", "value", "in", "properties", ".", "items", "(", ")", ":", "supported", "=", "self", ".", "supported_properties", "[", "resource_type", "]", "if", "key", "not", "in", "supported", ":", "raise", "InvalidGlobalsSectionException", "(", "self", ".", "_KEYWORD", ",", "\"'{key}' is not a supported property of '{section}'. \"", "\"Must be one of the following values - {supported}\"", ".", "format", "(", "key", "=", "key", ",", "section", "=", "section_name", ",", "supported", "=", "supported", ")", ")", "# Store all Global properties in a map with key being the AWS::Serverless::* resource type", "globals", "[", "resource_type", "]", "=", "GlobalProperties", "(", "properties", ")", "return", "globals" ]
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 that we don't support
[ "Takes", "a", "SAM", "template", "as", "input", "and", "parses", "the", "Globals", "section" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L110-L149
23,220
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._do_merge
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_value: Local value to be merged :return: Merged result """ token_global = self._token_of(global_value) token_local = self._token_of(local_value) # The following statements codify the rules explained in the doctring above if token_global != token_local: return self._prefer_local(global_value, local_value) elif self.TOKEN.PRIMITIVE == token_global == token_local: return self._prefer_local(global_value, local_value) elif self.TOKEN.DICT == token_global == token_local: return self._merge_dict(global_value, local_value) elif self.TOKEN.LIST == token_global == token_local: return self._merge_lists(global_value, local_value) else: raise TypeError( "Unsupported type of objects. GlobalType={}, LocalType={}".format(token_global, token_local))
python
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_value: Local value to be merged :return: Merged result """ token_global = self._token_of(global_value) token_local = self._token_of(local_value) # The following statements codify the rules explained in the doctring above if token_global != token_local: return self._prefer_local(global_value, local_value) elif self.TOKEN.PRIMITIVE == token_global == token_local: return self._prefer_local(global_value, local_value) elif self.TOKEN.DICT == token_global == token_local: return self._merge_dict(global_value, local_value) elif self.TOKEN.LIST == token_global == token_local: return self._merge_lists(global_value, local_value) else: raise TypeError( "Unsupported type of objects. GlobalType={}, LocalType={}".format(token_global, token_local))
[ "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 the rules explained in the doctring above", "if", "token_global", "!=", "token_local", ":", "return", "self", ".", "_prefer_local", "(", "global_value", ",", "local_value", ")", "elif", "self", ".", "TOKEN", ".", "PRIMITIVE", "==", "token_global", "==", "token_local", ":", "return", "self", ".", "_prefer_local", "(", "global_value", ",", "local_value", ")", "elif", "self", ".", "TOKEN", ".", "DICT", "==", "token_global", "==", "token_local", ":", "return", "self", ".", "_merge_dict", "(", "global_value", ",", "local_value", ")", "elif", "self", ".", "TOKEN", ".", "LIST", "==", "token_global", "==", "token_local", ":", "return", "self", ".", "_merge_lists", "(", "global_value", ",", "local_value", ")", "else", ":", "raise", "TypeError", "(", "\"Unsupported type of objects. GlobalType={}, LocalType={}\"", ".", "format", "(", "token_global", ",", "token_local", ")", ")" ]
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
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L286-L314
23,221
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._merge_dict
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 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 local_dict.keys(): if key in global_dict: # Both local & global contains the same key. Let's do a merge. global_dict[key] = self._do_merge(global_dict[key], local_dict[key]) else: # Key is not in globals, just in local. Copy it over global_dict[key] = local_dict[key] return global_dict
python
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 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 local_dict.keys(): if key in global_dict: # Both local & global contains the same key. Let's do a merge. global_dict[key] = self._do_merge(global_dict[key], local_dict[key]) else: # Key is not in globals, just in local. Copy it over global_dict[key] = local_dict[key] return global_dict
[ "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", "local_dict", ".", "keys", "(", ")", ":", "if", "key", "in", "global_dict", ":", "# Both local & global contains the same key. Let's do a merge.", "global_dict", "[", "key", "]", "=", "self", ".", "_do_merge", "(", "global_dict", "[", "key", "]", ",", "local_dict", "[", "key", "]", ")", "else", ":", "# Key is not in globals, just in local. Copy it over", "global_dict", "[", "key", "]", "=", "local_dict", "[", "key", "]", "return", "global_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
[ "Merges", "the", "two", "dictionaries", "together" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L327-L349
23,222
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
GlobalProperties._token_of
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_intrinsics(input): # Intrinsic functions are handled *exactly* like a primitive type because # they resolve to a primitive type when creating a stack with CloudFormation return self.TOKEN.PRIMITIVE else: return self.TOKEN.DICT elif isinstance(input, list): return self.TOKEN.LIST else: return self.TOKEN.PRIMITIVE
python
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_intrinsics(input): # Intrinsic functions are handled *exactly* like a primitive type because # they resolve to a primitive type when creating a stack with CloudFormation return self.TOKEN.PRIMITIVE else: return self.TOKEN.DICT elif isinstance(input, list): return self.TOKEN.LIST else: return self.TOKEN.PRIMITIVE
[ "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 because", "# they resolve to a primitive type when creating a stack with CloudFormation", "return", "self", ".", "TOKEN", ".", "PRIMITIVE", "else", ":", "return", "self", ".", "TOKEN", ".", "DICT", "elif", "isinstance", "(", "input", ",", "list", ")", ":", "return", "self", ".", "TOKEN", ".", "LIST", "else", ":", "return", "self", ".", "TOKEN", ".", "PRIMITIVE" ]
Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input
[ "Returns", "the", "token", "type", "of", "the", "input", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L362-L384
23,223
awslabs/serverless-application-model
samtranslator/validator/validator.py
SamTemplateValidator.validate
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 in template """ if not schema: schema = SamTemplateValidator._read_schema() validation_errors = "" try: jsonschema.validate(template_dict, schema) except ValidationError as ex: # Stringifying the exception will give us useful error message validation_errors = str(ex) # Swallowing expected exception here as our caller is expecting validation errors and # not the valiation exception itself pass return validation_errors
python
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 in template """ if not schema: schema = SamTemplateValidator._read_schema() validation_errors = "" try: jsonschema.validate(template_dict, schema) except ValidationError as ex: # Stringifying the exception will give us useful error message validation_errors = str(ex) # Swallowing expected exception here as our caller is expecting validation errors and # not the valiation exception itself pass return validation_errors
[ "def", "validate", "(", "template_dict", ",", "schema", "=", "None", ")", ":", "if", "not", "schema", ":", "schema", "=", "SamTemplateValidator", ".", "_read_schema", "(", ")", "validation_errors", "=", "\"\"", "try", ":", "jsonschema", ".", "validate", "(", "template_dict", ",", "schema", ")", "except", "ValidationError", "as", "ex", ":", "# Stringifying the exception will give us useful error message", "validation_errors", "=", "str", "(", "ex", ")", "# Swallowing expected exception here as our caller is expecting validation errors and", "# not the valiation exception itself", "pass", "return", "validation_errors" ]
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
[ "Is", "this", "a", "valid", "SAM", "template", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/validator/validator.py#L12-L35
23,224
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
generate_car_price
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 = 0 for i in range(len(location)): base_location_cost += ord(location.lower()[i]) - 97 age_multiplier = 1.10 if age < 25 else 1 # Select economy is car_type is not found if car_type not in car_types: car_type = car_types[0] return days * ((100 + base_location_cost) + ((car_types.index(car_type) * 50) * age_multiplier))
python
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 = 0 for i in range(len(location)): base_location_cost += ord(location.lower()[i]) - 97 age_multiplier = 1.10 if age < 25 else 1 # Select economy is car_type is not found if car_type not in car_types: car_type = car_types[0] return days * ((100 + base_location_cost) + ((car_types.index(car_type) * 50) * age_multiplier))
[ "def", "generate_car_price", "(", "location", ",", "days", ",", "age", ",", "car_type", ")", ":", "car_types", "=", "[", "'economy'", ",", "'standard'", ",", "'midsize'", ",", "'full size'", ",", "'minivan'", ",", "'luxury'", "]", "base_location_cost", "=", "0", "for", "i", "in", "range", "(", "len", "(", "location", ")", ")", ":", "base_location_cost", "+=", "ord", "(", "location", ".", "lower", "(", ")", "[", "i", "]", ")", "-", "97", "age_multiplier", "=", "1.10", "if", "age", "<", "25", "else", "1", "# Select economy is car_type is not found", "if", "car_type", "not", "in", "car_types", ":", "car_type", "=", "car_types", "[", "0", "]", "return", "days", "*", "(", "(", "100", "+", "base_location_cost", ")", "+", "(", "(", "car_types", ".", "index", "(", "car_type", ")", "*", "50", ")", "*", "age_multiplier", ")", ")" ]
Generates a number within a reasonable range that might be expected for a flight. The price is fixed for a given pair of locations.
[ "Generates", "a", "number", "within", "a", "reasonable", "range", "that", "might", "be", "expected", "for", "a", "flight", ".", "The", "price", "is", "fixed", "for", "a", "given", "pair", "of", "locations", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L97-L113
23,225
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
generate_hotel_price
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)): cost_of_living += ord(location.lower()[i]) - 97 return nights * (100 + cost_of_living + (100 + room_types.index(room_type.lower())))
python
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)): cost_of_living += ord(location.lower()[i]) - 97 return nights * (100 + cost_of_living + (100 + room_types.index(room_type.lower())))
[ "def", "generate_hotel_price", "(", "location", ",", "nights", ",", "room_type", ")", ":", "room_types", "=", "[", "'queen'", ",", "'king'", ",", "'deluxe'", "]", "cost_of_living", "=", "0", "for", "i", "in", "range", "(", "len", "(", "location", ")", ")", ":", "cost_of_living", "+=", "ord", "(", "location", ".", "lower", "(", ")", "[", "i", "]", ")", "-", "97", "return", "nights", "*", "(", "100", "+", "cost_of_living", "+", "(", "100", "+", "room_types", ".", "index", "(", "room_type", ".", "lower", "(", ")", ")", ")", ")" ]
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.
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L116-L127
23,226
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
book_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 used to guide conversation """ location = try_ex(lambda: intent_request['currentIntent']['slots']['Location']) checkin_date = try_ex(lambda: intent_request['currentIntent']['slots']['CheckInDate']) nights = safe_int(try_ex(lambda: intent_request['currentIntent']['slots']['Nights'])) room_type = try_ex(lambda: intent_request['currentIntent']['slots']['RoomType']) session_attributes = intent_request['sessionAttributes'] # Load confirmation history and track the current reservation. reservation = json.dumps({ 'ReservationType': 'Hotel', 'Location': location, 'RoomType': room_type, 'CheckInDate': checkin_date, 'Nights': nights }) session_attributes['currentReservation'] = reservation if intent_request['invocationSource'] == 'DialogCodeHook': # Validate any slots which have been specified. If any are invalid, re-elicit for their value validation_result = validate_hotel(intent_request['currentIntent']['slots']) if not validation_result['isValid']: slots = intent_request['currentIntent']['slots'] slots[validation_result['violatedSlot']] = None return elicit_slot( session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'] ) # Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price # back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes. if location and checkin_date and nights and room_type: # The price of the hotel has yet to be confirmed. price = generate_hotel_price(location, nights, room_type) session_attributes['currentReservationPrice'] = price else: try_ex(lambda: session_attributes.pop('currentReservationPrice')) session_attributes['currentReservation'] = reservation return delegate(session_attributes, intent_request['currentIntent']['slots']) # Booking the hotel. In a real application, this would likely involve a call to a backend service. logger.debug('bookHotel under={}'.format(reservation)) try_ex(lambda: session_attributes.pop('currentReservationPrice')) try_ex(lambda: session_attributes.pop('currentReservation')) session_attributes['lastConfirmedReservation'] = reservation return close( session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Thanks, I have placed your reservation. Please let me know if you would like to book a car ' 'rental, or another hotel.' } )
python
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 used to guide conversation """ location = try_ex(lambda: intent_request['currentIntent']['slots']['Location']) checkin_date = try_ex(lambda: intent_request['currentIntent']['slots']['CheckInDate']) nights = safe_int(try_ex(lambda: intent_request['currentIntent']['slots']['Nights'])) room_type = try_ex(lambda: intent_request['currentIntent']['slots']['RoomType']) session_attributes = intent_request['sessionAttributes'] # Load confirmation history and track the current reservation. reservation = json.dumps({ 'ReservationType': 'Hotel', 'Location': location, 'RoomType': room_type, 'CheckInDate': checkin_date, 'Nights': nights }) session_attributes['currentReservation'] = reservation if intent_request['invocationSource'] == 'DialogCodeHook': # Validate any slots which have been specified. If any are invalid, re-elicit for their value validation_result = validate_hotel(intent_request['currentIntent']['slots']) if not validation_result['isValid']: slots = intent_request['currentIntent']['slots'] slots[validation_result['violatedSlot']] = None return elicit_slot( session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'] ) # Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price # back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes. if location and checkin_date and nights and room_type: # The price of the hotel has yet to be confirmed. price = generate_hotel_price(location, nights, room_type) session_attributes['currentReservationPrice'] = price else: try_ex(lambda: session_attributes.pop('currentReservationPrice')) session_attributes['currentReservation'] = reservation return delegate(session_attributes, intent_request['currentIntent']['slots']) # Booking the hotel. In a real application, this would likely involve a call to a backend service. logger.debug('bookHotel under={}'.format(reservation)) try_ex(lambda: session_attributes.pop('currentReservationPrice')) try_ex(lambda: session_attributes.pop('currentReservation')) session_attributes['lastConfirmedReservation'] = reservation return close( session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Thanks, I have placed your reservation. Please let me know if you would like to book a car ' 'rental, or another hotel.' } )
[ "def", "book_hotel", "(", "intent_request", ")", ":", "location", "=", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Location'", "]", ")", "checkin_date", "=", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'CheckInDate'", "]", ")", "nights", "=", "safe_int", "(", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Nights'", "]", ")", ")", "room_type", "=", "try_ex", "(", "lambda", ":", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'RoomType'", "]", ")", "session_attributes", "=", "intent_request", "[", "'sessionAttributes'", "]", "# Load confirmation history and track the current reservation.", "reservation", "=", "json", ".", "dumps", "(", "{", "'ReservationType'", ":", "'Hotel'", ",", "'Location'", ":", "location", ",", "'RoomType'", ":", "room_type", ",", "'CheckInDate'", ":", "checkin_date", ",", "'Nights'", ":", "nights", "}", ")", "session_attributes", "[", "'currentReservation'", "]", "=", "reservation", "if", "intent_request", "[", "'invocationSource'", "]", "==", "'DialogCodeHook'", ":", "# Validate any slots which have been specified. If any are invalid, re-elicit for their value", "validation_result", "=", "validate_hotel", "(", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", ")", "if", "not", "validation_result", "[", "'isValid'", "]", ":", "slots", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "slots", "[", "validation_result", "[", "'violatedSlot'", "]", "]", "=", "None", "return", "elicit_slot", "(", "session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "slots", ",", "validation_result", "[", "'violatedSlot'", "]", ",", "validation_result", "[", "'message'", "]", ")", "# Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price", "# back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes.", "if", "location", "and", "checkin_date", "and", "nights", "and", "room_type", ":", "# The price of the hotel has yet to be confirmed.", "price", "=", "generate_hotel_price", "(", "location", ",", "nights", ",", "room_type", ")", "session_attributes", "[", "'currentReservationPrice'", "]", "=", "price", "else", ":", "try_ex", "(", "lambda", ":", "session_attributes", ".", "pop", "(", "'currentReservationPrice'", ")", ")", "session_attributes", "[", "'currentReservation'", "]", "=", "reservation", "return", "delegate", "(", "session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", ")", "# Booking the hotel. In a real application, this would likely involve a call to a backend service.", "logger", ".", "debug", "(", "'bookHotel under={}'", ".", "format", "(", "reservation", ")", ")", "try_ex", "(", "lambda", ":", "session_attributes", ".", "pop", "(", "'currentReservationPrice'", ")", ")", "try_ex", "(", "lambda", ":", "session_attributes", ".", "pop", "(", "'currentReservation'", ")", ")", "session_attributes", "[", "'lastConfirmedReservation'", "]", "=", "reservation", "return", "close", "(", "session_attributes", ",", "'Fulfilled'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'Thanks, I have placed your reservation. Please let me know if you would like to book a car '", "'rental, or another 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
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "hotel", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L261-L330
23,227
awslabs/serverless-application-model
samtranslator/model/eventsources/pull.py
PullEventSource.to_cloudformation
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 function :returns: a list of vanilla CloudFormation Resources, to which this pull event expands :rtype: list """ function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") resources = [] lambda_eventsourcemapping = LambdaEventSourceMapping(self.logical_id) resources.append(lambda_eventsourcemapping) try: # Name will not be available for Alias resources function_name_or_arn = function.get_runtime_attr("name") except NotImplementedError: function_name_or_arn = function.get_runtime_attr("arn") if not self.Stream and not self.Queue: raise InvalidEventException( self.relative_id, "No Queue (for SQS) or Stream (for Kinesis or DynamoDB) provided.") if self.Stream and not self.StartingPosition: raise InvalidEventException( self.relative_id, "StartingPosition is required for Kinesis and DynamoDB.") lambda_eventsourcemapping.FunctionName = function_name_or_arn lambda_eventsourcemapping.EventSourceArn = self.Stream or self.Queue lambda_eventsourcemapping.StartingPosition = self.StartingPosition lambda_eventsourcemapping.BatchSize = self.BatchSize lambda_eventsourcemapping.Enabled = self.Enabled if 'Condition' in function.resource_attributes: lambda_eventsourcemapping.set_resource_attribute('Condition', function.resource_attributes['Condition']) if 'role' in kwargs: self._link_policy(kwargs['role']) return resources
python
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 function :returns: a list of vanilla CloudFormation Resources, to which this pull event expands :rtype: list """ function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") resources = [] lambda_eventsourcemapping = LambdaEventSourceMapping(self.logical_id) resources.append(lambda_eventsourcemapping) try: # Name will not be available for Alias resources function_name_or_arn = function.get_runtime_attr("name") except NotImplementedError: function_name_or_arn = function.get_runtime_attr("arn") if not self.Stream and not self.Queue: raise InvalidEventException( self.relative_id, "No Queue (for SQS) or Stream (for Kinesis or DynamoDB) provided.") if self.Stream and not self.StartingPosition: raise InvalidEventException( self.relative_id, "StartingPosition is required for Kinesis and DynamoDB.") lambda_eventsourcemapping.FunctionName = function_name_or_arn lambda_eventsourcemapping.EventSourceArn = self.Stream or self.Queue lambda_eventsourcemapping.StartingPosition = self.StartingPosition lambda_eventsourcemapping.BatchSize = self.BatchSize lambda_eventsourcemapping.Enabled = self.Enabled if 'Condition' in function.resource_attributes: lambda_eventsourcemapping.set_resource_attribute('Condition', function.resource_attributes['Condition']) if 'role' in kwargs: self._link_policy(kwargs['role']) return resources
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "resources", "=", "[", "]", "lambda_eventsourcemapping", "=", "LambdaEventSourceMapping", "(", "self", ".", "logical_id", ")", "resources", ".", "append", "(", "lambda_eventsourcemapping", ")", "try", ":", "# Name will not be available for Alias resources", "function_name_or_arn", "=", "function", ".", "get_runtime_attr", "(", "\"name\"", ")", "except", "NotImplementedError", ":", "function_name_or_arn", "=", "function", ".", "get_runtime_attr", "(", "\"arn\"", ")", "if", "not", "self", ".", "Stream", "and", "not", "self", ".", "Queue", ":", "raise", "InvalidEventException", "(", "self", ".", "relative_id", ",", "\"No Queue (for SQS) or Stream (for Kinesis or DynamoDB) provided.\"", ")", "if", "self", ".", "Stream", "and", "not", "self", ".", "StartingPosition", ":", "raise", "InvalidEventException", "(", "self", ".", "relative_id", ",", "\"StartingPosition is required for Kinesis and DynamoDB.\"", ")", "lambda_eventsourcemapping", ".", "FunctionName", "=", "function_name_or_arn", "lambda_eventsourcemapping", ".", "EventSourceArn", "=", "self", ".", "Stream", "or", "self", ".", "Queue", "lambda_eventsourcemapping", ".", "StartingPosition", "=", "self", ".", "StartingPosition", "lambda_eventsourcemapping", ".", "BatchSize", "=", "self", ".", "BatchSize", "lambda_eventsourcemapping", ".", "Enabled", "=", "self", ".", "Enabled", "if", "'Condition'", "in", "function", ".", "resource_attributes", ":", "lambda_eventsourcemapping", ".", "set_resource_attribute", "(", "'Condition'", ",", "function", ".", "resource_attributes", "[", "'Condition'", "]", ")", "if", "'role'", "in", "kwargs", ":", "self", ".", "_link_policy", "(", "kwargs", "[", "'role'", "]", ")", "return", "resources" ]
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 CloudFormation Resources, to which this pull event expands :rtype: list
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L30-L73
23,228
awslabs/serverless-application-model
samtranslator/model/eventsources/pull.py
PullEventSource._link_policy
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_policy_arn() if role is not None and policy_arn not in role.ManagedPolicyArns: role.ManagedPolicyArns.append(policy_arn)
python
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_policy_arn() if role is not None and policy_arn not in role.ManagedPolicyArns: role.ManagedPolicyArns.append(policy_arn)
[ "def", "_link_policy", "(", "self", ",", "role", ")", ":", "policy_arn", "=", "self", ".", "get_policy_arn", "(", ")", "if", "role", "is", "not", "None", "and", "policy_arn", "not", "in", "role", ".", "ManagedPolicyArns", ":", "role", ".", "ManagedPolicyArns", ".", "append", "(", "policy_arn", ")" ]
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
[ "If", "this", "source", "triggers", "a", "Lambda", "function", "whose", "execution", "role", "is", "auto", "-", "generated", "by", "SAM", "add", "the", "appropriate", "managed", "policy", "to", "this", "Role", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/pull.py#L75-L83
23,229
awslabs/serverless-application-model
samtranslator/sdk/parameter.py
SamParameterValues.add_default_parameter_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 Default: default_value Param2: Type: String Default: default_value And, the user explicitly provided the following parameter values: { Param2: "new value" } then, this method will grab default value for Param1 and return the following result: { Param1: "default_value", Param2: "new value" } :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user :return dict: Merged parameter values """ parameter_definition = sam_template.get("Parameters", None) if not parameter_definition or not isinstance(parameter_definition, dict): return self.parameter_values for param_name, value in parameter_definition.items(): if param_name not in self.parameter_values and isinstance(value, dict) and "Default" in value: self.parameter_values[param_name] = value["Default"]
python
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 Default: default_value Param2: Type: String Default: default_value And, the user explicitly provided the following parameter values: { Param2: "new value" } then, this method will grab default value for Param1 and return the following result: { Param1: "default_value", Param2: "new value" } :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user :return dict: Merged parameter values """ parameter_definition = sam_template.get("Parameters", None) if not parameter_definition or not isinstance(parameter_definition, dict): return self.parameter_values for param_name, value in parameter_definition.items(): if param_name not in self.parameter_values and isinstance(value, dict) and "Default" in value: self.parameter_values[param_name] = value["Default"]
[ "def", "add_default_parameter_values", "(", "self", ",", "sam_template", ")", ":", "parameter_definition", "=", "sam_template", ".", "get", "(", "\"Parameters\"", ",", "None", ")", "if", "not", "parameter_definition", "or", "not", "isinstance", "(", "parameter_definition", ",", "dict", ")", ":", "return", "self", ".", "parameter_values", "for", "param_name", ",", "value", "in", "parameter_definition", ".", "items", "(", ")", ":", "if", "param_name", "not", "in", "self", ".", "parameter_values", "and", "isinstance", "(", "value", ",", "dict", ")", "and", "\"Default\"", "in", "value", ":", "self", ".", "parameter_values", "[", "param_name", "]", "=", "value", "[", "\"Default\"", "]" ]
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: Type: String Default: default_value And, the user explicitly provided the following parameter values: { Param2: "new value" } then, this method will grab default value for Param1 and return the following result: { Param1: "default_value", Param2: "new value" } :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user :return dict: Merged parameter values
[ "Method", "to", "read", "default", "values", "for", "template", "parameters", "and", "merge", "with", "user", "supplied", "values", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L19-L59
23,230
awslabs/serverless-application-model
samtranslator/model/preferences/deployment_preference_collection.py
DeploymentPreferenceCollection.add
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 :param deployment_preference_dict: the input SAM template deployment preference mapping """ if logical_id in self._resource_preferences: raise ValueError("logical_id {logical_id} previously added to this deployment_preference_collection".format( logical_id=logical_id)) self._resource_preferences[logical_id] = DeploymentPreference.from_dict(logical_id, deployment_preference_dict)
python
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 :param deployment_preference_dict: the input SAM template deployment preference mapping """ if logical_id in self._resource_preferences: raise ValueError("logical_id {logical_id} previously added to this deployment_preference_collection".format( logical_id=logical_id)) self._resource_preferences[logical_id] = DeploymentPreference.from_dict(logical_id, deployment_preference_dict)
[ "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\"", ".", "format", "(", "logical_id", "=", "logical_id", ")", ")", "self", ".", "_resource_preferences", "[", "logical_id", "]", "=", "DeploymentPreference", ".", "from_dict", "(", "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 :param deployment_preference_dict: the input SAM template deployment preference mapping
[ "Add", "this", "deployment", "preference", "to", "the", "collection" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference_collection.py#L32-L44
23,231
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
get_welcome_response
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 saying, " \ "my favorite color is red" # If the user either does not reply to the welcome message or says something # that is not understood, they will be prompted again with this text. reprompt_text = "Please tell me your favorite color by saying, " \ "my favorite color is red." should_end_session = False return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session))
python
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 saying, " \ "my favorite color is red" # If the user either does not reply to the welcome message or says something # that is not understood, they will be prompted again with this text. reprompt_text = "Please tell me your favorite color by saying, " \ "my favorite color is red." should_end_session = False return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session))
[ "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 user either does not reply to the welcome message or says something", "# that is not understood, they will be prompted again with this text.", "reprompt_text", "=", "\"Please tell me your favorite color by saying, \"", "\"my favorite color is red.\"", "should_end_session", "=", "False", "return", "build_response", "(", "session_attributes", ",", "build_speechlet_response", "(", "card_title", ",", "speech_output", ",", "reprompt_text", ",", "should_end_session", ")", ")" ]
If we wanted to initialize the session to have some attributes we could add those here
[ "If", "we", "wanted", "to", "initialize", "the", "session", "to", "have", "some", "attributes", "we", "could", "add", "those", "here" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L46-L62
23,232
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
set_color_in_session
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']['value'] session_attributes = create_favorite_color_attributes(favorite_color) speech_output = "I now know your favorite color is " + \ favorite_color + \ ". You can ask me your favorite color by saying, " \ "what's my favorite color?" reprompt_text = "You can ask me your favorite color by saying, " \ "what's my favorite color?" else: speech_output = "I'm not sure what your favorite color is. " \ "Please try again." reprompt_text = "I'm not sure what your favorite color is. " \ "You can tell me your favorite color by saying, " \ "my favorite color is red." return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session))
python
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']['value'] session_attributes = create_favorite_color_attributes(favorite_color) speech_output = "I now know your favorite color is " + \ favorite_color + \ ". You can ask me your favorite color by saying, " \ "what's my favorite color?" reprompt_text = "You can ask me your favorite color by saying, " \ "what's my favorite color?" else: speech_output = "I'm not sure what your favorite color is. " \ "Please try again." reprompt_text = "I'm not sure what your favorite color is. " \ "You can tell me your favorite color by saying, " \ "my favorite color is red." return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session))
[ "def", "set_color_in_session", "(", "intent", ",", "session", ")", ":", "card_title", "=", "intent", "[", "'name'", "]", "session_attributes", "=", "{", "}", "should_end_session", "=", "False", "if", "'Color'", "in", "intent", "[", "'slots'", "]", ":", "favorite_color", "=", "intent", "[", "'slots'", "]", "[", "'Color'", "]", "[", "'value'", "]", "session_attributes", "=", "create_favorite_color_attributes", "(", "favorite_color", ")", "speech_output", "=", "\"I now know your favorite color is \"", "+", "favorite_color", "+", "\". You can ask me your favorite color by saying, \"", "\"what's my favorite color?\"", "reprompt_text", "=", "\"You can ask me your favorite color by saying, \"", "\"what's my favorite color?\"", "else", ":", "speech_output", "=", "\"I'm not sure what your favorite color is. \"", "\"Please try again.\"", "reprompt_text", "=", "\"I'm not sure what your favorite color is. \"", "\"You can tell me your favorite color by saying, \"", "\"my favorite color is red.\"", "return", "build_response", "(", "session_attributes", ",", "build_speechlet_response", "(", "card_title", ",", "speech_output", ",", "reprompt_text", ",", "should_end_session", ")", ")" ]
Sets the color in the session and prepares the speech to reply to the user.
[ "Sets", "the", "color", "in", "the", "session", "and", "prepares", "the", "speech", "to", "reply", "to", "the", "user", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L79-L104
23,233
awslabs/serverless-application-model
examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py
on_intent
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'] # Dispatch to your skill's intent handlers if intent_name == "MyColorIsIntent": return set_color_in_session(intent, session) elif intent_name == "WhatsMyColorIntent": return get_color_from_session(intent, session) elif intent_name == "AMAZON.HelpIntent": return get_welcome_response() elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": return handle_session_end_request() else: raise ValueError("Invalid intent")
python
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'] # Dispatch to your skill's intent handlers if intent_name == "MyColorIsIntent": return set_color_in_session(intent, session) elif intent_name == "WhatsMyColorIntent": return get_color_from_session(intent, session) elif intent_name == "AMAZON.HelpIntent": return get_welcome_response() elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": return handle_session_end_request() else: raise ValueError("Invalid intent")
[ "def", "on_intent", "(", "intent_request", ",", "session", ")", ":", "print", "(", "\"on_intent requestId=\"", "+", "intent_request", "[", "'requestId'", "]", "+", "\", sessionId=\"", "+", "session", "[", "'sessionId'", "]", ")", "intent", "=", "intent_request", "[", "'intent'", "]", "intent_name", "=", "intent_request", "[", "'intent'", "]", "[", "'name'", "]", "# Dispatch to your skill's intent handlers", "if", "intent_name", "==", "\"MyColorIsIntent\"", ":", "return", "set_color_in_session", "(", "intent", ",", "session", ")", "elif", "intent_name", "==", "\"WhatsMyColorIntent\"", ":", "return", "get_color_from_session", "(", "intent", ",", "session", ")", "elif", "intent_name", "==", "\"AMAZON.HelpIntent\"", ":", "return", "get_welcome_response", "(", ")", "elif", "intent_name", "==", "\"AMAZON.CancelIntent\"", "or", "intent_name", "==", "\"AMAZON.StopIntent\"", ":", "return", "handle_session_end_request", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid intent\"", ")" ]
Called when the user specifies an intent for this skill
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "skill" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/alexa-skills-kit-color-expert-python/lambda_function.py#L148-L167
23,234
awslabs/serverless-application-model
samtranslator/translator/logical_id_generator.py
LogicalIdGenerator.get_hash
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_data_str = self.data_str if sys.version_info.major == 2: # In Py2, only unicode needs to be encoded. if isinstance(self.data_str, unicode): encoded_data_str = self.data_str.encode('utf-8') else: # data_str should always be unicode on python 3 encoded_data_str = self.data_str.encode('utf-8') data_hash = hashlib.sha1(encoded_data_str).hexdigest() return data_hash[:length]
python
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_data_str = self.data_str if sys.version_info.major == 2: # In Py2, only unicode needs to be encoded. if isinstance(self.data_str, unicode): encoded_data_str = self.data_str.encode('utf-8') else: # data_str should always be unicode on python 3 encoded_data_str = self.data_str.encode('utf-8') data_hash = hashlib.sha1(encoded_data_str).hexdigest() return data_hash[:length]
[ "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", ".", "major", "==", "2", ":", "# In Py2, only unicode needs to be encoded.", "if", "isinstance", "(", "self", ".", "data_str", ",", "unicode", ")", ":", "encoded_data_str", "=", "self", ".", "data_str", ".", "encode", "(", "'utf-8'", ")", "else", ":", "# data_str should always be unicode on python 3", "encoded_data_str", "=", "self", ".", "data_str", ".", "encode", "(", "'utf-8'", ")", "data_hash", "=", "hashlib", ".", "sha1", "(", "encoded_data_str", ")", ".", "hexdigest", "(", ")", "return", "data_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
[ "Generate", "and", "return", "a", "hash", "of", "data", "that", "can", "be", "used", "as", "suffix", "of", "logicalId" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L49-L72
23,235
awslabs/serverless-application-model
samtranslator/translator/logical_id_generator.py
LogicalIdGenerator._stringify
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 like string, dict, array etc, it will be properly serialized. Otherwise this method will throw a TypeError for non-JSON serializable objects :return: string representation of the dictionary :rtype string """ 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(data, separators=(',', ':'), sort_keys=True)
python
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 like string, dict, array etc, it will be properly serialized. Otherwise this method will throw a TypeError for non-JSON serializable objects :return: string representation of the dictionary :rtype string """ 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(data, separators=(',', ':'), sort_keys=True)
[ "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", "(", "data", ",", "separators", "=", "(", "','", ",", "':'", ")", ",", "sort_keys", "=", "True", ")" ]
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 be properly serialized. Otherwise this method will throw a TypeError for non-JSON serializable objects :return: string representation of the dictionary :rtype string
[ "Stable", "platform", "&", "language", "-", "independent", "stringification", "of", "a", "data", "with", "basic", "Python", "type", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/logical_id_generator.py#L74-L90
23,236
awslabs/serverless-application-model
samtranslator/intrinsics/resource_refs.py
SupportedResourceReferences.add
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" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing """ if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Property value must be a non-empty string") if logical_id not in self._refs: self._refs[logical_id] = {} if property in self._refs[logical_id]: raise ValueError("Cannot add second reference value to {}.{} property".format(logical_id, property)) self._refs[logical_id][property] = value
python
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" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing """ if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Property value must be a non-empty string") if logical_id not in self._refs: self._refs[logical_id] = {} if property in self._refs[logical_id]: raise ValueError("Cannot add second reference value to {}.{} property".format(logical_id, property)) self._refs[logical_id][property] = value
[ "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", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "raise", "ValueError", "(", "\"Property value must be a non-empty string\"", ")", "if", "logical_id", "not", "in", "self", ".", "_refs", ":", "self", ".", "_refs", "[", "logical_id", "]", "=", "{", "}", "if", "property", "in", "self", ".", "_refs", "[", "logical_id", "]", ":", "raise", "ValueError", "(", "\"Cannot add second reference value to {}.{} property\"", ".", "format", "(", "logical_id", ",", "property", ")", ")", "self", ".", "_refs", "[", "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" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L17-L44
23,237
awslabs/serverless-application-model
examples/2016-10-31/encryption_proxy/src/encryption.py
encrypt
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.encodestring(ret.get('CiphertextBlob')) except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to encrypt data: ", e) return encrypted_data.decode()
python
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.encodestring(ret.get('CiphertextBlob')) except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to encrypt data: ", e) return encrypted_data.decode()
[ "def", "encrypt", "(", "key", ",", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "encrypt", "(", "KeyId", "=", "key", ",", "Plaintext", "=", "message", ")", "encrypted_data", "=", "base64", ".", "encodestring", "(", "ret", ".", "get", "(", "'CiphertextBlob'", ")", ")", "except", "Exception", "as", "e", ":", "# returns http 500 back to user and log error details in Cloudwatch Logs", "raise", "Exception", "(", "\"Unable to encrypt data: \"", ",", "e", ")", "return", "encrypted_data", ".", "decode", "(", ")" ]
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
[ "encrypt", "leverages", "KMS", "encrypt", "and", "base64", "-", "encode", "encrypted", "blob" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/2016-10-31/encryption_proxy/src/encryption.py#L16-L29
23,238
awslabs/serverless-application-model
samtranslator/model/tags/resource_tagging.py
get_tag_list
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 ``` :param resource_tag_dict: Customer defined dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above) """ tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag) return tag_list
python
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 ``` :param resource_tag_dict: Customer defined dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above) """ tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag) return tag_list
[ "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", "=", "{", "_KEY", ":", "tag_key", ",", "_VALUE", ":", "tag_value", "if", "tag_value", "else", "\"\"", "}", "tag_list", ".", "append", "(", "tag", ")", "return", "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 dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above)
[ "Transforms", "the", "SAM", "defined", "Tags", "into", "the", "form", "CloudFormation", "is", "expecting", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/tags/resource_tagging.py#L7-L36
23,239
awslabs/serverless-application-model
samtranslator/translator/arn_generator.py
ArnGenerator.get_partition_name
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/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaultroles.py#L59 :param region: Optional name of the region :return: Partition name """ 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. region = boto3.session.Session().region_name region_string = region.lower() if region_string.startswith("cn-"): return "aws-cn" elif region_string.startswith("us-gov"): return "aws-us-gov" else: return "aws"
python
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/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaultroles.py#L59 :param region: Optional name of the region :return: Partition name """ 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. region = boto3.session.Session().region_name region_string = region.lower() if region_string.startswith("cn-"): return "aws-cn" elif region_string.startswith("us-gov"): return "aws-us-gov" else: return "aws"
[ "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.", "region", "=", "boto3", ".", "session", ".", "Session", "(", ")", ".", "region_name", "region_string", "=", "region", ".", "lower", "(", ")", "if", "region_string", ".", "startswith", "(", "\"cn-\"", ")", ":", "return", "\"aws-cn\"", "elif", "region_string", ".", "startswith", "(", "\"us-gov\"", ")", ":", "return", "\"aws-us-gov\"", "else", ":", "return", "\"aws\"" ]
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/createdefaultroles.py#L59 :param region: Optional name of the region :return: 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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/arn_generator.py#L33-L56
23,240
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.has_path
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._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
python
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._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
[ "def", "has_path", "(", "self", ",", "path", ",", "method", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "path_dict_exists", "=", "path_dict", "is", "not", "None", "if", "method", ":", "return", "path_dict_exists", "and", "method", "in", "path_dict", "return", "path_dict_exists" ]
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
[ "Returns", "True", "if", "this", "Swagger", "has", "the", "given", "path", "and", "optional", "method" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L46-L60
23,241
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.method_has_integration
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 """ for method_definition in self.get_method_contents(method): if self.method_definition_has_integration(method_definition): return True return False
python
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 """ for method_definition in self.get_method_contents(method): if self.method_definition_has_integration(method_definition): return True return False
[ "def", "method_has_integration", "(", "self", ",", "method", ")", ":", "for", "method_definition", "in", "self", ".", "get_method_contents", "(", "method", ")", ":", "if", "self", ".", "method_definition_has_integration", "(", "method_definition", ")", ":", "return", "True", "return", "False" ]
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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L62-L73
23,242
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.get_method_contents
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 dictionary :return: list of swagger component dictionaries for the method """ if self._CONDITIONAL_IF in method: return method[self._CONDITIONAL_IF][1:] return [method]
python
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 dictionary :return: list of swagger component dictionaries for the method """ if self._CONDITIONAL_IF in method: return method[self._CONDITIONAL_IF][1:] return [method]
[ "def", "get_method_contents", "(", "self", ",", "method", ")", ":", "if", "self", ".", "_CONDITIONAL_IF", "in", "method", ":", "return", "method", "[", "self", ".", "_CONDITIONAL_IF", "]", "[", "1", ":", "]", "return", "[", "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 dictionary :return: list of swagger component dictionaries for the 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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L86-L97
23,243
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_lambda_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 :param string integration_uri: URI for the integration. """ method = self._normalize_method_name(method) if self.has_integration(path, method): raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method)) self.add_path(path, method) # Wrap the integration_uri in a Condition if one exists on that function # This is necessary so CFN doesn't try to resolve the integration reference. if condition: integration_uri = make_conditional(condition, integration_uri) path_dict = self.get_path(path) path_dict[method][self._X_APIGW_INTEGRATION] = { 'type': 'aws_proxy', 'httpMethod': 'POST', 'uri': integration_uri } method_auth_config = method_auth_config or {} api_auth_config = api_auth_config or {} if method_auth_config.get('Authorizer') == 'AWS_IAM' \ or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config: self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = self._generate_integration_credentials( method_invoke_role=method_auth_config.get('InvokeRole'), api_invoke_role=api_auth_config.get('InvokeRole') ) # If 'responses' key is *not* present, add it with an empty dict as value path_dict[method].setdefault('responses', {}) # If a condition is present, wrap all method contents up into the condition if condition: path_dict[method] = make_conditional(condition, path_dict[method])
python
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 :param string integration_uri: URI for the integration. """ method = self._normalize_method_name(method) if self.has_integration(path, method): raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method)) self.add_path(path, method) # Wrap the integration_uri in a Condition if one exists on that function # This is necessary so CFN doesn't try to resolve the integration reference. if condition: integration_uri = make_conditional(condition, integration_uri) path_dict = self.get_path(path) path_dict[method][self._X_APIGW_INTEGRATION] = { 'type': 'aws_proxy', 'httpMethod': 'POST', 'uri': integration_uri } method_auth_config = method_auth_config or {} api_auth_config = api_auth_config or {} if method_auth_config.get('Authorizer') == 'AWS_IAM' \ or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config: self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = self._generate_integration_credentials( method_invoke_role=method_auth_config.get('InvokeRole'), api_invoke_role=api_auth_config.get('InvokeRole') ) # If 'responses' key is *not* present, add it with an empty dict as value path_dict[method].setdefault('responses', {}) # If a condition is present, wrap all method contents up into the condition if condition: path_dict[method] = make_conditional(condition, path_dict[method])
[ "def", "add_lambda_integration", "(", "self", ",", "path", ",", "method", ",", "integration_uri", ",", "method_auth_config", "=", "None", ",", "api_auth_config", "=", "None", ",", "condition", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "if", "self", ".", "has_integration", "(", "path", ",", "method", ")", ":", "raise", "ValueError", "(", "\"Lambda integration already exists on Path={}, Method={}\"", ".", "format", "(", "path", ",", "method", ")", ")", "self", ".", "add_path", "(", "path", ",", "method", ")", "# Wrap the integration_uri in a Condition if one exists on that function", "# This is necessary so CFN doesn't try to resolve the integration reference.", "if", "condition", ":", "integration_uri", "=", "make_conditional", "(", "condition", ",", "integration_uri", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "path_dict", "[", "method", "]", "[", "self", ".", "_X_APIGW_INTEGRATION", "]", "=", "{", "'type'", ":", "'aws_proxy'", ",", "'httpMethod'", ":", "'POST'", ",", "'uri'", ":", "integration_uri", "}", "method_auth_config", "=", "method_auth_config", "or", "{", "}", "api_auth_config", "=", "api_auth_config", "or", "{", "}", "if", "method_auth_config", ".", "get", "(", "'Authorizer'", ")", "==", "'AWS_IAM'", "or", "api_auth_config", ".", "get", "(", "'DefaultAuthorizer'", ")", "==", "'AWS_IAM'", "and", "not", "method_auth_config", ":", "self", ".", "paths", "[", "path", "]", "[", "method", "]", "[", "self", ".", "_X_APIGW_INTEGRATION", "]", "[", "'credentials'", "]", "=", "self", ".", "_generate_integration_credentials", "(", "method_invoke_role", "=", "method_auth_config", ".", "get", "(", "'InvokeRole'", ")", ",", "api_invoke_role", "=", "api_auth_config", ".", "get", "(", "'InvokeRole'", ")", ")", "# If 'responses' key is *not* present, add it with an empty dict as value", "path_dict", "[", "method", "]", ".", "setdefault", "(", "'responses'", ",", "{", "}", ")", "# If a condition is present, wrap all method contents up into the condition", "if", "condition", ":", "path_dict", "[", "method", "]", "=", "make_conditional", "(", "condition", ",", "path_dict", "[", "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.
[ "Adds", "aws_proxy", "APIGW", "integration", "to", "the", "given", "path", "+", "method", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L137-L179
23,244
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.make_path_conditional
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])
python
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", ")", ":", "self", ".", "paths", "[", "path", "]", "=", "make_conditional", "(", "condition", ",", "self", ".", "paths", "[", "path", "]", ")" ]
Wrap entire API path definition in a CloudFormation if condition.
[ "Wrap", "entire", "API", "path", "definition", "in", "a", "CloudFormation", "if", "condition", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L181-L185
23,245
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_cors
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. 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 themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty """ # Skip if Options is already present if self.has_path(path, self._OPTIONS_METHOD): return if not allowed_origins: raise ValueError("Invalid input. Value for AllowedOrigins is required") if not allowed_methods: # AllowMethods is not given. Let's try to generate the list from the given Swagger. allowed_methods = self._make_cors_allowed_methods_for_path(path) # APIGW expects the value to be a "string expression". Hence wrap in another quote. Ex: "'GET,POST,DELETE'" allowed_methods = "'{}'".format(allowed_methods) if allow_credentials is not True: allow_credentials = False # Add the Options method and the CORS response self.add_path(path, self._OPTIONS_METHOD) self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins, allowed_headers, allowed_methods, max_age, allow_credentials)
python
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. 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 themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty """ # Skip if Options is already present if self.has_path(path, self._OPTIONS_METHOD): return if not allowed_origins: raise ValueError("Invalid input. Value for AllowedOrigins is required") if not allowed_methods: # AllowMethods is not given. Let's try to generate the list from the given Swagger. allowed_methods = self._make_cors_allowed_methods_for_path(path) # APIGW expects the value to be a "string expression". Hence wrap in another quote. Ex: "'GET,POST,DELETE'" allowed_methods = "'{}'".format(allowed_methods) if allow_credentials is not True: allow_credentials = False # Add the Options method and the CORS response self.add_path(path, self._OPTIONS_METHOD) self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins, allowed_headers, allowed_methods, max_age, allow_credentials)
[ "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", "if", "self", ".", "has_path", "(", "path", ",", "self", ".", "_OPTIONS_METHOD", ")", ":", "return", "if", "not", "allowed_origins", ":", "raise", "ValueError", "(", "\"Invalid input. Value for AllowedOrigins is required\"", ")", "if", "not", "allowed_methods", ":", "# AllowMethods is not given. Let's try to generate the list from the given Swagger.", "allowed_methods", "=", "self", ".", "_make_cors_allowed_methods_for_path", "(", "path", ")", "# APIGW expects the value to be a \"string expression\". Hence wrap in another quote. Ex: \"'GET,POST,DELETE'\"", "allowed_methods", "=", "\"'{}'\"", ".", "format", "(", "allowed_methods", ")", "if", "allow_credentials", "is", "not", "True", ":", "allow_credentials", "=", "False", "# Add the Options method and the CORS response", "self", ".", "add_path", "(", "path", ",", "self", ".", "_OPTIONS_METHOD", ")", "self", ".", "get_path", "(", "path", ")", "[", "self", ".", "_OPTIONS_METHOD", "]", "=", "self", ".", "_options_method_response_for_cors", "(", "allowed_origins", ",", "allowed_headers", ",", "allowed_methods", ",", "max_age", ",", "allow_credentials", ")" ]
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 themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty
[ "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", "themselves", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L205-L254
23,246
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor._options_method_response_for_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 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 allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS """ ALLOW_ORIGIN = "Access-Control-Allow-Origin" ALLOW_HEADERS = "Access-Control-Allow-Headers" ALLOW_METHODS = "Access-Control-Allow-Methods" MAX_AGE = "Access-Control-Max-Age" ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials" HEADER_RESPONSE = (lambda x: "method.response.header." + x) response_parameters = { # AllowedOrigin is always required HEADER_RESPONSE(ALLOW_ORIGIN): allowed_origins } response_headers = { # Allow Origin is always required ALLOW_ORIGIN: { "type": "string" } } # Optional values. Skip the header if value is empty # # The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and # not supported in all the browsers. So it is important to skip the header if value is not given # https://fetch.spec.whatwg.org/#http-new-header-syntax # if allowed_headers: response_parameters[HEADER_RESPONSE(ALLOW_HEADERS)] = allowed_headers response_headers[ALLOW_HEADERS] = {"type": "string"} if allowed_methods: response_parameters[HEADER_RESPONSE(ALLOW_METHODS)] = allowed_methods response_headers[ALLOW_METHODS] = {"type": "string"} if max_age is not None: # MaxAge can be set to 0, which is a valid value. So explicitly check against None response_parameters[HEADER_RESPONSE(MAX_AGE)] = max_age response_headers[MAX_AGE] = {"type": "integer"} if allow_credentials is True: # Allow-Credentials only has a valid value of true, it should be omitted otherwise. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials response_parameters[HEADER_RESPONSE(ALLOW_CREDENTIALS)] = "'true'" response_headers[ALLOW_CREDENTIALS] = {"type": "string"} return { "summary": "CORS support", "consumes": ["application/json"], "produces": ["application/json"], self._X_APIGW_INTEGRATION: { "type": "mock", "requestTemplates": { "application/json": "{\n \"statusCode\" : 200\n}\n" }, "responses": { "default": { "statusCode": "200", "responseParameters": response_parameters, "responseTemplates": { "application/json": "{}\n" } } } }, "responses": { "200": { "description": "Default response for CORS method", "headers": response_headers } } }
python
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 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 allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS """ ALLOW_ORIGIN = "Access-Control-Allow-Origin" ALLOW_HEADERS = "Access-Control-Allow-Headers" ALLOW_METHODS = "Access-Control-Allow-Methods" MAX_AGE = "Access-Control-Max-Age" ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials" HEADER_RESPONSE = (lambda x: "method.response.header." + x) response_parameters = { # AllowedOrigin is always required HEADER_RESPONSE(ALLOW_ORIGIN): allowed_origins } response_headers = { # Allow Origin is always required ALLOW_ORIGIN: { "type": "string" } } # Optional values. Skip the header if value is empty # # The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and # not supported in all the browsers. So it is important to skip the header if value is not given # https://fetch.spec.whatwg.org/#http-new-header-syntax # if allowed_headers: response_parameters[HEADER_RESPONSE(ALLOW_HEADERS)] = allowed_headers response_headers[ALLOW_HEADERS] = {"type": "string"} if allowed_methods: response_parameters[HEADER_RESPONSE(ALLOW_METHODS)] = allowed_methods response_headers[ALLOW_METHODS] = {"type": "string"} if max_age is not None: # MaxAge can be set to 0, which is a valid value. So explicitly check against None response_parameters[HEADER_RESPONSE(MAX_AGE)] = max_age response_headers[MAX_AGE] = {"type": "integer"} if allow_credentials is True: # Allow-Credentials only has a valid value of true, it should be omitted otherwise. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials response_parameters[HEADER_RESPONSE(ALLOW_CREDENTIALS)] = "'true'" response_headers[ALLOW_CREDENTIALS] = {"type": "string"} return { "summary": "CORS support", "consumes": ["application/json"], "produces": ["application/json"], self._X_APIGW_INTEGRATION: { "type": "mock", "requestTemplates": { "application/json": "{\n \"statusCode\" : 200\n}\n" }, "responses": { "default": { "statusCode": "200", "responseParameters": response_parameters, "responseTemplates": { "application/json": "{}\n" } } } }, "responses": { "200": { "description": "Default response for CORS method", "headers": response_headers } } }
[ "def", "_options_method_response_for_cors", "(", "self", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "ALLOW_ORIGIN", "=", "\"Access-Control-Allow-Origin\"", "ALLOW_HEADERS", "=", "\"Access-Control-Allow-Headers\"", "ALLOW_METHODS", "=", "\"Access-Control-Allow-Methods\"", "MAX_AGE", "=", "\"Access-Control-Max-Age\"", "ALLOW_CREDENTIALS", "=", "\"Access-Control-Allow-Credentials\"", "HEADER_RESPONSE", "=", "(", "lambda", "x", ":", "\"method.response.header.\"", "+", "x", ")", "response_parameters", "=", "{", "# AllowedOrigin is always required", "HEADER_RESPONSE", "(", "ALLOW_ORIGIN", ")", ":", "allowed_origins", "}", "response_headers", "=", "{", "# Allow Origin is always required", "ALLOW_ORIGIN", ":", "{", "\"type\"", ":", "\"string\"", "}", "}", "# Optional values. Skip the header if value is empty", "#", "# The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and", "# not supported in all the browsers. So it is important to skip the header if value is not given", "# https://fetch.spec.whatwg.org/#http-new-header-syntax", "#", "if", "allowed_headers", ":", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_HEADERS", ")", "]", "=", "allowed_headers", "response_headers", "[", "ALLOW_HEADERS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "if", "allowed_methods", ":", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_METHODS", ")", "]", "=", "allowed_methods", "response_headers", "[", "ALLOW_METHODS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "if", "max_age", "is", "not", "None", ":", "# MaxAge can be set to 0, which is a valid value. So explicitly check against None", "response_parameters", "[", "HEADER_RESPONSE", "(", "MAX_AGE", ")", "]", "=", "max_age", "response_headers", "[", "MAX_AGE", "]", "=", "{", "\"type\"", ":", "\"integer\"", "}", "if", "allow_credentials", "is", "True", ":", "# Allow-Credentials only has a valid value of true, it should be omitted otherwise.", "# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_CREDENTIALS", ")", "]", "=", "\"'true'\"", "response_headers", "[", "ALLOW_CREDENTIALS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "return", "{", "\"summary\"", ":", "\"CORS support\"", ",", "\"consumes\"", ":", "[", "\"application/json\"", "]", ",", "\"produces\"", ":", "[", "\"application/json\"", "]", ",", "self", ".", "_X_APIGW_INTEGRATION", ":", "{", "\"type\"", ":", "\"mock\"", ",", "\"requestTemplates\"", ":", "{", "\"application/json\"", ":", "\"{\\n \\\"statusCode\\\" : 200\\n}\\n\"", "}", ",", "\"responses\"", ":", "{", "\"default\"", ":", "{", "\"statusCode\"", ":", "\"200\"", ",", "\"responseParameters\"", ":", "response_parameters", ",", "\"responseTemplates\"", ":", "{", "\"application/json\"", ":", "\"{}\\n\"", "}", "}", "}", "}", ",", "\"responses\"", ":", "{", "\"200\"", ":", "{", "\"description\"", ":", "\"Default response for CORS method\"", ",", "\"headers\"", ":", "response_headers", "}", "}", "}" ]
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 allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS
[ "Returns", "a", "Swagger", "snippet", "containing", "configuration", "for", "OPTIONS", "HTTP", "Method", "to", "configure", "CORS", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L256-L343
23,247
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_authorizers
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 {} for authorizer_name, authorizer in authorizers.items(): self.security_definitions[authorizer_name] = authorizer.generate_swagger()
python
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 {} for authorizer_name, authorizer in authorizers.items(): self.security_definitions[authorizer_name] = authorizer.generate_swagger()
[ "def", "add_authorizers", "(", "self", ",", "authorizers", ")", ":", "self", ".", "security_definitions", "=", "self", ".", "security_definitions", "or", "{", "}", "for", "authorizer_name", ",", "authorizer", "in", "authorizers", ".", "items", "(", ")", ":", "self", ".", "security_definitions", "[", "authorizer_name", "]", "=", "authorizer", ".", "generate_swagger", "(", ")" ]
Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.
[ "Add", "Authorizer", "definitions", "to", "the", "securityDefinitions", "part", "of", "Swagger", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L386-L395
23,248
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_gateway_responses
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_type, response in gateway_responses.items(): self.gateway_responses[response_type] = response.generate_swagger()
python
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_type, response in gateway_responses.items(): self.gateway_responses[response_type] = response.generate_swagger()
[ "def", "add_gateway_responses", "(", "self", ",", "gateway_responses", ")", ":", "self", ".", "gateway_responses", "=", "self", ".", "gateway_responses", "or", "{", "}", "for", "response_type", ",", "response", "in", "gateway_responses", ".", "items", "(", ")", ":", "self", ".", "gateway_responses", "[", "response_type", "]", "=", "response", ".", "generate_swagger", "(", ")" ]
Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.
[ "Add", "Gateway", "Response", "definitions", "to", "Swagger", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L516-L525
23,249
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.is_valid
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 \ isinstance(data.get('paths'), dict)
python
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 \ isinstance(data.get('paths'), dict)
[ "def", "is_valid", "(", "data", ")", ":", "return", "bool", "(", "data", ")", "and", "isinstance", "(", "data", ",", "dict", ")", "and", "bool", "(", "data", ".", "get", "(", "\"swagger\"", ")", ")", "and", "isinstance", "(", "data", ".", "get", "(", "'paths'", ")", ",", "dict", ")" ]
Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger
[ "Checks", "if", "the", "input", "data", "is", "a", "Swagger", "document" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L546-L556
23,250
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor._normalize_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 Method :return string: Normalized method name """ if not method or not isinstance(method, string_types): return method method = method.lower() if method == 'any': return SwaggerEditor._X_ANY_METHOD else: return method
python
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 Method :return string: Normalized method name """ if not method or not isinstance(method, string_types): return method method = method.lower() if method == 'any': return SwaggerEditor._X_ANY_METHOD else: return method
[ "def", "_normalize_method_name", "(", "method", ")", ":", "if", "not", "method", "or", "not", "isinstance", "(", "method", ",", "string_types", ")", ":", "return", "method", "method", "=", "method", ".", "lower", "(", ")", "if", "method", "==", "'any'", ":", "return", "SwaggerEditor", ".", "_X_ANY_METHOD", "else", ":", "return", "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 Method :return string: Normalized method name
[ "Returns", "a", "lower", "case", "normalized", "version", "of", "HTTP", "Method", ".", "It", "also", "know", "how", "to", "handle", "API", "Gateway", "specific", "methods", "like", "ANY" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L576-L593
23,251
awslabs/serverless-application-model
samtranslator/model/types.py
is_type
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 otherwise :rtype: callable """ def validate(value, should_raise=True): if not isinstance(value, valid_type): if should_raise: raise TypeError("Expected value of type {expected}, actual value was of type {actual}.".format( expected=valid_type, actual=type(value))) return False return True return validate
python
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 otherwise :rtype: callable """ def validate(value, should_raise=True): if not isinstance(value, valid_type): if should_raise: raise TypeError("Expected value of type {expected}, actual value was of type {actual}.".format( expected=valid_type, actual=type(value))) return False return True return validate
[ "def", "is_type", "(", "valid_type", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "if", "not", "isinstance", "(", "value", ",", "valid_type", ")", ":", "if", "should_raise", ":", "raise", "TypeError", "(", "\"Expected value of type {expected}, actual value was of type {actual}.\"", ".", "format", "(", "expected", "=", "valid_type", ",", "actual", "=", "type", "(", "value", ")", ")", ")", "return", "False", "return", "True", "return", "validate" ]
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
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "for", "inputs", "of", "the", "provided", "valid_type", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L15-L29
23,252
awslabs/serverless-application-model
samtranslator/model/types.py
list_of
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 its input is an list of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(list) if not validate_type(value, should_raise=should_raise): return False for item in value: try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "list contained an invalid item") raise return False return True return validate
python
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 its input is an list of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(list) if not validate_type(value, should_raise=should_raise): return False for item in value: try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "list contained an invalid item") raise return False return True return validate
[ "def", "list_of", "(", "validate_item", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "validate_type", "=", "is_type", "(", "list", ")", "if", "not", "validate_type", "(", "value", ",", "should_raise", "=", "should_raise", ")", ":", "return", "False", "for", "item", "in", "value", ":", "try", ":", "validate_item", "(", "item", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"list contained an invalid item\"", ")", "raise", "return", "False", "return", "True", "return", "validate" ]
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, and raises TypeError otherwise :rtype: callable
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L32-L54
23,253
awslabs/serverless-application-model
samtranslator/model/types.py
dict_of
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 the dict :param callable validate_item: the validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(dict) if not validate_type(value, should_raise=should_raise): return False for key, item in value.items(): try: validate_key(key) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid key") raise return False try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid value") raise return False return True return validate
python
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 the dict :param callable validate_item: the validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(dict) if not validate_type(value, should_raise=should_raise): return False for key, item in value.items(): try: validate_key(key) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid key") raise return False try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid value") raise return False return True return validate
[ "def", "dict_of", "(", "validate_key", ",", "validate_item", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "validate_type", "=", "is_type", "(", "dict", ")", "if", "not", "validate_type", "(", "value", ",", "should_raise", "=", "should_raise", ")", ":", "return", "False", "for", "key", ",", "item", "in", "value", ".", "items", "(", ")", ":", "try", ":", "validate_key", "(", "key", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"dict contained an invalid key\"", ")", "raise", "return", "False", "try", ":", "validate_item", "(", "item", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"dict contained an invalid value\"", ")", "raise", "return", "False", "return", "True", "return", "validate" ]
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 validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable
[ "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", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L57-L88
23,254
awslabs/serverless-application-model
samtranslator/model/types.py
one_of
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 otherwise :rtype: callable """ def validate(value, should_raise=True): if any(validate(value, should_raise=False) for validate in validators): return True if should_raise: raise TypeError("value did not match any allowable type") return False return validate
python
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 otherwise :rtype: callable """ def validate(value, should_raise=True): if any(validate(value, should_raise=False) for validate in validators): return True if should_raise: raise TypeError("value did not match any allowable type") return False return validate
[ "def", "one_of", "(", "*", "validators", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "if", "any", "(", "validate", "(", "value", ",", "should_raise", "=", "False", ")", "for", "validate", "in", "validators", ")", ":", "return", "True", "if", "should_raise", ":", "raise", "TypeError", "(", "\"value did not match any allowable type\"", ")", "return", "False", "return", "validate" ]
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: callable
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "if", "the", "input", "passes", "at", "least", "one", "of", "the", "provided", "validators", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L91-L106
23,255
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.to_statement
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: Dictionary containing policy statement :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters """ missing = self.missing_parameter_values(parameter_values) if len(missing) > 0: # str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message raise InsufficientParameterValues("Following required parameters of template '{}' don't have values: {}" .format(self.name, [str(m) for m in missing])) # Select only necessary parameter_values. this is to prevent malicious or accidental # injection of values for parameters not intended in the template. This is important because "Ref" resolution # will substitute any references for which a value is provided. necessary_parameter_values = {name: value for name, value in parameter_values.items() if name in self.parameters} # Only "Ref" is supported supported_intrinsics = { RefAction.intrinsic_name: RefAction() } resolver = IntrinsicsResolver(necessary_parameter_values, supported_intrinsics) definition_copy = copy.deepcopy(self.definition) return resolver.resolve_parameter_refs(definition_copy)
python
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: Dictionary containing policy statement :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters """ missing = self.missing_parameter_values(parameter_values) if len(missing) > 0: # str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message raise InsufficientParameterValues("Following required parameters of template '{}' don't have values: {}" .format(self.name, [str(m) for m in missing])) # Select only necessary parameter_values. this is to prevent malicious or accidental # injection of values for parameters not intended in the template. This is important because "Ref" resolution # will substitute any references for which a value is provided. necessary_parameter_values = {name: value for name, value in parameter_values.items() if name in self.parameters} # Only "Ref" is supported supported_intrinsics = { RefAction.intrinsic_name: RefAction() } resolver = IntrinsicsResolver(necessary_parameter_values, supported_intrinsics) definition_copy = copy.deepcopy(self.definition) return resolver.resolve_parameter_refs(definition_copy)
[ "def", "to_statement", "(", "self", ",", "parameter_values", ")", ":", "missing", "=", "self", ".", "missing_parameter_values", "(", "parameter_values", ")", "if", "len", "(", "missing", ")", ">", "0", ":", "# str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message", "raise", "InsufficientParameterValues", "(", "\"Following required parameters of template '{}' don't have values: {}\"", ".", "format", "(", "self", ".", "name", ",", "[", "str", "(", "m", ")", "for", "m", "in", "missing", "]", ")", ")", "# Select only necessary parameter_values. this is to prevent malicious or accidental", "# injection of values for parameters not intended in the template. This is important because \"Ref\" resolution", "# will substitute any references for which a value is provided.", "necessary_parameter_values", "=", "{", "name", ":", "value", "for", "name", ",", "value", "in", "parameter_values", ".", "items", "(", ")", "if", "name", "in", "self", ".", "parameters", "}", "# Only \"Ref\" is supported", "supported_intrinsics", "=", "{", "RefAction", ".", "intrinsic_name", ":", "RefAction", "(", ")", "}", "resolver", "=", "IntrinsicsResolver", "(", "necessary_parameter_values", ",", "supported_intrinsics", ")", "definition_copy", "=", "copy", ".", "deepcopy", "(", "self", ".", "definition", ")", "return", "resolver", ".", "resolve_parameter_refs", "(", "definition_copy", ")" ]
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 InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters
[ "With", "the", "given", "values", "for", "each", "parameter", "this", "method", "will", "return", "a", "policy", "statement", "that", "can", "be", "used", "directly", "with", "IAM", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L30-L62
23,256
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.missing_parameter_values
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 missing. :raises InvalidParameterValues: When parameter values is not a valid dictionary """ if not self._is_valid_parameter_values(parameter_values): raise InvalidParameterValues("Parameter values are required to process a policy template") return list(set(self.parameters.keys()) - set(parameter_values.keys()))
python
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 missing. :raises InvalidParameterValues: When parameter values is not a valid dictionary """ if not self._is_valid_parameter_values(parameter_values): raise InvalidParameterValues("Parameter values are required to process a policy template") return list(set(self.parameters.keys()) - set(parameter_values.keys()))
[ "def", "missing_parameter_values", "(", "self", ",", "parameter_values", ")", ":", "if", "not", "self", ".", "_is_valid_parameter_values", "(", "parameter_values", ")", ":", "raise", "InvalidParameterValues", "(", "\"Parameter values are required to process a policy template\"", ")", "return", "list", "(", "set", "(", "self", ".", "parameters", ".", "keys", "(", ")", ")", "-", "set", "(", "parameter_values", ".", "keys", "(", ")", ")", ")" ]
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 a valid dictionary
[ "Checks", "if", "the", "given", "input", "contains", "values", "for", "all", "parameters", "used", "by", "this", "template" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L64-L76
23,257
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.from_dict
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 JSON Schema validation. :return Template: Instance of this class containing the values provided in this dictionary """ parameters = template_values_dict.get("Parameters", {}) definition = template_values_dict.get("Definition", {}) return Template(template_name, parameters, definition)
python
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 JSON Schema validation. :return Template: Instance of this class containing the values provided in this dictionary """ parameters = template_values_dict.get("Parameters", {}) definition = template_values_dict.get("Definition", {}) return Template(template_name, parameters, definition)
[ "def", "from_dict", "(", "template_name", ",", "template_values_dict", ")", ":", "parameters", "=", "template_values_dict", ".", "get", "(", "\"Parameters\"", ",", "{", "}", ")", "definition", "=", "template_values_dict", ".", "get", "(", "\"Definition\"", ",", "{", "}", ")", "return", "Template", "(", "template_name", ",", "parameters", ",", "definition", ")" ]
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 class containing the values provided in this dictionary
[ "Parses", "the", "input", "and", "returns", "an", "instance", "of", "this", "class", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L102-L115
23,258
awslabs/serverless-application-model
samtranslator/plugins/__init__.py
SamPlugins.register
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.BasePlugin or if it is already registered :return: None """ if not plugin or not isinstance(plugin, BasePlugin): raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") if self.is_registered(plugin.name): raise ValueError("Plugin with name {} is already registered".format(plugin.name)) self._plugins.append(plugin)
python
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.BasePlugin or if it is already registered :return: None """ if not plugin or not isinstance(plugin, BasePlugin): raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") if self.is_registered(plugin.name): raise ValueError("Plugin with name {} is already registered".format(plugin.name)) self._plugins.append(plugin)
[ "def", "register", "(", "self", ",", "plugin", ")", ":", "if", "not", "plugin", "or", "not", "isinstance", "(", "plugin", ",", "BasePlugin", ")", ":", "raise", "ValueError", "(", "\"Plugin must be implemented as a subclass of BasePlugin class\"", ")", "if", "self", ".", "is_registered", "(", "plugin", ".", "name", ")", ":", "raise", "ValueError", "(", "\"Plugin with name {} is already registered\"", ".", "format", "(", "plugin", ".", "name", ")", ")", "self", ".", "_plugins", ".", "append", "(", "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.BasePlugin or if it is already registered :return: None
[ "Register", "a", "plugin", ".", "New", "plugins", "are", "added", "to", "the", "end", "of", "the", "plugins", "list", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/__init__.py#L64-L80
23,259
awslabs/serverless-application-model
samtranslator/plugins/__init__.py
SamPlugins._get
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 == plugin_name: return p return None
python
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 == plugin_name: return p return None
[ "def", "_get", "(", "self", ",", "plugin_name", ")", ":", "for", "p", "in", "self", ".", "_plugins", ":", "if", "p", ".", "name", "==", "plugin_name", ":", "return", "p", "return", "None" ]
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
[ "Retrieves", "the", "plugin", "with", "given", "name" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/__init__.py#L92-L104
23,260
awslabs/serverless-application-model
examples/2016-10-31/encryption_proxy/src/decryption.py
decrypt
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)) decrypted_data = ret.get('Plaintext') except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to decrypt data: ", e) return decrypted_data
python
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)) decrypted_data = ret.get('Plaintext') except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to decrypt data: ", e) return decrypted_data
[ "def", "decrypt", "(", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "decrypt", "(", "CiphertextBlob", "=", "base64", ".", "decodestring", "(", "message", ")", ")", "decrypted_data", "=", "ret", ".", "get", "(", "'Plaintext'", ")", "except", "Exception", "as", "e", ":", "# returns http 500 back to user and log error details in Cloudwatch Logs", "raise", "Exception", "(", "\"Unable to decrypt data: \"", ",", "e", ")", "return", "decrypted_data" ]
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
[ "decrypt", "leverages", "KMS", "decrypt", "and", "base64", "-", "encode", "decrypted", "blob" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/2016-10-31/encryption_proxy/src/decryption.py#L15-L29
23,261
awslabs/serverless-application-model
examples/apps/rekognition-python/lambda_function.py
lambda_handler
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'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Calls rekognition DetectFaces API to detect faces in S3 object response = detect_faces(bucket, key) # Calls rekognition DetectLabels API to detect labels in S3 object #response = detect_labels(bucket, key) # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection #response = index_faces(bucket, key) # Print response to console. print(response) return response except Exception as e: print(e) print("Error processing object {} from bucket {}. ".format(key, bucket) + "Make sure your object and bucket exist and your bucket is in the same region as this function.") raise e
python
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'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Calls rekognition DetectFaces API to detect faces in S3 object response = detect_faces(bucket, key) # Calls rekognition DetectLabels API to detect labels in S3 object #response = detect_labels(bucket, key) # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection #response = index_faces(bucket, key) # Print response to console. print(response) return response except Exception as e: print(e) print("Error processing object {} from bucket {}. ".format(key, bucket) + "Make sure your object and bucket exist and your bucket is in the same region as this function.") raise e
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "#print(\"Received event: \" + json.dumps(event, indent=2))", "# Get the object from the event", "bucket", "=", "event", "[", "'Records'", "]", "[", "0", "]", "[", "'s3'", "]", "[", "'bucket'", "]", "[", "'name'", "]", "key", "=", "urllib", ".", "unquote_plus", "(", "event", "[", "'Records'", "]", "[", "0", "]", "[", "'s3'", "]", "[", "'object'", "]", "[", "'key'", "]", ".", "encode", "(", "'utf8'", ")", ")", "try", ":", "# Calls rekognition DetectFaces API to detect faces in S3 object", "response", "=", "detect_faces", "(", "bucket", ",", "key", ")", "# Calls rekognition DetectLabels API to detect labels in S3 object", "#response = detect_labels(bucket, key)", "# Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection", "#response = index_faces(bucket, key)", "# Print response to console.", "print", "(", "response", ")", "return", "response", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "print", "(", "\"Error processing object {} from bucket {}. \"", ".", "format", "(", "key", ",", "bucket", ")", "+", "\"Make sure your object and bucket exist and your bucket is in the same region as this function.\"", ")", "raise", "e" ]
Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object.
[ "Demonstrates", "S3", "trigger", "that", "uses", "Rekognition", "APIs", "to", "detect", "faces", "labels", "and", "index", "faces", "in", "S3", "Object", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/rekognition-python/lambda_function.py#L42-L69
23,262
awslabs/serverless-application-model
examples/apps/api-gateway-authorizer-python/lambda_function.py
AuthPolicy._getStatementForEffect
def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
python
def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
[ "def", "_getStatementForEffect", "(", "self", ",", "effect", ",", "methods", ")", ":", "statements", "=", "[", "]", "if", "len", "(", "methods", ")", ">", "0", ":", "statement", "=", "self", ".", "_getEmptyStatement", "(", "effect", ")", "for", "curMethod", "in", "methods", ":", "if", "curMethod", "[", "'conditions'", "]", "is", "None", "or", "len", "(", "curMethod", "[", "'conditions'", "]", ")", "==", "0", ":", "statement", "[", "'Resource'", "]", ".", "append", "(", "curMethod", "[", "'resourceArn'", "]", ")", "else", ":", "conditionalStatement", "=", "self", ".", "_getEmptyStatement", "(", "effect", ")", "conditionalStatement", "[", "'Resource'", "]", ".", "append", "(", "curMethod", "[", "'resourceArn'", "]", ")", "conditionalStatement", "[", "'Condition'", "]", "=", "curMethod", "[", "'conditions'", "]", "statements", ".", "append", "(", "conditionalStatement", ")", "if", "statement", "[", "'Resource'", "]", ":", "statements", ".", "append", "(", "statement", ")", "return", "statements" ]
This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.
[ "This", "function", "loops", "over", "an", "array", "of", "objects", "containing", "a", "resourceArn", "and", "conditions", "statement", "and", "generates", "the", "array", "of", "statements", "for", "the", "policy", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/api-gateway-authorizer-python/lambda_function.py#L151-L171
23,263
awslabs/serverless-application-model
examples/apps/kinesis-analytics-process-kpl-record/lambda_function.py
lambda_handler
def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
python
def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "raw_kpl_records", "=", "event", "[", "'records'", "]", "output", "=", "[", "process_kpl_record", "(", "kpl_record", ")", "for", "kpl_record", "in", "raw_kpl_records", "]", "# Print number of successful and failed records.", "success_count", "=", "sum", "(", "1", "for", "record", "in", "output", "if", "record", "[", "'result'", "]", "==", "'Ok'", ")", "failure_count", "=", "sum", "(", "1", "for", "record", "in", "output", "if", "record", "[", "'result'", "]", "==", "'ProcessingFailed'", ")", "print", "(", "'Processing completed. Successful records: {0}, Failed records: {1}.'", ".", "format", "(", "success_count", ",", "failure_count", ")", ")", "return", "{", "'records'", ":", "output", "}" ]
A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.
[ "A", "Python", "AWS", "Lambda", "function", "to", "process", "aggregated", "records", "sent", "to", "KinesisAnalytics", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/kinesis-analytics-process-kpl-record/lambda_function.py#L25-L35
23,264
awslabs/serverless-application-model
samtranslator/translator/transform.py
transform
def transform(input_fragment, parameter_values, managed_policy_loader): """Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict """ sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
python
def transform(input_fragment, parameter_values, managed_policy_loader): """Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict """ sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
[ "def", "transform", "(", "input_fragment", ",", "parameter_values", ",", "managed_policy_loader", ")", ":", "sam_parser", "=", "Parser", "(", ")", "translator", "=", "Translator", "(", "managed_policy_loader", ".", "load", "(", ")", ",", "sam_parser", ")", "return", "translator", ".", "translate", "(", "input_fragment", ",", "parameter_values", "=", "parameter_values", ")" ]
Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict
[ "Translates", "the", "SAM", "manifest", "provided", "in", "the", "and", "returns", "the", "translation", "to", "CloudFormation", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/transform.py#L5-L16
23,265
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin.on_before_transform_template
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
python
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "template", "=", "SamTemplate", "(", "template_dict", ")", "# Temporarily add Serverless::Api resource corresponding to Implicit API to the template.", "# This will allow the processing code to work the same way for both Implicit & Explicit APIs", "# If there are no implicit APIs, we will remove from the template later.", "# If the customer has explicitly defined a resource with the id of \"ServerlessRestApi\",", "# capture it. If the template ends up not defining any implicit api's, instead of just", "# removing the \"ServerlessRestApi\" resource, we just restore what the author defined.", "self", ".", "existing_implicit_api_resource", "=", "copy", ".", "deepcopy", "(", "template", ".", "get", "(", "self", ".", "implicit_api_logical_id", ")", ")", "template", ".", "set", "(", "self", ".", "implicit_api_logical_id", ",", "ImplicitApiResource", "(", ")", ".", "to_dict", "(", ")", ")", "errors", "=", "[", "]", "for", "logicalId", ",", "function", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Function", ".", "value", ")", ":", "api_events", "=", "self", ".", "_get_api_events", "(", "function", ")", "condition", "=", "function", ".", "condition", "if", "len", "(", "api_events", ")", "==", "0", ":", "continue", "try", ":", "self", ".", "_process_api_events", "(", "function", ",", "api_events", ",", "template", ",", "condition", ")", "except", "InvalidEventException", "as", "ex", ":", "errors", ".", "append", "(", "InvalidResourceException", "(", "logicalId", ",", "ex", ".", "message", ")", ")", "self", ".", "_maybe_add_condition_to_implicit_api", "(", "template_dict", ")", "self", ".", "_maybe_add_conditions_to_implicit_api_paths", "(", "template", ")", "self", ".", "_maybe_remove_implicit_api", "(", "template", ")", "if", "len", "(", "errors", ")", ">", "0", ":", "raise", "InvalidDocumentException", "(", "errors", ")" ]
Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "the", "SAM", "template", "is", "processed", ".", "The", "template", "has", "pass", "the", "validation", "and", "is", "guaranteed", "to", "contain", "a", "non", "-", "empty", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L48-L89
23,266
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._get_api_events
def _get_api_events(self, function): """ Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" } """ if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
python
def _get_api_events(self, function): """ Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" } """ if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
[ "def", "_get_api_events", "(", "self", ",", "function", ")", ":", "if", "not", "(", "function", ".", "valid", "(", ")", "and", "isinstance", "(", "function", ".", "properties", ",", "dict", ")", "and", "isinstance", "(", "function", ".", "properties", ".", "get", "(", "\"Events\"", ")", ",", "dict", ")", ")", ":", "# Function resource structure is invalid.", "return", "{", "}", "api_events", "=", "{", "}", "for", "event_id", ",", "event", "in", "function", ".", "properties", "[", "\"Events\"", "]", ".", "items", "(", ")", ":", "if", "event", "and", "isinstance", "(", "event", ",", "dict", ")", "and", "event", ".", "get", "(", "\"Type\"", ")", "==", "\"Api\"", ":", "api_events", "[", "event_id", "]", "=", "event", "return", "api_events" ]
Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" }
[ "Method", "to", "return", "a", "dictionary", "of", "API", "Events", "on", "the", "function" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L91-L118
23,267
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._get_api_id
def _get_api_id(self, event_properties): """ Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id. """ api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
python
def _get_api_id(self, event_properties): """ Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id. """ api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
[ "def", "_get_api_id", "(", "self", ",", "event_properties", ")", ":", "api_id", "=", "event_properties", ".", "get", "(", "\"RestApiId\"", ")", "if", "isinstance", "(", "api_id", ",", "dict", ")", "and", "\"Ref\"", "in", "api_id", ":", "api_id", "=", "api_id", "[", "\"Ref\"", "]", "return", "api_id" ]
Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id.
[ "Get", "API", "logical", "id", "from", "API", "event", "properties", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L223-L232
23,268
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._add_combined_condition_to_template
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): """ Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition. """ # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
python
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): """ Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition. """ # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
[ "def", "_add_combined_condition_to_template", "(", "self", ",", "template_dict", ",", "condition_name", ",", "conditions_to_combine", ")", ":", "# defensive precondition check", "if", "not", "conditions_to_combine", "or", "len", "(", "conditions_to_combine", ")", "<", "2", ":", "raise", "ValueError", "(", "'conditions_to_combine must have at least 2 conditions'", ")", "template_conditions", "=", "template_dict", ".", "setdefault", "(", "'Conditions'", ",", "{", "}", ")", "new_template_conditions", "=", "make_combined_condition", "(", "sorted", "(", "list", "(", "conditions_to_combine", ")", ")", ",", "condition_name", ")", "for", "name", ",", "definition", "in", "new_template_conditions", ".", "items", "(", ")", ":", "template_conditions", "[", "name", "]", "=", "definition" ]
Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition.
[ "Add", "top", "-", "level", "template", "condition", "that", "combines", "the", "given", "list", "of", "conditions", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L264-L280
23,269
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._maybe_add_conditions_to_implicit_api_paths
def _maybe_add_conditions_to_implicit_api_paths(self, template): """ Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path. """ for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
python
def _maybe_add_conditions_to_implicit_api_paths(self, template): """ Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path. """ for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
[ "def", "_maybe_add_conditions_to_implicit_api_paths", "(", "self", ",", "template", ")", ":", "for", "api_id", ",", "api", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Api", ".", "value", ")", ":", "if", "not", "api", ".", "properties", ".", "get", "(", "'__MANAGE_SWAGGER'", ")", ":", "continue", "swagger", "=", "api", ".", "properties", ".", "get", "(", "\"DefinitionBody\"", ")", "editor", "=", "SwaggerEditor", "(", "swagger", ")", "for", "path", "in", "editor", ".", "iter_on_path", "(", ")", ":", "all_method_conditions", "=", "set", "(", "[", "condition", "for", "method", ",", "condition", "in", "self", ".", "api_conditions", "[", "api_id", "]", "[", "path", "]", ".", "items", "(", ")", "]", ")", "at_least_one_method", "=", "len", "(", "all_method_conditions", ")", ">", "0", "all_methods_contain_conditions", "=", "None", "not", "in", "all_method_conditions", "if", "at_least_one_method", "and", "all_methods_contain_conditions", ":", "if", "len", "(", "all_method_conditions", ")", "==", "1", ":", "editor", ".", "make_path_conditional", "(", "path", ",", "all_method_conditions", ".", "pop", "(", ")", ")", "else", ":", "path_condition_name", "=", "self", ".", "_path_condition_name", "(", "api_id", ",", "path", ")", "self", ".", "_add_combined_condition_to_template", "(", "template", ".", "template_dict", ",", "path_condition_name", ",", "all_method_conditions", ")", "editor", ".", "make_path_conditional", "(", "path", ",", "path_condition_name", ")", "api", ".", "properties", "[", "\"DefinitionBody\"", "]", "=", "editor", ".", "swagger", "template", ".", "set", "(", "api_id", ",", "api", ")" ]
Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path.
[ "Add", "conditions", "to", "implicit", "API", "paths", "if", "necessary", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L282-L317
23,270
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._path_condition_name
def _path_condition_name(self, api_id, path): """ Generate valid condition logical id from the given API logical id and swagger resource path. """ # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
python
def _path_condition_name(self, api_id, path): """ Generate valid condition logical id from the given API logical id and swagger resource path. """ # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
[ "def", "_path_condition_name", "(", "self", ",", "api_id", ",", "path", ")", ":", "# only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain", "# slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace", "# non-alphanumeric characters.", "path_logical_id", "=", "path", ".", "replace", "(", "'/'", ",", "'SLASH'", ")", ".", "replace", "(", "'{'", ",", "'OB'", ")", ".", "replace", "(", "'}'", ",", "'CB'", ")", "return", "'{}{}PathCondition'", ".", "format", "(", "api_id", ",", "path_logical_id", ")" ]
Generate valid condition logical id from the given API logical id and swagger resource path.
[ "Generate", "valid", "condition", "logical", "id", "from", "the", "given", "API", "logical", "id", "and", "swagger", "resource", "path", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L319-L327
23,271
awslabs/serverless-application-model
samtranslator/model/apigateway.py
ApiGatewayDeployment.make_auto_deployable
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
python
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
[ "def", "make_auto_deployable", "(", "self", ",", "stage", ",", "swagger", "=", "None", ")", ":", "if", "not", "swagger", ":", "return", "# CloudFormation does NOT redeploy the API unless it has a new deployment resource", "# that points to latest RestApi resource. Append a hash of Swagger Body location to", "# redeploy only when the API data changes. First 10 characters of hash is good enough", "# to prevent redeployment when API has not changed", "# NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat", "generator", "=", "logical_id_generator", ".", "LogicalIdGenerator", "(", "self", ".", "logical_id", ",", "str", "(", "swagger", ")", ")", "self", ".", "logical_id", "=", "generator", ".", "gen", "(", ")", "hash", "=", "generator", ".", "get_hash", "(", "length", "=", "40", ")", "# Get the full hash", "self", ".", "Description", "=", "\"RestApi deployment id: {}\"", ".", "format", "(", "hash", ")", "stage", ".", "update_deployment_ref", "(", "self", ".", "logical_id", ")" ]
Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API
[ "Sets", "up", "the", "resource", "such", "that", "it", "will", "triggers", "a", "re", "-", "deployment", "when", "Swagger", "changes" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/apigateway.py#L76-L95
23,272
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py
StreamingBody.read
def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
python
def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
[ "def", "read", "(", "self", ",", "amt", "=", "None", ")", ":", "chunk", "=", "self", ".", "_raw_stream", ".", "read", "(", "amt", ")", "self", ".", "_amount_read", "+=", "len", "(", "chunk", ")", "return", "chunk" ]
Read at most amt bytes from the stream. If the amt argument is omitted, read all data.
[ "Read", "at", "most", "amt", "bytes", "from", "the", "stream", ".", "If", "the", "amt", "argument", "is", "omitted", "read", "all", "data", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py#L126-L132
23,273
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._can_process_application
def _can_process_application(self, app): """ Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties """ return (self.LOCATION_KEY in app.properties and isinstance(app.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
python
def _can_process_application(self, app): """ Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties """ return (self.LOCATION_KEY in app.properties and isinstance(app.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
[ "def", "_can_process_application", "(", "self", ",", "app", ")", ":", "return", "(", "self", ".", "LOCATION_KEY", "in", "app", ".", "properties", "and", "isinstance", "(", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "dict", ")", "and", "self", ".", "APPLICATION_ID_KEY", "in", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", "and", "self", ".", "SEMANTIC_VERSION_KEY", "in", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ")" ]
Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties
[ "Determines", "whether", "or", "not", "the", "on_before_transform_template", "event", "can", "process", "this", "application" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L126-L135
23,274
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_get_application_request
def _handle_get_application_request(self, app_id, semver, key, logical_id): """ Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver))) try: self._sar_service_call(get_application, logical_id, app_id, semver) self._applications[key] = {'Available'} except EndpointConnectionError as e: # No internet connection. Don't break verification, but do show a warning. warning_message = "{}. Unable to verify access to {}/{}.".format(e, app_id, semver) logging.warning(warning_message) self._applications[key] = {'Unable to verify'}
python
def _handle_get_application_request(self, app_id, semver, key, logical_id): """ Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver))) try: self._sar_service_call(get_application, logical_id, app_id, semver) self._applications[key] = {'Available'} except EndpointConnectionError as e: # No internet connection. Don't break verification, but do show a warning. warning_message = "{}. Unable to verify access to {}/{}.".format(e, app_id, semver) logging.warning(warning_message) self._applications[key] = {'Unable to verify'}
[ "def", "_handle_get_application_request", "(", "self", ",", "app_id", ",", "semver", ",", "key", ",", "logical_id", ")", ":", "get_application", "=", "(", "lambda", "app_id", ",", "semver", ":", "self", ".", "_sar_client", ".", "get_application", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "app_id", ")", ",", "SemanticVersion", "=", "self", ".", "_sanitize_sar_str_param", "(", "semver", ")", ")", ")", "try", ":", "self", ".", "_sar_service_call", "(", "get_application", ",", "logical_id", ",", "app_id", ",", "semver", ")", "self", ".", "_applications", "[", "key", "]", "=", "{", "'Available'", "}", "except", "EndpointConnectionError", "as", "e", ":", "# No internet connection. Don't break verification, but do show a warning.", "warning_message", "=", "\"{}. Unable to verify access to {}/{}.\"", ".", "format", "(", "e", ",", "app_id", ",", "semver", ")", "logging", ".", "warning", "(", "warning_message", ")", "self", ".", "_applications", "[", "key", "]", "=", "{", "'Unable to verify'", "}" ]
Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource
[ "Method", "that", "handles", "the", "get_application", "API", "call", "to", "the", "serverless", "application", "repo" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L137-L159
23,275
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_create_cfn_template_request
def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): """ Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
python
def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): """ Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
[ "def", "_handle_create_cfn_template_request", "(", "self", ",", "app_id", ",", "semver", ",", "key", ",", "logical_id", ")", ":", "create_cfn_template", "=", "(", "lambda", "app_id", ",", "semver", ":", "self", ".", "_sar_client", ".", "create_cloud_formation_template", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "app_id", ")", ",", "SemanticVersion", "=", "self", ".", "_sanitize_sar_str_param", "(", "semver", ")", ")", ")", "response", "=", "self", ".", "_sar_service_call", "(", "create_cfn_template", ",", "logical_id", ",", "app_id", ",", "semver", ")", "self", ".", "_applications", "[", "key", "]", "=", "response", "[", "self", ".", "TEMPLATE_URL_KEY", "]", "if", "response", "[", "'Status'", "]", "!=", "\"ACTIVE\"", ":", "self", ".", "_in_progress_templates", ".", "append", "(", "(", "response", "[", "self", ".", "APPLICATION_ID_KEY", "]", ",", "response", "[", "'TemplateId'", "]", ")", ")" ]
Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource
[ "Method", "that", "handles", "the", "create_cloud_formation_template", "API", "call", "to", "the", "serverless", "application", "repo" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L161-L177
23,276
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._check_for_dictionary_key
def _check_for_dictionary_key(self, logical_id, dictionary, keys): """ Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary """ for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
python
def _check_for_dictionary_key(self, logical_id, dictionary, keys): """ Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary """ for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
[ "def", "_check_for_dictionary_key", "(", "self", ",", "logical_id", ",", "dictionary", ",", "keys", ")", ":", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "dictionary", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "'Resource is missing the required [{}] '", "'property.'", ".", "format", "(", "key", ")", ")" ]
Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary
[ "Checks", "a", "dictionary", "to", "make", "sure", "it", "has", "a", "specific", "key", ".", "If", "it", "does", "not", "an", "InvalidResourceException", "is", "thrown", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L249-L261
23,277
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin.on_after_transform_template
def on_after_transform_template(self, template): """ Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing """ if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
python
def on_after_transform_template(self, template): """ Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing """ if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
[ "def", "on_after_transform_template", "(", "self", ",", "template", ")", ":", "if", "self", ".", "_wait_for_template_active_status", "and", "not", "self", ".", "_validate_only", ":", "start_time", "=", "time", "(", ")", "while", "(", "time", "(", ")", "-", "start_time", ")", "<", "self", ".", "TEMPLATE_WAIT_TIMEOUT_SECONDS", ":", "temp", "=", "self", ".", "_in_progress_templates", "self", ".", "_in_progress_templates", "=", "[", "]", "# Check each resource to make sure it's active", "for", "application_id", ",", "template_id", "in", "temp", ":", "get_cfn_template", "=", "(", "lambda", "application_id", ",", "template_id", ":", "self", ".", "_sar_client", ".", "get_cloud_formation_template", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "application_id", ")", ",", "TemplateId", "=", "self", ".", "_sanitize_sar_str_param", "(", "template_id", ")", ")", ")", "response", "=", "self", ".", "_sar_service_call", "(", "get_cfn_template", ",", "application_id", ",", "application_id", ",", "template_id", ")", "self", ".", "_handle_get_cfn_template_response", "(", "response", ",", "application_id", ",", "template_id", ")", "# Don't sleep if there are no more templates with PREPARING status", "if", "len", "(", "self", ".", "_in_progress_templates", ")", "==", "0", ":", "break", "# Sleep a little so we don't spam service calls", "sleep", "(", "self", ".", "SLEEP_TIME_SECONDS", ")", "# Not all templates reached active status", "if", "len", "(", "self", ".", "_in_progress_templates", ")", "!=", "0", ":", "application_ids", "=", "[", "items", "[", "0", "]", "for", "items", "in", "self", ".", "_in_progress_templates", "]", "raise", "InvalidResourceException", "(", "application_ids", ",", "\"Timed out waiting for nested stack templates \"", "\"to reach ACTIVE status.\"", ")" ]
Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "after", "the", "template", "is", "processed" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L263-L298
23,278
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_get_cfn_template_response
def _handle_get_cfn_template_response(self, response, application_id, template_id): """ Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application """ status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
python
def _handle_get_cfn_template_response(self, response, application_id, template_id): """ Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application """ status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
[ "def", "_handle_get_cfn_template_response", "(", "self", ",", "response", ",", "application_id", ",", "template_id", ")", ":", "status", "=", "response", "[", "'Status'", "]", "if", "status", "!=", "\"ACTIVE\"", ":", "# Other options are PREPARING and EXPIRED.", "if", "status", "==", "'EXPIRED'", ":", "message", "=", "(", "\"Template for {} with id {} returned status: {}. Cannot access an expired \"", "\"template.\"", ".", "format", "(", "application_id", ",", "template_id", ",", "status", ")", ")", "raise", "InvalidResourceException", "(", "application_id", ",", "message", ")", "self", ".", "_in_progress_templates", ".", "append", "(", "(", "application_id", ",", "template_id", ")", ")" ]
Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application
[ "Handles", "the", "response", "from", "the", "SAR", "service", "call" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L300-L315
23,279
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._sar_service_call
def _sar_service_call(self, service_call_lambda, logical_id, *args): """ Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda """ try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
python
def _sar_service_call(self, service_call_lambda, logical_id, *args): """ Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda """ try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
[ "def", "_sar_service_call", "(", "self", ",", "service_call_lambda", ",", "logical_id", ",", "*", "args", ")", ":", "try", ":", "response", "=", "service_call_lambda", "(", "*", "args", ")", "logging", ".", "info", "(", "response", ")", "return", "response", "except", "ClientError", "as", "e", ":", "error_code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "if", "error_code", "in", "(", "'AccessDeniedException'", ",", "'NotFoundException'", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", ")", "# 'ForbiddenException'- SAR rejects connection", "logging", ".", "exception", "(", "e", ")", "raise", "e" ]
Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda
[ "Handles", "service", "calls", "and", "exception", "management", "for", "service", "calls", "to", "the", "Serverless", "Application", "Repository", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L317-L337
23,280
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.iterate
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield logicalId, resource
python
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield logicalId, resource
[ "def", "iterate", "(", "self", ",", "resource_type", "=", "None", ")", ":", "for", "logicalId", ",", "resource_dict", "in", "self", ".", "resources", ".", "items", "(", ")", ":", "resource", "=", "SamResource", "(", "resource_dict", ")", "needs_filter", "=", "resource", ".", "valid", "(", ")", "if", "resource_type", ":", "needs_filter", "=", "needs_filter", "and", "resource", ".", "type", "==", "resource_type", "if", "needs_filter", ":", "yield", "logicalId", ",", "resource" ]
Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource
[ "Iterate", "over", "all", "resources", "within", "the", "SAM", "template", "optionally", "filtering", "by", "type" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L22-L38
23,281
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.set
def set(self, logicalId, resource): """ Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data """ resource_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
python
def set(self, logicalId, resource): """ Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data """ resource_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
[ "def", "set", "(", "self", ",", "logicalId", ",", "resource", ")", ":", "resource_dict", "=", "resource", "if", "isinstance", "(", "resource", ",", "SamResource", ")", ":", "resource_dict", "=", "resource", ".", "to_dict", "(", ")", "self", ".", "resources", "[", "logicalId", "]", "=", "resource_dict" ]
Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data
[ "Adds", "the", "resource", "to", "dictionary", "with", "given", "logical", "Id", ".", "It", "will", "overwrite", "if", "the", "logicalId", "is", "already", "used", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L40-L52
23,282
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.get
def get(self, logicalId): """ Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise """ if logicalId not in self.resources: return None return SamResource(self.resources.get(logicalId))
python
def get(self, logicalId): """ Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise """ if logicalId not in self.resources: return None return SamResource(self.resources.get(logicalId))
[ "def", "get", "(", "self", ",", "logicalId", ")", ":", "if", "logicalId", "not", "in", "self", ".", "resources", ":", "return", "None", "return", "SamResource", "(", "self", ".", "resources", ".", "get", "(", "logicalId", ")", ")" ]
Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise
[ "Gets", "the", "resource", "at", "the", "given", "logicalId", "if", "present" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L54-L64
23,283
awslabs/serverless-application-model
samtranslator/translator/translator.py
prepare_plugins
def prepare_plugins(plugins, parameters={}): """ Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins` """ required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
python
def prepare_plugins(plugins, parameters={}): """ Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins` """ required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
[ "def", "prepare_plugins", "(", "plugins", ",", "parameters", "=", "{", "}", ")", ":", "required_plugins", "=", "[", "DefaultDefinitionBodyPlugin", "(", ")", ",", "make_implicit_api_plugin", "(", ")", ",", "GlobalsPlugin", "(", ")", ",", "make_policy_template_for_function_plugin", "(", ")", ",", "]", "plugins", "=", "[", "]", "if", "not", "plugins", "else", "plugins", "# If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list.", "if", "not", "any", "(", "isinstance", "(", "plugin", ",", "ServerlessAppPlugin", ")", "for", "plugin", "in", "plugins", ")", ":", "required_plugins", ".", "insert", "(", "0", ",", "ServerlessAppPlugin", "(", "parameters", "=", "parameters", ")", ")", "# Execute customer's plugins first before running SAM plugins. It is very important to retain this order because", "# other plugins will be dependent on this ordering.", "return", "SamPlugins", "(", "plugins", "+", "required_plugins", ")" ]
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins`
[ "Creates", "&", "returns", "a", "plugins", "object", "with", "the", "given", "list", "of", "plugins", "installed", ".", "In", "addition", "to", "the", "given", "plugins", "we", "will", "also", "install", "a", "few", "required", "plugins", "that", "are", "necessary", "to", "provide", "complete", "support", "for", "SAM", "template", "spec", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L163-L188
23,284
awslabs/serverless-application-model
samtranslator/translator/translator.py
Translator.translate
def translate(self, sam_template, parameter_values): """Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template """ sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
python
def translate(self, sam_template, parameter_values): """Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template """ sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
[ "def", "translate", "(", "self", ",", "sam_template", ",", "parameter_values", ")", ":", "sam_parameter_values", "=", "SamParameterValues", "(", "parameter_values", ")", "sam_parameter_values", ".", "add_default_parameter_values", "(", "sam_template", ")", "sam_parameter_values", ".", "add_pseudo_parameter_values", "(", ")", "parameter_values", "=", "sam_parameter_values", ".", "parameter_values", "# Create & Install plugins", "sam_plugins", "=", "prepare_plugins", "(", "self", ".", "plugins", ",", "parameter_values", ")", "self", ".", "sam_parser", ".", "parse", "(", "sam_template", "=", "sam_template", ",", "parameter_values", "=", "parameter_values", ",", "sam_plugins", "=", "sam_plugins", ")", "template", "=", "copy", ".", "deepcopy", "(", "sam_template", ")", "macro_resolver", "=", "ResourceTypeResolver", "(", "sam_resources", ")", "intrinsics_resolver", "=", "IntrinsicsResolver", "(", "parameter_values", ")", "deployment_preference_collection", "=", "DeploymentPreferenceCollection", "(", ")", "supported_resource_refs", "=", "SupportedResourceReferences", "(", ")", "document_errors", "=", "[", "]", "changed_logical_ids", "=", "{", "}", "for", "logical_id", ",", "resource_dict", "in", "self", ".", "_get_resources_to_iterate", "(", "sam_template", ",", "macro_resolver", ")", ":", "try", ":", "macro", "=", "macro_resolver", ".", "resolve_resource_type", "(", "resource_dict", ")", ".", "from_dict", "(", "logical_id", ",", "resource_dict", ",", "sam_plugins", "=", "sam_plugins", ")", "kwargs", "=", "macro", ".", "resources_to_link", "(", "sam_template", "[", "'Resources'", "]", ")", "kwargs", "[", "'managed_policy_map'", "]", "=", "self", ".", "managed_policy_map", "kwargs", "[", "'intrinsics_resolver'", "]", "=", "intrinsics_resolver", "kwargs", "[", "'deployment_preference_collection'", "]", "=", "deployment_preference_collection", "translated", "=", "macro", ".", "to_cloudformation", "(", "*", "*", "kwargs", ")", "supported_resource_refs", "=", "macro", ".", "get_resource_references", "(", "translated", ",", "supported_resource_refs", ")", "# Some resources mutate their logical ids. Track those to change all references to them:", "if", "logical_id", "!=", "macro", ".", "logical_id", ":", "changed_logical_ids", "[", "logical_id", "]", "=", "macro", ".", "logical_id", "del", "template", "[", "'Resources'", "]", "[", "logical_id", "]", "for", "resource", "in", "translated", ":", "if", "verify_unique_logical_id", "(", "resource", ",", "sam_template", "[", "'Resources'", "]", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "resource", ".", "to_dict", "(", ")", ")", "else", ":", "document_errors", ".", "append", "(", "DuplicateLogicalIdException", "(", "logical_id", ",", "resource", ".", "logical_id", ",", "resource", ".", "resource_type", ")", ")", "except", "(", "InvalidResourceException", ",", "InvalidEventException", ")", "as", "e", ":", "document_errors", ".", "append", "(", "e", ")", "if", "deployment_preference_collection", ".", "any_enabled", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "codedeploy_application", ".", "to_dict", "(", ")", ")", "if", "not", "deployment_preference_collection", ".", "can_skip_service_role", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "codedeploy_iam_role", ".", "to_dict", "(", ")", ")", "for", "logical_id", "in", "deployment_preference_collection", ".", "enabled_logical_ids", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "deployment_group", "(", "logical_id", ")", ".", "to_dict", "(", ")", ")", "# Run the after-transform plugin target", "try", ":", "sam_plugins", ".", "act", "(", "LifeCycleEvents", ".", "after_transform_template", ",", "template", ")", "except", "(", "InvalidDocumentException", ",", "InvalidResourceException", ")", "as", "e", ":", "document_errors", ".", "append", "(", "e", ")", "# Cleanup", "if", "'Transform'", "in", "template", ":", "del", "template", "[", "'Transform'", "]", "if", "len", "(", "document_errors", ")", "==", "0", ":", "template", "=", "intrinsics_resolver", ".", "resolve_sam_resource_id_refs", "(", "template", ",", "changed_logical_ids", ")", "template", "=", "intrinsics_resolver", ".", "resolve_sam_resource_refs", "(", "template", ",", "supported_resource_refs", ")", "return", "template", "else", ":", "raise", "InvalidDocumentException", "(", "document_errors", ")" ]
Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template
[ "Loads", "the", "SAM", "resources", "from", "the", "given", "SAM", "manifest", "replaces", "them", "with", "their", "corresponding", "CloudFormation", "resources", "and", "returns", "the", "resulting", "CloudFormation", "template", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L34-L122
23,285
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._validate_logical_id
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
python
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
[ "def", "_validate_logical_id", "(", "cls", ",", "logical_id", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'^[A-Za-z0-9]+$'", ")", "if", "logical_id", "is", "not", "None", "and", "pattern", ".", "match", "(", "logical_id", ")", ":", "return", "True", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Logical ids must be alphanumeric.\"", ")" ]
Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid
[ "Validates", "that", "the", "provided", "logical", "id", "is", "an", "alphanumeric", "string", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L129-L140
23,286
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._validate_resource_dict
def _validate_resource_dict(cls, logical_id, resource_dict): """Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format """ if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
python
def _validate_resource_dict(cls, logical_id, resource_dict): """Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format """ if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
[ "def", "_validate_resource_dict", "(", "cls", ",", "logical_id", ",", "resource_dict", ")", ":", "if", "'Type'", "not", "in", "resource_dict", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Resource dict missing key 'Type'.\"", ")", "if", "resource_dict", "[", "'Type'", "]", "!=", "cls", ".", "resource_type", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Resource has incorrect Type; expected '{expected}', \"", "\"got '{actual}'\"", ".", "format", "(", "expected", "=", "cls", ".", "resource_type", ",", "actual", "=", "resource_dict", "[", "'Type'", "]", ")", ")", "if", "'Properties'", "in", "resource_dict", "and", "not", "isinstance", "(", "resource_dict", "[", "'Properties'", "]", ",", "dict", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Properties of a resource must be an object.\"", ")" ]
Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format
[ "Validates", "that", "the", "provided", "resource", "dict", "contains", "the", "correct", "Type", "string", "and", "the", "required", "Properties", "dict", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L143-L160
23,287
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._generate_resource_dict
def _generate_resource_dict(self): """Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict """ resource_dict = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
python
def _generate_resource_dict(self): """Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict """ resource_dict = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
[ "def", "_generate_resource_dict", "(", "self", ")", ":", "resource_dict", "=", "{", "}", "resource_dict", "[", "'Type'", "]", "=", "self", ".", "resource_type", "if", "self", ".", "depends_on", ":", "resource_dict", "[", "'DependsOn'", "]", "=", "self", ".", "depends_on", "resource_dict", ".", "update", "(", "self", ".", "resource_attributes", ")", "properties_dict", "=", "{", "}", "for", "name", "in", "self", ".", "property_types", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "if", "value", "is", "not", "None", ":", "properties_dict", "[", "name", "]", "=", "value", "resource_dict", "[", "'Properties'", "]", "=", "properties_dict", "return", "resource_dict" ]
Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict
[ "Generates", "the", "resource", "dict", "for", "this", "Resource", "the", "value", "associated", "with", "the", "logical", "id", "in", "a", "CloudFormation", "template", "s", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L189-L213
23,288
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.validate_properties
def validate_properties(self): """Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid """ for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
python
def validate_properties(self): """Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid """ for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
[ "def", "validate_properties", "(", "self", ")", ":", "for", "name", ",", "property_type", "in", "self", ".", "property_types", ".", "items", "(", ")", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "# If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation", "if", "property_type", ".", "supports_intrinsics", "and", "self", ".", "_is_intrinsic_function", "(", "value", ")", ":", "continue", "# If the property value has not been set, verify that the property is not required.", "if", "value", "is", "None", ":", "if", "property_type", ".", "required", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Missing required property '{property_name}'.\"", ".", "format", "(", "property_name", "=", "name", ")", ")", "# Otherwise, validate the value of the property.", "elif", "not", "property_type", ".", "validate", "(", "value", ",", "should_raise", "=", "False", ")", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Type of property '{property_name}' is invalid.\"", ".", "format", "(", "property_name", "=", "name", ")", ")" ]
Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid
[ "Validates", "that", "the", "required", "properties", "for", "this", "Resource", "have", "been", "populated", "and", "that", "all", "properties", "have", "valid", "values", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L230-L255
23,289
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.set_resource_attribute
def set_resource_attribute(self, attr, value): """Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list """ if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
python
def set_resource_attribute(self, attr, value): """Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list """ if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
[ "def", "set_resource_attribute", "(", "self", ",", "attr", ",", "value", ")", ":", "if", "attr", "not", "in", "self", ".", "_supported_resource_attributes", ":", "raise", "KeyError", "(", "\"Unsupported resource attribute specified: %s\"", "%", "attr", ")", "self", ".", "resource_attributes", "[", "attr", "]", "=", "value" ]
Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list
[ "Sets", "attributes", "on", "resource", ".", "Resource", "attributes", "are", "top", "-", "level", "entries", "of", "a", "CloudFormation", "resource", "that", "exist", "outside", "of", "the", "Properties", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L257-L270
23,290
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.get_resource_attribute
def get_resource_attribute(self, attr): """Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise """ if attr not in self.resource_attributes: raise KeyError("%s is not in resource attributes" % attr) return self.resource_attributes[attr]
python
def get_resource_attribute(self, attr): """Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise """ if attr not in self.resource_attributes: raise KeyError("%s is not in resource attributes" % attr) return self.resource_attributes[attr]
[ "def", "get_resource_attribute", "(", "self", ",", "attr", ")", ":", "if", "attr", "not", "in", "self", ".", "resource_attributes", ":", "raise", "KeyError", "(", "\"%s is not in resource attributes\"", "%", "attr", ")", "return", "self", ".", "resource_attributes", "[", "attr", "]" ]
Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise
[ "Gets", "the", "resource", "attribute", "if", "available" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L272-L281
23,291
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.get_runtime_attr
def get_runtime_attr(self, attr_name): """ Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed """ if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
python
def get_runtime_attr(self, attr_name): """ Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed """ if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
[ "def", "get_runtime_attr", "(", "self", ",", "attr_name", ")", ":", "if", "attr_name", "in", "self", ".", "runtime_attrs", ":", "return", "self", ".", "runtime_attrs", "[", "attr_name", "]", "(", "self", ")", "else", ":", "raise", "NotImplementedError", "(", "attr_name", "+", "\" attribute is not implemented for resource \"", "+", "self", ".", "resource_type", ")" ]
Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed
[ "Returns", "a", "CloudFormation", "construct", "that", "provides", "value", "for", "this", "attribute", ".", "If", "the", "resource", "does", "not", "provide", "this", "attribute", "then", "this", "method", "raises", "an", "exception" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L295-L306
23,292
awslabs/serverless-application-model
samtranslator/model/__init__.py
ResourceTypeResolver.resolve_resource_type
def resolve_resource_type(self, resource_dict): """Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class """ if not self.can_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
python
def resolve_resource_type(self, resource_dict): """Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class """ if not self.can_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
[ "def", "resolve_resource_type", "(", "self", ",", "resource_dict", ")", ":", "if", "not", "self", ".", "can_resolve", "(", "resource_dict", ")", ":", "raise", "TypeError", "(", "\"Resource dict has missing or invalid value for key Type. Event Type is: {}.\"", ".", "format", "(", "resource_dict", ".", "get", "(", "'Type'", ")", ")", ")", "if", "resource_dict", "[", "'Type'", "]", "not", "in", "self", ".", "resource_types", ":", "raise", "TypeError", "(", "\"Invalid resource type {resource_type}\"", ".", "format", "(", "resource_type", "=", "resource_dict", "[", "'Type'", "]", ")", ")", "return", "self", ".", "resource_types", "[", "resource_dict", "[", "'Type'", "]", "]" ]
Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class
[ "Returns", "the", "Resource", "class", "corresponding", "to", "the", "Type", "key", "in", "the", "given", "resource", "dict", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L469-L481
23,293
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_response_card
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
python
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
[ "def", "build_response_card", "(", "title", ",", "subtitle", ",", "options", ")", ":", "buttons", "=", "None", "if", "options", "is", "not", "None", ":", "buttons", "=", "[", "]", "for", "i", "in", "range", "(", "min", "(", "5", ",", "len", "(", "options", ")", ")", ")", ":", "buttons", ".", "append", "(", "options", "[", "i", "]", ")", "return", "{", "'contentType'", ":", "'application/vnd.amazonaws.card.generic'", ",", "'version'", ":", "1", ",", "'genericAttachments'", ":", "[", "{", "'title'", ":", "title", ",", "'subTitle'", ":", "subtitle", ",", "'buttons'", ":", "buttons", "}", "]", "}" ]
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
[ "Build", "a", "responseCard", "with", "a", "title", "subtitle", "and", "an", "optional", "set", "of", "options", "which", "should", "be", "displayed", "as", "buttons", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L75-L93
23,294
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
get_availabilities
def get_availabilities(date): """ Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. """ day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return availabilities
python
def get_availabilities(date): """ Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. """ day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return availabilities
[ "def", "get_availabilities", "(", "date", ")", ":", "day_of_week", "=", "dateutil", ".", "parser", ".", "parse", "(", "date", ")", ".", "weekday", "(", ")", "availabilities", "=", "[", "]", "available_probability", "=", "0.3", "if", "day_of_week", "==", "0", ":", "start_hour", "=", "10", "while", "start_hour", "<=", "16", ":", "if", "random", ".", "random", "(", ")", "<", "available_probability", ":", "# Add an availability window for the given hour, with duration determined by another random number.", "appointment_type", "=", "get_random_int", "(", "1", ",", "4", ")", "if", "appointment_type", "==", "1", ":", "availabilities", ".", "append", "(", "'{}:00'", ".", "format", "(", "start_hour", ")", ")", "elif", "appointment_type", "==", "2", ":", "availabilities", ".", "append", "(", "'{}:30'", ".", "format", "(", "start_hour", ")", ")", "else", ":", "availabilities", ".", "append", "(", "'{}:00'", ".", "format", "(", "start_hour", ")", ")", "availabilities", ".", "append", "(", "'{}:30'", ".", "format", "(", "start_hour", ")", ")", "start_hour", "+=", "1", "if", "day_of_week", "==", "2", "or", "day_of_week", "==", "4", ":", "availabilities", ".", "append", "(", "'10:00'", ")", "availabilities", ".", "append", "(", "'16:00'", ")", "availabilities", ".", "append", "(", "'16:30'", ")", "return", "availabilities" ]
Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.
[ "Helper", "function", "which", "in", "a", "full", "implementation", "would", "feed", "into", "a", "backend", "API", "to", "provide", "query", "schedule", "availability", ".", "The", "output", "of", "this", "function", "is", "an", "array", "of", "30", "minute", "periods", "of", "availability", "expressed", "in", "ISO", "-", "8601", "time", "format", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L135-L169
23,295
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
get_availabilities_for_duration
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
python
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
[ "def", "get_availabilities_for_duration", "(", "duration", ",", "availabilities", ")", ":", "duration_availabilities", "=", "[", "]", "start_time", "=", "'10:00'", "while", "start_time", "!=", "'17:00'", ":", "if", "start_time", "in", "availabilities", ":", "if", "duration", "==", "30", ":", "duration_availabilities", ".", "append", "(", "start_time", ")", "elif", "increment_time_by_thirty_mins", "(", "start_time", ")", "in", "availabilities", ":", "duration_availabilities", ".", "append", "(", "start_time", ")", "start_time", "=", "increment_time_by_thirty_mins", "(", "start_time", ")", "return", "duration_availabilities" ]
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
[ "Helper", "function", "to", "return", "the", "windows", "of", "availability", "of", "the", "given", "duration", "when", "provided", "a", "set", "of", "30", "minute", "windows", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L192-L207
23,296
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_available_time_string
def build_available_time_string(availabilities): """ Build a string eliciting for a possible time slot among at least two availabilities. """ prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
python
def build_available_time_string(availabilities): """ Build a string eliciting for a possible time slot among at least two availabilities. """ prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
[ "def", "build_available_time_string", "(", "availabilities", ")", ":", "prefix", "=", "'We have availabilities at '", "if", "len", "(", "availabilities", ")", ">", "3", ":", "prefix", "=", "'We have plenty of availability, including '", "prefix", "+=", "build_time_output_string", "(", "availabilities", "[", "0", "]", ")", "if", "len", "(", "availabilities", ")", "==", "2", ":", "return", "'{} and {}'", ".", "format", "(", "prefix", ",", "build_time_output_string", "(", "availabilities", "[", "1", "]", ")", ")", "return", "'{}, {} and {}'", ".", "format", "(", "prefix", ",", "build_time_output_string", "(", "availabilities", "[", "1", "]", ")", ",", "build_time_output_string", "(", "availabilities", "[", "2", "]", ")", ")" ]
Build a string eliciting for a possible time slot among at least two availabilities.
[ "Build", "a", "string", "eliciting", "for", "a", "possible", "time", "slot", "among", "at", "least", "two", "availabilities", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L261-L273
23,297
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_options
def build_options(slot, appointment_type, date, booking_map): """ Build a list of potential options for a given slot, to be used in responseCard generation. """ day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
python
def build_options(slot, appointment_type, date, booking_map): """ Build a list of potential options for a given slot, to be used in responseCard generation. """ day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
[ "def", "build_options", "(", "slot", ",", "appointment_type", ",", "date", ",", "booking_map", ")", ":", "day_strings", "=", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", "]", "if", "slot", "==", "'AppointmentType'", ":", "return", "[", "{", "'text'", ":", "'cleaning (30 min)'", ",", "'value'", ":", "'cleaning'", "}", ",", "{", "'text'", ":", "'root canal (60 min)'", ",", "'value'", ":", "'root canal'", "}", ",", "{", "'text'", ":", "'whitening (30 min)'", ",", "'value'", ":", "'whitening'", "}", "]", "elif", "slot", "==", "'Date'", ":", "# Return the next five weekdays.", "options", "=", "[", "]", "potential_date", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "while", "len", "(", "options", ")", "<", "5", ":", "potential_date", "=", "potential_date", "+", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "if", "potential_date", ".", "weekday", "(", ")", "<", "5", ":", "options", ".", "append", "(", "{", "'text'", ":", "'{}-{} ({})'", ".", "format", "(", "(", "potential_date", ".", "month", ")", ",", "potential_date", ".", "day", ",", "day_strings", "[", "potential_date", ".", "weekday", "(", ")", "]", ")", ",", "'value'", ":", "potential_date", ".", "strftime", "(", "'%A, %B %d, %Y'", ")", "}", ")", "return", "options", "elif", "slot", "==", "'Time'", ":", "# Return the availabilities on the given date.", "if", "not", "appointment_type", "or", "not", "date", ":", "return", "None", "availabilities", "=", "try_ex", "(", "lambda", ":", "booking_map", "[", "date", "]", ")", "if", "not", "availabilities", ":", "return", "None", "availabilities", "=", "get_availabilities_for_duration", "(", "get_duration", "(", "appointment_type", ")", ",", "availabilities", ")", "if", "len", "(", "availabilities", ")", "==", "0", ":", "return", "None", "options", "=", "[", "]", "for", "i", "in", "range", "(", "min", "(", "len", "(", "availabilities", ")", ",", "5", ")", ")", ":", "options", ".", "append", "(", "{", "'text'", ":", "build_time_output_string", "(", "availabilities", "[", "i", "]", ")", ",", "'value'", ":", "build_time_output_string", "(", "availabilities", "[", "i", "]", ")", "}", ")", "return", "options" ]
Build a list of potential options for a given slot, to be used in responseCard generation.
[ "Build", "a", "list", "of", "potential", "options", "for", "a", "given", "slot", "to", "be", "used", "in", "responseCard", "generation", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L276-L314
23,298
awslabs/serverless-application-model
samtranslator/model/intrinsics.py
is_instrinsic
def is_instrinsic(input): """ Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes """ if input is not None \ and isinstance(input, dict) \ and len(input) == 1: key = list(input.keys())[0] return key == "Ref" or key == "Condition" or key.startswith("Fn::") return False
python
def is_instrinsic(input): """ Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes """ if input is not None \ and isinstance(input, dict) \ and len(input) == 1: key = list(input.keys())[0] return key == "Ref" or key == "Condition" or key.startswith("Fn::") return False
[ "def", "is_instrinsic", "(", "input", ")", ":", "if", "input", "is", "not", "None", "and", "isinstance", "(", "input", ",", "dict", ")", "and", "len", "(", "input", ")", "==", "1", ":", "key", "=", "list", "(", "input", ".", "keys", "(", ")", ")", "[", "0", "]", "return", "key", "==", "\"Ref\"", "or", "key", "==", "\"Condition\"", "or", "key", ".", "startswith", "(", "\"Fn::\"", ")", "return", "False" ]
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single key that is the name of the intrinsics. :param input: Input value to check if it is an intrinsic :return: True, if yes
[ "Checks", "if", "the", "given", "input", "is", "an", "intrinsic", "function", "dictionary", ".", "Intrinsic", "function", "is", "a", "dictionary", "with", "single", "key", "that", "is", "the", "name", "of", "the", "intrinsics", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/intrinsics.py#L124-L140
23,299
awslabs/serverless-application-model
samtranslator/intrinsics/actions.py
Action.can_handle
def can_handle(self, input_dict): """ Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise """ return input_dict is not None \ and isinstance(input_dict, dict) \ and len(input_dict) == 1 \ and self.intrinsic_name in input_dict
python
def can_handle(self, input_dict): """ Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise """ return input_dict is not None \ and isinstance(input_dict, dict) \ and len(input_dict) == 1 \ and self.intrinsic_name in input_dict
[ "def", "can_handle", "(", "self", ",", "input_dict", ")", ":", "return", "input_dict", "is", "not", "None", "and", "isinstance", "(", "input_dict", ",", "dict", ")", "and", "len", "(", "input_dict", ")", "==", "1", "and", "self", ".", "intrinsic_name", "in", "input_dict" ]
Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise
[ "Validates", "that", "the", "input", "dictionary", "contains", "only", "one", "key", "and", "is", "of", "the", "given", "intrinsic_name" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/actions.py#L41-L52