partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
ApiGenerator._add_auth
Add Auth configuration to the Swagger file, if necessary
samtranslator/model/api/api_generator.py
def _add_auth(self): """ Add Auth configuration to the Swagger file, if necessary """ if not self.auth: return if self.auth and not self.definition_body: raise InvalidResourceException(self.logical_id, "Auth wor...
def _add_auth(self): """ Add Auth configuration to the Swagger file, if necessary """ if not self.auth: return if self.auth and not self.definition_body: raise InvalidResourceException(self.logical_id, "Auth wor...
[ "Add", "Auth", "configuration", "to", "the", "Swagger", "file", "if", "necessary" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L251-L281
[ "def", "_add_auth", "(", "self", ")", ":", "if", "not", "self", ".", "auth", ":", "return", "if", "self", ".", "auth", "and", "not", "self", ".", "definition_body", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Auth work...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
ApiGenerator._add_gateway_responses
Add Gateway Response configuration to the Swagger file, if necessary
samtranslator/model/api/api_generator.py
def _add_gateway_responses(self): """ Add Gateway Response configuration to the Swagger file, if necessary """ if not self.gateway_responses: return if self.gateway_responses and not self.definition_body: raise InvalidResourceException( s...
def _add_gateway_responses(self): """ Add Gateway Response configuration to the Swagger file, if necessary """ if not self.gateway_responses: return if self.gateway_responses and not self.definition_body: raise InvalidResourceException( s...
[ "Add", "Gateway", "Response", "configuration", "to", "the", "Swagger", "file", "if", "necessary" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L283-L324
[ "def", "_add_gateway_responses", "(", "self", ")", ":", "if", "not", "self", ".", "gateway_responses", ":", "return", "if", "self", ".", "gateway_responses", "and", "not", "self", ".", "definition_body", ":", "raise", "InvalidResourceException", "(", "self", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
ApiGenerator._get_permission
Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission
samtranslator/model/api/api_generator.py
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn): """Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission """ rest_api = ApiGateway...
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn): """Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission """ rest_api = ApiGateway...
[ "Constructs", "and", "returns", "the", "Lambda", "Permission", "resource", "allowing", "the", "Authorizer", "to", "invoke", "the", "function", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L360-L381
[ "def", "_get_permission", "(", "self", ",", "authorizer_name", ",", "authorizer_lambda_function_arn", ")", ":", "rest_api", "=", "ApiGatewayRestApi", "(", "self", ".", "logical_id", ",", "depends_on", "=", "self", ".", "depends_on", ",", "attributes", "=", "self",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
ApiGenerator._set_endpoint_configuration
Sets endpoint configuration property of AWS::ApiGateway::RestApi resource :param rest_api: RestApi resource :param string/dict value: Value to be set
samtranslator/model/api/api_generator.py
def _set_endpoint_configuration(self, rest_api, value): """ Sets endpoint configuration property of AWS::ApiGateway::RestApi resource :param rest_api: RestApi resource :param string/dict value: Value to be set """ rest_api.EndpointConfiguration = {"Types": [value]} ...
def _set_endpoint_configuration(self, rest_api, value): """ Sets endpoint configuration property of AWS::ApiGateway::RestApi resource :param rest_api: RestApi resource :param string/dict value: Value to be set """ rest_api.EndpointConfiguration = {"Types": [value]} ...
[ "Sets", "endpoint", "configuration", "property", "of", "AWS", "::", "ApiGateway", "::", "RestApi", "resource", ":", "param", "rest_api", ":", "RestApi", "resource", ":", "param", "string", "/", "dict", "value", ":", "Value", "to", "be", "set" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L416-L424
[ "def", "_set_endpoint_configuration", "(", "self", ",", "rest_api", ",", "value", ")", ":", "rest_api", ".", "EndpointConfiguration", "=", "{", "\"Types\"", ":", "[", "value", "]", "}", "rest_api", ".", "Parameters", "=", "{", "\"endpointConfigurationTypes\"", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
retry
The retry function will keep retrying `task_to_try` until either: (1) it returns None, then retry() finishes (2) `max_attempts` is reached, then retry() raises an exception. (3) if retrying one more time will cause total wait time to go above: `expiration_duration`, then retry() raises an exception ...
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/utils/exponential_backoff.py
def retry(time_unit, multiplier, backoff_coefficient, max_delay, max_attempts, expiration_duration, enable_jitter): """ The retry function will keep retrying `task_to_try` until either: (1) it returns None, then retry() finishes (2) `max_attempts` is reached, then retry() raises an exception. (3) if...
def retry(time_unit, multiplier, backoff_coefficient, max_delay, max_attempts, expiration_duration, enable_jitter): """ The retry function will keep retrying `task_to_try` until either: (1) it returns None, then retry() finishes (2) `max_attempts` is reached, then retry() raises an exception. (3) if...
[ "The", "retry", "function", "will", "keep", "retrying", "task_to_try", "until", "either", ":", "(", "1", ")", "it", "returns", "None", "then", "retry", "()", "finishes", "(", "2", ")", "max_attempts", "is", "reached", "then", "retry", "()", "raises", "an",...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/utils/exponential_backoff.py#L47-L116
[ "def", "retry", "(", "time_unit", ",", "multiplier", ",", "backoff_coefficient", ",", "max_delay", ",", "max_attempts", ",", "expiration_duration", ",", "enable_jitter", ")", ":", "def", "deco_retry", "(", "task_to_try", ")", ":", "@", "wraps", "(", "task_to_try...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
to_cloudformation
Returns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Fun...
samtranslator/model/sam_resources.py
def to_cloudformation(self, **kwargs): """Returns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of v...
def to_cloudformation(self, **kwargs): """Returns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of v...
[ "Returns", "the", "Lambda", "function", "role", "and", "event", "resources", "to", "which", "this", "SAM", "Function", "corresponds", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L80-L126
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "intrinsics_resolver", "=", "kwargs", "[", "\"intrinsics_resolver\"", "]", "if", "self", ".", "DeadLetterQueue", ":", "self", ".", "_validate_dlq", "(", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_get_resolved_alias_name
Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this method raises an exception. If alias name is just a plain string, it will return as is ...
samtranslator/model/sam_resources.py
def _get_resolved_alias_name(self, property_name, original_alias_value, intrinsics_resolver): """ Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function wa...
def _get_resolved_alias_name(self, property_name, original_alias_value, intrinsics_resolver): """ Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function wa...
[ "Alias", "names", "can", "be", "supplied", "as", "an", "intrinsic", "function", ".", "This", "method", "tries", "to", "extract", "alias", "name", "from", "a", "reference", "to", "a", "parameter", ".", "If", "it", "cannot", "completely", "resolve", "(", "ie...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L128-L150
[ "def", "_get_resolved_alias_name", "(", "self", ",", "property_name", ",", "original_alias_value", ",", "intrinsics_resolver", ")", ":", "# Try to resolve.", "resolved_alias_name", "=", "intrinsics_resolver", ".", "resolve_parameter_refs", "(", "original_alias_value", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_construct_lambda_function
Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list
samtranslator/model/sam_resources.py
def _construct_lambda_function(self): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ lambda_function = LambdaFunction(self.logical_id, depends_on=self.depends_on, ...
def _construct_lambda_function(self): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ lambda_function = LambdaFunction(self.logical_id, depends_on=self.depends_on, ...
[ "Constructs", "and", "returns", "the", "Lambda", "function", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L152-L184
[ "def", "_construct_lambda_function", "(", "self", ")", ":", "lambda_function", "=", "LambdaFunction", "(", "self", ".", "logical_id", ",", "depends_on", "=", "self", ".", "depends_on", ",", "attributes", "=", "self", ".", "resource_attributes", ")", "if", "self"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_construct_role
Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole
samtranslator/model/sam_resources.py
def _construct_role(self, managed_policy_map): """Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole """ execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_...
def _construct_role(self, managed_policy_map): """Constructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole """ execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_...
[ "Constructs", "a", "Lambda", "execution", "role", "based", "on", "this", "SAM", "function", "s", "Policies", "property", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L186-L246
[ "def", "_construct_role", "(", "self", ",", "managed_policy_map", ")", ":", "execution_role", "=", "IAMRole", "(", "self", ".", "logical_id", "+", "'Role'", ",", "attributes", "=", "self", ".", "get_passthrough_resource_attributes", "(", ")", ")", "execution_role"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_validate_dlq
Validates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException
samtranslator/model/sam_resources.py
def _validate_dlq(self): """Validates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException """ # Validate required logical ids valid_dlq_types = str(list(self.dead_letter_queue_policy_actions.keys())) if not self.DeadLetterQueue.get('Type')...
def _validate_dlq(self): """Validates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException """ # Validate required logical ids valid_dlq_types = str(list(self.dead_letter_queue_policy_actions.keys())) if not self.DeadLetterQueue.get('Type')...
[ "Validates", "whether", "the", "DeadLetterQueue", "LogicalId", "is", "validation", ":", "raise", ":", "InvalidResourceException" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L248-L262
[ "def", "_validate_dlq", "(", "self", ")", ":", "# Validate required logical ids", "valid_dlq_types", "=", "str", "(", "list", "(", "self", ".", "dead_letter_queue_policy_actions", ".", "keys", "(", ")", ")", ")", "if", "not", "self", ".", "DeadLetterQueue", ".",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_generate_event_resources
Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs...
samtranslator/model/sam_resources.py
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): """Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_ro...
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): """Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_ro...
[ "Generates", "and", "returns", "the", "resources", "associated", "with", "this", "function", "s", "events", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L276-L309
[ "def", "_generate_event_resources", "(", "self", ",", "lambda_function", ",", "execution_role", ",", "event_resources", ",", "lambda_alias", "=", "None", ")", ":", "resources", "=", "[", "]", "if", "self", ".", "Events", ":", "for", "logical_id", ",", "event_d...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_construct_version
Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version ...
samtranslator/model/sam_resources.py
def _construct_version(self, function, intrinsics_resolver): """Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunctio...
def _construct_version(self, function, intrinsics_resolver): """Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunctio...
[ "Constructs", "a", "Lambda", "Version", "resource", "that", "will", "be", "auto", "-", "published", "when", "CodeUri", "of", "the", "function", "changes", ".", "Old", "versions", "will", "not", "be", "deleted", "without", "a", "direct", "reference", "from", ...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L321-L371
[ "def", "_construct_version", "(", "self", ",", "function", ",", "intrinsics_resolver", ")", ":", "code_dict", "=", "function", ".", "Code", "if", "not", "code_dict", ":", "raise", "ValueError", "(", "\"Lambda function code must be a valid non-empty dictionary\"", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
_construct_alias
Constructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model.lambda_.LambdaVersion version: Lambda version object to associat...
samtranslator/model/sam_resources.py
def _construct_alias(self, name, function, version): """Constructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model....
def _construct_alias(self, name, function, version): """Constructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model....
[ "Constructs", "a", "Lambda", "Alias", "for", "the", "given", "function", "and", "pointing", "to", "the", "given", "version" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L373-L392
[ "def", "_construct_alias", "(", "self", ",", "name", ",", "function", ",", "version", ")", ":", "if", "not", "name", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Alias name is required to create an alias\"", ")", "logical_id", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamApi.to_cloudformation
Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function...
samtranslator/model/sam_resources.py
def to_cloudformation(self, **kwargs): """Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanill...
def to_cloudformation(self, **kwargs): """Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanill...
[ "Returns", "the", "API", "Gateway", "RestApi", "Deployment", "and", "Stage", "to", "which", "this", "SAM", "Api", "corresponds", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L456-L493
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "api_generator", "=", "ApiGenerator", "(", "self", ".", "logical_id", ",", "self", ".", "CacheClusterEnabled", ",", "self", ".", "CacheClusterSize", ",", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamApplication._construct_nested_stack
Constructs a AWS::CloudFormation::Stack resource
samtranslator/model/sam_resources.py
def _construct_nested_stack(self): """Constructs a AWS::CloudFormation::Stack resource """ nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on, attributes=self.get_passthrough_resource_attributes()) nested_stack.Parameters = self.Para...
def _construct_nested_stack(self): """Constructs a AWS::CloudFormation::Stack resource """ nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on, attributes=self.get_passthrough_resource_attributes()) nested_stack.Parameters = self.Para...
[ "Constructs", "a", "AWS", "::", "CloudFormation", "::", "Stack", "resource" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L583-L595
[ "def", "_construct_nested_stack", "(", "self", ")", ":", "nested_stack", "=", "NestedStack", "(", "self", ".", "logical_id", ",", "depends_on", "=", "self", ".", "depends_on", ",", "attributes", "=", "self", ".", "get_passthrough_resource_attributes", "(", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamApplication._get_application_tags
Adds tags to the stack if this resource is using the serverless app repo
samtranslator/model/sam_resources.py
def _get_application_tags(self): """Adds tags to the stack if this resource is using the serverless app repo """ application_tags = {} if isinstance(self.Location, dict): if (self.APPLICATION_ID_KEY in self.Location.keys() and self.Location[self.APPLICATIO...
def _get_application_tags(self): """Adds tags to the stack if this resource is using the serverless app repo """ application_tags = {} if isinstance(self.Location, dict): if (self.APPLICATION_ID_KEY in self.Location.keys() and self.Location[self.APPLICATIO...
[ "Adds", "tags", "to", "the", "stack", "if", "this", "resource", "is", "using", "the", "serverless", "app", "repo" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L597-L608
[ "def", "_get_application_tags", "(", "self", ")", ":", "application_tags", "=", "{", "}", "if", "isinstance", "(", "self", ".", "Location", ",", "dict", ")", ":", "if", "(", "self", ".", "APPLICATION_ID_KEY", "in", "self", ".", "Location", ".", "keys", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamLayerVersion.to_cloudformation
Returns the Lambda layer to which this SAM Layer corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function expands :rtype: lis...
samtranslator/model/sam_resources.py
def to_cloudformation(self, **kwargs): """Returns the Lambda layer to which this SAM Layer corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, ...
def to_cloudformation(self, **kwargs): """Returns the Lambda layer to which this SAM Layer corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, ...
[ "Returns", "the", "Lambda", "layer", "to", "which", "this", "SAM", "Layer", "corresponds", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L628-L642
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "# Append any CFN resources:", "intrinsics_resolver", "=", "kwargs", "[", "\"intrinsics_resolver\"", "]", "resources", ".", "append", "(", "self", ".", "_cons...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamLayerVersion._construct_lambda_layer
Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list
samtranslator/model/sam_resources.py
def _construct_lambda_layer(self, intrinsics_resolver): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ # Resolve intrinsics if applicable: self.LayerName = self._resolve_string_...
def _construct_lambda_layer(self, intrinsics_resolver): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ # Resolve intrinsics if applicable: self.LayerName = self._resolve_string_...
[ "Constructs", "and", "returns", "the", "Lambda", "function", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L644-L688
[ "def", "_construct_lambda_layer", "(", "self", ",", "intrinsics_resolver", ")", ":", "# Resolve intrinsics if applicable:", "self", ".", "LayerName", "=", "self", ".", "_resolve_string_parameter", "(", "intrinsics_resolver", ",", "self", ".", "LayerName", ",", "'LayerNa...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SamLayerVersion._get_retention_policy_value
Sets the deletion policy on this resource. The default is 'Retain'. :return: value for the DeletionPolicy attribute.
samtranslator/model/sam_resources.py
def _get_retention_policy_value(self): """ Sets the deletion policy on this resource. The default is 'Retain'. :return: value for the DeletionPolicy attribute. """ if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower(): return self.RE...
def _get_retention_policy_value(self): """ Sets the deletion policy on this resource. The default is 'Retain'. :return: value for the DeletionPolicy attribute. """ if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower(): return self.RE...
[ "Sets", "the", "deletion", "policy", "on", "this", "resource", ".", "The", "default", "is", "Retain", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L690-L704
[ "def", "_get_retention_policy_value", "(", "self", ")", ":", "if", "self", ".", "RetentionPolicy", "is", "None", "or", "self", ".", "RetentionPolicy", ".", "lower", "(", ")", "==", "self", ".", "RETAIN", ".", "lower", "(", ")", ":", "return", "self", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
order_flowers
Performs dialog management and fulfillment for ordering flowers. Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting.
examples/apps/lex-order-flowers-python/lambda_function.py
def order_flowers(intent_request): """ Performs dialog management and fulfillment for ordering flowers. Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting. """ flower_type = get_slots(intent_request)["Fl...
def order_flowers(intent_request): """ Performs dialog management and fulfillment for ordering flowers. Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting. """ flower_type = get_slots(intent_request)["Fl...
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "ordering", "flowers", ".", "Beyond", "fulfillment", "the", "implementation", "of", "this", "intent", "demonstrates", "the", "use", "of", "the", "elicitSlot", "dialog", "action", "in", "slot", "valid...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-order-flowers-python/lambda_function.py#L119-L158
[ "def", "order_flowers", "(", "intent_request", ")", ":", "flower_type", "=", "get_slots", "(", "intent_request", ")", "[", "\"FlowerType\"", "]", "date", "=", "get_slots", "(", "intent_request", ")", "[", "\"PickupDate\"", "]", "time", "=", "get_slots", "(", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
dispatch
Called when the user specifies an intent for this bot.
examples/apps/lex-order-flowers-python/lambda_function.py
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "bot", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-order-flowers-python/lambda_function.py#L164-L177
[ "def", "dispatch", "(", "intent_request", ")", ":", "logger", ".", "debug", "(", "'dispatch userId={}, intentName={}'", ".", "format", "(", "intent_request", "[", "'userId'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ")", ")", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
PushEventSource._construct_permission
Constructs the Lambda Permission resource allowing the source service to invoke the function this event source triggers. :returns: the permission resource :rtype: model.lambda_.LambdaPermission
samtranslator/model/eventsources/push.py
def _construct_permission(self, function, source_arn=None, source_account=None, suffix="", event_source_token=None): """Constructs the Lambda Permission resource allowing the source service to invoke the function this event source triggers. :returns: the permission resource :rtype: mode...
def _construct_permission(self, function, source_arn=None, source_account=None, suffix="", event_source_token=None): """Constructs the Lambda Permission resource allowing the source service to invoke the function this event source triggers. :returns: the permission resource :rtype: mode...
[ "Constructs", "the", "Lambda", "Permission", "resource", "allowing", "the", "source", "service", "to", "invoke", "the", "function", "this", "event", "source", "triggers", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L43-L66
[ "def", "_construct_permission", "(", "self", ",", "function", ",", "source_arn", "=", "None", ",", "source_account", "=", "None", ",", "suffix", "=", "\"\"", ",", "event_source_token", "=", "None", ")", ":", "lambda_permission", "=", "LambdaPermission", "(", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Schedule.to_cloudformation
Returns the CloudWatch Events Rule and Lambda Permission to which this Schedule event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this pull event expands :rtype: list
samtranslator/model/eventsources/push.py
def to_cloudformation(self, **kwargs): """Returns the CloudWatch Events Rule and Lambda Permission to which this Schedule event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this pull event expand...
def to_cloudformation(self, **kwargs): """Returns the CloudWatch Events Rule and Lambda Permission to which this Schedule event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this pull event expand...
[ "Returns", "the", "CloudWatch", "Events", "Rule", "and", "Lambda", "Permission", "to", "which", "this", "Schedule", "event", "source", "corresponds", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L78-L103
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "resources...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
CloudWatchEvent._construct_target
Constructs the Target property for the CloudWatch Events Rule. :returns: the Target property :rtype: dict
samtranslator/model/eventsources/push.py
def _construct_target(self, function): """Constructs the Target property for the CloudWatch Events Rule. :returns: the Target property :rtype: dict """ target = { 'Arn': function.get_runtime_attr("arn"), 'Id': self.logical_id + 'LambdaTarget' ...
def _construct_target(self, function): """Constructs the Target property for the CloudWatch Events Rule. :returns: the Target property :rtype: dict """ target = { 'Arn': function.get_runtime_attr("arn"), 'Id': self.logical_id + 'LambdaTarget' ...
[ "Constructs", "the", "Target", "property", "for", "the", "CloudWatch", "Events", "Rule", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L159-L174
[ "def", "_construct_target", "(", "self", ",", "function", ")", ":", "target", "=", "{", "'Arn'", ":", "function", ".", "get_runtime_attr", "(", "\"arn\"", ")", ",", "'Id'", ":", "self", ".", "logical_id", "+", "'LambdaTarget'", "}", "if", "self", ".", "I...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
S3.to_cloudformation
Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list
samtranslator/model/eventsources/push.py
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list ...
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers. :param dict kwargs: S3 bucket resource :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands :rtype: list ...
[ "Returns", "the", "Lambda", "Permission", "resource", "allowing", "S3", "to", "invoke", "the", "function", "this", "event", "source", "triggers", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L197-L241
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "if", "'...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
S3._depend_on_lambda_permissions
Make the S3 bucket depends on Lambda Permissions resource because when S3 adds a Notification Configuration, it will check whether it has permissions to access Lambda. This will fail if the Lambda::Permissions is not already applied for this bucket to invoke the Lambda. :param dict bucket: Dict...
samtranslator/model/eventsources/push.py
def _depend_on_lambda_permissions(self, bucket, permission): """ Make the S3 bucket depends on Lambda Permissions resource because when S3 adds a Notification Configuration, it will check whether it has permissions to access Lambda. This will fail if the Lambda::Permissions is not alread...
def _depend_on_lambda_permissions(self, bucket, permission): """ Make the S3 bucket depends on Lambda Permissions resource because when S3 adds a Notification Configuration, it will check whether it has permissions to access Lambda. This will fail if the Lambda::Permissions is not alread...
[ "Make", "the", "S3", "bucket", "depends", "on", "Lambda", "Permissions", "resource", "because", "when", "S3", "adds", "a", "Notification", "Configuration", "it", "will", "check", "whether", "it", "has", "permissions", "to", "access", "Lambda", ".", "This", "wi...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L243-L266
[ "def", "_depend_on_lambda_permissions", "(", "self", ",", "bucket", ",", "permission", ")", ":", "depends_on", "=", "bucket", ".", "get", "(", "\"DependsOn\"", ",", "[", "]", ")", "# DependsOn can be either a list of strings or a scalar string", "if", "isinstance", "(...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
S3._depend_on_lambda_permissions_using_tag
Since conditional DependsOn is not supported this undocumented way of implicitely making dependency through tags is used. See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-dependson It is done by using Ref wrapped in a conditional Fn::If. Using Ref implies a ...
samtranslator/model/eventsources/push.py
def _depend_on_lambda_permissions_using_tag(self, bucket, permission): """ Since conditional DependsOn is not supported this undocumented way of implicitely making dependency through tags is used. See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-depend...
def _depend_on_lambda_permissions_using_tag(self, bucket, permission): """ Since conditional DependsOn is not supported this undocumented way of implicitely making dependency through tags is used. See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-depend...
[ "Since", "conditional", "DependsOn", "is", "not", "supported", "this", "undocumented", "way", "of", "implicitely", "making", "dependency", "through", "tags", "is", "used", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L268-L297
[ "def", "_depend_on_lambda_permissions_using_tag", "(", "self", ",", "bucket", ",", "permission", ")", ":", "properties", "=", "bucket", ".", "get", "(", "'Properties'", ",", "None", ")", "if", "properties", "is", "None", ":", "properties", "=", "{", "}", "bu...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
SNS.to_cloudformation
Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands :rtype: list
samtranslator/model/eventsources/push.py
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands ...
def to_cloudformation(self, **kwargs): """Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands ...
[ "Returns", "the", "Lambda", "Permission", "resource", "allowing", "SNS", "to", "invoke", "the", "function", "this", "event", "source", "triggers", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L350-L363
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "return", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Api.resources_to_link
If this API Event Source refers to an explicit API resource, resolve the reference and grab necessary data from the explicit API
samtranslator/model/eventsources/push.py
def resources_to_link(self, resources): """ If this API Event Source refers to an explicit API resource, resolve the reference and grab necessary data from the explicit API """ rest_api_id = self.RestApiId if isinstance(rest_api_id, dict) and "Ref" in rest_api_id: ...
def resources_to_link(self, resources): """ If this API Event Source refers to an explicit API resource, resolve the reference and grab necessary data from the explicit API """ rest_api_id = self.RestApiId if isinstance(rest_api_id, dict) and "Ref" in rest_api_id: ...
[ "If", "this", "API", "Event", "Source", "refers", "to", "an", "explicit", "API", "resource", "resolve", "the", "reference", "and", "grab", "necessary", "data", "from", "the", "explicit", "API" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L392-L439
[ "def", "resources_to_link", "(", "self", ",", "resources", ")", ":", "rest_api_id", "=", "self", ".", "RestApiId", "if", "isinstance", "(", "rest_api_id", ",", "dict", ")", "and", "\"Ref\"", "in", "rest_api_id", ":", "rest_api_id", "=", "rest_api_id", "[", "...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Api.to_cloudformation
If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the x-amazon-apigateway-integration into the Swagger body for a provided implicit API. ...
samtranslator/model/eventsources/push.py
def to_cloudformation(self, **kwargs): """If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the x-amazon-apigateway-integration int...
def to_cloudformation(self, **kwargs): """If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the x-amazon-apigateway-integration int...
[ "If", "the", "Api", "event", "source", "has", "a", "RestApi", "property", "then", "simply", "return", "the", "Lambda", "Permission", "resource", "allowing", "API", "Gateway", "to", "call", "the", "function", ".", "If", "no", "RestApi", "is", "provided", "the...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L441-L468
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argume...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
Api._add_swagger_integration
Adds the path and method for this Api event source to the Swagger body for the provided RestApi. :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi to which the path and method should be added.
samtranslator/model/eventsources/push.py
def _add_swagger_integration(self, api, function): """Adds the path and method for this Api event source to the Swagger body for the provided RestApi. :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi to which the path and method should be added. """ swagger_body = api.get...
def _add_swagger_integration(self, api, function): """Adds the path and method for this Api event source to the Swagger body for the provided RestApi. :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi to which the path and method should be added. """ swagger_body = api.get...
[ "Adds", "the", "path", "and", "method", "for", "this", "Api", "event", "source", "to", "the", "Swagger", "body", "for", "the", "provided", "RestApi", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/push.py#L507-L567
[ "def", "_add_swagger_integration", "(", "self", ",", "api", ",", "function", ")", ":", "swagger_body", "=", "api", ".", "get", "(", "\"DefinitionBody\"", ")", "if", "swagger_body", "is", "None", ":", "return", "function_arn", "=", "function", ".", "get_runtime...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver.resolve_parameter_refs
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as !GetAtt, !Sub or !Ref to non-parameters will be left untouched. Result is a dictionary where parameter values are inlined. Don't pass this dictionary directly into transform's output bec...
samtranslator/intrinsics/resolver.py
def resolve_parameter_refs(self, input): """ Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as !GetAtt, !Sub or !Ref to non-parameters will be left untouched. Result is a dictionary where parameter values are inlined. Don't pass...
def resolve_parameter_refs(self, input): """ Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as !GetAtt, !Sub or !Ref to non-parameters will be left untouched. Result is a dictionary where parameter values are inlined. Don't pass...
[ "Resolves", "references", "to", "parameters", "within", "the", "given", "dictionary", "recursively", ".", "Other", "intrinsic", "functions", "such", "as", "!GetAtt", "!Sub", "or", "!Ref", "to", "non", "-", "parameters", "will", "be", "left", "untouched", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L30-L41
[ "def", "resolve_parameter_refs", "(", "self", ",", "input", ")", ":", "return", "self", ".", "_traverse", "(", "input", ",", "self", ".", "parameters", ",", "self", ".", "_try_resolve_parameter_refs", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver.resolve_sam_resource_refs
Customers can provide a reference to a "derived" SAM resource such as Alias of a Function or Stage of an API resource. This method recursively walks the tree, converting all derived references to the real resource name, if it is present. Example: {"Ref": "MyFunction.Alias"} -> {"Ref...
samtranslator/intrinsics/resolver.py
def resolve_sam_resource_refs(self, input, supported_resource_refs): """ Customers can provide a reference to a "derived" SAM resource such as Alias of a Function or Stage of an API resource. This method recursively walks the tree, converting all derived references to the real resource name, ...
def resolve_sam_resource_refs(self, input, supported_resource_refs): """ Customers can provide a reference to a "derived" SAM resource such as Alias of a Function or Stage of an API resource. This method recursively walks the tree, converting all derived references to the real resource name, ...
[ "Customers", "can", "provide", "a", "reference", "to", "a", "derived", "SAM", "resource", "such", "as", "Alias", "of", "a", "Function", "or", "Stage", "of", "an", "API", "resource", ".", "This", "method", "recursively", "walks", "the", "tree", "converting", ...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L43-L65
[ "def", "resolve_sam_resource_refs", "(", "self", ",", "input", ",", "supported_resource_refs", ")", ":", "return", "self", ".", "_traverse", "(", "input", ",", "supported_resource_refs", ",", "self", ".", "_try_resolve_sam_resource_refs", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver.resolve_sam_resource_id_refs
Some SAM resources have their logical ids mutated from the original id that the customer writes in the template. This method recursively walks the tree and updates these logical ids from the old value to the new value that is generated by SAM. Example: {"Ref": "MyLayer"} -> {"Ref": ...
samtranslator/intrinsics/resolver.py
def resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): """ Some SAM resources have their logical ids mutated from the original id that the customer writes in the template. This method recursively walks the tree and updates these logical ids from the old value to the n...
def resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): """ Some SAM resources have their logical ids mutated from the original id that the customer writes in the template. This method recursively walks the tree and updates these logical ids from the old value to the n...
[ "Some", "SAM", "resources", "have", "their", "logical", "ids", "mutated", "from", "the", "original", "id", "that", "the", "customer", "writes", "in", "the", "template", ".", "This", "method", "recursively", "walks", "the", "tree", "and", "updates", "these", ...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L67-L88
[ "def", "resolve_sam_resource_id_refs", "(", "self", ",", "input", ",", "supported_resource_id_refs", ")", ":", "return", "self", ".", "_traverse", "(", "input", ",", "supported_resource_id_refs", ",", "self", ".", "_try_resolve_sam_resource_id_refs", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._traverse
Driver method that performs the actual traversal of input and calls the appropriate `resolver_method` when to perform the resolution. :param input: Any primitive type (dict, array, string etc) whose value might contain an intrinsic function :param resolution_data: Data that will help with reso...
samtranslator/intrinsics/resolver.py
def _traverse(self, input, resolution_data, resolver_method): """ Driver method that performs the actual traversal of input and calls the appropriate `resolver_method` when to perform the resolution. :param input: Any primitive type (dict, array, string etc) whose value might contain a...
def _traverse(self, input, resolution_data, resolver_method): """ Driver method that performs the actual traversal of input and calls the appropriate `resolver_method` when to perform the resolution. :param input: Any primitive type (dict, array, string etc) whose value might contain a...
[ "Driver", "method", "that", "performs", "the", "actual", "traversal", "of", "input", "and", "calls", "the", "appropriate", "resolver_method", "when", "to", "perform", "the", "resolution", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L90-L132
[ "def", "_traverse", "(", "self", ",", "input", ",", "resolution_data", ",", "resolver_method", ")", ":", "# There is data to help with resolution. Skip the traversal altogether", "if", "len", "(", "resolution_data", ")", "==", "0", ":", "return", "input", "#", "# Trav...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._traverse_dict
Traverse a dictionary to resolve intrinsic functions on every value :param input_dict: Input dictionary to traverse :param resolution_data: Data that the `resolver_method` needs to operate :param resolver_method: Method that can actually resolve an intrinsic function, if it detects one ...
samtranslator/intrinsics/resolver.py
def _traverse_dict(self, input_dict, resolution_data, resolver_method): """ Traverse a dictionary to resolve intrinsic functions on every value :param input_dict: Input dictionary to traverse :param resolution_data: Data that the `resolver_method` needs to operate :param resolve...
def _traverse_dict(self, input_dict, resolution_data, resolver_method): """ Traverse a dictionary to resolve intrinsic functions on every value :param input_dict: Input dictionary to traverse :param resolution_data: Data that the `resolver_method` needs to operate :param resolve...
[ "Traverse", "a", "dictionary", "to", "resolve", "intrinsic", "functions", "on", "every", "value" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L134-L146
[ "def", "_traverse_dict", "(", "self", ",", "input_dict", ",", "resolution_data", ",", "resolver_method", ")", ":", "for", "key", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "input_dict", "[", "key", "]", "=", "self", ".", "_traverse", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._traverse_list
Traverse a list to resolve intrinsic functions on every element :param input_list: List of input :param resolution_data: Data that the `resolver_method` needs to operate :param resolver_method: Method that can actually resolve an intrinsic function, if it detects one :return: Modified l...
samtranslator/intrinsics/resolver.py
def _traverse_list(self, input_list, resolution_data, resolver_method): """ Traverse a list to resolve intrinsic functions on every element :param input_list: List of input :param resolution_data: Data that the `resolver_method` needs to operate :param resolver_method: Method th...
def _traverse_list(self, input_list, resolution_data, resolver_method): """ Traverse a list to resolve intrinsic functions on every element :param input_list: List of input :param resolution_data: Data that the `resolver_method` needs to operate :param resolver_method: Method th...
[ "Traverse", "a", "list", "to", "resolve", "intrinsic", "functions", "on", "every", "element" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L148-L160
[ "def", "_traverse_list", "(", "self", ",", "input_list", ",", "resolution_data", ",", "resolver_method", ")", ":", "for", "index", ",", "value", "in", "enumerate", "(", "input_list", ")", ":", "input_list", "[", "index", "]", "=", "self", ".", "_traverse", ...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._try_resolve_parameter_refs
Try to resolve parameter references on the given input object. The object could be of any type. If the input is not in the format used by intrinsics (ie. dictionary with one key), input is returned unmodified. If the single key in dictionary is one of the supported intrinsic function types, go a...
samtranslator/intrinsics/resolver.py
def _try_resolve_parameter_refs(self, input, parameters): """ Try to resolve parameter references on the given input object. The object could be of any type. If the input is not in the format used by intrinsics (ie. dictionary with one key), input is returned unmodified. If the single ke...
def _try_resolve_parameter_refs(self, input, parameters): """ Try to resolve parameter references on the given input object. The object could be of any type. If the input is not in the format used by intrinsics (ie. dictionary with one key), input is returned unmodified. If the single ke...
[ "Try", "to", "resolve", "parameter", "references", "on", "the", "given", "input", "object", ".", "The", "object", "could", "be", "of", "any", "type", ".", "If", "the", "input", "is", "not", "in", "the", "format", "used", "by", "intrinsics", "(", "ie", ...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L162-L177
[ "def", "_try_resolve_parameter_refs", "(", "self", ",", "input", ",", "parameters", ")", ":", "if", "not", "self", ".", "_is_intrinsic_dict", "(", "input", ")", ":", "return", "input", "function_type", "=", "list", "(", "input", ".", "keys", "(", ")", ")",...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._try_resolve_sam_resource_refs
Try to resolve SAM resource references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input unmodified. :param dict input: Dictionary that may represent an intrinsic funct...
samtranslator/intrinsics/resolver.py
def _try_resolve_sam_resource_refs(self, input, supported_resource_refs): """ Try to resolve SAM resource references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input ...
def _try_resolve_sam_resource_refs(self, input, supported_resource_refs): """ Try to resolve SAM resource references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input ...
[ "Try", "to", "resolve", "SAM", "resource", "references", "on", "the", "given", "template", ".", "If", "the", "given", "object", "looks", "like", "one", "of", "the", "supported", "intrinsics", "it", "calls", "the", "appropriate", "resolution", "on", "it", "."...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L179-L194
[ "def", "_try_resolve_sam_resource_refs", "(", "self", ",", "input", ",", "supported_resource_refs", ")", ":", "if", "not", "self", ".", "_is_intrinsic_dict", "(", "input", ")", ":", "return", "input", "function_type", "=", "list", "(", "input", ".", "keys", "(...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._try_resolve_sam_resource_id_refs
Try to resolve SAM resource id references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input unmodified. :param dict input: Dictionary that may represent an intrinsic fu...
samtranslator/intrinsics/resolver.py
def _try_resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): """ Try to resolve SAM resource id references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original...
def _try_resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): """ Try to resolve SAM resource id references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original...
[ "Try", "to", "resolve", "SAM", "resource", "id", "references", "on", "the", "given", "template", ".", "If", "the", "given", "object", "looks", "like", "one", "of", "the", "supported", "intrinsics", "it", "calls", "the", "appropriate", "resolution", "on", "it...
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L196-L210
[ "def", "_try_resolve_sam_resource_id_refs", "(", "self", ",", "input", ",", "supported_resource_id_refs", ")", ":", "if", "not", "self", ".", "_is_intrinsic_dict", "(", "input", ")", ":", "return", "input", "function_type", "=", "list", "(", "input", ".", "keys"...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
IntrinsicsResolver._is_intrinsic_dict
Can the input represent an intrinsic function in it? :param input: Object to be checked :return: True, if the input contains a supported intrinsic function. False otherwise
samtranslator/intrinsics/resolver.py
def _is_intrinsic_dict(self, input): """ Can the input represent an intrinsic function in it? :param input: Object to be checked :return: True, if the input contains a supported intrinsic function. False otherwise """ # All intrinsic functions are dictionaries with just...
def _is_intrinsic_dict(self, input): """ Can the input represent an intrinsic function in it? :param input: Object to be checked :return: True, if the input contains a supported intrinsic function. False otherwise """ # All intrinsic functions are dictionaries with just...
[ "Can", "the", "input", "represent", "an", "intrinsic", "function", "in", "it?" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L212-L222
[ "def", "_is_intrinsic_dict", "(", "self", ",", "input", ")", ":", "# All intrinsic functions are dictionaries with just one key", "return", "isinstance", "(", "input", ",", "dict", ")", "and", "len", "(", "input", ")", "==", "1", "and", "list", "(", "input", "."...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
CloudWatchLogs.to_cloudformation
Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to which this push event expands :rtype: list
samtranslator/model/eventsources/cloudwatchlogs.py
def to_cloudformation(self, **kwargs): """Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to ...
def to_cloudformation(self, **kwargs): """Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source corresponds. :param dict kwargs: no existing resources need to be modified :returns: a list of vanilla CloudFormation Resources, to ...
[ "Returns", "the", "CloudWatch", "Logs", "Subscription", "Filter", "and", "Lambda", "Permission", "to", "which", "this", "CloudWatch", "Logs", "event", "source", "corresponds", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/eventsources/cloudwatchlogs.py#L18-L36
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "source_ar...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
PolicyTemplatesProcessor.convert
Converts the given template to IAM-ready policy statement by substituting template parameters with the given values. :param template_name: Name of the template :param parameter_values: Values for all parameters of the template :return dict: Dictionary containing policy statement ...
samtranslator/policy_template_processor/processor.py
def convert(self, template_name, parameter_values): """ Converts the given template to IAM-ready policy statement by substituting template parameters with the given values. :param template_name: Name of the template :param parameter_values: Values for all parameters of the templ...
def convert(self, template_name, parameter_values): """ Converts the given template to IAM-ready policy statement by substituting template parameters with the given values. :param template_name: Name of the template :param parameter_values: Values for all parameters of the templ...
[ "Converts", "the", "given", "template", "to", "IAM", "-", "ready", "policy", "statement", "by", "substituting", "template", "parameters", "with", "the", "given", "values", "." ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/processor.py#L84-L100
[ "def", "convert", "(", "self", ",", "template_name", ",", "parameter_values", ")", ":", "if", "not", "self", ".", "has", "(", "template_name", ")", ":", "raise", "TemplateNotFoundException", "(", "template_name", ")", "template", "=", "self", ".", "get", "("...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
PolicyTemplatesProcessor._is_valid_templates_dict
Is this a valid policy template dictionary :param dict policy_templates_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing policy template :return: True, if it is valid. :raises ValueError: If the template dictionary doesn't match up ...
samtranslator/policy_template_processor/processor.py
def _is_valid_templates_dict(policy_templates_dict, schema=None): """ Is this a valid policy template dictionary :param dict policy_templates_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing policy template :return: True, if...
def _is_valid_templates_dict(policy_templates_dict, schema=None): """ Is this a valid policy template dictionary :param dict policy_templates_dict: Data to be validated :param dict schema: Optional, dictionary containing JSON Schema representing policy template :return: True, if...
[ "Is", "this", "a", "valid", "policy", "template", "dictionary" ]
awslabs/serverless-application-model
python
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/processor.py#L103-L122
[ "def", "_is_valid_templates_dict", "(", "policy_templates_dict", ",", "schema", "=", "None", ")", ":", "if", "not", "schema", ":", "schema", "=", "PolicyTemplatesProcessor", ".", "_read_schema", "(", ")", "try", ":", "jsonschema", ".", "validate", "(", "policy_t...
cccb0c96b5c91e53355ebc07e542467303a5eedd
train
RenderEngine.render_chart_to_file
Render a chart or page to local html files. :param chart: A Chart or Page object :param path: The destination file which the html code write to :param template_name: The name of template file.
pyecharts/render/engine.py
def render_chart_to_file(self, template_name: str, chart: Any, path: str): """ Render a chart or page to local html files. :param chart: A Chart or Page object :param path: The destination file which the html code write to :param template_name: The name of template file. ...
def render_chart_to_file(self, template_name: str, chart: Any, path: str): """ Render a chart or page to local html files. :param chart: A Chart or Page object :param path: The destination file which the html code write to :param template_name: The name of template file. ...
[ "Render", "a", "chart", "or", "page", "to", "local", "html", "files", "." ]
pyecharts/pyecharts
python
https://github.com/pyecharts/pyecharts/blob/02050acb0e94bb9453b88a25028de7a0ce23f125/pyecharts/render/engine.py#L36-L46
[ "def", "render_chart_to_file", "(", "self", ",", "template_name", ":", "str", ",", "chart", ":", "Any", ",", "path", ":", "str", ")", ":", "tpl", "=", "self", ".", "env", ".", "get_template", "(", "template_name", ")", "html", "=", "tpl", ".", "render"...
02050acb0e94bb9453b88a25028de7a0ce23f125
train
decode_base64
Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string.
pyecharts/render/snapshot.py
def decode_base64(data: str) -> bytes: """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ missing_padding = len(data) % 4 if missing_padding != 0: data += "=" * (4 - missing_padding) return base64.decodeb...
def decode_base64(data: str) -> bytes: """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ missing_padding = len(data) % 4 if missing_padding != 0: data += "=" * (4 - missing_padding) return base64.decodeb...
[ "Decode", "base64", "padding", "being", "optional", "." ]
pyecharts/pyecharts
python
https://github.com/pyecharts/pyecharts/blob/02050acb0e94bb9453b88a25028de7a0ce23f125/pyecharts/render/snapshot.py#L58-L67
[ "def", "decode_base64", "(", "data", ":", "str", ")", "->", "bytes", ":", "missing_padding", "=", "len", "(", "data", ")", "%", "4", "if", "missing_padding", "!=", "0", ":", "data", "+=", "\"=\"", "*", "(", "4", "-", "missing_padding", ")", "return", ...
02050acb0e94bb9453b88a25028de7a0ce23f125
train
Tree._set_collapse_interval
间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。 :param data: 节点数据 :param interval: 指定间隔
pyecharts/charts/basic_charts/tree.py
def _set_collapse_interval(data, interval): """ 间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。 :param data: 节点数据 :param interval: 指定间隔 """ if interval <= 0: return data if data and isinstance(data, list): for d in data: children = d...
def _set_collapse_interval(data, interval): """ 间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。 :param data: 节点数据 :param interval: 指定间隔 """ if interval <= 0: return data if data and isinstance(data, list): for d in data: children = d...
[ "间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。", ":", "param", "data", ":", "节点数据", ":", "param", "interval", ":", "指定间隔" ]
pyecharts/pyecharts
python
https://github.com/pyecharts/pyecharts/blob/02050acb0e94bb9453b88a25028de7a0ce23f125/pyecharts/charts/basic_charts/tree.py#L19-L35
[ "def", "_set_collapse_interval", "(", "data", ",", "interval", ")", ":", "if", "interval", "<=", "0", ":", "return", "data", "if", "data", "and", "isinstance", "(", "data", ",", "list", ")", ":", "for", "d", "in", "data", ":", "children", "=", "d", "...
02050acb0e94bb9453b88a25028de7a0ce23f125
train
parse_pin
Parses a string and returns a pin-num.
ports/nrf/boards/make-pins.py
def parse_pin(name_str): """Parses a string and returns a pin-num.""" if len(name_str) < 1: raise ValueError("Expecting pin name to be at least 4 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") pin_str = name_str[1:].split('/')[0] if not pin...
def parse_pin(name_str): """Parses a string and returns a pin-num.""" if len(name_str) < 1: raise ValueError("Expecting pin name to be at least 4 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") pin_str = name_str[1:].split('/')[0] if not pin...
[ "Parses", "a", "string", "and", "returns", "a", "pin", "-", "num", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/nrf/boards/make-pins.py#L14-L23
[ "def", "parse_pin", "(", "name_str", ")", ":", "if", "len", "(", "name_str", ")", "<", "1", ":", "raise", "ValueError", "(", "\"Expecting pin name to be at least 4 charcters.\"", ")", "if", "name_str", "[", "0", "]", "!=", "'P'", ":", "raise", "ValueError", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
AlternateFunction.ptr
Returns the numbered function (i.e. USART6) for this AF.
ports/nrf/boards/make-pins.py
def ptr(self): """Returns the numbered function (i.e. USART6) for this AF.""" if self.fn_num is None: return self.func return '{:s}{:d}'.format(self.func, self.fn_num)
def ptr(self): """Returns the numbered function (i.e. USART6) for this AF.""" if self.fn_num is None: return self.func return '{:s}{:d}'.format(self.func, self.fn_num)
[ "Returns", "the", "numbered", "function", "(", "i", ".", "e", ".", "USART6", ")", "for", "this", "AF", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/nrf/boards/make-pins.py#L61-L65
[ "def", "ptr", "(", "self", ")", ":", "if", "self", ".", "fn_num", "is", "None", ":", "return", "self", ".", "func", "return", "'{:s}{:d}'", ".", "format", "(", "self", ".", "func", ",", "self", ".", "fn_num", ")" ]
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
AlternateFunction.print
Prints the C representation of this AF.
ports/nrf/boards/make-pins.py
def print(self): """Prints the C representation of this AF.""" if self.supported: print(' AF', end='') else: print(' //', end='') fn_num = self.fn_num if fn_num is None: fn_num = 0 print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}...
def print(self): """Prints the C representation of this AF.""" if self.supported: print(' AF', end='') else: print(' //', end='') fn_num = self.fn_num if fn_num is None: fn_num = 0 print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}...
[ "Prints", "the", "C", "representation", "of", "this", "AF", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/nrf/boards/make-pins.py#L70-L80
[ "def", "print", "(", "self", ")", ":", "if", "self", ".", "supported", ":", "print", "(", "' AF'", ",", "end", "=", "''", ")", "else", ":", "print", "(", "' //'", ",", "end", "=", "''", ")", "fn_num", "=", "self", ".", "fn_num", "if", "fn_num",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
run_loop
Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects
examples/switch.py
def run_loop(leds=all_leds): """ Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects """ print('Loop started.\nPress Ctrl+C to break out of the loop.') while 1: try: if switch(): [led.on() for led...
def run_loop(leds=all_leds): """ Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects """ print('Loop started.\nPress Ctrl+C to break out of the loop.') while 1: try: if switch(): [led.on() for led...
[ "Start", "the", "loop", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/examples/switch.py#L27-L42
[ "def", "run_loop", "(", "leds", "=", "all_leds", ")", ":", "print", "(", "'Loop started.\\nPress Ctrl+C to break out of the loop.'", ")", "while", "1", ":", "try", ":", "if", "switch", "(", ")", ":", "[", "led", ".", "on", "(", ")", "for", "led", "in", "...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
find_c_file
Search vpaths for the c file that matches the provided object_file. :param str obj_file: object file to find the matching c file for :param List[str] vpath: List of base paths, similar to gcc vpath :return: str path to c file or None
py/makemoduledefs.py
def find_c_file(obj_file, vpath): """ Search vpaths for the c file that matches the provided object_file. :param str obj_file: object file to find the matching c file for :param List[str] vpath: List of base paths, similar to gcc vpath :return: str path to c file or None """ c_file = None r...
def find_c_file(obj_file, vpath): """ Search vpaths for the c file that matches the provided object_file. :param str obj_file: object file to find the matching c file for :param List[str] vpath: List of base paths, similar to gcc vpath :return: str path to c file or None """ c_file = None r...
[ "Search", "vpaths", "for", "the", "c", "file", "that", "matches", "the", "provided", "object_file", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/py/makemoduledefs.py#L22-L38
[ "def", "find_c_file", "(", "obj_file", ",", "vpath", ")", ":", "c_file", "=", "None", "relative_c_file", "=", "os", ".", "path", ".", "splitext", "(", "obj_file", ")", "[", "0", "]", "+", "\".c\"", "relative_c_file", "=", "relative_c_file", ".", "lstrip", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
find_module_registrations
Find any MP_REGISTER_MODULE definitions in the provided c file. :param str c_file: path to c file to check :return: List[(module_name, obj_module, enabled_define)]
py/makemoduledefs.py
def find_module_registrations(c_file): """ Find any MP_REGISTER_MODULE definitions in the provided c file. :param str c_file: path to c file to check :return: List[(module_name, obj_module, enabled_define)] """ global pattern if c_file is None: # No c file to match the object file, ski...
def find_module_registrations(c_file): """ Find any MP_REGISTER_MODULE definitions in the provided c file. :param str c_file: path to c file to check :return: List[(module_name, obj_module, enabled_define)] """ global pattern if c_file is None: # No c file to match the object file, ski...
[ "Find", "any", "MP_REGISTER_MODULE", "definitions", "in", "the", "provided", "c", "file", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/py/makemoduledefs.py#L41-L54
[ "def", "find_module_registrations", "(", "c_file", ")", ":", "global", "pattern", "if", "c_file", "is", "None", ":", "# No c file to match the object file, skip", "return", "set", "(", ")", "with", "io", ".", "open", "(", "c_file", ",", "encoding", "=", "'utf-8'...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
generate_module_table_header
Generate header with module table entries for builtin modules. :param List[(module_name, obj_module, enabled_define)] modules: module defs :return: None
py/makemoduledefs.py
def generate_module_table_header(modules): """ Generate header with module table entries for builtin modules. :param List[(module_name, obj_module, enabled_define)] modules: module defs :return: None """ # Print header file for all external modules. mod_defs = [] print("// Automatically ge...
def generate_module_table_header(modules): """ Generate header with module table entries for builtin modules. :param List[(module_name, obj_module, enabled_define)] modules: module defs :return: None """ # Print header file for all external modules. mod_defs = [] print("// Automatically ge...
[ "Generate", "header", "with", "module", "table", "entries", "for", "builtin", "modules", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/py/makemoduledefs.py#L57-L86
[ "def", "generate_module_table_header", "(", "modules", ")", ":", "# Print header file for all external modules.", "mod_defs", "=", "[", "]", "print", "(", "\"// Automatically generated by makemoduledefs.py.\\n\"", ")", "for", "module_name", ",", "obj_module", ",", "enabled_de...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
readfiles
Reads test files
tools/gen-cpydiff.py
def readfiles(): """ Reads test files """ tests = list(filter(lambda x: x.endswith('.py'), os.listdir(TESTPATH))) tests.sort() files = [] for test in tests: text = open(TESTPATH + test, 'r').read() try: class_, desc, cause, workaround, code = [x.rstrip() for x in \ ...
def readfiles(): """ Reads test files """ tests = list(filter(lambda x: x.endswith('.py'), os.listdir(TESTPATH))) tests.sort() files = [] for test in tests: text = open(TESTPATH + test, 'r').read() try: class_, desc, cause, workaround, code = [x.rstrip() for x in \ ...
[ "Reads", "test", "files" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L63-L80
[ "def", "readfiles", "(", ")", ":", "tests", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "endswith", "(", "'.py'", ")", ",", "os", ".", "listdir", "(", "TESTPATH", ")", ")", ")", "tests", ".", "sort", "(", ")", "files", "=", "...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
uimports
converts CPython module names into MicroPython equivalents
tools/gen-cpydiff.py
def uimports(code): """ converts CPython module names into MicroPython equivalents """ for uimport in UIMPORTLIST: uimport = bytes(uimport, 'utf8') code = code.replace(uimport, b'u' + uimport) return code
def uimports(code): """ converts CPython module names into MicroPython equivalents """ for uimport in UIMPORTLIST: uimport = bytes(uimport, 'utf8') code = code.replace(uimport, b'u' + uimport) return code
[ "converts", "CPython", "module", "names", "into", "MicroPython", "equivalents" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L82-L87
[ "def", "uimports", "(", "code", ")", ":", "for", "uimport", "in", "UIMPORTLIST", ":", "uimport", "=", "bytes", "(", "uimport", ",", "'utf8'", ")", "code", "=", "code", ".", "replace", "(", "uimport", ",", "b'u'", "+", "uimport", ")", "return", "code" ]
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
indent
indents paragraphs of text for rst formatting
tools/gen-cpydiff.py
def indent(block, spaces): """ indents paragraphs of text for rst formatting """ new_block = '' for line in block.split('\n'): new_block += spaces + line + '\n' return new_block
def indent(block, spaces): """ indents paragraphs of text for rst formatting """ new_block = '' for line in block.split('\n'): new_block += spaces + line + '\n' return new_block
[ "indents", "paragraphs", "of", "text", "for", "rst", "formatting" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L116-L121
[ "def", "indent", "(", "block", ",", "spaces", ")", ":", "new_block", "=", "''", "for", "line", "in", "block", ".", "split", "(", "'\\n'", ")", ":", "new_block", "+=", "spaces", "+", "line", "+", "'\\n'", "return", "new_block" ]
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
gen_table
creates a table given any set of columns
tools/gen-cpydiff.py
def gen_table(contents): """ creates a table given any set of columns """ xlengths = [] ylengths = [] for column in contents: col_len = 0 for entry in column: lines = entry.split('\n') for line in lines: col_len = max(len(line) + 2, col_len) ...
def gen_table(contents): """ creates a table given any set of columns """ xlengths = [] ylengths = [] for column in contents: col_len = 0 for entry in column: lines = entry.split('\n') for line in lines: col_len = max(len(line) + 2, col_len) ...
[ "creates", "a", "table", "given", "any", "set", "of", "columns" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L123-L154
[ "def", "gen_table", "(", "contents", ")", ":", "xlengths", "=", "[", "]", "ylengths", "=", "[", "]", "for", "column", "in", "contents", ":", "col_len", "=", "0", "for", "entry", "in", "column", ":", "lines", "=", "entry", ".", "split", "(", "'\\n'", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
gen_rst
creates restructured text documents to display tests
tools/gen-cpydiff.py
def gen_rst(results): """ creates restructured text documents to display tests """ # make sure the destination directory exists try: os.mkdir(DOCPATH) except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: raise toctree = [] class_ = [] ...
def gen_rst(results): """ creates restructured text documents to display tests """ # make sure the destination directory exists try: os.mkdir(DOCPATH) except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: raise toctree = [] class_ = [] ...
[ "creates", "restructured", "text", "documents", "to", "display", "tests" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L156-L213
[ "def", "gen_rst", "(", "results", ")", ":", "# make sure the destination directory exists", "try", ":", "os", ".", "mkdir", "(", "DOCPATH", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "args", "[", "0", "]", "!=", "errno", ".", "EEXIST", "an...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
main
Main function
tools/gen-cpydiff.py
def main(): """ Main function """ # set search path so that test scripts find the test modules (and no other ones) os.environ['PYTHONPATH'] = TESTPATH os.environ['MICROPYPATH'] = TESTPATH files = readfiles() results = run_tests(files) gen_rst(results)
def main(): """ Main function """ # set search path so that test scripts find the test modules (and no other ones) os.environ['PYTHONPATH'] = TESTPATH os.environ['MICROPYPATH'] = TESTPATH files = readfiles() results = run_tests(files) gen_rst(results)
[ "Main", "function" ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/gen-cpydiff.py#L215-L224
[ "def", "main", "(", ")", ":", "# set search path so that test scripts find the test modules (and no other ones)", "os", ".", "environ", "[", "'PYTHONPATH'", "]", "=", "TESTPATH", "os", ".", "environ", "[", "'MICROPYPATH'", "]", "=", "TESTPATH", "files", "=", "readfile...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
init
Initializes the found DFU device so that we can program it.
tools/pydfu.py
def init(): """Initializes the found DFU device so that we can program it.""" global __dev, __cfg_descr devices = get_dfu_devices(idVendor=__VID, idProduct=__PID) if not devices: raise ValueError('No DFU device found') if len(devices) > 1: raise ValueError("Multiple DFU devices found...
def init(): """Initializes the found DFU device so that we can program it.""" global __dev, __cfg_descr devices = get_dfu_devices(idVendor=__VID, idProduct=__PID) if not devices: raise ValueError('No DFU device found') if len(devices) > 1: raise ValueError("Multiple DFU devices found...
[ "Initializes", "the", "found", "DFU", "device", "so", "that", "we", "can", "program", "it", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L92-L126
[ "def", "init", "(", ")", ":", "global", "__dev", ",", "__cfg_descr", "devices", "=", "get_dfu_devices", "(", "idVendor", "=", "__VID", ",", "idProduct", "=", "__PID", ")", "if", "not", "devices", ":", "raise", "ValueError", "(", "'No DFU device found'", ")",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
mass_erase
Performs a MASS erase (i.e. erases the entire device.
tools/pydfu.py
def mass_erase(): """Performs a MASS erase (i.e. erases the entire device.""" # Send DNLOAD with first byte=0x41 __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: ra...
def mass_erase(): """Performs a MASS erase (i.e. erases the entire device.""" # Send DNLOAD with first byte=0x41 __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: ra...
[ "Performs", "a", "MASS", "erase", "(", "i", ".", "e", ".", "erases", "the", "entire", "device", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L148-L160
[ "def", "mass_erase", "(", ")", ":", "# Send DNLOAD with first byte=0x41", "__dev", ".", "ctrl_transfer", "(", "0x21", ",", "__DFU_DNLOAD", ",", "0", ",", "__DFU_INTERFACE", ",", "\"\\x41\"", ",", "__TIMEOUT", ")", "# Execute last command", "if", "get_status", "(", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
page_erase
Erases a single page.
tools/pydfu.py
def page_erase(addr): """Erases a single page.""" if __verbose: print("Erasing page: 0x%x..." % (addr)) # Send DNLOAD with first byte=0x41 and page address buf = struct.pack("<BI", 0x41, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last co...
def page_erase(addr): """Erases a single page.""" if __verbose: print("Erasing page: 0x%x..." % (addr)) # Send DNLOAD with first byte=0x41 and page address buf = struct.pack("<BI", 0x41, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last co...
[ "Erases", "a", "single", "page", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L163-L179
[ "def", "page_erase", "(", "addr", ")", ":", "if", "__verbose", ":", "print", "(", "\"Erasing page: 0x%x...\"", "%", "(", "addr", ")", ")", "# Send DNLOAD with first byte=0x41 and page address", "buf", "=", "struct", ".", "pack", "(", "\"<BI\"", ",", "0x41", ",",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
set_address
Sets the address for the next operation.
tools/pydfu.py
def set_address(addr): """Sets the address for the next operation.""" # Send DNLOAD with first byte=0x21 and page address buf = struct.pack("<BI", 0x21, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DO...
def set_address(addr): """Sets the address for the next operation.""" # Send DNLOAD with first byte=0x21 and page address buf = struct.pack("<BI", 0x21, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DO...
[ "Sets", "the", "address", "for", "the", "next", "operation", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L182-L194
[ "def", "set_address", "(", "addr", ")", ":", "# Send DNLOAD with first byte=0x21 and page address", "buf", "=", "struct", ".", "pack", "(", "\"<BI\"", ",", "0x21", ",", "addr", ")", "__dev", ".", "ctrl_transfer", "(", "0x21", ",", "__DFU_DNLOAD", ",", "0", ","...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
write_memory
Writes a buffer into memory. This routine assumes that memory has already been erased.
tools/pydfu.py
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0): """Writes a buffer into memory. This routine assumes that memory has already been erased. """ xfer_count = 0 xfer_bytes = 0 xfer_total = len(buf) xfer_base = addr while xfer_bytes < xfer_total: if __v...
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0): """Writes a buffer into memory. This routine assumes that memory has already been erased. """ xfer_count = 0 xfer_bytes = 0 xfer_total = len(buf) xfer_base = addr while xfer_bytes < xfer_total: if __v...
[ "Writes", "a", "buffer", "into", "memory", ".", "This", "routine", "assumes", "that", "memory", "has", "already", "been", "erased", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L197-L233
[ "def", "write_memory", "(", "addr", ",", "buf", ",", "progress", "=", "None", ",", "progress_addr", "=", "0", ",", "progress_size", "=", "0", ")", ":", "xfer_count", "=", "0", "xfer_bytes", "=", "0", "xfer_total", "=", "len", "(", "buf", ")", "xfer_bas...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
write_page
Writes a single page. This routine assumes that memory has already been erased.
tools/pydfu.py
def write_page(buf, xfer_offset): """Writes a single page. This routine assumes that memory has already been erased. """ xfer_base = 0x08000000 # Set mem write address set_address(xfer_base+xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERF...
def write_page(buf, xfer_offset): """Writes a single page. This routine assumes that memory has already been erased. """ xfer_base = 0x08000000 # Set mem write address set_address(xfer_base+xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERF...
[ "Writes", "a", "single", "page", ".", "This", "routine", "assumes", "that", "memory", "has", "already", "been", "erased", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L236-L258
[ "def", "write_page", "(", "buf", ",", "xfer_offset", ")", ":", "xfer_base", "=", "0x08000000", "# Set mem write address", "set_address", "(", "xfer_base", "+", "xfer_offset", ")", "# Send DNLOAD with fw data", "__dev", ".", "ctrl_transfer", "(", "0x21", ",", "__DFU_...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
exit_dfu
Exit DFU mode, and start running the program.
tools/pydfu.py
def exit_dfu(): """Exit DFU mode, and start running the program.""" # set jump address set_address(0x08000000) # Send DNLOAD with 0 length to exit DFU __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT) try: # Execute last command ...
def exit_dfu(): """Exit DFU mode, and start running the program.""" # set jump address set_address(0x08000000) # Send DNLOAD with 0 length to exit DFU __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT) try: # Execute last command ...
[ "Exit", "DFU", "mode", "and", "start", "running", "the", "program", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L261-L279
[ "def", "exit_dfu", "(", ")", ":", "# set jump address", "set_address", "(", "0x08000000", ")", "# Send DNLOAD with 0 length to exit DFU", "__dev", ".", "ctrl_transfer", "(", "0x21", ",", "__DFU_DNLOAD", ",", "0", ",", "__DFU_INTERFACE", ",", "None", ",", "__TIMEOUT"...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
consume
Parses the struct defined by `fmt` from `data`, stores the parsed fields into a named tuple using `names`. Returns the named tuple, and the data with the struct stripped off.
tools/pydfu.py
def consume(fmt, data, names): """Parses the struct defined by `fmt` from `data`, stores the parsed fields into a named tuple using `names`. Returns the named tuple, and the data with the struct stripped off.""" size = struct.calcsize(fmt) return named(struct.unpack(fmt, data[:size]), names), data[s...
def consume(fmt, data, names): """Parses the struct defined by `fmt` from `data`, stores the parsed fields into a named tuple using `names`. Returns the named tuple, and the data with the struct stripped off.""" size = struct.calcsize(fmt) return named(struct.unpack(fmt, data[:size]), names), data[s...
[ "Parses", "the", "struct", "defined", "by", "fmt", "from", "data", "stores", "the", "parsed", "fields", "into", "a", "named", "tuple", "using", "names", ".", "Returns", "the", "named", "tuple", "and", "the", "data", "with", "the", "struct", "stripped", "of...
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L287-L292
[ "def", "consume", "(", "fmt", ",", "data", ",", "names", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "fmt", ")", "return", "named", "(", "struct", ".", "unpack", "(", "fmt", ",", "data", "[", ":", "size", "]", ")", ",", "names", ")", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
read_dfu_file
Reads a DFU file, and parses the individual elements from the file. Returns an array of elements. Each element is a dictionary with the following keys: num - The element index address - The address that the element data should be written to. size - The size of the element ddata. ...
tools/pydfu.py
def read_dfu_file(filename): """Reads a DFU file, and parses the individual elements from the file. Returns an array of elements. Each element is a dictionary with the following keys: num - The element index address - The address that the element data should be written to. size ...
def read_dfu_file(filename): """Reads a DFU file, and parses the individual elements from the file. Returns an array of elements. Each element is a dictionary with the following keys: num - The element index address - The address that the element data should be written to. size ...
[ "Reads", "a", "DFU", "file", "and", "parses", "the", "individual", "elements", "from", "the", "file", ".", "Returns", "an", "array", "of", "elements", ".", "Each", "element", "is", "a", "dictionary", "with", "the", "following", "keys", ":", "num", "-", "...
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L305-L398
[ "def", "read_dfu_file", "(", "filename", ")", ":", "print", "(", "\"File: {}\"", ".", "format", "(", "filename", ")", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fin", ":", "data", "=", "fin", ".", "read", "(", ")", "crc", "=", "...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
get_dfu_devices
Returns a list of USB device which are currently in DFU mode. Additional filters (like idProduct and idVendor) can be passed in to refine the search.
tools/pydfu.py
def get_dfu_devices(*args, **kwargs): """Returns a list of USB device which are currently in DFU mode. Additional filters (like idProduct and idVendor) can be passed in to refine the search. """ # convert to list for compatibility with newer pyusb return list(usb.core.find(*args, find_all=True, ...
def get_dfu_devices(*args, **kwargs): """Returns a list of USB device which are currently in DFU mode. Additional filters (like idProduct and idVendor) can be passed in to refine the search. """ # convert to list for compatibility with newer pyusb return list(usb.core.find(*args, find_all=True, ...
[ "Returns", "a", "list", "of", "USB", "device", "which", "are", "currently", "in", "DFU", "mode", ".", "Additional", "filters", "(", "like", "idProduct", "and", "idVendor", ")", "can", "be", "passed", "in", "to", "refine", "the", "search", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L413-L420
[ "def", "get_dfu_devices", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# convert to list for compatibility with newer pyusb", "return", "list", "(", "usb", ".", "core", ".", "find", "(", "*", "args", ",", "find_all", "=", "True", ",", "custom_match", ...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
get_memory_layout
Returns an array which identifies the memory layout. Each entry of the array will contain a dictionary with the following keys: addr - Address of this memory segment last_addr - Last address contained within the memory segment. size - size of the segment, in bytes num...
tools/pydfu.py
def get_memory_layout(device): """Returns an array which identifies the memory layout. Each entry of the array will contain a dictionary with the following keys: addr - Address of this memory segment last_addr - Last address contained within the memory segment. size - siz...
def get_memory_layout(device): """Returns an array which identifies the memory layout. Each entry of the array will contain a dictionary with the following keys: addr - Address of this memory segment last_addr - Last address contained within the memory segment. size - siz...
[ "Returns", "an", "array", "which", "identifies", "the", "memory", "layout", ".", "Each", "entry", "of", "the", "array", "will", "contain", "a", "dictionary", "with", "the", "following", "keys", ":", "addr", "-", "Address", "of", "this", "memory", "segment", ...
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L423-L455
[ "def", "get_memory_layout", "(", "device", ")", ":", "cfg", "=", "device", "[", "0", "]", "intf", "=", "cfg", "[", "(", "0", ",", "0", ")", "]", "mem_layout_str", "=", "get_string", "(", "device", ",", "intf", ".", "iInterface", ")", "mem_layout", "=...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
list_dfu_devices
Prints a lits of devices detected in DFU mode.
tools/pydfu.py
def list_dfu_devices(*args, **kwargs): """Prints a lits of devices detected in DFU mode.""" devices = get_dfu_devices(*args, **kwargs) if not devices: print("No DFU capable devices found") return for device in devices: print("Bus {} Device {:03d}: ID {:04x}:{:04x}" ...
def list_dfu_devices(*args, **kwargs): """Prints a lits of devices detected in DFU mode.""" devices = get_dfu_devices(*args, **kwargs) if not devices: print("No DFU capable devices found") return for device in devices: print("Bus {} Device {:03d}: ID {:04x}:{:04x}" ...
[ "Prints", "a", "lits", "of", "devices", "detected", "in", "DFU", "mode", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L458-L473
[ "def", "list_dfu_devices", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "devices", "=", "get_dfu_devices", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "devices", ":", "print", "(", "\"No DFU capable devices found\"", ")", "return",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
write_elements
Writes the indicated elements into the target memory, erasing as needed.
tools/pydfu.py
def write_elements(elements, mass_erase_used, progress=None): """Writes the indicated elements into the target memory, erasing as needed. """ mem_layout = get_memory_layout(__dev) for elem in elements: addr = elem['addr'] size = elem['size'] data = elem['data'] elem_...
def write_elements(elements, mass_erase_used, progress=None): """Writes the indicated elements into the target memory, erasing as needed. """ mem_layout = get_memory_layout(__dev) for elem in elements: addr = elem['addr'] size = elem['size'] data = elem['data'] elem_...
[ "Writes", "the", "indicated", "elements", "into", "the", "target", "memory", "erasing", "as", "needed", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L476-L510
[ "def", "write_elements", "(", "elements", ",", "mass_erase_used", ",", "progress", "=", "None", ")", ":", "mem_layout", "=", "get_memory_layout", "(", "__dev", ")", "for", "elem", "in", "elements", ":", "addr", "=", "elem", "[", "'addr'", "]", "size", "=",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
cli_progress
Prints a progress report suitable for use on the command line.
tools/pydfu.py
def cli_progress(addr, offset, size): """Prints a progress report suitable for use on the command line.""" width = 25 done = offset * width // size print("\r0x{:08x} {:7d} [{}{}] {:3d}% " .format(addr, size, '=' * done, ' ' * (width - done), offset * 100 // size), end="") ...
def cli_progress(addr, offset, size): """Prints a progress report suitable for use on the command line.""" width = 25 done = offset * width // size print("\r0x{:08x} {:7d} [{}{}] {:3d}% " .format(addr, size, '=' * done, ' ' * (width - done), offset * 100 // size), end="") ...
[ "Prints", "a", "progress", "report", "suitable", "for", "use", "on", "the", "command", "line", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L513-L525
[ "def", "cli_progress", "(", "addr", ",", "offset", ",", "size", ")", ":", "width", "=", "25", "done", "=", "offset", "*", "width", "//", "size", "print", "(", "\"\\r0x{:08x} {:7d} [{}{}] {:3d}% \"", ".", "format", "(", "addr", ",", "size", ",", "'='", "*...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
main
Test program for verifying this files functionality.
tools/pydfu.py
def main(): """Test program for verifying this files functionality.""" global __verbose # Parse CMD args parser = argparse.ArgumentParser(description='DFU Python Util') #parser.add_argument("path", help="file path") parser.add_argument( "-l", "--list", help="list available DFU de...
def main(): """Test program for verifying this files functionality.""" global __verbose # Parse CMD args parser = argparse.ArgumentParser(description='DFU Python Util') #parser.add_argument("path", help="file path") parser.add_argument( "-l", "--list", help="list available DFU de...
[ "Test", "program", "for", "verifying", "this", "files", "functionality", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/tools/pydfu.py#L528-L583
[ "def", "main", "(", ")", ":", "global", "__verbose", "# Parse CMD args", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'DFU Python Util'", ")", "#parser.add_argument(\"path\", help=\"file path\")", "parser", ".", "add_argument", "(", "\"-l\...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
parse_port_pin
Parses a string and returns a (port-num, pin-num) tuple.
ports/stm32/boards/make-pins.py
def parse_port_pin(name_str): """Parses a string and returns a (port-num, pin-num) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") if name_str[1] < 'A' or name...
def parse_port_pin(name_str): """Parses a string and returns a (port-num, pin-num) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") if name_str[1] < 'A' or name...
[ "Parses", "a", "string", "and", "returns", "a", "(", "port", "-", "num", "pin", "-", "num", ")", "tuple", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/stm32/boards/make-pins.py#L33-L45
[ "def", "parse_port_pin", "(", "name_str", ")", ":", "if", "len", "(", "name_str", ")", "<", "3", ":", "raise", "ValueError", "(", "\"Expecting pin name to be at least 3 charcters.\"", ")", "if", "name_str", "[", "0", "]", "!=", "'P'", ":", "raise", "ValueError...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
AlternateFunction.print
Prints the C representation of this AF.
ports/stm32/boards/make-pins.py
def print(self): """Prints the C representation of this AF.""" cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') else: print(' //', en...
def print(self): """Prints the C representation of this AF.""" cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') else: print(' //', en...
[ "Prints", "the", "C", "representation", "of", "this", "AF", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/stm32/boards/make-pins.py#L121-L135
[ "def", "print", "(", "self", ")", ":", "cond_var", "=", "None", "if", "self", ".", "supported", ":", "cond_var", "=", "conditional_var", "(", "'{}{}'", ".", "format", "(", "self", ".", "func", ",", "self", ".", "fn_num", ")", ")", "print_conditional_if",...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
parse_port_pin
Parses a string and returns a (port, gpio_bit) tuple.
ports/cc3200/boards/make-pins.py
def parse_port_pin(name_str): """Parses a string and returns a (port, gpio_bit) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin name to start with GP") if not name_str[2:].isdigit(...
def parse_port_pin(name_str): """Parses a string and returns a (port, gpio_bit) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin name to start with GP") if not name_str[2:].isdigit(...
[ "Parses", "a", "string", "and", "returns", "a", "(", "port", "gpio_bit", ")", "tuple", "." ]
micropython/micropython
python
https://github.com/micropython/micropython/blob/8031b7a25c21fb864fe9dd1fa40740030be66c11/ports/cc3200/boards/make-pins.py#L20-L30
[ "def", "parse_port_pin", "(", "name_str", ")", ":", "if", "len", "(", "name_str", ")", "<", "3", ":", "raise", "ValueError", "(", "\"Expecting pin name to be at least 3 characters\"", ")", "if", "name_str", "[", ":", "2", "]", "!=", "'GP'", ":", "raise", "Va...
8031b7a25c21fb864fe9dd1fa40740030be66c11
train
Backend.run_node
Simple run one operator and return the results. Args: outputs_info: a list of tuples, which contains the element type and shape of each output. First element of the tuple is the dtype, and the second element is the shape. More use case can be found in https://gith...
onnx/backend/base.py
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
[ "Simple", "run", "one", "operator", "and", "return", "the", "results", ".", "Args", ":", "outputs_info", ":", "a", "list", "of", "tuples", "which", "contains", "the", "element", "type", "and", "shape", "of", "each", "output", ".", "First", "element", "of",...
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/backend/base.py#L89-L111
[ "def", "run_node", "(", "cls", ",", "node", ",", "# type: NodeProto", "inputs", ",", "# type: Any", "device", "=", "'CPU'", ",", "# type: Text", "outputs_info", "=", "None", ",", "# type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]]", "*", "*", "kwargs", "#...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
load_external_data_for_tensor
Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data.
onnx/external_data_helper.py
def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. """ if tensor.HasField("raw_data"): # already loaded ...
def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. """ if tensor.HasField("raw_data"): # already loaded ...
[ "Load", "data", "from", "an", "external", "file", "for", "tensor", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L32-L54
[ "def", "load_external_data_for_tensor", "(", "tensor", ",", "base_dir", ")", ":", "# type: (TensorProto, Text) -> None", "if", "tensor", ".", "HasField", "(", "\"raw_data\"", ")", ":", "# already loaded", "return", "info", "=", "ExternalDataInfo", "(", "tensor", ")", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
load_external_data_for_model
Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data
onnx/external_data_helper.py
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None """ Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data """ for tensor in _get_all_tensors(model): if uses_external...
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None """ Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data """ for tensor in _get_all_tensors(model): if uses_external...
[ "Loads", "external", "tensors", "into", "model" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L57-L67
[ "def", "load_external_data_for_model", "(", "model", ",", "base_dir", ")", ":", "# type: (ModelProto, Text) -> None", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "load_external_data_for_tensor",...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
convert_model_to_external_data
call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be converted. all_tensors_to_one_file: If true, save all tensors to one external file specified by location. If false, save ...
onnx/external_data_helper.py
def convert_model_to_external_data(model, all_tensors_to_one_file=True, location=None): # type: (ModelProto, bool, Optional[Text]) -> None """ call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be...
def convert_model_to_external_data(model, all_tensors_to_one_file=True, location=None): # type: (ModelProto, bool, Optional[Text]) -> None """ call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be...
[ "call", "to", "set", "all", "tensors", "as", "external", "data", ".", "save_model", "saves", "all", "the", "tensors", "data", "as", "external", "data", "after", "calling", "this", "function", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L92-L111
[ "def", "convert_model_to_external_data", "(", "model", ",", "all_tensors_to_one_file", "=", "True", ",", "location", "=", "None", ")", ":", "# type: (ModelProto, bool, Optional[Text]) -> None", "if", "all_tensors_to_one_file", ":", "file_name", "=", "Text", "(", "uuid", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
convert_model_from_external_data
call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted.
onnx/external_data_helper.py
def convert_model_from_external_data(model): # type: (ModelProto) -> None """ call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted. """ for tensor in _get_all_tensors(model): ...
def convert_model_from_external_data(model): # type: (ModelProto) -> None """ call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted. """ for tensor in _get_all_tensors(model): ...
[ "call", "to", "set", "all", "tensors", "data", "as", "embedded", "data", ".", "save_model", "saves", "all", "the", "tensors", "data", "as", "embedded", "data", "after", "calling", "this", "function", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L114-L125
[ "def", "convert_model_from_external_data", "(", "model", ")", ":", "# type: (ModelProto) -> None", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "if", "not", "tensor", ".", "HasField", "(", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
save_external_data
Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored
onnx/external_data_helper.py
def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None """ Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored ""...
def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None """ Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored ""...
[ "Write", "tensor", "data", "to", "an", "external", "file", "according", "to", "information", "in", "the", "external_data", "field", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L128-L159
[ "def", "save_external_data", "(", "tensor", ",", "base_path", ")", ":", "# type: (TensorProto, Text) -> None", "info", "=", "ExternalDataInfo", "(", "tensor", ")", "external_data_file_path", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "info", ".", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
_get_attribute_tensors
Create an iterator of tensors from node attributes of an ONNX model.
onnx/external_data_helper.py
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield ...
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield ...
[ "Create", "an", "iterator", "of", "tensors", "from", "node", "attributes", "of", "an", "ONNX", "model", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L174-L181
[ "def", "_get_attribute_tensors", "(", "onnx_model_proto", ")", ":", "# type: (ModelProto) -> Iterable[TensorProto]", "for", "node", "in", "onnx_model_proto", ".", "graph", ".", "node", ":", "for", "attribute", "in", "node", ".", "attribute", ":", "if", "attribute", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
remove_external_data_field
Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed
onnx/external_data_helper.py
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be remove...
[ "Remove", "a", "field", "from", "a", "Tensor", "s", "external_data", "key", "-", "value", "store", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L197-L209
[ "def", "remove_external_data_field", "(", "tensor", ",", "field_key", ")", ":", "# type: (TensorProto, Text) -> None", "for", "(", "i", ",", "field", ")", "in", "enumerate", "(", "tensor", ".", "external_data", ")", ":", "if", "field", ".", "key", "==", "field...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
write_external_data_tensors
Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tensors to serialize. filepath: System path to the directory which should be treated as base path for ext...
onnx/external_data_helper.py
def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto """ Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tenso...
def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto """ Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tenso...
[ "Write", "external", "data", "of", "all", "tensors", "to", "files", "on", "disk", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/external_data_helper.py#L212-L230
[ "def", "write_external_data_tensors", "(", "model", ",", "filepath", ")", ":", "# type: (ModelProto, Text) -> ModelProto", "for", "tensor", "in", "_get_all_tensors", "(", "model", ")", ":", "if", "uses_external_data", "(", "tensor", ")", ":", "save_external_data", "("...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
PkgWriter._import
Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional"
tools/protoc-gen-mypy.py
def _import(self, path, name): # type: (Text, Text) -> Text """Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" """ imp = path.replace('/', '.') self.imports[imp].add(name) return name
def _import(self, path, name): # type: (Text, Text) -> Text """Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" """ imp = path.replace('/', '.') self.imports[imp].add(name) return name
[ "Imports", "a", "stdlib", "path", "and", "returns", "a", "handle", "to", "it", "eg", ".", "self", ".", "_import", "(", "typing", "Optional", ")", "-", ">", "Optional" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/tools/protoc-gen-mypy.py#L74-L81
[ "def", "_import", "(", "self", ",", "path", ",", "name", ")", ":", "# type: (Text, Text) -> Text", "imp", "=", "path", ".", "replace", "(", "'/'", ",", "'.'", ")", "self", ".", "imports", "[", "imp", "]", ".", "add", "(", "name", ")", "return", "name...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
PkgWriter._import_message
Import a referenced message and return a handle
tools/protoc-gen-mypy.py
def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return ...
def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return ...
[ "Import", "a", "referenced", "message", "and", "return", "a", "handle" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/tools/protoc-gen-mypy.py#L83-L112
[ "def", "_import_message", "(", "self", ",", "type_name", ")", ":", "# type: (d.FieldDescriptorProto) -> Text", "name", "=", "cast", "(", "Text", ",", "type_name", ")", "if", "name", "[", "0", "]", "==", "'.'", "and", "name", "[", "1", "]", ".", "isupper", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
mypy_type_check.run
Run command.
setup.py
def run(self): """Run command.""" onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
def run(self): """Run command.""" onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
[ "Run", "command", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/setup.py#L252-L256
[ "def", "run", "(", "self", ")", ":", "onnx_script", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "\...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
make_node
Construct a NodeProto. Arguments: op_type (string): The name of the operator to construct inputs (list of string): list of input names outputs (list of string): list of output names name (string, default None): optional unique identifier for NodeProto doc_string (string, def...
onnx/helper.py
def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **kwargs # type: Any ): # type: (...) -> NodeP...
def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **kwargs # type: Any ): # type: (...) -> NodeP...
[ "Construct", "a", "NodeProto", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L20-L57
[ "def", "make_node", "(", "op_type", ",", "# type: Text", "inputs", ",", "# type: Sequence[Text]", "outputs", ",", "# type: Sequence[Text]", "name", "=", "None", ",", "# type: Optional[Text]", "doc_string", "=", "None", ",", "# type: Optional[Text]", "domain", "=", "No...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
make_operatorsetid
Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id
onnx/helper.py
def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id """ operatorsetid =...
def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id """ operatorsetid =...
[ "Construct", "an", "OperatorSetIdProto", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L60-L73
[ "def", "make_operatorsetid", "(", "domain", ",", "# type: Text", "version", ",", "# type: int", ")", ":", "# type: (...) -> OperatorSetIdProto", "operatorsetid", "=", "OperatorSetIdProto", "(", ")", "operatorsetid", ".", "domain", "=", "domain", "operatorsetid", ".", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
_to_bytes_or_false
An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('utf-8') - Otherwise, return False
onnx/helper.py
def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicod...
def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicod...
[ "An", "internal", "graph", "to", "convert", "the", "input", "to", "a", "bytes", "or", "to", "False", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L179-L194
[ "def", "_to_bytes_or_false", "(", "val", ")", ":", "# type: (Union[Text, bytes]) -> Union[bytes, bool]", "if", "isinstance", "(", "val", ",", "bytes", ")", ":", "return", "val", "else", ":", "try", ":", "return", "val", ".", "encode", "(", "'utf-8'", ")", "exc...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
make_attribute
Makes an AttributeProto based on the value type.
onnx/helper.py
def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_strin...
def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_strin...
[ "Makes", "an", "AttributeProto", "based", "on", "the", "value", "type", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L197-L256
[ "def", "make_attribute", "(", "key", ",", "# type: Text", "value", ",", "# type: Any", "doc_string", "=", "None", "# type: Optional[Text]", ")", ":", "# type: (...) -> AttributeProto", "attr", "=", "AttributeProto", "(", ")", "attr", ".", "name", "=", "key", "if",...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
make_tensor_value_info
Makes a ValueInfoProto based on the data type and shape.
onnx/helper.py
def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based o...
def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueInfoProto """Makes a ValueInfoProto based o...
[ "Makes", "a", "ValueInfoProto", "based", "on", "the", "data", "type", "and", "shape", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L290-L340
[ "def", "make_tensor_value_info", "(", "name", ",", "# type: Text", "elem_type", ",", "# type: int", "shape", ",", "# type: Optional[Sequence[Union[Text, int]]]", "doc_string", "=", "\"\"", ",", "# type: Text", "shape_denotation", "=", "None", ",", "# type: Optional[List[Tex...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
strip_doc_string
Empties `doc_string` field on any nested protobuf messages
onnx/helper.py
def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': ...
def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': ...
[ "Empties", "doc_string", "field", "on", "any", "nested", "protobuf", "messages" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/helper.py#L538-L551
[ "def", "strip_doc_string", "(", "proto", ")", ":", "# type: (google.protobuf.message.Message) -> None", "assert", "isinstance", "(", "proto", ",", "google", ".", "protobuf", ".", "message", ".", "Message", ")", "for", "descriptor", "in", "proto", ".", "DESCRIPTOR", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
to_array
Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array.
onnx/numpy_helper.py
def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. """ if tensor.HasField("segment"): raise ValueError( "Currently not supporti...
def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. """ if tensor.HasField("segment"): raise ValueError( "Currently not supporti...
[ "Converts", "a", "tensor", "def", "object", "to", "a", "numpy", "array", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/numpy_helper.py#L24-L66
[ "def", "to_array", "(", "tensor", ")", ":", "# type: (TensorProto) -> np.ndarray[Any]", "if", "tensor", ".", "HasField", "(", "\"segment\"", ")", ":", "raise", "ValueError", "(", "\"Currently not supporting loading segments.\"", ")", "if", "tensor", ".", "data_type", ...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
from_array
Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def.
onnx/numpy_helper.py
def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto """Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def. """ tensor = TensorProto()...
def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto """Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def. """ tensor = TensorProto()...
[ "Converts", "a", "numpy", "array", "to", "a", "tensor", "def", "." ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/numpy_helper.py#L69-L117
[ "def", "from_array", "(", "arr", ",", "name", "=", "None", ")", ":", "# type: (np.ndarray[Any], Optional[Text]) -> TensorProto", "tensor", "=", "TensorProto", "(", ")", "tensor", ".", "dims", ".", "extend", "(", "arr", ".", "shape", ")", "if", "name", ":", "...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
_serialize
Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes
onnx/__init__.py
def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes ''' if isinstance(proto, bytes): return...
def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params proto is a in-memory proto, such as a ModelProto, TensorProto, etc @return Serialized proto in bytes ''' if isinstance(proto, bytes): return...
[ "Serialize", "a", "in", "-", "memory", "proto", "to", "bytes" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L53-L70
[ "def", "_serialize", "(", "proto", ")", ":", "# type: (Union[bytes, google.protobuf.message.Message]) -> bytes", "if", "isinstance", "(", "proto", ",", "bytes", ")", ":", "return", "proto", "elif", "hasattr", "(", "proto", ",", "'SerializeToString'", ")", "and", "ca...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4
train
_deserialize
Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s
onnx/__init__.py
def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto ''' Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s ''' if not isinstance(s, bytes): raise ValueError...
def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto ''' Parse bytes into a in-memory proto @params s is bytes containing serialized proto proto is a in-memory proto object @return The proto instance filled in by s ''' if not isinstance(s, bytes): raise ValueError...
[ "Parse", "bytes", "into", "a", "in", "-", "memory", "proto" ]
onnx/onnx
python
https://github.com/onnx/onnx/blob/2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4/onnx/__init__.py#L76-L99
[ "def", "_deserialize", "(", "s", ",", "proto", ")", ":", "# type: (bytes, _Proto) -> _Proto", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "raise", "ValueError", "(", "'Parameter s must be bytes, but got type: {}'", ".", "format", "(", "type", "(",...
2f7dc10f03a072526d94b6820cedbf2a1ec5a2c4