Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def set_path_default_authorizer(self, path, default_authorizer, authorizers):
for method_name, method in self.get_path(path).items():
self.set_method_authorizer(path, method_name, default_authorizer, authorizers,
... | [
"\n Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer\n was defined at the Function/Path/Method level\n\n :param string path: Path name\n :param string default_authorizer: Name of the authorizer to use as the default. Must be a k... |
Please provide a description of the function:def add_auth_to_method(self, path, method_name, auth, api):
method_authorizer = auth and auth.get('Authorizer')
if method_authorizer:
api_auth = api.get('Auth')
api_authorizers = api_auth and api_auth.get('Authorizers')
... | [
"\n Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers\n but this method will eventually include setting other auth settings such as API Key,\n Resource Policy, etc.\n\n :param string path: Path name\n :param string method_name: Method n... |
Please provide a description of the function: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() | [
"\n Add Gateway Response definitions to Swagger.\n\n :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.\n "
] |
Please provide a description of the function:def swagger(self):
# Make sure any changes to the paths are reflected back in output
self._doc["paths"] = self.paths
if self.security_definitions:
self._doc["securityDefinitions"] = self.security_definitions
if self.gate... | [
"\n Returns a **copy** of the Swagger document as a dictionary.\n\n :return dict: Dictionary containing the Swagger document\n "
] |
Please provide a description of the function:def is_valid(data):
return bool(data) and \
isinstance(data, dict) and \
bool(data.get("swagger")) and \
isinstance(data.get('paths'), dict) | [
"\n Checks if the input data is a Swagger document\n\n :param dict data: Data to be validated\n :return: True, if data is a Swagger\n "
] |
Please provide a description of the function: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 ... | [
"\n Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods\n like \"ANY\"\n\n NOTE: Always normalize before using the `method` value passed in as input\n\n :param string method: Name of the HTTP Method\n :return string: Nor... |
Please provide a description of the function:def on_before_transform_template(self, template_dict):
try:
global_section = Globals(template_dict)
except InvalidGlobalsSectionException as ex:
raise InvalidDocumentException([ex])
# For each resource in template, t... | [
"\n Hook method that runs before a template gets transformed. In this method, we parse and process Globals section\n from the template (if present).\n\n :param dict template_dict: SAM template as a dictionary\n "
] |
Please provide a description of the function: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(
... | [
"Returns a validator function that succeeds only for inputs of the provided valid_type.\n\n :param type valid_type: the type that should be considered valid for the validator\n :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise\n :rtype: callable\... |
Please provide a description of the function: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_i... | [
"Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input\n to the provided validator validate_item.\n\n :param callable validate_item: the validator function for items in the list\n :returns: a function which returns True its input is an list of val... |
Please provide a description of the function: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:... | [
"Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes\n as input to the provided validators validate_key and validate_item, respectively.\n\n :param callable validate_key: the validator function for keys in the dict\n :param callable validate_ite... |
Please provide a description of the function: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")
... | [
"Returns a validator function that succeeds only if the input passes at least one of the provided validators.\n\n :param callable validators: the validator functions\n :returns: a function which returns True its input passes at least one of the validators, and raises TypeError\n otherwise\n :r... |
Please provide a description of the function: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
... | [
"\n With the given values for each parameter, this method will return a policy statement that can be used\n directly with IAM.\n\n :param dict parameter_values: Dict containing values for each parameter defined in the template\n :return dict: Dictionary containing policy statement\n ... |
Please provide a description of the function: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.k... | [
"\n Checks if the given input contains values for all parameters used by this template\n\n :param dict parameter_values: Dictionary of values for each parameter used in the template\n :return list: List of names of parameters that are missing.\n :raises InvalidParameterValues: When param... |
Please provide a description of the function: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) | [
"\n Parses the input and returns an instance of this class.\n\n :param string template_name: Name of the template\n :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed\n the JSON Schema validation.\n :return Template: I... |
Please provide a description of the function: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 w... | [
"\n Register a plugin. New plugins are added to the end of the plugins list.\n\n :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks\n :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already... |
Please provide a description of the function:def _get(self, plugin_name):
for p in self._plugins:
if p.name == plugin_name:
return p
return None | [
"\n Retrieves the plugin with given name\n\n :param plugin_name: Name of the plugin to retrieve\n :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise\n "
] |
Please provide a description of the function:def act(self, event, *args, **kwargs):
if not isinstance(event, LifeCycleEvents):
raise ValueError("'event' must be an instance of LifeCycleEvents class")
method_name = "on_" + event.name
for plugin in self._plugins:
... | [
"\n Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins.\n *args and **kwargs will be passed directly to the plugin's hook functions\n\n :param samtranslator.plugins.LifeCycleEvents event: Event to act upon\n :return: Nothing\n ... |
Please provide a description of the function:def from_dict(cls, logical_id, deployment_preference_dict):
enabled = deployment_preference_dict.get('Enabled', True)
if not enabled:
return DeploymentPreference(None, None, None, None, False, None)
if 'Type' not in deployment_pr... | [
"\n :param logical_id: the logical_id of the resource that owns this deployment preference\n :param deployment_preference_dict: the dict object taken from the SAM template\n :return:\n "
] |
Please provide a description of the function: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(
CiphertextB... | [] |
Please provide a description of the function:def prepend(exception, message, end=': '):
exception.args = exception.args or ('',)
exception.args = (message + end + exception.args[0], ) + exception.args[1:]
return exception | [
"Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message.\n Useful for reraising exceptions with additional information.\n\n :param BaseException exception: the exception to prepend\n :param str message: the message to prepend\n :param str end: the sepa... |
Please provide a description of the function:def lambda_handler(event, context):
# incoming token value
token = event['authorizationToken']
print("Method ARN: " + event['methodArn'])
'''
Validate the incoming token and produce the principal user identifier
associated with the token. This can be... | [] |
Please provide a description of the function: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:... | [] |
Please provide a description of the function:def on_before_transform_resource(self, logical_id, resource_type, resource_properties):
if not self._is_supported(resource_type):
return
function_policies = FunctionPolicies(resource_properties, self._policy_template_processor)
... | [
"\n Hook method that gets called before \"each\" SAM resource gets processed\n\n :param string logical_id: Logical ID of the resource being processed\n :param string resource_type: Type of the resource being processed\n :param dict resource_properties: Properties of the resource\n ... |
Please provide a description of the function: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 su... | [] |
Please provide a description of the function: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.\n\n :param dict input_fragment: the SAM template to transform\n :param dict parameter_values: Parameter values provided by the user\n :returns: the transformed CloudFormation template\n :rtype: dict\n "
] |
Please provide a description of the function:def to_dict(self):
dict_with_nones = self._asdict()
codedeploy_lambda_alias_update_dict = dict((k, v) for k, v in dict_with_nones.items()
if v != ref(None) and v is not None)
return {'CodeDep... | [
"\n :return: a dict that can be used as part of a cloudformation template\n "
] |
Please provide a description of the function: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 wa... | [
"\n Hook method that gets called before the SAM template is processed.\n The template has pass the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n :param dict template_dict: Dictionary of the SAM template\n :return: Nothing\n "
] |
Please provide a description of the function: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 i... | [
"\n Method to return a dictionary of API Events on the function\n\n :param SamResource function: Function Resource object\n :return dict: Dictionary of API events along with any other configuration passed to it.\n Example: {\n FooEvent: {Path: \"/foo\", Method: \"post\... |
Please provide a description of the function:def _process_api_events(self, function, api_events, template, condition=None):
for logicalId, event in api_events.items():
event_properties = event.get("Properties", {})
if not event_properties:
continue
... | [
"\n Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api\n resource from the template\n\n :param SamResource function: SAM Function containing the API events to be processed\n :param dict api_events: API Events extracted from the ... |
Please provide a description of the function:def _add_api_to_swagger(self, event_id, event_properties, template):
# Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition
api_id = self._get_api_id(event_properties)
# RestApiId is not pointi... | [
"\n Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event\n refers to.\n\n :param string event_id: LogicalId of the event\n :param dict event_properties: Properties of the event\n :param SamTemplate template: SAM Template to searc... |
Please provide a description of the function: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 | [
"\n Get API logical id from API event properties.\n\n Handles case where API id is not specified or is a reference to a logical id.\n "
] |
Please provide a description of the function:def _maybe_add_condition_to_implicit_api(self, template_dict):
# Short-circuit if template doesn't have any functions with implicit API events
if not self.api_conditions.get(self.implicit_api_logical_id, {}):
return
# Add a condi... | [
"\n Decides whether to add a condition to the implicit api resource.\n :param dict template_dict: SAM template dictionary\n "
] |
Please provide a description of the function: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 mu... | [
"\n Add top-level template condition that combines the given list of conditions.\n\n :param dict template_dict: SAM template dictionary\n :param string condition_name: Name of top-level template condition\n :param list conditions_to_combine: List of conditions that should be combined (vi... |
Please provide a description of the function: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("D... | [
"\n Add conditions to implicit API paths if necessary.\n\n Implicit API resource methods are constructed from API events on individual serverless functions within the SAM\n template. Since serverless functions can have conditions on them, it's possible to have a case where all methods\n ... |
Please provide a description of the function: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
# no... | [
"\n Generate valid condition logical id from the given API logical id and swagger resource path.\n "
] |
Please provide a description of the function:def _maybe_remove_implicit_api(self, template):
# Remove Implicit API resource if no paths got added
implicit_api_resource = template.get(self.implicit_api_logical_id)
if implicit_api_resource and len(implicit_api_resource.properties["Defin... | [
"\n Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit\n APIs. They need to removed from the template, if there are *no* API events attached to this resource.\n This method removes the Implicit API if it does not contain any Swagger path... |
Please provide a description of the function: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 Bod... | [
"\n Sets up the resource such that it will triggers a re-deployment when Swagger changes\n\n :param swagger: Dictionary containing the Swagger definition of the API\n "
] |
Please provide a description of the function:def _invoke_internal(self, function_arn, payload, client_context, invocation_type="RequestResponse"):
customer_logger.info('Invoking Lambda function "{}" with Greengrass Message "{}"'.format(function_arn, payload))
try:
invocation_id = s... | [
"\n This private method is seperate from the main, public invoke method so that other code within this SDK can\n give this Lambda client a raw payload/client context to invoke with, rather than having it built for them.\n This lets you include custom ExtensionMap_ values like subject which are ... |
Please provide a description of the function: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.\n If the amt argument is omitted, read all data.\n "
] |
Please provide a description of the function:def post_work(self, function_arn, input_bytes, client_context, invocation_type="RequestResponse"):
url = self._get_url(function_arn)
runtime_logger.info('Posting work for function [{}] to {}'.format(function_arn, url))
request = Request(url,... | [
"\n Send work item to specified :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param input_bytes: The data making up the work being posted.\n :type input_bytes: bytes\n\n ... |
Please provide a description of the function:def get_work(self, function_arn):
url = self._get_work_url(function_arn)
runtime_logger.info('Getting work for function [{}] from {}'.format(function_arn, url))
request = Request(url)
request.add_header(HEADER_AUTH_TOKEN, self.auth_t... | [
"\n Retrieve the next work item for specified :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :returns: Next work item to be processed by the function.\n :type returns: WorkItem... |
Please provide a description of the function:def post_work_result(self, function_arn, work_item):
url = self._get_work_url(function_arn)
runtime_logger.info('Posting work result for invocation id [{}] to {}'.format(work_item.invocation_id, url))
request = Request(url, work_item.payload... | [
"\n Post the result of processing work item by :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param work_item: The WorkItem holding the results of the work being posted.\n :ty... |
Please provide a description of the function:def post_handler_err(self, function_arn, invocation_id, handler_err):
url = self._get_work_url(function_arn)
runtime_logger.info('Posting handler error for invocation id [{}] to {}'.format(invocation_id, url))
payload = json.dumps({
... | [
"\n Post the error message from executing the function handler for :code:`function_arn`\n with specifid :code:`invocation_id`\n\n\n :param function_arn: Arn of the Lambda function which has the handler error message.\n :type function_arn: string\n\n :param invocation_id: Invocatio... |
Please provide a description of the function:def get_work_result(self, function_arn, invocation_id):
url = self._get_url(function_arn)
runtime_logger.info('Getting work result for invocation id [{}] from {}'.format(invocation_id, url))
request = Request(url)
request.add_header... | [
"\n Retrieve the result of the work processed by :code:`function_arn`\n with specified :code:`invocation_id`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param invocation_id: Invocation ID of th... |
Please provide a description of the function:def on_before_transform_template(self, template_dict):
template = SamTemplate(template_dict)
intrinsic_resolvers = self._get_intrinsic_resolvers(template_dict.get('Mappings', {}))
service_call = None
if self._validate_only:
... | [
"\n Hook method that gets called before the SAM template is processed.\n The template has passed the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n This plugin needs to run as soon as possible to allow some time for templates to become available.\n This ve... |
Please provide a description of the function: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
... | [
"\n Determines whether or not the on_before_transform_template event can process this application\n\n :param dict app: the application and its properties\n "
] |
Please provide a description of the function: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),
Semant... | [
"\n Method that handles the create_cloud_formation_template API call to the serverless application repo\n\n :param string app_id: ApplicationId\n :param string semver: SemanticVersion\n :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion)\n :param s... |
Please provide a description of the function:def on_before_transform_resource(self, logical_id, resource_type, resource_properties):
if not self._resource_is_supported(resource_type):
return
# Sanitize properties
self._check_for_dictionary_key(logical_id, resource_properti... | [
"\n Hook method that gets called before \"each\" SAM resource gets processed\n\n Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl.\n\n :param string logical_id: Logical ID of the resource being processed\n :param string resource_type: Type of the resource being pr... |
Please provide a description of the function: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 [{}] '
... | [
"\n Checks a dictionary to make sure it has a specific key. If it does not, an\n InvalidResourceException is thrown.\n\n :param string logical_id: logical id of this resource\n :param dict dictionary: the dictionary to check\n :param list keys: list of keys that should exist in th... |
Please provide a description of the function: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._... | [
"\n Hook method that gets called after the template is processed\n\n Go through all the stored applications and make sure they're all ACTIVE.\n\n :param dict template: Dictionary of the SAM template\n :return: Nothing\n "
] |
Please provide a description of the function: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 ... | [
"\n Handles the response from the SAR service call\n\n :param dict response: the response dictionary from the app repo\n :param string application_id: the ApplicationId\n :param string template_id: the unique TemplateId for this application\n "
] |
Please provide a description of the function: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['E... | [
"\n Handles service calls and exception management for service calls\n to the Serverless Application Repository.\n\n :param lambda service_call_lambda: lambda function that contains the service call\n :param string logical_id: Logical ID of the resource being processed\n :param li... |
Please provide a description of the function:def _validate(self, sam_template, parameter_values):
if parameter_values is None:
raise ValueError("`parameter_values` argument is required")
if ("Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) or not
... | [
" Validates the template and parameter values and raises exceptions if there's an issue\n\n :param dict sam_template: SAM template\n :param dict parameter_values: Dictionary of parameter values provided by the user\n "
] |
Please provide a description of the function: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_... | [
"\n Iterate over all resources within the SAM template, optionally filtering by type\n\n :param string resource_type: Optional type to filter the resources by\n :yields (string, SamResource): Tuple containing LogicalId and the resource\n "
] |
Please provide a description of the function:def set(self, logicalId, resource):
resource_dict = resource
if isinstance(resource, SamResource):
resource_dict = resource.to_dict()
self.resources[logicalId] = resource_dict | [
"\n Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used.\n\n :param string logicalId: Logical Id to set to\n :param SamResource or dict resource: The actual resource data\n "
] |
Please provide a description of the function:def get(self, logicalId):
if logicalId not in self.resources:
return None
return SamResource(self.resources.get(logicalId)) | [
"\n Gets the resource at the given logicalId if present\n\n :param string logicalId: Id of the resource\n :return SamResource: Resource, if available at the Id. None, otherwise\n "
] |
Please provide a description of the function:def prepare_plugins(plugins, parameters={}):
required_plugins = [
DefaultDefinitionBodyPlugin(),
make_implicit_api_plugin(),
GlobalsPlugin(),
make_policy_template_for_function_plugin(),
]
plugins = [] if not plugins else plu... | [
"\n Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,\n we will also install a few \"required\" plugins that are necessary to provide complete support for SAM template spec.\n\n :param plugins: list of samtranslator.plugins.BasePlugin plugins: Li... |
Please provide a description of the function: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()
parame... | [
"Loads the SAM resources from the given SAM manifest, replaces them with their corresponding\n CloudFormation resources, and returns the resulting CloudFormation template.\n\n :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \\\n Clo... |
Please provide a description of the function:def _get_resources_to_iterate(self, sam_template, macro_resolver):
functions = []
apis = []
others = []
resources = sam_template["Resources"]
for logicalId, resource in resources.items():
data = (logicalId, reso... | [
"\n Returns a list of resources to iterate, order them based on the following order:\n\n 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource.\n 2. AWS::Serverless::Api\n 3. Anything else\n\n This is necessary beca... |
Please provide a description of the function:def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None):
resource = cls(logical_id, relative_id=relative_id)
resource._validate_resource_dict(logical_id, resource_dict)
# Default to empty properties dictionary. If... | [
"Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict\n is the value associated with the logical id in a CloudFormation template's Resources section, and takes the\n following format. ::\n\n {\n \"Type\": \"<resource type... |
Please provide a description of the function: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.\n\n :param str logical_id: the logical id to validate\n :returns: True if the logical id is valid\n :rtype: bool\n :raises TypeError: if the logical id is invalid\n "
] |
Please provide a description of the function: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 ... | [
"Validates that the provided resource dict contains the correct Type string, and the required Properties dict.\n\n :param dict resource_dict: the resource dict to validate\n :returns: True if the resource dict has the expected format\n :rtype: bool\n :raises InvalidResourceException: if ... |
Please provide a description of the function:def to_dict(self):
self.validate_properties()
resource_dict = self._generate_resource_dict()
return {self.logical_id: resource_dict} | [
"Validates that the required properties for this Resource have been provided, then returns a dict\n corresponding to the given Resource object. This dict will take the format of a single entry in the Resources\n section of a CloudFormation template, and will take the following format. ::\n\n ... |
Please provide a description of the function: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)
p... | [
"Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation\n template's Resources section.\n\n :returns: the resource dict for this Resource\n :rtype: dict\n "
] |
Please provide a description of the function: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
... | [
"Validates that the required properties for this Resource have been populated, and that all properties have\n valid values.\n\n :returns: True if all properties are valid\n :rtype: bool\n :raises TypeError: if any properties are invalid\n "
] |
Please provide a description of the function: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\n that exist outside of the Properties dictionary\n\n :param attr: Attribute name\n :param value: Attribute value\n :return: None\n :raises KeyError if `attr` is not in the support... |
Please provide a description of the function: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\n\n :param attr: Name of the attribute\n :return: Value of the attribute, if set in the resource. None otherwise\n "
] |
Please provide a description of the function: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_t... | [
"\n Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide\n this attribute, then this method raises an exception\n\n :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed\n "
] |
Please provide a description of the function:def get_resource_references(self, generated_cfn_resources, supported_resource_refs):
if supported_resource_refs is None:
raise ValueError("`supported_resource_refs` object is required")
# Create a map of {ResourceType: LogicalId} for qu... | [
"\n Constructs the list of supported resource references by going through the list of CFN resources generated\n by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it\n supports and the type of CFN resource this property resolves to.\n\n :... |
Please provide a description of the function: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')))
... | [
"Returns the Resource class corresponding to the 'Type' key in the given resource dict.\n\n :param dict resource_dict: the resource dict to resolve\n :returns: the resolved Resource class\n :rtype: class\n "
] |
Please provide a description of the function: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.ca... | [
"\n Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.\n "
] |
Please provide a description of the function:def get_random_int(minimum, maximum):
min_int = math.ceil(minimum)
max_int = math.floor(maximum)
return random.randint(min_int, max_int - 1) | [
"\n Returns a random integer between min (included) and max (excluded)\n "
] |
Please provide a description of the function: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_prob... | [
"\n Helper function which in a full implementation would feed into a backend API to provide query schedule availability.\n The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format.\n\n In order to enable quick demonstration of all possible conversatio... |
Please provide a description of the function:def is_available(time, duration, availabilities):
if duration == 30:
return time in availabilities
elif duration == 60:
second_half_hour_time = increment_time_by_thirty_mins(time)
return time in availabilities and second_half_hour_time in... | [
"\n Helper function to check if the given time and duration fits within a known set of availability windows.\n Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.\n "
] |
Please provide a description of the function: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.appe... | [
"\n Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.\n "
] |
Please provide a description of the function: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)... | [
"\n Build a string eliciting for a possible time slot among at least two availabilities.\n "
] |
Please provide a description of the function: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': 'roo... | [
"\n Build a list of potential options for a given slot, to be used in responseCard generation.\n "
] |
Please provide a description of the function:def make_appointment(intent_request):
appointment_type = intent_request['currentIntent']['slots']['AppointmentType']
date = intent_request['currentIntent']['slots']['Date']
time = intent_request['currentIntent']['slots']['Time']
source = intent_request['... | [
"\n Performs dialog management and fulfillment for booking a dentists appointment.\n\n Beyond fulfillment, the implementation for this intent demonstrates the following:\n 1) Use of elicitSlot in slot validation and re-prompting\n 2) Use of confirmIntent to support the confirmation of inferred slot valu... |
Please provide a description of the function:def dispatch(intent_request):
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot's intent handlers
if... | [
"\n Called when the user specifies an intent for this bot.\n "
] |
Please provide a description of the function:def lambda_handler(event, context):
'''Demonstrates a simple HTTP endpoint using API Gateway. You have full
access to the request and response payload, including headers and
status code.
TableName provided by template.yaml.
To scan a DynamoDB table, make a... | [] |
Please provide a description of the function:def lambda_handler(event, context):
'''Demonstrates a simple HTTP endpoint using API Gateway. You have full
access to the request and response payload, including headers and
status code.
To scan a DynamoDB table, make a GET request with the TableName as a
... | [] |
Please provide a description of the function:def make_combined_condition(conditions_list, condition_name):
if len(conditions_list) < 2:
# Can't make a condition if <2 conditions provided.
return None
# Total number of conditions allows in an Fn::Or statement. See docs:
# https://docs.a... | [
"\n Makes a combined condition using Fn::Or. Since Fn::Or only accepts up to 10 conditions,\n this method optionally creates multiple conditions. These conditions are named based on\n the condition_name parameter that is passed into the method.\n\n :param list conditions_list: list of conditions\n :p... |
Please provide a description of the function: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 | [
"\n Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single\n key that is the name of the intrinsics.\n\n :param input: Input value to check if it is an intrinsic\n :return: True, if yes\n "
] |
Please provide a description of the function: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 | [
"\n Validates that the input dictionary contains only one key and is of the given intrinsic_name\n\n :param input_dict: Input dictionary representing the intrinsic function\n :return: True if it matches expected structure, False otherwise\n "
] |
Please provide a description of the function:def _parse_resource_reference(cls, ref_value):
no_result = (None, None)
if not isinstance(ref_value, string_types):
return no_result
splits = ref_value.split(cls._resource_ref_separator, 1)
# Either there is no 'dot' (o... | [
"\n Splits a resource reference of structure \"LogicalId.Property\" and returns the \"LogicalId\" and \"Property\"\n separately.\n\n :param string ref_value: Input reference value which *may* contain the structure \"LogicalId.Property\"\n :return string, string: Returns two values - logi... |
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters):
if not self.can_handle(input_dict):
return input_dict
param_name = input_dict[self.intrinsic_name]
if not isinstance(param_name, string_types):
return input_d... | [
"\n Resolves references that are present in the parameters and returns the value. If it is not in parameters,\n this method simply returns the input unchanged.\n\n :param input_dict: Dictionary representing the Ref function. Must contain only one key and it should be \"Ref\".\n Ex: {... |
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs):
if not self.can_handle(input_dict):
return input_dict
ref_value = input_dict[self.intrinsic_name]
logical_id, property = self._parse_resource_reference(ref_va... | [
"\n Resolves references to some property of a resource. These are runtime properties which can't be converted\n to a value here. Instead we output another reference that will more actually resolve to the value when\n executed via CloudFormation\n\n Example:\n {\"Ref\": \"Logic... |
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
if not self.can_handle(input_dict):
return input_dict
ref_value = input_dict[self.intrinsic_name]
if not isinstance(ref_value, string_types) or self._re... | [
"\n Updates references to the old logical id of a resource to the new (generated) logical id.\n\n Example:\n {\"Ref\": \"MyLayer\"} => {\"Ref\": \"MyLayerABC123\"}\n\n :param dict input_dict: Dictionary representing the Ref function to be resolved.\n :param dict supported_reso... |
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters):
def do_replacement(full_ref, prop_name):
return parameters.get(prop_name, full_ref)
return self._handle_sub_action(input_dict, do_replacement) | [
"\n Substitute references found within the string of `Fn::Sub` intrinsic function\n\n :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be\n `Fn::Sub`. Ex: {\"Fn::Sub\": ...}\n\n :param parameters: Dictionary of parameter values ... |
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs):
def do_replacement(full_ref, ref_value):
# Split the value by separator, expecting to separate out LogicalId.Property
splits = ref_value.split(self._... | [
"\n Resolves reference to some property of a resource. Inside string to be substituted, there could be either a\n \"Ref\" or a \"GetAtt\" usage of this property. They have to be handled differently.\n\n Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split un... |
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
def do_replacement(full_ref, ref_value):
# Split the value by separator, expecting to separate out LogicalId
splits = ref_value.split(self._res... | [
"\n Resolves reference to some property of a resource. Inside string to be substituted, there could be either a\n \"Ref\" or a \"GetAtt\" usage of this property. They have to be handled differently.\n\n Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split un... |
Please provide a description of the function:def _handle_sub_action(self, input_dict, handler):
if not self.can_handle(input_dict):
return input_dict
key = self.intrinsic_name
sub_value = input_dict[key]
input_dict[key] = self._handle_sub_value(sub_value, handler)
... | [
"\n Handles resolving replacements in the Sub action based on the handler that is passed as an input.\n\n :param input_dict: Dictionary to be resolved\n :param supported_values: One of several different objects that contain the supported values that\n need to be changed. See each met... |
Please provide a description of the function:def _handle_sub_value(self, sub_value, handler_method):
# Just handle known references within the string to be substituted and return the whole dictionary
# because that's the best we can do here.
if isinstance(sub_value, string_types):
... | [
"\n Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside\n the string portion of the value.\n\n :param sub_value: Value of the Sub function\n :param handler_method: Method to be called on every occurrence of `${LogicalId}` structure within t... |
Please provide a description of the function:def _sub_all_refs(self, text, handler_method):
# RegExp to find pattern "${logicalId.property}" and return the word inside bracket
logical_id_regex = '[A-Za-z0-9\.]+|AWS::[A-Z][A-Za-z]*'
ref_pattern = re.compile(r'\$\{(' + logical_id_regex +... | [
"\n Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every\n occurrence of this structure. The value returned by this method directly replaces the reference structure.\n\n Ex:\n text = \"${key1}-hello-${key2}\n def handle... |
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs):
if not self.can_handle(input_dict):
return input_dict
key = self.intrinsic_name
value = input_dict[key]
# Value must be an array with *at least* two ... | [
"\n Resolve resource references within a GetAtt dict.\n\n Example:\n { \"Fn::GetAtt\": [\"LogicalId.Property\", \"Arn\"] } => {\"Fn::GetAtt\": [\"ResolvedLogicalId\", \"Arn\"]}\n\n\n Theoretically, only the first element of the array can contain reference to SAM resources. The sec... |
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
if not self.can_handle(input_dict):
return input_dict
key = self.intrinsic_name
value = input_dict[key]
# Value must be an array with *at least... | [
"\n Resolve resource references within a GetAtt dict.\n\n Example:\n { \"Fn::GetAtt\": [\"LogicalId\", \"Arn\"] } => {\"Fn::GetAtt\": [\"ResolvedLogicalId\", \"Arn\"]}\n\n\n Theoretically, only the first element of the array can contain reference to SAM resources. The second eleme... |
Please provide a description of the function:def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining):
if resolved_value:
# We resolved to a new resource logicalId. Use this as the first element and keep remaining elements intact
# This is the new value of ... | [
"\n Resolves the function and returns the updated dictionary\n\n :param input_dict: Dictionary to be resolved\n :param key: Name of this intrinsic.\n :param resolved_value: Resolved or updated value for this action.\n :param remaining: Remaining sections for the GetAtt action.\n ... |
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters):
if not self.can_handle(input_dict):
return input_dict
value = input_dict[self.intrinsic_name]
# FindInMap expects an array with 3 values
if not isinstance(value, ... | [
"\n Recursively resolves \"Fn::FindInMap\"references that are present in the mappings and returns the value.\n If it is not in mappings, this method simply returns the input unchanged.\n\n :param input_dict: Dictionary representing the FindInMap function. Must contain only one key and it\n ... |
Please provide a description of the function:def lambda_handler(event, context):
''' Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
'''
# event is a dict containing a base64 string gzipped
event = json.loads(gzip.GzipFile(fileobj=StringIO(event['awslogs']['data'].dec... | [] |
Please provide a description of the function:def _construct_rest_api(self):
rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes)
rest_api.BinaryMediaTypes = self.binary_media
rest_api.MinimumCompressionSize = self.minimum_compres... | [
"Constructs and returns the ApiGateway RestApi.\n\n :returns: the RestApi to which this SAM Api corresponds\n :rtype: model.apigateway.ApiGatewayRestApi\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.