id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,700 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/_validators.py | get_file_path_validator | def get_file_path_validator(default_file_param=None):
""" Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'.
Allows another path-type parameter to be named which can supply a default filename. """
def validator(namespace):
if not hasattr(namespace, 'path'):
return
path = namespace.path
dir_name, file_name = os.path.split(path) if path else (None, '')
if default_file_param and '.' not in file_name:
dir_name = path
file_name = os.path.split(getattr(namespace, default_file_param))[1]
namespace.directory_name = dir_name
namespace.file_name = file_name
del namespace.path
return validator | python | def get_file_path_validator(default_file_param=None):
def validator(namespace):
if not hasattr(namespace, 'path'):
return
path = namespace.path
dir_name, file_name = os.path.split(path) if path else (None, '')
if default_file_param and '.' not in file_name:
dir_name = path
file_name = os.path.split(getattr(namespace, default_file_param))[1]
namespace.directory_name = dir_name
namespace.file_name = file_name
del namespace.path
return validator | [
"def",
"get_file_path_validator",
"(",
"default_file_param",
"=",
"None",
")",
":",
"def",
"validator",
"(",
"namespace",
")",
":",
"if",
"not",
"hasattr",
"(",
"namespace",
",",
"'path'",
")",
":",
"return",
"path",
"=",
"namespace",
".",
"path",
"dir_name"... | Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'.
Allows another path-type parameter to be named which can supply a default filename. | [
"Creates",
"a",
"namespace",
"validator",
"that",
"splits",
"out",
"path",
"into",
"directory_name",
"and",
"file_name",
".",
"Allows",
"another",
"path",
"-",
"type",
"parameter",
"to",
"be",
"named",
"which",
"can",
"supply",
"a",
"default",
"filename",
"."
... | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/_validators.py#L301-L319 |
228,701 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/_validators.py | ipv4_range_type | def ipv4_range_type(string):
""" Validates an IPv4 address or address range. """
import re
ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
if not re.match("^{}$".format(ip_format), string):
if not re.match("^{ip_format}-{ip_format}$".format(ip_format=ip_format), string):
raise ValueError
return string | python | def ipv4_range_type(string):
import re
ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
if not re.match("^{}$".format(ip_format), string):
if not re.match("^{ip_format}-{ip_format}$".format(ip_format=ip_format), string):
raise ValueError
return string | [
"def",
"ipv4_range_type",
"(",
"string",
")",
":",
"import",
"re",
"ip_format",
"=",
"r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'",
"if",
"not",
"re",
".",
"match",
"(",
"\"^{}$\"",
".",
"format",
"(",
"ip_format",
")",
",",
"string",
")",
":",
"if",
"not",
... | Validates an IPv4 address or address range. | [
"Validates",
"an",
"IPv4",
"address",
"or",
"address",
"range",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/_validators.py#L378-L385 |
228,702 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/_validators.py | resource_type_type | def resource_type_type(loader):
""" Returns a function which validates that resource types string contains only a combination of service,
container, and object. Their shorthand representations are s, c, and o. """
def impl(string):
t_resources = loader.get_models('common.models#ResourceTypes')
if set(string) - set("sco"):
raise ValueError
return t_resources(_str=''.join(set(string)))
return impl | python | def resource_type_type(loader):
def impl(string):
t_resources = loader.get_models('common.models#ResourceTypes')
if set(string) - set("sco"):
raise ValueError
return t_resources(_str=''.join(set(string)))
return impl | [
"def",
"resource_type_type",
"(",
"loader",
")",
":",
"def",
"impl",
"(",
"string",
")",
":",
"t_resources",
"=",
"loader",
".",
"get_models",
"(",
"'common.models#ResourceTypes'",
")",
"if",
"set",
"(",
"string",
")",
"-",
"set",
"(",
"\"sco\"",
")",
":",... | Returns a function which validates that resource types string contains only a combination of service,
container, and object. Their shorthand representations are s, c, and o. | [
"Returns",
"a",
"function",
"which",
"validates",
"that",
"resource",
"types",
"string",
"contains",
"only",
"a",
"combination",
"of",
"service",
"container",
"and",
"object",
".",
"Their",
"shorthand",
"representations",
"are",
"s",
"c",
"and",
"o",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/_validators.py#L388-L398 |
228,703 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/_validators.py | services_type | def services_type(loader):
""" Returns a function which validates that services string contains only a combination of blob, queue, table,
and file. Their shorthand representations are b, q, t, and f. """
def impl(string):
t_services = loader.get_models('common.models#Services')
if set(string) - set("bqtf"):
raise ValueError
return t_services(_str=''.join(set(string)))
return impl | python | def services_type(loader):
def impl(string):
t_services = loader.get_models('common.models#Services')
if set(string) - set("bqtf"):
raise ValueError
return t_services(_str=''.join(set(string)))
return impl | [
"def",
"services_type",
"(",
"loader",
")",
":",
"def",
"impl",
"(",
"string",
")",
":",
"t_services",
"=",
"loader",
".",
"get_models",
"(",
"'common.models#Services'",
")",
"if",
"set",
"(",
"string",
")",
"-",
"set",
"(",
"\"bqtf\"",
")",
":",
"raise"... | Returns a function which validates that services string contains only a combination of blob, queue, table,
and file. Their shorthand representations are b, q, t, and f. | [
"Returns",
"a",
"function",
"which",
"validates",
"that",
"services",
"string",
"contains",
"only",
"a",
"combination",
"of",
"blob",
"queue",
"table",
"and",
"file",
".",
"Their",
"shorthand",
"representations",
"are",
"b",
"q",
"t",
"and",
"f",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/_validators.py#L401-L411 |
228,704 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_validators.py | validate_k8s_version | def validate_k8s_version(namespace):
"""Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server
to use its default version."""
if namespace.kubernetes_version:
k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*)$')
found = k8s_release_regex.findall(namespace.kubernetes_version)
if found:
namespace.kubernetes_version = found[0]
else:
raise CLIError('--kubernetes-version should be the full version number, '
'such as "1.7.12" or "1.8.7"') | python | def validate_k8s_version(namespace):
if namespace.kubernetes_version:
k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*)$')
found = k8s_release_regex.findall(namespace.kubernetes_version)
if found:
namespace.kubernetes_version = found[0]
else:
raise CLIError('--kubernetes-version should be the full version number, '
'such as "1.7.12" or "1.8.7"') | [
"def",
"validate_k8s_version",
"(",
"namespace",
")",
":",
"if",
"namespace",
".",
"kubernetes_version",
":",
"k8s_release_regex",
"=",
"re",
".",
"compile",
"(",
"r'^[v|V]?(\\d+\\.\\d+\\.\\d+.*)$'",
")",
"found",
"=",
"k8s_release_regex",
".",
"findall",
"(",
"name... | Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server
to use its default version. | [
"Validates",
"a",
"string",
"as",
"a",
"possible",
"Kubernetes",
"version",
".",
"An",
"empty",
"string",
"is",
"also",
"valid",
"which",
"tells",
"the",
"server",
"to",
"use",
"its",
"default",
"version",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_validators.py#L58-L68 |
228,705 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_validators.py | validate_linux_host_name | def validate_linux_host_name(namespace):
"""Validates a string as a legal host name component.
This validation will also occur server-side in the ARM API, but that may take
a minute or two before the user sees it. So it's more user-friendly to validate
in the CLI pre-flight.
"""
# https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
rfc1123_regex = re.compile(r'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$') # pylint:disable=line-too-long
found = rfc1123_regex.findall(namespace.name)
if not found:
raise CLIError('--name cannot exceed 63 characters and can only contain '
'letters, numbers, or dashes (-).') | python | def validate_linux_host_name(namespace):
# https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
rfc1123_regex = re.compile(r'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$') # pylint:disable=line-too-long
found = rfc1123_regex.findall(namespace.name)
if not found:
raise CLIError('--name cannot exceed 63 characters and can only contain '
'letters, numbers, or dashes (-).') | [
"def",
"validate_linux_host_name",
"(",
"namespace",
")",
":",
"# https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address",
"rfc1123_regex",
"=",
"re",
".",
"compile",
"(",
"r'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9... | Validates a string as a legal host name component.
This validation will also occur server-side in the ARM API, but that may take
a minute or two before the user sees it. So it's more user-friendly to validate
in the CLI pre-flight. | [
"Validates",
"a",
"string",
"as",
"a",
"legal",
"host",
"name",
"component",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_validators.py#L71-L83 |
228,706 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_validators.py | validate_max_pods | def validate_max_pods(namespace):
"""Validates that max_pods is set to a reasonable minimum number."""
# kube-proxy and kube-svc reside each nodes,
# 2 kube-proxy pods, 1 azureproxy/heapster/dashboard/tunnelfront are in kube-system
minimum_pods_required = ceil((namespace.node_count * 2 + 6 + 1) / namespace.node_count)
if namespace.max_pods != 0 and namespace.max_pods < minimum_pods_required:
raise CLIError('--max-pods must be at least {} for a managed Kubernetes cluster to function.'
.format(minimum_pods_required)) | python | def validate_max_pods(namespace):
# kube-proxy and kube-svc reside each nodes,
# 2 kube-proxy pods, 1 azureproxy/heapster/dashboard/tunnelfront are in kube-system
minimum_pods_required = ceil((namespace.node_count * 2 + 6 + 1) / namespace.node_count)
if namespace.max_pods != 0 and namespace.max_pods < minimum_pods_required:
raise CLIError('--max-pods must be at least {} for a managed Kubernetes cluster to function.'
.format(minimum_pods_required)) | [
"def",
"validate_max_pods",
"(",
"namespace",
")",
":",
"# kube-proxy and kube-svc reside each nodes,",
"# 2 kube-proxy pods, 1 azureproxy/heapster/dashboard/tunnelfront are in kube-system",
"minimum_pods_required",
"=",
"ceil",
"(",
"(",
"namespace",
".",
"node_count",
"*",
"2",
... | Validates that max_pods is set to a reasonable minimum number. | [
"Validates",
"that",
"max_pods",
"is",
"set",
"to",
"a",
"reasonable",
"minimum",
"number",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_validators.py#L86-L93 |
228,707 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_validators.py | validate_nodes_count | def validate_nodes_count(namespace):
"""Validate that min_count and max_count is set to 1-100"""
if namespace.min_count is not None:
if namespace.min_count < 1 or namespace.min_count > 100:
raise CLIError('--min-count must be in the range [1,100]')
if namespace.max_count is not None:
if namespace.max_count < 1 or namespace.max_count > 100:
raise CLIError('--max-count must be in the range [1,100]') | python | def validate_nodes_count(namespace):
if namespace.min_count is not None:
if namespace.min_count < 1 or namespace.min_count > 100:
raise CLIError('--min-count must be in the range [1,100]')
if namespace.max_count is not None:
if namespace.max_count < 1 or namespace.max_count > 100:
raise CLIError('--max-count must be in the range [1,100]') | [
"def",
"validate_nodes_count",
"(",
"namespace",
")",
":",
"if",
"namespace",
".",
"min_count",
"is",
"not",
"None",
":",
"if",
"namespace",
".",
"min_count",
"<",
"1",
"or",
"namespace",
".",
"min_count",
">",
"100",
":",
"raise",
"CLIError",
"(",
"'--min... | Validate that min_count and max_count is set to 1-100 | [
"Validate",
"that",
"min_count",
"and",
"max_count",
"is",
"set",
"to",
"1",
"-",
"100"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_validators.py#L96-L103 |
228,708 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_validators.py | validate_nodepool_name | def validate_nodepool_name(namespace):
"""Validates a nodepool name to be at most 12 characters, alphanumeric only."""
if namespace.nodepool_name != "":
if len(namespace.nodepool_name) > 12:
raise CLIError('--nodepool-name can contain atmost 12 characters')
if not namespace.nodepool_name.isalnum():
raise CLIError('--nodepool-name should only contain alphanumeric characters') | python | def validate_nodepool_name(namespace):
if namespace.nodepool_name != "":
if len(namespace.nodepool_name) > 12:
raise CLIError('--nodepool-name can contain atmost 12 characters')
if not namespace.nodepool_name.isalnum():
raise CLIError('--nodepool-name should only contain alphanumeric characters') | [
"def",
"validate_nodepool_name",
"(",
"namespace",
")",
":",
"if",
"namespace",
".",
"nodepool_name",
"!=",
"\"\"",
":",
"if",
"len",
"(",
"namespace",
".",
"nodepool_name",
")",
">",
"12",
":",
"raise",
"CLIError",
"(",
"'--nodepool-name can contain atmost 12 cha... | Validates a nodepool name to be at most 12 characters, alphanumeric only. | [
"Validates",
"a",
"nodepool",
"name",
"to",
"be",
"at",
"most",
"12",
"characters",
"alphanumeric",
"only",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_validators.py#L117-L123 |
228,709 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py | CloudStorageAccount.create_block_blob_service | def create_block_blob_service(self):
'''
Creates a BlockBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService`
'''
try:
from azure.storage.blob.blockblobservice import BlockBlobService
return BlockBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | python | def create_block_blob_service(self):
'''
Creates a BlockBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService`
'''
try:
from azure.storage.blob.blockblobservice import BlockBlobService
return BlockBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | [
"def",
"create_block_blob_service",
"(",
"self",
")",
":",
"try",
":",
"from",
"azure",
".",
"storage",
".",
"blob",
".",
"blockblobservice",
"import",
"BlockBlobService",
"return",
"BlockBlobService",
"(",
"self",
".",
"account_name",
",",
"self",
".",
"account... | Creates a BlockBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.blockblobservice.BlockBlobService` | [
"Creates",
"a",
"BlockBlobService",
"object",
"with",
"the",
"settings",
"specified",
"in",
"the",
"CloudStorageAccount",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py#L51-L66 |
228,710 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py | CloudStorageAccount.create_page_blob_service | def create_page_blob_service(self):
'''
Creates a PageBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.pageblobservice.PageBlobService`
'''
try:
from azure.storage.blob.pageblobservice import PageBlobService
return PageBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | python | def create_page_blob_service(self):
'''
Creates a PageBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.pageblobservice.PageBlobService`
'''
try:
from azure.storage.blob.pageblobservice import PageBlobService
return PageBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | [
"def",
"create_page_blob_service",
"(",
"self",
")",
":",
"try",
":",
"from",
"azure",
".",
"storage",
".",
"blob",
".",
"pageblobservice",
"import",
"PageBlobService",
"return",
"PageBlobService",
"(",
"self",
".",
"account_name",
",",
"self",
".",
"account_key... | Creates a PageBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.pageblobservice.PageBlobService` | [
"Creates",
"a",
"PageBlobService",
"object",
"with",
"the",
"settings",
"specified",
"in",
"the",
"CloudStorageAccount",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py#L68-L83 |
228,711 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py | CloudStorageAccount.create_append_blob_service | def create_append_blob_service(self):
'''
Creates a AppendBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.appendblobservice.AppendBlobService`
'''
try:
from azure.storage.blob.appendblobservice import AppendBlobService
return AppendBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | python | def create_append_blob_service(self):
'''
Creates a AppendBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.appendblobservice.AppendBlobService`
'''
try:
from azure.storage.blob.appendblobservice import AppendBlobService
return AppendBlobService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-blob is required. '
+ 'Please install it using "pip install azure-storage-blob"') | [
"def",
"create_append_blob_service",
"(",
"self",
")",
":",
"try",
":",
"from",
"azure",
".",
"storage",
".",
"blob",
".",
"appendblobservice",
"import",
"AppendBlobService",
"return",
"AppendBlobService",
"(",
"self",
".",
"account_name",
",",
"self",
".",
"acc... | Creates a AppendBlobService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.blob.appendblobservice.AppendBlobService` | [
"Creates",
"a",
"AppendBlobService",
"object",
"with",
"the",
"settings",
"specified",
"in",
"the",
"CloudStorageAccount",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py#L85-L100 |
228,712 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py | CloudStorageAccount.create_queue_service | def create_queue_service(self):
'''
Creates a QueueService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.queue.queueservice.QueueService`
'''
try:
from azure.storage.queue.queueservice import QueueService
return QueueService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-queue is required. '
+ 'Please install it using "pip install azure-storage-queue"') | python | def create_queue_service(self):
'''
Creates a QueueService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.queue.queueservice.QueueService`
'''
try:
from azure.storage.queue.queueservice import QueueService
return QueueService(self.account_name, self.account_key,
sas_token=self.sas_token,
is_emulated=self.is_emulated)
except ImportError:
raise Exception('The package azure-storage-queue is required. '
+ 'Please install it using "pip install azure-storage-queue"') | [
"def",
"create_queue_service",
"(",
"self",
")",
":",
"try",
":",
"from",
"azure",
".",
"storage",
".",
"queue",
".",
"queueservice",
"import",
"QueueService",
"return",
"QueueService",
"(",
"self",
".",
"account_name",
",",
"self",
".",
"account_key",
",",
... | Creates a QueueService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.queue.queueservice.QueueService` | [
"Creates",
"a",
"QueueService",
"object",
"with",
"the",
"settings",
"specified",
"in",
"the",
"CloudStorageAccount",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/common/cloudstorageaccount.py#L102-L117 |
228,713 | Azure/azure-cli-extensions | src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/queue/queueservice.py | QueueService.exists | def exists(self, queue_name, timeout=None):
'''
Returns a boolean indicating whether the queue exists.
:param str queue_name:
The name of queue to check for existence.
:param int timeout:
The server timeout, expressed in seconds.
:return: A boolean indicating whether the queue exists.
:rtype: bool
'''
try:
self.get_queue_metadata(queue_name, timeout=timeout)
return True
except AzureHttpError as ex:
_dont_fail_not_exist(ex)
return False | python | def exists(self, queue_name, timeout=None):
'''
Returns a boolean indicating whether the queue exists.
:param str queue_name:
The name of queue to check for existence.
:param int timeout:
The server timeout, expressed in seconds.
:return: A boolean indicating whether the queue exists.
:rtype: bool
'''
try:
self.get_queue_metadata(queue_name, timeout=timeout)
return True
except AzureHttpError as ex:
_dont_fail_not_exist(ex)
return False | [
"def",
"exists",
"(",
"self",
",",
"queue_name",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"get_queue_metadata",
"(",
"queue_name",
",",
"timeout",
"=",
"timeout",
")",
"return",
"True",
"except",
"AzureHttpError",
"as",
"ex",
":",
... | Returns a boolean indicating whether the queue exists.
:param str queue_name:
The name of queue to check for existence.
:param int timeout:
The server timeout, expressed in seconds.
:return: A boolean indicating whether the queue exists.
:rtype: bool | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"queue",
"exists",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/storage-preview/azext_storage_preview/vendored_sdks/azure_storage/v2018_03_28/queue/queueservice.py#L636-L652 |
228,714 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | space_toolbar | def space_toolbar(settings_items, empty_space):
""" formats the toolbar """
counter = 0
for part in settings_items:
counter += len(part)
if len(settings_items) == 1:
spacing = ''
else:
spacing = empty_space[
:int(math.floor((len(empty_space) - counter) / (len(settings_items) - 1)))]
settings = spacing.join(settings_items)
empty_space = empty_space[len(NOTIFICATIONS) + len(settings) + 1:]
return settings, empty_space | python | def space_toolbar(settings_items, empty_space):
counter = 0
for part in settings_items:
counter += len(part)
if len(settings_items) == 1:
spacing = ''
else:
spacing = empty_space[
:int(math.floor((len(empty_space) - counter) / (len(settings_items) - 1)))]
settings = spacing.join(settings_items)
empty_space = empty_space[len(NOTIFICATIONS) + len(settings) + 1:]
return settings, empty_space | [
"def",
"space_toolbar",
"(",
"settings_items",
",",
"empty_space",
")",
":",
"counter",
"=",
"0",
"for",
"part",
"in",
"settings_items",
":",
"counter",
"+=",
"len",
"(",
"part",
")",
"if",
"len",
"(",
"settings_items",
")",
"==",
"1",
":",
"spacing",
"=... | formats the toolbar | [
"formats",
"the",
"toolbar"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L62-L77 |
228,715 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.cli | def cli(self):
""" Makes the interface or refreshes it """
if self._cli is None:
self._cli = self.create_interface()
return self._cli | python | def cli(self):
if self._cli is None:
self._cli = self.create_interface()
return self._cli | [
"def",
"cli",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cli",
"is",
"None",
":",
"self",
".",
"_cli",
"=",
"self",
".",
"create_interface",
"(",
")",
"return",
"self",
".",
"_cli"
] | Makes the interface or refreshes it | [
"Makes",
"the",
"interface",
"or",
"refreshes",
"it"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L151-L155 |
228,716 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.on_input_timeout | def on_input_timeout(self, cli):
"""
brings up the metadata for the command if there is a valid command already typed
"""
document = cli.current_buffer.document
text = document.text
text = text.replace('az ', '')
if self.default_command:
text = self.default_command + ' ' + text
param_info, example = self.generate_help_text()
self.param_docs = u'{}'.format(param_info)
self.example_docs = u'{}'.format(example)
self._update_default_info()
cli.buffers['description'].reset(
initial_document=Document(self.description_docs, cursor_position=0))
cli.buffers['parameter'].reset(
initial_document=Document(self.param_docs))
cli.buffers['examples'].reset(
initial_document=Document(self.example_docs))
cli.buffers['default_values'].reset(
initial_document=Document(
u'{}'.format(self.config_default if self.config_default else 'No Default Values')))
self._update_toolbar()
cli.request_redraw() | python | def on_input_timeout(self, cli):
document = cli.current_buffer.document
text = document.text
text = text.replace('az ', '')
if self.default_command:
text = self.default_command + ' ' + text
param_info, example = self.generate_help_text()
self.param_docs = u'{}'.format(param_info)
self.example_docs = u'{}'.format(example)
self._update_default_info()
cli.buffers['description'].reset(
initial_document=Document(self.description_docs, cursor_position=0))
cli.buffers['parameter'].reset(
initial_document=Document(self.param_docs))
cli.buffers['examples'].reset(
initial_document=Document(self.example_docs))
cli.buffers['default_values'].reset(
initial_document=Document(
u'{}'.format(self.config_default if self.config_default else 'No Default Values')))
self._update_toolbar()
cli.request_redraw() | [
"def",
"on_input_timeout",
"(",
"self",
",",
"cli",
")",
":",
"document",
"=",
"cli",
".",
"current_buffer",
".",
"document",
"text",
"=",
"document",
".",
"text",
"text",
"=",
"text",
".",
"replace",
"(",
"'az '",
",",
"''",
")",
"if",
"self",
".",
... | brings up the metadata for the command if there is a valid command already typed | [
"brings",
"up",
"the",
"metadata",
"for",
"the",
"command",
"if",
"there",
"is",
"a",
"valid",
"command",
"already",
"typed"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L168-L196 |
228,717 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell._space_examples | def _space_examples(self, list_examples, rows, section_value):
""" makes the example text """
examples_with_index = []
for i, _ in list(enumerate(list_examples)):
if len(list_examples[i]) > 1:
examples_with_index.append("[" + str(i + 1) + "] " + list_examples[i][0] +
list_examples[i][1])
example = "".join(exam for exam in examples_with_index)
num_newline = example.count('\n')
page_number = ''
if num_newline > rows * PART_SCREEN_EXAMPLE and rows > PART_SCREEN_EXAMPLE * 10:
len_of_excerpt = math.floor(float(rows) * PART_SCREEN_EXAMPLE)
group = example.split('\n')
end = int(section_value * len_of_excerpt)
begin = int((section_value - 1) * len_of_excerpt)
if end < num_newline:
example = '\n'.join(group[begin:end]) + "\n"
else:
# default chops top off
example = '\n'.join(group[begin:]) + "\n"
while ((section_value - 1) * len_of_excerpt) > num_newline:
self.example_page -= 1
page_number = '\n' + str(section_value) + "/" + str(int(math.ceil(num_newline / len_of_excerpt)))
return example + page_number + ' CTRL+Y (^) CTRL+N (v)' | python | def _space_examples(self, list_examples, rows, section_value):
examples_with_index = []
for i, _ in list(enumerate(list_examples)):
if len(list_examples[i]) > 1:
examples_with_index.append("[" + str(i + 1) + "] " + list_examples[i][0] +
list_examples[i][1])
example = "".join(exam for exam in examples_with_index)
num_newline = example.count('\n')
page_number = ''
if num_newline > rows * PART_SCREEN_EXAMPLE and rows > PART_SCREEN_EXAMPLE * 10:
len_of_excerpt = math.floor(float(rows) * PART_SCREEN_EXAMPLE)
group = example.split('\n')
end = int(section_value * len_of_excerpt)
begin = int((section_value - 1) * len_of_excerpt)
if end < num_newline:
example = '\n'.join(group[begin:end]) + "\n"
else:
# default chops top off
example = '\n'.join(group[begin:]) + "\n"
while ((section_value - 1) * len_of_excerpt) > num_newline:
self.example_page -= 1
page_number = '\n' + str(section_value) + "/" + str(int(math.ceil(num_newline / len_of_excerpt)))
return example + page_number + ' CTRL+Y (^) CTRL+N (v)' | [
"def",
"_space_examples",
"(",
"self",
",",
"list_examples",
",",
"rows",
",",
"section_value",
")",
":",
"examples_with_index",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"list",
"(",
"enumerate",
"(",
"list_examples",
")",
")",
":",
"if",
"len",
"(",
... | makes the example text | [
"makes",
"the",
"example",
"text"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L207-L236 |
228,718 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.generate_help_text | def generate_help_text(self):
""" generates the help text based on commands typed """
param_descrip = example = ""
self.description_docs = u''
rows, _ = get_window_dim()
rows = int(rows)
param_args = self.completer.leftover_args
last_word = self.completer.unfinished_word
command = self.completer.current_command
new_command = ' '.join([command, last_word]).strip()
if not self.completer.complete_command and new_command in self.completer.command_description:
command = new_command
# get command/group help
if self.completer and command in self.completer.command_description:
self.description_docs = u'{}'.format(self.completer.command_description[command])
# get parameter help if full command
if self.completer and command in self.completer.command_param_info:
param = param_args[-1] if param_args else ''
param = last_word if last_word.startswith('-') else param
if param in self.completer.command_param_info[command] and self.completer.has_description(
command + " " + param):
param_descrip = ''.join([
param, ":", '\n', self.completer.param_description.get(command + " " + param, '')])
if command in self.completer.command_examples:
string_example = []
for example in self.completer.command_examples[command]:
for part in example:
string_example.append(part)
''.join(string_example)
example = self._space_examples(
self.completer.command_examples[command], rows, self.example_page)
return param_descrip, example | python | def generate_help_text(self):
param_descrip = example = ""
self.description_docs = u''
rows, _ = get_window_dim()
rows = int(rows)
param_args = self.completer.leftover_args
last_word = self.completer.unfinished_word
command = self.completer.current_command
new_command = ' '.join([command, last_word]).strip()
if not self.completer.complete_command and new_command in self.completer.command_description:
command = new_command
# get command/group help
if self.completer and command in self.completer.command_description:
self.description_docs = u'{}'.format(self.completer.command_description[command])
# get parameter help if full command
if self.completer and command in self.completer.command_param_info:
param = param_args[-1] if param_args else ''
param = last_word if last_word.startswith('-') else param
if param in self.completer.command_param_info[command] and self.completer.has_description(
command + " " + param):
param_descrip = ''.join([
param, ":", '\n', self.completer.param_description.get(command + " " + param, '')])
if command in self.completer.command_examples:
string_example = []
for example in self.completer.command_examples[command]:
for part in example:
string_example.append(part)
''.join(string_example)
example = self._space_examples(
self.completer.command_examples[command], rows, self.example_page)
return param_descrip, example | [
"def",
"generate_help_text",
"(",
"self",
")",
":",
"param_descrip",
"=",
"example",
"=",
"\"\"",
"self",
".",
"description_docs",
"=",
"u''",
"rows",
",",
"_",
"=",
"get_window_dim",
"(",
")",
"rows",
"=",
"int",
"(",
"rows",
")",
"param_args",
"=",
"se... | generates the help text based on commands typed | [
"generates",
"the",
"help",
"text",
"based",
"on",
"commands",
"typed"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L283-L322 |
228,719 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.create_application | def create_application(self, full_layout=True):
""" makes the application object and the buffers """
layout_manager = LayoutManager(self)
if full_layout:
layout = layout_manager.create_layout(ExampleLexer, ToolbarLexer)
else:
layout = layout_manager.create_tutorial_layout()
buffers = {
DEFAULT_BUFFER: Buffer(is_multiline=True),
'description': Buffer(is_multiline=True, read_only=True),
'parameter': Buffer(is_multiline=True, read_only=True),
'examples': Buffer(is_multiline=True, read_only=True),
'bottom_toolbar': Buffer(is_multiline=True),
'example_line': Buffer(is_multiline=True),
'default_values': Buffer(),
'symbols': Buffer(),
'progress': Buffer(is_multiline=False)
}
writing_buffer = Buffer(
history=self.history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True,
completer=self.completer,
complete_while_typing=Always()
)
return Application(
mouse_support=False,
style=self.style,
buffer=writing_buffer,
on_input_timeout=self.on_input_timeout,
key_bindings_registry=InteractiveKeyBindings(self).registry,
layout=layout,
buffers=buffers,
) | python | def create_application(self, full_layout=True):
layout_manager = LayoutManager(self)
if full_layout:
layout = layout_manager.create_layout(ExampleLexer, ToolbarLexer)
else:
layout = layout_manager.create_tutorial_layout()
buffers = {
DEFAULT_BUFFER: Buffer(is_multiline=True),
'description': Buffer(is_multiline=True, read_only=True),
'parameter': Buffer(is_multiline=True, read_only=True),
'examples': Buffer(is_multiline=True, read_only=True),
'bottom_toolbar': Buffer(is_multiline=True),
'example_line': Buffer(is_multiline=True),
'default_values': Buffer(),
'symbols': Buffer(),
'progress': Buffer(is_multiline=False)
}
writing_buffer = Buffer(
history=self.history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True,
completer=self.completer,
complete_while_typing=Always()
)
return Application(
mouse_support=False,
style=self.style,
buffer=writing_buffer,
on_input_timeout=self.on_input_timeout,
key_bindings_registry=InteractiveKeyBindings(self).registry,
layout=layout,
buffers=buffers,
) | [
"def",
"create_application",
"(",
"self",
",",
"full_layout",
"=",
"True",
")",
":",
"layout_manager",
"=",
"LayoutManager",
"(",
"self",
")",
"if",
"full_layout",
":",
"layout",
"=",
"layout_manager",
".",
"create_layout",
"(",
"ExampleLexer",
",",
"ToolbarLexe... | makes the application object and the buffers | [
"makes",
"the",
"application",
"object",
"and",
"the",
"buffers"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L334-L370 |
228,720 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.set_prompt | def set_prompt(self, prompt_command="", position=0):
""" writes the prompt line """
self.description_docs = u'{}'.format(prompt_command)
self.cli.current_buffer.reset(
initial_document=Document(
self.description_docs,
cursor_position=position))
self.cli.request_redraw() | python | def set_prompt(self, prompt_command="", position=0):
self.description_docs = u'{}'.format(prompt_command)
self.cli.current_buffer.reset(
initial_document=Document(
self.description_docs,
cursor_position=position))
self.cli.request_redraw() | [
"def",
"set_prompt",
"(",
"self",
",",
"prompt_command",
"=",
"\"\"",
",",
"position",
"=",
"0",
")",
":",
"self",
".",
"description_docs",
"=",
"u'{}'",
".",
"format",
"(",
"prompt_command",
")",
"self",
".",
"cli",
".",
"current_buffer",
".",
"reset",
... | writes the prompt line | [
"writes",
"the",
"prompt",
"line"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L378-L385 |
228,721 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.set_scope | def set_scope(self, value):
""" narrows the scopes the commands """
if self.default_command:
self.default_command += ' ' + value
else:
self.default_command += value
return value | python | def set_scope(self, value):
if self.default_command:
self.default_command += ' ' + value
else:
self.default_command += value
return value | [
"def",
"set_scope",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"default_command",
":",
"self",
".",
"default_command",
"+=",
"' '",
"+",
"value",
"else",
":",
"self",
".",
"default_command",
"+=",
"value",
"return",
"value"
] | narrows the scopes the commands | [
"narrows",
"the",
"scopes",
"the",
"commands"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L387-L393 |
228,722 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.handle_example | def handle_example(self, text, continue_flag):
""" parses for the tutorial """
cmd = text.partition(SELECT_SYMBOL['example'])[0].rstrip()
num = text.partition(SELECT_SYMBOL['example'])[2].strip()
example = ""
try:
num = int(num) - 1
except ValueError:
print("An Integer should follow the colon", file=self.output)
return ""
if cmd in self.completer.command_examples:
if num >= 0 and num < len(self.completer.command_examples[cmd]):
example = self.completer.command_examples[cmd][num][1]
example = example.replace('\n', '')
else:
print('Invalid example number', file=self.output)
return '', True
example = example.replace('az', '')
starting_index = None
counter = 0
example_no_fill = ""
flag_fill = True
for word in example.split():
if flag_fill:
example_no_fill += word + " "
if word.startswith('-'):
example_no_fill += word + " "
if not starting_index:
starting_index = counter
flag_fill = False
counter += 1
return self.example_repl(example_no_fill, example, starting_index, continue_flag) | python | def handle_example(self, text, continue_flag):
cmd = text.partition(SELECT_SYMBOL['example'])[0].rstrip()
num = text.partition(SELECT_SYMBOL['example'])[2].strip()
example = ""
try:
num = int(num) - 1
except ValueError:
print("An Integer should follow the colon", file=self.output)
return ""
if cmd in self.completer.command_examples:
if num >= 0 and num < len(self.completer.command_examples[cmd]):
example = self.completer.command_examples[cmd][num][1]
example = example.replace('\n', '')
else:
print('Invalid example number', file=self.output)
return '', True
example = example.replace('az', '')
starting_index = None
counter = 0
example_no_fill = ""
flag_fill = True
for word in example.split():
if flag_fill:
example_no_fill += word + " "
if word.startswith('-'):
example_no_fill += word + " "
if not starting_index:
starting_index = counter
flag_fill = False
counter += 1
return self.example_repl(example_no_fill, example, starting_index, continue_flag) | [
"def",
"handle_example",
"(",
"self",
",",
"text",
",",
"continue_flag",
")",
":",
"cmd",
"=",
"text",
".",
"partition",
"(",
"SELECT_SYMBOL",
"[",
"'example'",
"]",
")",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
"num",
"=",
"text",
".",
"partition",
"... | parses for the tutorial | [
"parses",
"for",
"the",
"tutorial"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L395-L429 |
228,723 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.example_repl | def example_repl(self, text, example, start_index, continue_flag):
""" REPL for interactive tutorials """
if start_index:
start_index = start_index + 1
cmd = ' '.join(text.split()[:start_index])
example_cli = CommandLineInterface(
application=self.create_application(
full_layout=False),
eventloop=create_eventloop())
example_cli.buffers['example_line'].reset(
initial_document=Document(u'{}\n'.format(
add_new_lines(example)))
)
while start_index < len(text.split()):
if self.default_command:
cmd = cmd.replace(self.default_command + ' ', '')
example_cli.buffers[DEFAULT_BUFFER].reset(
initial_document=Document(
u'{}'.format(cmd),
cursor_position=len(cmd)))
example_cli.request_redraw()
answer = example_cli.run()
if not answer:
return "", True
answer = answer.text
if answer.strip('\n') == cmd.strip('\n'):
continue
else:
if len(answer.split()) > 1:
start_index += 1
cmd += " " + answer.split()[-1] + " " +\
u' '.join(text.split()[start_index:start_index + 1])
example_cli.exit()
del example_cli
else:
cmd = text
return cmd, continue_flag | python | def example_repl(self, text, example, start_index, continue_flag):
if start_index:
start_index = start_index + 1
cmd = ' '.join(text.split()[:start_index])
example_cli = CommandLineInterface(
application=self.create_application(
full_layout=False),
eventloop=create_eventloop())
example_cli.buffers['example_line'].reset(
initial_document=Document(u'{}\n'.format(
add_new_lines(example)))
)
while start_index < len(text.split()):
if self.default_command:
cmd = cmd.replace(self.default_command + ' ', '')
example_cli.buffers[DEFAULT_BUFFER].reset(
initial_document=Document(
u'{}'.format(cmd),
cursor_position=len(cmd)))
example_cli.request_redraw()
answer = example_cli.run()
if not answer:
return "", True
answer = answer.text
if answer.strip('\n') == cmd.strip('\n'):
continue
else:
if len(answer.split()) > 1:
start_index += 1
cmd += " " + answer.split()[-1] + " " +\
u' '.join(text.split()[start_index:start_index + 1])
example_cli.exit()
del example_cli
else:
cmd = text
return cmd, continue_flag | [
"def",
"example_repl",
"(",
"self",
",",
"text",
",",
"example",
",",
"start_index",
",",
"continue_flag",
")",
":",
"if",
"start_index",
":",
"start_index",
"=",
"start_index",
"+",
"1",
"cmd",
"=",
"' '",
".",
"join",
"(",
"text",
".",
"split",
"(",
... | REPL for interactive tutorials | [
"REPL",
"for",
"interactive",
"tutorials"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L431-L468 |
228,724 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.handle_jmespath_query | def handle_jmespath_query(self, args):
""" handles the jmespath query for injection or printing """
continue_flag = False
query_symbol = SELECT_SYMBOL['query']
symbol_len = len(query_symbol)
try:
if len(args) == 1:
# if arguments start with query_symbol, just print query result
if args[0] == query_symbol:
result = self.last.result
elif args[0].startswith(query_symbol):
result = jmespath.search(args[0][symbol_len:], self.last.result)
print(json.dumps(result, sort_keys=True, indent=2), file=self.output)
elif args[0].startswith(query_symbol):
# print error message, user unsure of query shortcut usage
print(("Usage Error: " + os.linesep +
"1. Use {0} stand-alone to display previous result with optional filtering "
"(Ex: {0}[jmespath query])" +
os.linesep + "OR:" + os.linesep +
"2. Use {0} to query the previous result for argument values "
"(Ex: group show --name {0}[jmespath query])").format(query_symbol), file=self.output)
else:
# query, inject into cmd
def jmespath_query(match):
if match.group(0) == query_symbol:
return str(self.last.result)
query_result = jmespath.search(match.group(0)[symbol_len:], self.last.result)
return str(query_result)
def sub_result(arg):
escaped_symbol = re.escape(query_symbol)
# regex captures query symbol and all characters following it in the argument
return json.dumps(re.sub(r'%s.*' % escaped_symbol, jmespath_query, arg))
cmd_base = ' '.join(map(sub_result, args))
self.cli_execute(cmd_base)
continue_flag = True
except (jmespath.exceptions.ParseError, CLIError) as e:
print("Invalid Query Input: " + str(e), file=self.output)
continue_flag = True
return continue_flag | python | def handle_jmespath_query(self, args):
continue_flag = False
query_symbol = SELECT_SYMBOL['query']
symbol_len = len(query_symbol)
try:
if len(args) == 1:
# if arguments start with query_symbol, just print query result
if args[0] == query_symbol:
result = self.last.result
elif args[0].startswith(query_symbol):
result = jmespath.search(args[0][symbol_len:], self.last.result)
print(json.dumps(result, sort_keys=True, indent=2), file=self.output)
elif args[0].startswith(query_symbol):
# print error message, user unsure of query shortcut usage
print(("Usage Error: " + os.linesep +
"1. Use {0} stand-alone to display previous result with optional filtering "
"(Ex: {0}[jmespath query])" +
os.linesep + "OR:" + os.linesep +
"2. Use {0} to query the previous result for argument values "
"(Ex: group show --name {0}[jmespath query])").format(query_symbol), file=self.output)
else:
# query, inject into cmd
def jmespath_query(match):
if match.group(0) == query_symbol:
return str(self.last.result)
query_result = jmespath.search(match.group(0)[symbol_len:], self.last.result)
return str(query_result)
def sub_result(arg):
escaped_symbol = re.escape(query_symbol)
# regex captures query symbol and all characters following it in the argument
return json.dumps(re.sub(r'%s.*' % escaped_symbol, jmespath_query, arg))
cmd_base = ' '.join(map(sub_result, args))
self.cli_execute(cmd_base)
continue_flag = True
except (jmespath.exceptions.ParseError, CLIError) as e:
print("Invalid Query Input: " + str(e), file=self.output)
continue_flag = True
return continue_flag | [
"def",
"handle_jmespath_query",
"(",
"self",
",",
"args",
")",
":",
"continue_flag",
"=",
"False",
"query_symbol",
"=",
"SELECT_SYMBOL",
"[",
"'query'",
"]",
"symbol_len",
"=",
"len",
"(",
"query_symbol",
")",
"try",
":",
"if",
"len",
"(",
"args",
")",
"==... | handles the jmespath query for injection or printing | [
"handles",
"the",
"jmespath",
"query",
"for",
"injection",
"or",
"printing"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L533-L572 |
228,725 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.handle_scoping_input | def handle_scoping_input(self, continue_flag, cmd, text):
""" handles what to do with a scoping gesture """
default_split = text.partition(SELECT_SYMBOL['scope'])[2].split()
cmd = cmd.replace(SELECT_SYMBOL['scope'], '')
continue_flag = True
if not default_split:
self.default_command = ""
print('unscoping all', file=self.output)
return continue_flag, cmd
while default_split:
if not text:
value = ''
else:
value = default_split[0]
tree_path = self.default_command.split()
tree_path.append(value)
if self.completer.command_tree.in_tree(tree_path):
self.set_scope(value)
print("defaulting: " + value, file=self.output)
cmd = cmd.replace(SELECT_SYMBOL['scope'], '')
elif SELECT_SYMBOL['unscope'] == default_split[0] and self.default_command.split():
value = self.default_command.split()[-1]
self.default_command = ' ' + ' '.join(self.default_command.split()[:-1])
if not self.default_command.strip():
self.default_command = self.default_command.strip()
print('unscoping: ' + value, file=self.output)
elif SELECT_SYMBOL['unscope'] not in text:
print("Scope must be a valid command", file=self.output)
default_split = default_split[1:]
return continue_flag, cmd | python | def handle_scoping_input(self, continue_flag, cmd, text):
default_split = text.partition(SELECT_SYMBOL['scope'])[2].split()
cmd = cmd.replace(SELECT_SYMBOL['scope'], '')
continue_flag = True
if not default_split:
self.default_command = ""
print('unscoping all', file=self.output)
return continue_flag, cmd
while default_split:
if not text:
value = ''
else:
value = default_split[0]
tree_path = self.default_command.split()
tree_path.append(value)
if self.completer.command_tree.in_tree(tree_path):
self.set_scope(value)
print("defaulting: " + value, file=self.output)
cmd = cmd.replace(SELECT_SYMBOL['scope'], '')
elif SELECT_SYMBOL['unscope'] == default_split[0] and self.default_command.split():
value = self.default_command.split()[-1]
self.default_command = ' ' + ' '.join(self.default_command.split()[:-1])
if not self.default_command.strip():
self.default_command = self.default_command.strip()
print('unscoping: ' + value, file=self.output)
elif SELECT_SYMBOL['unscope'] not in text:
print("Scope must be a valid command", file=self.output)
default_split = default_split[1:]
return continue_flag, cmd | [
"def",
"handle_scoping_input",
"(",
"self",
",",
"continue_flag",
",",
"cmd",
",",
"text",
")",
":",
"default_split",
"=",
"text",
".",
"partition",
"(",
"SELECT_SYMBOL",
"[",
"'scope'",
"]",
")",
"[",
"2",
"]",
".",
"split",
"(",
")",
"cmd",
"=",
"cmd... | handles what to do with a scoping gesture | [
"handles",
"what",
"to",
"do",
"with",
"a",
"scoping",
"gesture"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L574-L613 |
228,726 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.cli_execute | def cli_execute(self, cmd):
""" sends the command to the CLI to be executed """
try:
args = parse_quotes(cmd)
if args and args[0] == 'feedback':
self.config.set_feedback('yes')
self.user_feedback = False
azure_folder = get_config_dir()
if not os.path.exists(azure_folder):
os.makedirs(azure_folder)
ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
CONFIG.load(os.path.join(azure_folder, 'az.json'))
SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
invocation = self.cli_ctx.invocation_cls(cli_ctx=self.cli_ctx,
parser_cls=self.cli_ctx.parser_cls,
commands_loader_cls=self.cli_ctx.commands_loader_cls,
help_cls=self.cli_ctx.help_cls)
if '--progress' in args:
args.remove('--progress')
execute_args = [args]
thread = Thread(target=invocation.execute, args=execute_args)
thread.daemon = True
thread.start()
self.threads.append(thread)
self.curr_thread = thread
progress_args = [self]
thread = Thread(target=progress_view, args=progress_args)
thread.daemon = True
thread.start()
self.threads.append(thread)
result = None
else:
result = invocation.execute(args)
self.last_exit = 0
if result and result.result is not None:
if self.output:
self.output.write(result)
self.output.flush()
else:
formatter = self.cli_ctx.output.get_formatter(self.cli_ctx.invocation.data['output'])
self.cli_ctx.output.out(result, formatter=formatter, out_file=sys.stdout)
self.last = result
except Exception as ex: # pylint: disable=broad-except
self.last_exit = handle_exception(ex)
except SystemExit as ex:
self.last_exit = int(ex.code) | python | def cli_execute(self, cmd):
try:
args = parse_quotes(cmd)
if args and args[0] == 'feedback':
self.config.set_feedback('yes')
self.user_feedback = False
azure_folder = get_config_dir()
if not os.path.exists(azure_folder):
os.makedirs(azure_folder)
ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
CONFIG.load(os.path.join(azure_folder, 'az.json'))
SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
invocation = self.cli_ctx.invocation_cls(cli_ctx=self.cli_ctx,
parser_cls=self.cli_ctx.parser_cls,
commands_loader_cls=self.cli_ctx.commands_loader_cls,
help_cls=self.cli_ctx.help_cls)
if '--progress' in args:
args.remove('--progress')
execute_args = [args]
thread = Thread(target=invocation.execute, args=execute_args)
thread.daemon = True
thread.start()
self.threads.append(thread)
self.curr_thread = thread
progress_args = [self]
thread = Thread(target=progress_view, args=progress_args)
thread.daemon = True
thread.start()
self.threads.append(thread)
result = None
else:
result = invocation.execute(args)
self.last_exit = 0
if result and result.result is not None:
if self.output:
self.output.write(result)
self.output.flush()
else:
formatter = self.cli_ctx.output.get_formatter(self.cli_ctx.invocation.data['output'])
self.cli_ctx.output.out(result, formatter=formatter, out_file=sys.stdout)
self.last = result
except Exception as ex: # pylint: disable=broad-except
self.last_exit = handle_exception(ex)
except SystemExit as ex:
self.last_exit = int(ex.code) | [
"def",
"cli_execute",
"(",
"self",
",",
"cmd",
")",
":",
"try",
":",
"args",
"=",
"parse_quotes",
"(",
"cmd",
")",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'feedback'",
":",
"self",
".",
"config",
".",
"set_feedback",
"(",
"'yes'",
")",
"... | sends the command to the CLI to be executed | [
"sends",
"the",
"command",
"to",
"the",
"CLI",
"to",
"be",
"executed"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L621-L674 |
228,727 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.progress_patch | def progress_patch(self, _=False):
""" forces to use the Shell Progress """
from .progress import ShellProgressView
self.cli_ctx.progress_controller.init_progress(ShellProgressView())
return self.cli_ctx.progress_controller | python | def progress_patch(self, _=False):
from .progress import ShellProgressView
self.cli_ctx.progress_controller.init_progress(ShellProgressView())
return self.cli_ctx.progress_controller | [
"def",
"progress_patch",
"(",
"self",
",",
"_",
"=",
"False",
")",
":",
"from",
".",
"progress",
"import",
"ShellProgressView",
"self",
".",
"cli_ctx",
".",
"progress_controller",
".",
"init_progress",
"(",
"ShellProgressView",
"(",
")",
")",
"return",
"self",... | forces to use the Shell Progress | [
"forces",
"to",
"use",
"the",
"Shell",
"Progress"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L676-L680 |
228,728 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/app.py | AzInteractiveShell.run | def run(self):
""" starts the REPL """
from .progress import ShellProgressView
self.cli_ctx.get_progress_controller().init_progress(ShellProgressView())
self.cli_ctx.get_progress_controller = self.progress_patch
self.command_table_thread = LoadCommandTableThread(self.restart_completer, self)
self.command_table_thread.start()
from .configuration import SHELL_HELP
self.cli.buffers['symbols'].reset(
initial_document=Document(u'{}'.format(SHELL_HELP)))
# flush telemetry for new commands and send successful interactive mode entry event
telemetry.set_success()
telemetry.flush()
while True:
try:
document = self.cli.run(reset_current_buffer=True)
text = document.text
if not text:
# not input
self.set_prompt()
continue
cmd = text
outside = False
except AttributeError:
# when the user pressed Control D
break
except (KeyboardInterrupt, ValueError):
# CTRL C
self.set_prompt()
continue
else:
self.history.append(text)
b_flag, c_flag, outside, cmd = self._special_cases(cmd, outside)
if b_flag:
break
if c_flag:
self.set_prompt()
continue
self.set_prompt()
if outside:
subprocess.Popen(cmd, shell=True).communicate()
else:
telemetry.start()
self.cli_execute(cmd)
if self.last_exit and self.last_exit != 0:
telemetry.set_failure()
else:
telemetry.set_success()
telemetry.flush()
telemetry.conclude() | python | def run(self):
from .progress import ShellProgressView
self.cli_ctx.get_progress_controller().init_progress(ShellProgressView())
self.cli_ctx.get_progress_controller = self.progress_patch
self.command_table_thread = LoadCommandTableThread(self.restart_completer, self)
self.command_table_thread.start()
from .configuration import SHELL_HELP
self.cli.buffers['symbols'].reset(
initial_document=Document(u'{}'.format(SHELL_HELP)))
# flush telemetry for new commands and send successful interactive mode entry event
telemetry.set_success()
telemetry.flush()
while True:
try:
document = self.cli.run(reset_current_buffer=True)
text = document.text
if not text:
# not input
self.set_prompt()
continue
cmd = text
outside = False
except AttributeError:
# when the user pressed Control D
break
except (KeyboardInterrupt, ValueError):
# CTRL C
self.set_prompt()
continue
else:
self.history.append(text)
b_flag, c_flag, outside, cmd = self._special_cases(cmd, outside)
if b_flag:
break
if c_flag:
self.set_prompt()
continue
self.set_prompt()
if outside:
subprocess.Popen(cmd, shell=True).communicate()
else:
telemetry.start()
self.cli_execute(cmd)
if self.last_exit and self.last_exit != 0:
telemetry.set_failure()
else:
telemetry.set_success()
telemetry.flush()
telemetry.conclude() | [
"def",
"run",
"(",
"self",
")",
":",
"from",
".",
"progress",
"import",
"ShellProgressView",
"self",
".",
"cli_ctx",
".",
"get_progress_controller",
"(",
")",
".",
"init_progress",
"(",
"ShellProgressView",
"(",
")",
")",
"self",
".",
"cli_ctx",
".",
"get_pr... | starts the REPL | [
"starts",
"the",
"REPL"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L682-L737 |
228,729 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/progress.py | progress_view | def progress_view(shell):
""" updates the view """
while not ShellProgressView.done:
_, col = get_window_dim()
col = int(col)
progress = get_progress_message()
if '\n' in progress:
prog_list = progress.split('\n')
prog_val = len(prog_list[-1])
else:
prog_val = len(progress)
buffer_size = col - prog_val - 4
if ShellProgressView.progress_bar:
doc = u'{}:{}'.format(progress, ShellProgressView.progress_bar)
shell.spin_val = -1
counter = 0
ShellProgressView.heart_bar = ''
else:
if progress and not ShellProgressView.done:
heart_bar = ShellProgressView.heart_bar
if shell.spin_val >= 0:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
heart_bar = heart_bar[len(beat):]
len_beat = len(heart_bar)
if len_beat > buffer_size:
heart_bar = heart_bar[len_beat - buffer_size:]
while len(heart_bar) < buffer_size:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
else:
shell.spin_val = 0
counter = 0
while counter < buffer_size:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
counter += len(beat)
ShellProgressView.heart_bar = heart_bar
doc = u'{}:{}'.format(progress, ShellProgressView.heart_bar)
shell.cli.buffers['progress'].reset(
initial_document=Document(doc))
shell.cli.request_redraw()
sleep(shell.intermediate_sleep)
ShellProgressView.done = False
ShellProgressView.progress_bar = ''
shell.spin_val = -1
sleep(shell.final_sleep)
return True | python | def progress_view(shell):
while not ShellProgressView.done:
_, col = get_window_dim()
col = int(col)
progress = get_progress_message()
if '\n' in progress:
prog_list = progress.split('\n')
prog_val = len(prog_list[-1])
else:
prog_val = len(progress)
buffer_size = col - prog_val - 4
if ShellProgressView.progress_bar:
doc = u'{}:{}'.format(progress, ShellProgressView.progress_bar)
shell.spin_val = -1
counter = 0
ShellProgressView.heart_bar = ''
else:
if progress and not ShellProgressView.done:
heart_bar = ShellProgressView.heart_bar
if shell.spin_val >= 0:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
heart_bar = heart_bar[len(beat):]
len_beat = len(heart_bar)
if len_beat > buffer_size:
heart_bar = heart_bar[len_beat - buffer_size:]
while len(heart_bar) < buffer_size:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
else:
shell.spin_val = 0
counter = 0
while counter < buffer_size:
beat = ShellProgressView.heart_beat_values[_get_heart_frequency()]
heart_bar += beat
counter += len(beat)
ShellProgressView.heart_bar = heart_bar
doc = u'{}:{}'.format(progress, ShellProgressView.heart_bar)
shell.cli.buffers['progress'].reset(
initial_document=Document(doc))
shell.cli.request_redraw()
sleep(shell.intermediate_sleep)
ShellProgressView.done = False
ShellProgressView.progress_bar = ''
shell.spin_val = -1
sleep(shell.final_sleep)
return True | [
"def",
"progress_view",
"(",
"shell",
")",
":",
"while",
"not",
"ShellProgressView",
".",
"done",
":",
"_",
",",
"col",
"=",
"get_window_dim",
"(",
")",
"col",
"=",
"int",
"(",
"col",
")",
"progress",
"=",
"get_progress_message",
"(",
")",
"if",
"'\\n'",... | updates the view | [
"updates",
"the",
"view"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/progress.py#L67-L118 |
228,730 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/progress.py | ShellProgressView.write | def write(self, args): # pylint: disable=no-self-use
""" writes the progres """
ShellProgressView.done = False
message = args.get('message', '')
percent = args.get('percent', None)
if percent:
ShellProgressView.progress_bar = _format_value(message, percent)
if int(percent) == 1:
ShellProgressView.progress_bar = None
ShellProgressView.progress = message | python | def write(self, args): # pylint: disable=no-self-use
ShellProgressView.done = False
message = args.get('message', '')
percent = args.get('percent', None)
if percent:
ShellProgressView.progress_bar = _format_value(message, percent)
if int(percent) == 1:
ShellProgressView.progress_bar = None
ShellProgressView.progress = message | [
"def",
"write",
"(",
"self",
",",
"args",
")",
":",
"# pylint: disable=no-self-use",
"ShellProgressView",
".",
"done",
"=",
"False",
"message",
"=",
"args",
".",
"get",
"(",
"'message'",
",",
"''",
")",
"percent",
"=",
"args",
".",
"get",
"(",
"'percent'",... | writes the progres | [
"writes",
"the",
"progres"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/progress.py#L26-L36 |
228,731 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_list | def sqlvm_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machines in a resource group or subscription.
'''
if resource_group_name:
# List all sql vms in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vms in the subscription
return client.list() | python | def sqlvm_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machines in a resource group or subscription.
'''
if resource_group_name:
# List all sql vms in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vms in the subscription
return client.list() | [
"def",
"sqlvm_list",
"(",
"client",
",",
"resource_group_name",
"=",
"None",
")",
":",
"if",
"resource_group_name",
":",
"# List all sql vms in the resource group",
"return",
"client",
".",
"list_by_resource_group",
"(",
"resource_group_name",
"=",
"resource_group_name",
... | Lists all SQL virtual machines in a resource group or subscription. | [
"Lists",
"all",
"SQL",
"virtual",
"machines",
"in",
"a",
"resource",
"group",
"or",
"subscription",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L31-L42 |
228,732 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_group_list | def sqlvm_group_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machine groups in a resource group or subscription.
'''
if resource_group_name:
# List all sql vm groups in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vm groups in the subscription
return client.list() | python | def sqlvm_group_list(
client,
resource_group_name=None):
'''
Lists all SQL virtual machine groups in a resource group or subscription.
'''
if resource_group_name:
# List all sql vm groups in the resource group
return client.list_by_resource_group(resource_group_name=resource_group_name)
# List all sql vm groups in the subscription
return client.list() | [
"def",
"sqlvm_group_list",
"(",
"client",
",",
"resource_group_name",
"=",
"None",
")",
":",
"if",
"resource_group_name",
":",
"# List all sql vm groups in the resource group",
"return",
"client",
".",
"list_by_resource_group",
"(",
"resource_group_name",
"=",
"resource_gro... | Lists all SQL virtual machine groups in a resource group or subscription. | [
"Lists",
"all",
"SQL",
"virtual",
"machine",
"groups",
"in",
"a",
"resource",
"group",
"or",
"subscription",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L45-L56 |
228,733 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_group_create | def sqlvm_group_create(client, cmd, sql_virtual_machine_group_name, resource_group_name, location, sql_image_offer,
sql_image_sku, domain_fqdn, cluster_operator_account, sql_service_account,
storage_account_url, storage_account_key, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Creates a SQL virtual machine group.
'''
tags = tags or {}
# Create the windows server failover cluster domain profile object.
wsfc_domain_profile_object = WsfcDomainProfile(domain_fqdn=domain_fqdn,
ou_path=ou_path,
cluster_bootstrap_account=cluster_bootstrap_account,
cluster_operator_account=cluster_operator_account,
sql_service_account=sql_service_account,
file_share_witness_path=file_share_witness_path,
storage_account_url=storage_account_url,
storage_account_primary_key=storage_account_key)
sqlvm_group_object = SqlVirtualMachineGroup(sql_image_offer=sql_image_offer,
sql_image_sku=sql_image_sku,
wsfc_domain_profile=wsfc_domain_profile_object,
location=location,
tags=tags)
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.create_or_update, resource_group_name,
sql_virtual_machine_group_name, sqlvm_group_object))
return client.get(resource_group_name, sql_virtual_machine_group_name) | python | def sqlvm_group_create(client, cmd, sql_virtual_machine_group_name, resource_group_name, location, sql_image_offer,
sql_image_sku, domain_fqdn, cluster_operator_account, sql_service_account,
storage_account_url, storage_account_key, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Creates a SQL virtual machine group.
'''
tags = tags or {}
# Create the windows server failover cluster domain profile object.
wsfc_domain_profile_object = WsfcDomainProfile(domain_fqdn=domain_fqdn,
ou_path=ou_path,
cluster_bootstrap_account=cluster_bootstrap_account,
cluster_operator_account=cluster_operator_account,
sql_service_account=sql_service_account,
file_share_witness_path=file_share_witness_path,
storage_account_url=storage_account_url,
storage_account_primary_key=storage_account_key)
sqlvm_group_object = SqlVirtualMachineGroup(sql_image_offer=sql_image_offer,
sql_image_sku=sql_image_sku,
wsfc_domain_profile=wsfc_domain_profile_object,
location=location,
tags=tags)
# Since it's a running operation, we will do the put and then the get to display the instance.
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.create_or_update, resource_group_name,
sql_virtual_machine_group_name, sqlvm_group_object))
return client.get(resource_group_name, sql_virtual_machine_group_name) | [
"def",
"sqlvm_group_create",
"(",
"client",
",",
"cmd",
",",
"sql_virtual_machine_group_name",
",",
"resource_group_name",
",",
"location",
",",
"sql_image_offer",
",",
"sql_image_sku",
",",
"domain_fqdn",
",",
"cluster_operator_account",
",",
"sql_service_account",
",",
... | Creates a SQL virtual machine group. | [
"Creates",
"a",
"SQL",
"virtual",
"machine",
"group",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L60-L90 |
228,734 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_group_update | def sqlvm_group_update(instance, domain_fqdn=None, sql_image_sku=None, sql_image_offer=None,
cluster_operator_account=None, sql_service_account=None,
storage_account_url=None, storage_account_key=None, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Updates a SQL virtual machine group.
'''
if sql_image_sku is not None:
instance.sql_image_sku = sql_image_sku
if sql_image_offer is not None:
instance.sql_image_offer = sql_image_offer
if domain_fqdn is not None:
instance.wsfc_domain_profile.domain_fqdn = domain_fqdn
if cluster_operator_account is not None:
instance.wsfc_domain_profile.cluster_operator_account = cluster_operator_account
if cluster_bootstrap_account is not None:
instance.wsfc_domain_profile.cluster_bootstrap_account = cluster_bootstrap_account
if sql_service_account is not None:
instance.wsfc_domain_profile.sql_service_account = sql_service_account
if storage_account_url is not None:
instance.wsfc_domain_profile.storage_account_url = storage_account_url
if storage_account_key is not None:
instance.wsfc_domain_profile.storage_access_key = storage_account_key
if file_share_witness_path is not None:
instance.wsfc_domain_profile.file_share_witness_path = file_share_witness_path
if ou_path is not None:
instance.wsfc_domain_profile.ou_path = ou_path
if tags is not None:
instance.tags = tags
return instance | python | def sqlvm_group_update(instance, domain_fqdn=None, sql_image_sku=None, sql_image_offer=None,
cluster_operator_account=None, sql_service_account=None,
storage_account_url=None, storage_account_key=None, cluster_bootstrap_account=None,
file_share_witness_path=None, ou_path=None, tags=None):
'''
Updates a SQL virtual machine group.
'''
if sql_image_sku is not None:
instance.sql_image_sku = sql_image_sku
if sql_image_offer is not None:
instance.sql_image_offer = sql_image_offer
if domain_fqdn is not None:
instance.wsfc_domain_profile.domain_fqdn = domain_fqdn
if cluster_operator_account is not None:
instance.wsfc_domain_profile.cluster_operator_account = cluster_operator_account
if cluster_bootstrap_account is not None:
instance.wsfc_domain_profile.cluster_bootstrap_account = cluster_bootstrap_account
if sql_service_account is not None:
instance.wsfc_domain_profile.sql_service_account = sql_service_account
if storage_account_url is not None:
instance.wsfc_domain_profile.storage_account_url = storage_account_url
if storage_account_key is not None:
instance.wsfc_domain_profile.storage_access_key = storage_account_key
if file_share_witness_path is not None:
instance.wsfc_domain_profile.file_share_witness_path = file_share_witness_path
if ou_path is not None:
instance.wsfc_domain_profile.ou_path = ou_path
if tags is not None:
instance.tags = tags
return instance | [
"def",
"sqlvm_group_update",
"(",
"instance",
",",
"domain_fqdn",
"=",
"None",
",",
"sql_image_sku",
"=",
"None",
",",
"sql_image_offer",
"=",
"None",
",",
"cluster_operator_account",
"=",
"None",
",",
"sql_service_account",
"=",
"None",
",",
"storage_account_url",
... | Updates a SQL virtual machine group. | [
"Updates",
"a",
"SQL",
"virtual",
"machine",
"group",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L94-L124 |
228,735 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_aglistener_create | def sqlvm_aglistener_create(client, cmd, availability_group_listener_name, sql_virtual_machine_group_name,
resource_group_name, availability_group_name, ip_address, subnet_resource_id,
load_balancer_resource_id, probe_port, sql_virtual_machine_instances, port=1433,
public_ip_address_resource_id=None):
'''
Creates an availability group listener
'''
if not is_valid_resource_id(subnet_resource_id):
raise CLIError("Invalid subnet resource id.")
if not is_valid_resource_id(load_balancer_resource_id):
raise CLIError("Invalid load balancer resource id.")
if public_ip_address_resource_id and not is_valid_resource_id(public_ip_address_resource_id):
raise CLIError("Invalid public IP address resource id.")
for sqlvm in sql_virtual_machine_instances:
if not is_valid_resource_id(sqlvm):
raise CLIError("Invalid SQL virtual machine resource id.")
# Create the private ip address
private_ip_object = PrivateIPAddress(ip_address=ip_address,
subnet_resource_id=subnet_resource_id
if is_valid_resource_id(subnet_resource_id) else None)
# Create the load balancer configurations
load_balancer_object = LoadBalancerConfiguration(private_ip_address=private_ip_object,
public_ip_address_resource_id=public_ip_address_resource_id,
load_balancer_resource_id=load_balancer_resource_id,
probe_port=probe_port,
sql_virtual_machine_instances=sql_virtual_machine_instances)
# Create the availability group listener object
ag_listener_object = AvailabilityGroupListener(availability_group_name=availability_group_name,
load_balancer_configurations=load_balancer_object,
port=port)
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.create_or_update, resource_group_name,
sql_virtual_machine_group_name, availability_group_listener_name,
ag_listener_object))
return client.get(resource_group_name, sql_virtual_machine_group_name, availability_group_listener_name) | python | def sqlvm_aglistener_create(client, cmd, availability_group_listener_name, sql_virtual_machine_group_name,
resource_group_name, availability_group_name, ip_address, subnet_resource_id,
load_balancer_resource_id, probe_port, sql_virtual_machine_instances, port=1433,
public_ip_address_resource_id=None):
'''
Creates an availability group listener
'''
if not is_valid_resource_id(subnet_resource_id):
raise CLIError("Invalid subnet resource id.")
if not is_valid_resource_id(load_balancer_resource_id):
raise CLIError("Invalid load balancer resource id.")
if public_ip_address_resource_id and not is_valid_resource_id(public_ip_address_resource_id):
raise CLIError("Invalid public IP address resource id.")
for sqlvm in sql_virtual_machine_instances:
if not is_valid_resource_id(sqlvm):
raise CLIError("Invalid SQL virtual machine resource id.")
# Create the private ip address
private_ip_object = PrivateIPAddress(ip_address=ip_address,
subnet_resource_id=subnet_resource_id
if is_valid_resource_id(subnet_resource_id) else None)
# Create the load balancer configurations
load_balancer_object = LoadBalancerConfiguration(private_ip_address=private_ip_object,
public_ip_address_resource_id=public_ip_address_resource_id,
load_balancer_resource_id=load_balancer_resource_id,
probe_port=probe_port,
sql_virtual_machine_instances=sql_virtual_machine_instances)
# Create the availability group listener object
ag_listener_object = AvailabilityGroupListener(availability_group_name=availability_group_name,
load_balancer_configurations=load_balancer_object,
port=port)
LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(False, client.create_or_update, resource_group_name,
sql_virtual_machine_group_name, availability_group_listener_name,
ag_listener_object))
return client.get(resource_group_name, sql_virtual_machine_group_name, availability_group_listener_name) | [
"def",
"sqlvm_aglistener_create",
"(",
"client",
",",
"cmd",
",",
"availability_group_listener_name",
",",
"sql_virtual_machine_group_name",
",",
"resource_group_name",
",",
"availability_group_name",
",",
"ip_address",
",",
"subnet_resource_id",
",",
"load_balancer_resource_id... | Creates an availability group listener | [
"Creates",
"an",
"availability",
"group",
"listener"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L128-L167 |
228,736 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | sqlvm_update | def sqlvm_update(instance, sql_server_license_type=None, enable_auto_patching=None,
day_of_week=None, maintenance_window_starting_hour=None, maintenance_window_duration=None,
enable_auto_backup=None, enable_encryption=False, retention_period=None, storage_account_url=None,
storage_access_key=None, backup_password=None, backup_system_dbs=False, backup_schedule_type=None,
full_backup_frequency=None, full_backup_start_time=None, full_backup_window_hours=None, log_backup_frequency=None,
enable_key_vault_credential=None, credential_name=None, azure_key_vault_url=None, service_principal_name=None,
service_principal_secret=None, connectivity_type=None, port=None, sql_workload_type=None, enable_r_services=None, tags=None):
'''
Updates a SQL virtual machine.
'''
if tags is not None:
instance.tags = tags
if sql_server_license_type is not None:
instance.sql_server_license_type = sql_server_license_type
if (enable_auto_patching is not None or day_of_week is not None or maintenance_window_starting_hour is not None or maintenance_window_duration is not None):
enable_auto_patching = enable_auto_patching if enable_auto_patching is False else True
instance.auto_patching_settings = AutoPatchingSettings(enable=enable_auto_patching,
day_of_week=day_of_week,
maintenance_window_starting_hour=maintenance_window_starting_hour,
maintenance_window_duration=maintenance_window_duration)
if (enable_auto_backup is not None or enable_encryption or retention_period is not None or storage_account_url is not None or
storage_access_key is not None or backup_password is not None or backup_system_dbs or backup_schedule_type is not None or
full_backup_frequency is not None or full_backup_start_time is not None or full_backup_window_hours is not None or
log_backup_frequency is not None):
enable_auto_backup = enable_auto_backup if enable_auto_backup is False else True
instance.auto_backup_settings = AutoBackupSettings(enable=enable_auto_backup,
enable_encryption=enable_encryption if enable_auto_backup else None,
retention_period=retention_period,
storage_account_url=storage_account_url,
storage_access_key=storage_access_key,
password=backup_password,
backup_system_dbs=backup_system_dbs if enable_auto_backup else None,
backup_schedule_type=backup_schedule_type,
full_backup_frequency=full_backup_frequency,
full_backup_start_time=full_backup_start_time,
full_backup_window_hours=full_backup_window_hours,
log_backup_frequency=log_backup_frequency)
if (enable_key_vault_credential is not None or credential_name is not None or azure_key_vault_url is not None or
service_principal_name is not None or service_principal_secret is not None):
enable_key_vault_credential = enable_key_vault_credential if enable_key_vault_credential is False else True
instance.key_vault_credential_settings = KeyVaultCredentialSettings(enable=enable_key_vault_credential,
credential_name=credential_name,
service_principal_name=service_principal_name,
service_principal_secret=service_principal_secret,
azure_key_vault_url=azure_key_vault_url)
instance.server_configurations_management_settings = ServerConfigurationsManagementSettings()
if (connectivity_type is not None or port is not None):
instance.server_configurations_management_settings.sql_connectivity_update_settings = SqlConnectivityUpdateSettings(connectivity_type=connectivity_type,
port=port)
if sql_workload_type is not None:
instance.server_configurations_management_settings.sql_workload_type_update_settings = SqlWorkloadTypeUpdateSettings(sql_workload_type=sql_workload_type)
if enable_r_services is not None:
instance.server_configurations_management_settings.additional_features_server_configurations = AdditionalFeaturesServerConfigurations(is_rservices_enabled=enable_r_services)
# If none of the settings was modified, reset server_configurations_management_settings to be null
if (instance.server_configurations_management_settings.sql_connectivity_update_settings is None and
instance.server_configurations_management_settings.sql_workload_type_update_settings is None and
instance.server_configurations_management_settings.sql_storage_update_settings is None and
instance.server_configurations_management_settings.additional_features_server_configurations is None):
instance.server_configurations_management_settings = None
return instance | python | def sqlvm_update(instance, sql_server_license_type=None, enable_auto_patching=None,
day_of_week=None, maintenance_window_starting_hour=None, maintenance_window_duration=None,
enable_auto_backup=None, enable_encryption=False, retention_period=None, storage_account_url=None,
storage_access_key=None, backup_password=None, backup_system_dbs=False, backup_schedule_type=None,
full_backup_frequency=None, full_backup_start_time=None, full_backup_window_hours=None, log_backup_frequency=None,
enable_key_vault_credential=None, credential_name=None, azure_key_vault_url=None, service_principal_name=None,
service_principal_secret=None, connectivity_type=None, port=None, sql_workload_type=None, enable_r_services=None, tags=None):
'''
Updates a SQL virtual machine.
'''
if tags is not None:
instance.tags = tags
if sql_server_license_type is not None:
instance.sql_server_license_type = sql_server_license_type
if (enable_auto_patching is not None or day_of_week is not None or maintenance_window_starting_hour is not None or maintenance_window_duration is not None):
enable_auto_patching = enable_auto_patching if enable_auto_patching is False else True
instance.auto_patching_settings = AutoPatchingSettings(enable=enable_auto_patching,
day_of_week=day_of_week,
maintenance_window_starting_hour=maintenance_window_starting_hour,
maintenance_window_duration=maintenance_window_duration)
if (enable_auto_backup is not None or enable_encryption or retention_period is not None or storage_account_url is not None or
storage_access_key is not None or backup_password is not None or backup_system_dbs or backup_schedule_type is not None or
full_backup_frequency is not None or full_backup_start_time is not None or full_backup_window_hours is not None or
log_backup_frequency is not None):
enable_auto_backup = enable_auto_backup if enable_auto_backup is False else True
instance.auto_backup_settings = AutoBackupSettings(enable=enable_auto_backup,
enable_encryption=enable_encryption if enable_auto_backup else None,
retention_period=retention_period,
storage_account_url=storage_account_url,
storage_access_key=storage_access_key,
password=backup_password,
backup_system_dbs=backup_system_dbs if enable_auto_backup else None,
backup_schedule_type=backup_schedule_type,
full_backup_frequency=full_backup_frequency,
full_backup_start_time=full_backup_start_time,
full_backup_window_hours=full_backup_window_hours,
log_backup_frequency=log_backup_frequency)
if (enable_key_vault_credential is not None or credential_name is not None or azure_key_vault_url is not None or
service_principal_name is not None or service_principal_secret is not None):
enable_key_vault_credential = enable_key_vault_credential if enable_key_vault_credential is False else True
instance.key_vault_credential_settings = KeyVaultCredentialSettings(enable=enable_key_vault_credential,
credential_name=credential_name,
service_principal_name=service_principal_name,
service_principal_secret=service_principal_secret,
azure_key_vault_url=azure_key_vault_url)
instance.server_configurations_management_settings = ServerConfigurationsManagementSettings()
if (connectivity_type is not None or port is not None):
instance.server_configurations_management_settings.sql_connectivity_update_settings = SqlConnectivityUpdateSettings(connectivity_type=connectivity_type,
port=port)
if sql_workload_type is not None:
instance.server_configurations_management_settings.sql_workload_type_update_settings = SqlWorkloadTypeUpdateSettings(sql_workload_type=sql_workload_type)
if enable_r_services is not None:
instance.server_configurations_management_settings.additional_features_server_configurations = AdditionalFeaturesServerConfigurations(is_rservices_enabled=enable_r_services)
# If none of the settings was modified, reset server_configurations_management_settings to be null
if (instance.server_configurations_management_settings.sql_connectivity_update_settings is None and
instance.server_configurations_management_settings.sql_workload_type_update_settings is None and
instance.server_configurations_management_settings.sql_storage_update_settings is None and
instance.server_configurations_management_settings.additional_features_server_configurations is None):
instance.server_configurations_management_settings = None
return instance | [
"def",
"sqlvm_update",
"(",
"instance",
",",
"sql_server_license_type",
"=",
"None",
",",
"enable_auto_patching",
"=",
"None",
",",
"day_of_week",
"=",
"None",
",",
"maintenance_window_starting_hour",
"=",
"None",
",",
"maintenance_window_duration",
"=",
"None",
",",
... | Updates a SQL virtual machine. | [
"Updates",
"a",
"SQL",
"virtual",
"machine",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L271-L342 |
228,737 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | add_sqlvm_to_group | def add_sqlvm_to_group(instance, sql_virtual_machine_group_resource_id, sql_service_account_password,
cluster_operator_account_password, cluster_bootstrap_account_password=None):
'''
Add a SQL virtual machine to a SQL virtual machine group.
'''
if not is_valid_resource_id(sql_virtual_machine_group_resource_id):
raise CLIError("Invalid SQL virtual machine group resource id.")
instance.sql_virtual_machine_group_resource_id = sql_virtual_machine_group_resource_id
instance.wsfc_domain_credentials = WsfcDomainCredentials(cluster_bootstrap_account_password=cluster_bootstrap_account_password,
cluster_operator_account_password=cluster_operator_account_password,
sql_service_account_password=sql_service_account_password)
return instance | python | def add_sqlvm_to_group(instance, sql_virtual_machine_group_resource_id, sql_service_account_password,
cluster_operator_account_password, cluster_bootstrap_account_password=None):
'''
Add a SQL virtual machine to a SQL virtual machine group.
'''
if not is_valid_resource_id(sql_virtual_machine_group_resource_id):
raise CLIError("Invalid SQL virtual machine group resource id.")
instance.sql_virtual_machine_group_resource_id = sql_virtual_machine_group_resource_id
instance.wsfc_domain_credentials = WsfcDomainCredentials(cluster_bootstrap_account_password=cluster_bootstrap_account_password,
cluster_operator_account_password=cluster_operator_account_password,
sql_service_account_password=sql_service_account_password)
return instance | [
"def",
"add_sqlvm_to_group",
"(",
"instance",
",",
"sql_virtual_machine_group_resource_id",
",",
"sql_service_account_password",
",",
"cluster_operator_account_password",
",",
"cluster_bootstrap_account_password",
"=",
"None",
")",
":",
"if",
"not",
"is_valid_resource_id",
"(",... | Add a SQL virtual machine to a SQL virtual machine group. | [
"Add",
"a",
"SQL",
"virtual",
"machine",
"to",
"a",
"SQL",
"virtual",
"machine",
"group",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L345-L358 |
228,738 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | add_sqlvm_to_aglistener | def add_sqlvm_to_aglistener(instance, sqlvm_resource_id):
'''
Add a SQL virtual machine to an availability group listener.
'''
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id not in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.append(sqlvm_resource_id)
return instance | python | def add_sqlvm_to_aglistener(instance, sqlvm_resource_id):
'''
Add a SQL virtual machine to an availability group listener.
'''
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id not in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.append(sqlvm_resource_id)
return instance | [
"def",
"add_sqlvm_to_aglistener",
"(",
"instance",
",",
"sqlvm_resource_id",
")",
":",
"if",
"not",
"is_valid_resource_id",
"(",
"sqlvm_resource_id",
")",
":",
"raise",
"CLIError",
"(",
"\"Invalid SQL virtual machine resource id.\"",
")",
"vm_list",
"=",
"instance",
"."... | Add a SQL virtual machine to an availability group listener. | [
"Add",
"a",
"SQL",
"virtual",
"machine",
"to",
"an",
"availability",
"group",
"listener",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L370-L382 |
228,739 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/custom.py | remove_sqlvm_from_aglistener | def remove_sqlvm_from_aglistener(instance, sqlvm_resource_id):
'''
Remove a SQL virtual machine from an availability group listener.
'''
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.remove(sqlvm_resource_id)
return instance | python | def remove_sqlvm_from_aglistener(instance, sqlvm_resource_id):
'''
Remove a SQL virtual machine from an availability group listener.
'''
if not is_valid_resource_id(sqlvm_resource_id):
raise CLIError("Invalid SQL virtual machine resource id.")
vm_list = instance.load_balancer_configurations[0].sql_virtual_machine_instances
if sqlvm_resource_id in vm_list:
instance.load_balancer_configurations[0].sql_virtual_machine_instances.remove(sqlvm_resource_id)
return instance | [
"def",
"remove_sqlvm_from_aglistener",
"(",
"instance",
",",
"sqlvm_resource_id",
")",
":",
"if",
"not",
"is_valid_resource_id",
"(",
"sqlvm_resource_id",
")",
":",
"raise",
"CLIError",
"(",
"\"Invalid SQL virtual machine resource id.\"",
")",
"vm_list",
"=",
"instance",
... | Remove a SQL virtual machine from an availability group listener. | [
"Remove",
"a",
"SQL",
"virtual",
"machine",
"from",
"an",
"availability",
"group",
"listener",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/custom.py#L385-L397 |
228,740 | Azure/azure-cli-extensions | src/botservice/azext_bot/custom.py | publish_app | def publish_app(cmd, client, resource_group_name, resource_name, code_dir=None, proj_name=None, version='v3'):
"""Publish local bot code to Azure.
This method is directly called via "bot publish"
:param cmd:
:param client:
:param resource_group_name:
:param resource_name:
:param code_dir:
:param proj_name:
:param version:
:return:
"""
if version == 'v3':
return publish_appv3(cmd, client, resource_group_name, resource_name, code_dir)
# Get the bot information and ensure it's not only a registration bot.
bot = client.bots.get(
resource_group_name=resource_group_name,
resource_name=resource_name
)
if bot.kind == 'bot':
raise CLIError('Bot kind is \'bot\', meaning it is a registration bot. '
'Source publish is not supported for registration only bots.')
# If the user does not pass in a path to the local bot project, get the current working directory.
if not code_dir:
code_dir = os.getcwd()
logger.info('Parameter --code-dir not provided, defaulting to current working directory, %s. '
'For more information, run \'az bot publish -h\'', code_dir)
if not os.path.isdir(code_dir):
raise CLIError('The path %s is not a valid directory. '
'Please supply a valid directory path containing your source code.' % code_dir)
# Ensure that the directory contains appropriate post deploy scripts folder
if 'PostDeployScripts' not in os.listdir(code_dir):
BotPublishPrep.prepare_publish_v4(logger, code_dir, proj_name)
logger.info('Creating upload zip file.')
zip_filepath = BotPublishPrep.create_upload_zip(logger, code_dir, include_node_modules=False)
logger.info('Zip file path created, at %s.', zip_filepath)
kudu_client = KuduClient(cmd, resource_group_name, resource_name, bot)
output = kudu_client.publish(zip_filepath)
logger.info('Bot source published. Preparing bot application to run the new source.')
os.remove('upload.zip')
if os.path.exists(os.path.join('.', 'package.json')):
logger.info('Detected language javascript. Installing node dependencies in remote bot.')
__install_node_dependencies(kudu_client)
if output.get('active'):
logger.info('Deployment successful!')
if not output.get('active'):
scm_url = output.get('url')
deployment_id = output.get('id')
# Instead of replacing "latest", which would could be in the bot name, we replace "deployments/latest"
deployment_url = scm_url.replace('deployments/latest', 'deployments/%s' % deployment_id)
logger.error('Deployment failed. To find out more information about this deployment, please visit %s.'
% deployment_url)
return output | python | def publish_app(cmd, client, resource_group_name, resource_name, code_dir=None, proj_name=None, version='v3'):
if version == 'v3':
return publish_appv3(cmd, client, resource_group_name, resource_name, code_dir)
# Get the bot information and ensure it's not only a registration bot.
bot = client.bots.get(
resource_group_name=resource_group_name,
resource_name=resource_name
)
if bot.kind == 'bot':
raise CLIError('Bot kind is \'bot\', meaning it is a registration bot. '
'Source publish is not supported for registration only bots.')
# If the user does not pass in a path to the local bot project, get the current working directory.
if not code_dir:
code_dir = os.getcwd()
logger.info('Parameter --code-dir not provided, defaulting to current working directory, %s. '
'For more information, run \'az bot publish -h\'', code_dir)
if not os.path.isdir(code_dir):
raise CLIError('The path %s is not a valid directory. '
'Please supply a valid directory path containing your source code.' % code_dir)
# Ensure that the directory contains appropriate post deploy scripts folder
if 'PostDeployScripts' not in os.listdir(code_dir):
BotPublishPrep.prepare_publish_v4(logger, code_dir, proj_name)
logger.info('Creating upload zip file.')
zip_filepath = BotPublishPrep.create_upload_zip(logger, code_dir, include_node_modules=False)
logger.info('Zip file path created, at %s.', zip_filepath)
kudu_client = KuduClient(cmd, resource_group_name, resource_name, bot)
output = kudu_client.publish(zip_filepath)
logger.info('Bot source published. Preparing bot application to run the new source.')
os.remove('upload.zip')
if os.path.exists(os.path.join('.', 'package.json')):
logger.info('Detected language javascript. Installing node dependencies in remote bot.')
__install_node_dependencies(kudu_client)
if output.get('active'):
logger.info('Deployment successful!')
if not output.get('active'):
scm_url = output.get('url')
deployment_id = output.get('id')
# Instead of replacing "latest", which would could be in the bot name, we replace "deployments/latest"
deployment_url = scm_url.replace('deployments/latest', 'deployments/%s' % deployment_id)
logger.error('Deployment failed. To find out more information about this deployment, please visit %s.'
% deployment_url)
return output | [
"def",
"publish_app",
"(",
"cmd",
",",
"client",
",",
"resource_group_name",
",",
"resource_name",
",",
"code_dir",
"=",
"None",
",",
"proj_name",
"=",
"None",
",",
"version",
"=",
"'v3'",
")",
":",
"if",
"version",
"==",
"'v3'",
":",
"return",
"publish_ap... | Publish local bot code to Azure.
This method is directly called via "bot publish"
:param cmd:
:param client:
:param resource_group_name:
:param resource_name:
:param code_dir:
:param proj_name:
:param version:
:return: | [
"Publish",
"local",
"bot",
"code",
"to",
"Azure",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/botservice/azext_bot/custom.py#L41-L105 |
228,741 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/command_tree.py | CommandTree.get_child | def get_child(self, child_name): # pylint: disable=no-self-use
""" returns the object with the name supplied """
child = self.children.get(child_name, None)
if child:
return child
raise ValueError("Value {} not in this tree".format(child_name)) | python | def get_child(self, child_name): # pylint: disable=no-self-use
child = self.children.get(child_name, None)
if child:
return child
raise ValueError("Value {} not in this tree".format(child_name)) | [
"def",
"get_child",
"(",
"self",
",",
"child_name",
")",
":",
"# pylint: disable=no-self-use",
"child",
"=",
"self",
".",
"children",
".",
"get",
"(",
"child_name",
",",
"None",
")",
"if",
"child",
":",
"return",
"child",
"raise",
"ValueError",
"(",
"\"Value... | returns the object with the name supplied | [
"returns",
"the",
"object",
"with",
"the",
"name",
"supplied"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/command_tree.py#L16-L21 |
228,742 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/command_tree.py | CommandTree.in_tree | def in_tree(self, cmd_args):
""" if a command is in the tree """
if not cmd_args:
return True
tree = self
try:
for datum in cmd_args:
tree = tree.get_child(datum)
except ValueError:
return False
return True | python | def in_tree(self, cmd_args):
if not cmd_args:
return True
tree = self
try:
for datum in cmd_args:
tree = tree.get_child(datum)
except ValueError:
return False
return True | [
"def",
"in_tree",
"(",
"self",
",",
"cmd_args",
")",
":",
"if",
"not",
"cmd_args",
":",
"return",
"True",
"tree",
"=",
"self",
"try",
":",
"for",
"datum",
"in",
"cmd_args",
":",
"tree",
"=",
"tree",
".",
"get_child",
"(",
"datum",
")",
"except",
"Val... | if a command is in the tree | [
"if",
"a",
"command",
"is",
"in",
"the",
"tree"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/command_tree.py#L32-L42 |
228,743 | Azure/azure-cli-extensions | src/alias/azext_alias/telemetry.py | AliasExtensionTelemetrySession.generate_payload | def generate_payload(self):
"""
Generate a list of telemetry events as payload
"""
events = []
transformation_task = self._get_alias_transformation_properties()
transformation_task.update(self._get_based_properties())
events.append(transformation_task)
for exception in self.exceptions:
properties = {
'Reserved.DataModel.Fault.TypeString': exception.__class__.__name__,
'Reserved.DataModel.Fault.Exception.Message': self.get_exception_message(exception),
'Reserved.DataModel.Fault.Exception.StackTrace': _get_stack_trace(),
}
self.set_custom_properties(properties, 'ActionType', 'Exception')
self.set_custom_properties(properties, 'Version', VERSION)
events.append(properties)
return events | python | def generate_payload(self):
events = []
transformation_task = self._get_alias_transformation_properties()
transformation_task.update(self._get_based_properties())
events.append(transformation_task)
for exception in self.exceptions:
properties = {
'Reserved.DataModel.Fault.TypeString': exception.__class__.__name__,
'Reserved.DataModel.Fault.Exception.Message': self.get_exception_message(exception),
'Reserved.DataModel.Fault.Exception.StackTrace': _get_stack_trace(),
}
self.set_custom_properties(properties, 'ActionType', 'Exception')
self.set_custom_properties(properties, 'Version', VERSION)
events.append(properties)
return events | [
"def",
"generate_payload",
"(",
"self",
")",
":",
"events",
"=",
"[",
"]",
"transformation_task",
"=",
"self",
".",
"_get_alias_transformation_properties",
"(",
")",
"transformation_task",
".",
"update",
"(",
"self",
".",
"_get_based_properties",
"(",
")",
")",
... | Generate a list of telemetry events as payload | [
"Generate",
"a",
"list",
"of",
"telemetry",
"events",
"as",
"payload"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/telemetry.py#L38-L57 |
228,744 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | sort_completions | def sort_completions(completions_gen):
""" sorts the completions """
from knack.help import REQUIRED_TAG
def _get_weight(val):
""" weights the completions with required things first the lexicographically"""
priority = ''
if val.display_meta and val.display_meta.startswith(REQUIRED_TAG):
priority = ' ' # a space has the lowest ordinance
return priority + val.text
return sorted(completions_gen, key=_get_weight) | python | def sort_completions(completions_gen):
from knack.help import REQUIRED_TAG
def _get_weight(val):
""" weights the completions with required things first the lexicographically"""
priority = ''
if val.display_meta and val.display_meta.startswith(REQUIRED_TAG):
priority = ' ' # a space has the lowest ordinance
return priority + val.text
return sorted(completions_gen, key=_get_weight) | [
"def",
"sort_completions",
"(",
"completions_gen",
")",
":",
"from",
"knack",
".",
"help",
"import",
"REQUIRED_TAG",
"def",
"_get_weight",
"(",
"val",
")",
":",
"\"\"\" weights the completions with required things first the lexicographically\"\"\"",
"priority",
"=",
"''",
... | sorts the completions | [
"sorts",
"the",
"completions"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L34-L45 |
228,745 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.validate_param_completion | def validate_param_completion(self, param, leftover_args):
""" validates that a param should be completed """
# validates param starts with unfinished word
completes = self.validate_completion(param)
# show parameter completions when started
full_param = self.unfinished_word.startswith("--") and param.startswith("--")
char_param = self.unfinished_word.startswith("-") and not param.startswith("--")
# show full parameters before any are used
new_param = not self.unfinished_word and not leftover_args and param.startswith("--")
# checks for parameters already in the line as well as aliases
no_doubles = True
command_doubles = self.command_param_info.get(self.current_command, {})
for alias in command_doubles.get(param, []):
if alias in leftover_args:
no_doubles = False
return completes and no_doubles and any((full_param, char_param, new_param)) | python | def validate_param_completion(self, param, leftover_args):
# validates param starts with unfinished word
completes = self.validate_completion(param)
# show parameter completions when started
full_param = self.unfinished_word.startswith("--") and param.startswith("--")
char_param = self.unfinished_word.startswith("-") and not param.startswith("--")
# show full parameters before any are used
new_param = not self.unfinished_word and not leftover_args and param.startswith("--")
# checks for parameters already in the line as well as aliases
no_doubles = True
command_doubles = self.command_param_info.get(self.current_command, {})
for alias in command_doubles.get(param, []):
if alias in leftover_args:
no_doubles = False
return completes and no_doubles and any((full_param, char_param, new_param)) | [
"def",
"validate_param_completion",
"(",
"self",
",",
"param",
",",
"leftover_args",
")",
":",
"# validates param starts with unfinished word",
"completes",
"=",
"self",
".",
"validate_completion",
"(",
"param",
")",
"# show parameter completions when started",
"full_param",
... | validates that a param should be completed | [
"validates",
"that",
"a",
"param",
"should",
"be",
"completed"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L117-L136 |
228,746 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.process_dynamic_completion | def process_dynamic_completion(self, completion):
""" how to validate and generate completion for dynamic params """
if len(completion.split()) > 1:
completion = '\"' + completion + '\"'
if self.validate_completion(completion):
yield Completion(completion, -len(self.unfinished_word)) | python | def process_dynamic_completion(self, completion):
if len(completion.split()) > 1:
completion = '\"' + completion + '\"'
if self.validate_completion(completion):
yield Completion(completion, -len(self.unfinished_word)) | [
"def",
"process_dynamic_completion",
"(",
"self",
",",
"completion",
")",
":",
"if",
"len",
"(",
"completion",
".",
"split",
"(",
")",
")",
">",
"1",
":",
"completion",
"=",
"'\\\"'",
"+",
"completion",
"+",
"'\\\"'",
"if",
"self",
".",
"validate_completio... | how to validate and generate completion for dynamic params | [
"how",
"to",
"validate",
"and",
"generate",
"completion",
"for",
"dynamic",
"params"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L141-L147 |
228,747 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.gen_enum_completions | def gen_enum_completions(self, arg_name):
""" generates dynamic enumeration completions """
try: # if enum completion
for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
if self.validate_completion(choice):
yield Completion(choice, -len(self.unfinished_word))
except TypeError: # there is no choices option
pass | python | def gen_enum_completions(self, arg_name):
try: # if enum completion
for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
if self.validate_completion(choice):
yield Completion(choice, -len(self.unfinished_word))
except TypeError: # there is no choices option
pass | [
"def",
"gen_enum_completions",
"(",
"self",
",",
"arg_name",
")",
":",
"try",
":",
"# if enum completion",
"for",
"choice",
"in",
"self",
".",
"cmdtab",
"[",
"self",
".",
"current_command",
"]",
".",
"arguments",
"[",
"arg_name",
"]",
".",
"choices",
":",
... | generates dynamic enumeration completions | [
"generates",
"dynamic",
"enumeration",
"completions"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L181-L189 |
228,748 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.get_arg_name | def get_arg_name(self, param):
""" gets the argument name used in the command table for a parameter """
if self.current_command in self.cmdtab:
for arg in self.cmdtab[self.current_command].arguments:
for name in self.cmdtab[self.current_command].arguments[arg].options_list:
if name == param:
return arg
return None | python | def get_arg_name(self, param):
if self.current_command in self.cmdtab:
for arg in self.cmdtab[self.current_command].arguments:
for name in self.cmdtab[self.current_command].arguments[arg].options_list:
if name == param:
return arg
return None | [
"def",
"get_arg_name",
"(",
"self",
",",
"param",
")",
":",
"if",
"self",
".",
"current_command",
"in",
"self",
".",
"cmdtab",
":",
"for",
"arg",
"in",
"self",
".",
"cmdtab",
"[",
"self",
".",
"current_command",
"]",
".",
"arguments",
":",
"for",
"name... | gets the argument name used in the command table for a parameter | [
"gets",
"the",
"argument",
"name",
"used",
"in",
"the",
"command",
"table",
"for",
"a",
"parameter"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L191-L199 |
228,749 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.mute_parse_args | def mute_parse_args(self, text):
""" mutes the parser error when parsing, then puts it back """
error = AzCliCommandParser.error
_check_value = AzCliCommandParser._check_value
AzCliCommandParser.error = error_pass
AzCliCommandParser._check_value = _check_value_muted
# No exception is expected. However, we add this try-catch block, as this may have far-reaching effects.
try:
parse_args = self.argsfinder.get_parsed_args(parse_quotes(text, quotes=False, string=False))
except Exception: # pylint: disable=broad-except
pass
AzCliCommandParser.error = error
AzCliCommandParser._check_value = _check_value
return parse_args | python | def mute_parse_args(self, text):
error = AzCliCommandParser.error
_check_value = AzCliCommandParser._check_value
AzCliCommandParser.error = error_pass
AzCliCommandParser._check_value = _check_value_muted
# No exception is expected. However, we add this try-catch block, as this may have far-reaching effects.
try:
parse_args = self.argsfinder.get_parsed_args(parse_quotes(text, quotes=False, string=False))
except Exception: # pylint: disable=broad-except
pass
AzCliCommandParser.error = error
AzCliCommandParser._check_value = _check_value
return parse_args | [
"def",
"mute_parse_args",
"(",
"self",
",",
"text",
")",
":",
"error",
"=",
"AzCliCommandParser",
".",
"error",
"_check_value",
"=",
"AzCliCommandParser",
".",
"_check_value",
"AzCliCommandParser",
".",
"error",
"=",
"error_pass",
"AzCliCommandParser",
".",
"_check_... | mutes the parser error when parsing, then puts it back | [
"mutes",
"the",
"parser",
"error",
"when",
"parsing",
"then",
"puts",
"it",
"back"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L202-L218 |
228,750 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.gen_dynamic_completions | def gen_dynamic_completions(self, text):
""" generates the dynamic values, like the names of resource groups """
try: # pylint: disable=too-many-nested-blocks
param = self.leftover_args[-1]
# command table specific name
arg_name = self.get_arg_name(param)
for comp in self.gen_enum_completions(arg_name):
yield comp
parsed_args = self.mute_parse_args(text)
# there are 3 formats for completers the cli uses
# this try catches which format it is
if self.cmdtab[self.current_command].arguments[arg_name].completer:
completions = []
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer(
prefix=self.unfinished_word, action=None, parsed_args=parsed_args)
except TypeError:
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer(
prefix=self.unfinished_word)
except TypeError:
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer()
except TypeError:
pass # other completion method used
for comp in completions:
for completion in self.process_dynamic_completion(comp):
yield completion
# if the user isn't logged in
except Exception: # pylint: disable=broad-except
pass | python | def gen_dynamic_completions(self, text):
try: # pylint: disable=too-many-nested-blocks
param = self.leftover_args[-1]
# command table specific name
arg_name = self.get_arg_name(param)
for comp in self.gen_enum_completions(arg_name):
yield comp
parsed_args = self.mute_parse_args(text)
# there are 3 formats for completers the cli uses
# this try catches which format it is
if self.cmdtab[self.current_command].arguments[arg_name].completer:
completions = []
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer(
prefix=self.unfinished_word, action=None, parsed_args=parsed_args)
except TypeError:
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer(
prefix=self.unfinished_word)
except TypeError:
try:
completions = self.cmdtab[self.current_command].arguments[arg_name].completer()
except TypeError:
pass # other completion method used
for comp in completions:
for completion in self.process_dynamic_completion(comp):
yield completion
# if the user isn't logged in
except Exception: # pylint: disable=broad-except
pass | [
"def",
"gen_dynamic_completions",
"(",
"self",
",",
"text",
")",
":",
"try",
":",
"# pylint: disable=too-many-nested-blocks",
"param",
"=",
"self",
".",
"leftover_args",
"[",
"-",
"1",
"]",
"# command table specific name",
"arg_name",
"=",
"self",
".",
"get_arg_name... | generates the dynamic values, like the names of resource groups | [
"generates",
"the",
"dynamic",
"values",
"like",
"the",
"names",
"of",
"resource",
"groups"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L221-L257 |
228,751 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.yield_param_completion | def yield_param_completion(self, param, last_word):
""" yields a parameter """
return Completion(param, -len(last_word), display_meta=self.param_description.get(
self.current_command + " " + str(param), '').replace(os.linesep, '')) | python | def yield_param_completion(self, param, last_word):
return Completion(param, -len(last_word), display_meta=self.param_description.get(
self.current_command + " " + str(param), '').replace(os.linesep, '')) | [
"def",
"yield_param_completion",
"(",
"self",
",",
"param",
",",
"last_word",
")",
":",
"return",
"Completion",
"(",
"param",
",",
"-",
"len",
"(",
"last_word",
")",
",",
"display_meta",
"=",
"self",
".",
"param_description",
".",
"get",
"(",
"self",
".",
... | yields a parameter | [
"yields",
"a",
"parameter"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L259-L262 |
228,752 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.gen_cmd_and_param_completions | def gen_cmd_and_param_completions(self):
""" generates command and parameter completions """
if self.complete_command:
for param in self.command_param_info.get(self.current_command, []):
if self.validate_param_completion(param, self.leftover_args):
yield self.yield_param_completion(param, self.unfinished_word)
elif not self.leftover_args:
for child_command in self.subtree.children:
if self.validate_completion(child_command):
yield Completion(child_command, -len(self.unfinished_word)) | python | def gen_cmd_and_param_completions(self):
if self.complete_command:
for param in self.command_param_info.get(self.current_command, []):
if self.validate_param_completion(param, self.leftover_args):
yield self.yield_param_completion(param, self.unfinished_word)
elif not self.leftover_args:
for child_command in self.subtree.children:
if self.validate_completion(child_command):
yield Completion(child_command, -len(self.unfinished_word)) | [
"def",
"gen_cmd_and_param_completions",
"(",
"self",
")",
":",
"if",
"self",
".",
"complete_command",
":",
"for",
"param",
"in",
"self",
".",
"command_param_info",
".",
"get",
"(",
"self",
".",
"current_command",
",",
"[",
"]",
")",
":",
"if",
"self",
".",... | generates command and parameter completions | [
"generates",
"command",
"and",
"parameter",
"completions"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L264-L273 |
228,753 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.has_description | def has_description(self, param):
""" if a parameter has a description """
return param in self.param_description.keys() and \
not self.param_description[param].isspace() | python | def has_description(self, param):
return param in self.param_description.keys() and \
not self.param_description[param].isspace() | [
"def",
"has_description",
"(",
"self",
",",
"param",
")",
":",
"return",
"param",
"in",
"self",
".",
"param_description",
".",
"keys",
"(",
")",
"and",
"not",
"self",
".",
"param_description",
"[",
"param",
"]",
".",
"isspace",
"(",
")"
] | if a parameter has a description | [
"if",
"a",
"parameter",
"has",
"a",
"description"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L293-L296 |
228,754 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/az_completer.py | AzCompleter.reformat_cmd | def reformat_cmd(self, text):
""" reformat the text to be stripped of noise """
# remove az if there
text = text.replace('az', '')
# disregard defaulting symbols
if text and SELECT_SYMBOL['scope'] == text[0:2]:
text = text.replace(SELECT_SYMBOL['scope'], "")
if self.shell_ctx.default_command:
text = self.shell_ctx.default_command + ' ' + text
return text | python | def reformat_cmd(self, text):
# remove az if there
text = text.replace('az', '')
# disregard defaulting symbols
if text and SELECT_SYMBOL['scope'] == text[0:2]:
text = text.replace(SELECT_SYMBOL['scope'], "")
if self.shell_ctx.default_command:
text = self.shell_ctx.default_command + ' ' + text
return text | [
"def",
"reformat_cmd",
"(",
"self",
",",
"text",
")",
":",
"# remove az if there",
"text",
"=",
"text",
".",
"replace",
"(",
"'az'",
",",
"''",
")",
"# disregard defaulting symbols",
"if",
"text",
"and",
"SELECT_SYMBOL",
"[",
"'scope'",
"]",
"==",
"text",
"[... | reformat the text to be stripped of noise | [
"reformat",
"the",
"text",
"to",
"be",
"stripped",
"of",
"noise"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/az_completer.py#L298-L308 |
228,755 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/custom.py | _remove_nulls | def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization.
"""
attrs = ['tags']
ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id']
sp_attrs = ['secret']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
for ap_profile in managed_cluster.agent_pool_profiles:
for attr in ap_attrs:
if getattr(ap_profile, attr, None) is None:
delattr(ap_profile, attr)
for attr in sp_attrs:
if getattr(managed_cluster.service_principal_profile, attr, None) is None:
delattr(managed_cluster.service_principal_profile, attr)
return managed_clusters | python | def _remove_nulls(managed_clusters):
attrs = ['tags']
ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id']
sp_attrs = ['secret']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
for ap_profile in managed_cluster.agent_pool_profiles:
for attr in ap_attrs:
if getattr(ap_profile, attr, None) is None:
delattr(ap_profile, attr)
for attr in sp_attrs:
if getattr(managed_cluster.service_principal_profile, attr, None) is None:
delattr(managed_cluster.service_principal_profile, attr)
return managed_clusters | [
"def",
"_remove_nulls",
"(",
"managed_clusters",
")",
":",
"attrs",
"=",
"[",
"'tags'",
"]",
"ap_attrs",
"=",
"[",
"'os_disk_size_gb'",
",",
"'vnet_subnet_id'",
"]",
"sp_attrs",
"=",
"[",
"'secret'",
"]",
"for",
"managed_cluster",
"in",
"managed_clusters",
":",
... | Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization. | [
"Remove",
"some",
"often",
"-",
"empty",
"fields",
"from",
"a",
"list",
"of",
"ManagedClusters",
"so",
"the",
"JSON",
"representation",
"doesn",
"t",
"contain",
"distracting",
"null",
"fields",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/custom.py#L622-L644 |
228,756 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/argfinder.py | ArgsFinder.get_parsed_args | def get_parsed_args(self, comp_words):
""" gets the parsed args from a patched parser """
active_parsers = self._patch_argument_parser()
parsed_args = argparse.Namespace()
self.completing = True
if USING_PYTHON2:
# Python 2 argparse only properly works with byte strings.
comp_words = [ensure_bytes(word) for word in comp_words]
try:
active_parsers[0].parse_known_args(comp_words, namespace=parsed_args)
except BaseException: # pylint: disable=broad-except
pass
self.completing = False
return parsed_args | python | def get_parsed_args(self, comp_words):
active_parsers = self._patch_argument_parser()
parsed_args = argparse.Namespace()
self.completing = True
if USING_PYTHON2:
# Python 2 argparse only properly works with byte strings.
comp_words = [ensure_bytes(word) for word in comp_words]
try:
active_parsers[0].parse_known_args(comp_words, namespace=parsed_args)
except BaseException: # pylint: disable=broad-except
pass
self.completing = False
return parsed_args | [
"def",
"get_parsed_args",
"(",
"self",
",",
"comp_words",
")",
":",
"active_parsers",
"=",
"self",
".",
"_patch_argument_parser",
"(",
")",
"parsed_args",
"=",
"argparse",
".",
"Namespace",
"(",
")",
"self",
".",
"completing",
"=",
"True",
"if",
"USING_PYTHON2... | gets the parsed args from a patched parser | [
"gets",
"the",
"parsed",
"args",
"from",
"a",
"patched",
"parser"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/argfinder.py#L19-L36 |
228,757 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | get_alias_table | def get_alias_table():
"""
Get the current alias table.
"""
try:
alias_table = get_config_parser()
alias_table.read(azext_alias.alias.GLOBAL_ALIAS_PATH)
return alias_table
except Exception: # pylint: disable=broad-except
return get_config_parser() | python | def get_alias_table():
try:
alias_table = get_config_parser()
alias_table.read(azext_alias.alias.GLOBAL_ALIAS_PATH)
return alias_table
except Exception: # pylint: disable=broad-except
return get_config_parser() | [
"def",
"get_alias_table",
"(",
")",
":",
"try",
":",
"alias_table",
"=",
"get_config_parser",
"(",
")",
"alias_table",
".",
"read",
"(",
"azext_alias",
".",
"alias",
".",
"GLOBAL_ALIAS_PATH",
")",
"return",
"alias_table",
"except",
"Exception",
":",
"# pylint: d... | Get the current alias table. | [
"Get",
"the",
"current",
"alias",
"table",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L35-L44 |
228,758 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | is_alias_command | def is_alias_command(subcommands, args):
"""
Check if the user is invoking one of the comments in 'subcommands' in the from az alias .
Args:
subcommands: The list of subcommands to check through.
args: The CLI arguments to process.
Returns:
True if the user is invoking 'az alias {command}'.
"""
if not args:
return False
for subcommand in subcommands:
if args[:2] == ['alias', subcommand]:
return True
return False | python | def is_alias_command(subcommands, args):
if not args:
return False
for subcommand in subcommands:
if args[:2] == ['alias', subcommand]:
return True
return False | [
"def",
"is_alias_command",
"(",
"subcommands",
",",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"False",
"for",
"subcommand",
"in",
"subcommands",
":",
"if",
"args",
"[",
":",
"2",
"]",
"==",
"[",
"'alias'",
",",
"subcommand",
"]",
":",
"retu... | Check if the user is invoking one of the comments in 'subcommands' in the from az alias .
Args:
subcommands: The list of subcommands to check through.
args: The CLI arguments to process.
Returns:
True if the user is invoking 'az alias {command}'. | [
"Check",
"if",
"the",
"user",
"is",
"invoking",
"one",
"of",
"the",
"comments",
"in",
"subcommands",
"in",
"the",
"from",
"az",
"alias",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L47-L65 |
228,759 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | remove_pos_arg_placeholders | def remove_pos_arg_placeholders(alias_command):
"""
Remove positional argument placeholders from alias_command.
Args:
alias_command: The alias command to remove from.
Returns:
The alias command string without positional argument placeholder.
"""
# Boundary index is the index at which named argument or positional argument starts
split_command = shlex.split(alias_command)
boundary_index = len(split_command)
for i, subcommand in enumerate(split_command):
if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
boundary_index = i
break
return ' '.join(split_command[:boundary_index]).lower() | python | def remove_pos_arg_placeholders(alias_command):
# Boundary index is the index at which named argument or positional argument starts
split_command = shlex.split(alias_command)
boundary_index = len(split_command)
for i, subcommand in enumerate(split_command):
if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
boundary_index = i
break
return ' '.join(split_command[:boundary_index]).lower() | [
"def",
"remove_pos_arg_placeholders",
"(",
"alias_command",
")",
":",
"# Boundary index is the index at which named argument or positional argument starts",
"split_command",
"=",
"shlex",
".",
"split",
"(",
"alias_command",
")",
"boundary_index",
"=",
"len",
"(",
"split_command... | Remove positional argument placeholders from alias_command.
Args:
alias_command: The alias command to remove from.
Returns:
The alias command string without positional argument placeholder. | [
"Remove",
"positional",
"argument",
"placeholders",
"from",
"alias_command",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L82-L100 |
228,760 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | filter_aliases | def filter_aliases(alias_table):
"""
Filter aliases that does not have a command field in the configuration file.
Args:
alias_table: The alias table.
Yield:
A tuple with [0] being the first word of the alias and
[1] being the command that the alias points to.
"""
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
yield (alias.split()[0], remove_pos_arg_placeholders(alias_table.get(alias, 'command'))) | python | def filter_aliases(alias_table):
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
yield (alias.split()[0], remove_pos_arg_placeholders(alias_table.get(alias, 'command'))) | [
"def",
"filter_aliases",
"(",
"alias_table",
")",
":",
"for",
"alias",
"in",
"alias_table",
".",
"sections",
"(",
")",
":",
"if",
"alias_table",
".",
"has_option",
"(",
"alias",
",",
"'command'",
")",
":",
"yield",
"(",
"alias",
".",
"split",
"(",
")",
... | Filter aliases that does not have a command field in the configuration file.
Args:
alias_table: The alias table.
Yield:
A tuple with [0] being the first word of the alias and
[1] being the command that the alias points to. | [
"Filter",
"aliases",
"that",
"does",
"not",
"have",
"a",
"command",
"field",
"in",
"the",
"configuration",
"file",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L103-L116 |
228,761 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | reduce_alias_table | def reduce_alias_table(alias_table):
"""
Reduce the alias table to a tuple that contains the alias and the command that the alias points to.
Args:
The alias table to be reduced.
Yields
A tuple that contains the alias and the command that the alias points to.
"""
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
yield (alias, alias_table.get(alias, 'command')) | python | def reduce_alias_table(alias_table):
for alias in alias_table.sections():
if alias_table.has_option(alias, 'command'):
yield (alias, alias_table.get(alias, 'command')) | [
"def",
"reduce_alias_table",
"(",
"alias_table",
")",
":",
"for",
"alias",
"in",
"alias_table",
".",
"sections",
"(",
")",
":",
"if",
"alias_table",
".",
"has_option",
"(",
"alias",
",",
"'command'",
")",
":",
"yield",
"(",
"alias",
",",
"alias_table",
"."... | Reduce the alias table to a tuple that contains the alias and the command that the alias points to.
Args:
The alias table to be reduced.
Yields
A tuple that contains the alias and the command that the alias points to. | [
"Reduce",
"the",
"alias",
"table",
"to",
"a",
"tuple",
"that",
"contains",
"the",
"alias",
"and",
"the",
"command",
"that",
"the",
"alias",
"points",
"to",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L168-L180 |
228,762 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | retrieve_file_from_url | def retrieve_file_from_url(url):
"""
Retrieve a file from an URL
Args:
url: The URL to retrieve the file from.
Returns:
The absolute path of the downloaded file.
"""
try:
alias_source, _ = urlretrieve(url)
# Check for HTTPError in Python 2.x
with open(alias_source, 'r') as f:
content = f.read()
if content[:3].isdigit():
raise CLIError(ALIAS_FILE_URL_ERROR.format(url, content.strip()))
except Exception as exception:
if isinstance(exception, CLIError):
raise
# Python 3.x
raise CLIError(ALIAS_FILE_URL_ERROR.format(url, exception))
return alias_source | python | def retrieve_file_from_url(url):
try:
alias_source, _ = urlretrieve(url)
# Check for HTTPError in Python 2.x
with open(alias_source, 'r') as f:
content = f.read()
if content[:3].isdigit():
raise CLIError(ALIAS_FILE_URL_ERROR.format(url, content.strip()))
except Exception as exception:
if isinstance(exception, CLIError):
raise
# Python 3.x
raise CLIError(ALIAS_FILE_URL_ERROR.format(url, exception))
return alias_source | [
"def",
"retrieve_file_from_url",
"(",
"url",
")",
":",
"try",
":",
"alias_source",
",",
"_",
"=",
"urlretrieve",
"(",
"url",
")",
"# Check for HTTPError in Python 2.x",
"with",
"open",
"(",
"alias_source",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
"f"... | Retrieve a file from an URL
Args:
url: The URL to retrieve the file from.
Returns:
The absolute path of the downloaded file. | [
"Retrieve",
"a",
"file",
"from",
"an",
"URL"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L183-L207 |
228,763 | Azure/azure-cli-extensions | src/alias/azext_alias/util.py | filter_alias_create_namespace | def filter_alias_create_namespace(namespace):
"""
Filter alias name and alias command inside alias create namespace to appropriate strings.
Args
namespace: The alias create namespace.
Returns:
Filtered namespace where excessive whitespaces are removed in strings.
"""
def filter_string(s):
return ' '.join(s.strip().split())
namespace.alias_name = filter_string(namespace.alias_name)
namespace.alias_command = filter_string(namespace.alias_command)
return namespace | python | def filter_alias_create_namespace(namespace):
def filter_string(s):
return ' '.join(s.strip().split())
namespace.alias_name = filter_string(namespace.alias_name)
namespace.alias_command = filter_string(namespace.alias_command)
return namespace | [
"def",
"filter_alias_create_namespace",
"(",
"namespace",
")",
":",
"def",
"filter_string",
"(",
"s",
")",
":",
"return",
"' '",
".",
"join",
"(",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
"namespace",
".",
"alias_name",
"=",
"filter_stri... | Filter alias name and alias command inside alias create namespace to appropriate strings.
Args
namespace: The alias create namespace.
Returns:
Filtered namespace where excessive whitespaces are removed in strings. | [
"Filter",
"alias",
"name",
"and",
"alias",
"command",
"inside",
"alias",
"create",
"namespace",
"to",
"appropriate",
"strings",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/util.py#L210-L225 |
228,764 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | get_lexers | def get_lexers(main_lex, exam_lex, tool_lex):
""" gets all the lexer wrappers """
if not main_lex:
return None, None, None
lexer = None
if main_lex:
if issubclass(main_lex, PromptLex):
lexer = main_lex
elif issubclass(main_lex, PygLex):
lexer = PygmentsLexer(main_lex)
if exam_lex:
if issubclass(exam_lex, PygLex):
exam_lex = PygmentsLexer(exam_lex)
if tool_lex:
if issubclass(tool_lex, PygLex):
tool_lex = PygmentsLexer(tool_lex)
return lexer, exam_lex, tool_lex | python | def get_lexers(main_lex, exam_lex, tool_lex):
if not main_lex:
return None, None, None
lexer = None
if main_lex:
if issubclass(main_lex, PromptLex):
lexer = main_lex
elif issubclass(main_lex, PygLex):
lexer = PygmentsLexer(main_lex)
if exam_lex:
if issubclass(exam_lex, PygLex):
exam_lex = PygmentsLexer(exam_lex)
if tool_lex:
if issubclass(tool_lex, PygLex):
tool_lex = PygmentsLexer(tool_lex)
return lexer, exam_lex, tool_lex | [
"def",
"get_lexers",
"(",
"main_lex",
",",
"exam_lex",
",",
"tool_lex",
")",
":",
"if",
"not",
"main_lex",
":",
"return",
"None",
",",
"None",
",",
"None",
"lexer",
"=",
"None",
"if",
"main_lex",
":",
"if",
"issubclass",
"(",
"main_lex",
",",
"PromptLex"... | gets all the lexer wrappers | [
"gets",
"all",
"the",
"lexer",
"wrappers"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L215-L234 |
228,765 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | get_anyhline | def get_anyhline(config):
""" if there is a line between descriptions and example """
if config.BOOLEAN_STATES[config.config.get('Layout', 'command_description')] or\
config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line))
return get_empty() | python | def get_anyhline(config):
if config.BOOLEAN_STATES[config.config.get('Layout', 'command_description')] or\
config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line))
return get_empty() | [
"def",
"get_anyhline",
"(",
"config",
")",
":",
"if",
"config",
".",
"BOOLEAN_STATES",
"[",
"config",
".",
"config",
".",
"get",
"(",
"'Layout'",
",",
"'command_description'",
")",
"]",
"or",
"config",
".",
"BOOLEAN_STATES",
"[",
"config",
".",
"config",
"... | if there is a line between descriptions and example | [
"if",
"there",
"is",
"a",
"line",
"between",
"descriptions",
"and",
"example"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L237-L245 |
228,766 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | get_example | def get_example(config, exam_lex):
""" example description window """
if config.BOOLEAN_STATES[config.config.get('Layout', 'examples')]:
return Window(
content=BufferControl(
buffer_name="examples",
lexer=exam_lex))
return get_empty() | python | def get_example(config, exam_lex):
if config.BOOLEAN_STATES[config.config.get('Layout', 'examples')]:
return Window(
content=BufferControl(
buffer_name="examples",
lexer=exam_lex))
return get_empty() | [
"def",
"get_example",
"(",
"config",
",",
"exam_lex",
")",
":",
"if",
"config",
".",
"BOOLEAN_STATES",
"[",
"config",
".",
"config",
".",
"get",
"(",
"'Layout'",
",",
"'examples'",
")",
"]",
":",
"return",
"Window",
"(",
"content",
"=",
"BufferControl",
... | example description window | [
"example",
"description",
"window"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L264-L271 |
228,767 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | get_hline | def get_hline():
""" gets a horiztonal line """
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) | python | def get_hline():
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) | [
"def",
"get_hline",
"(",
")",
":",
"return",
"Window",
"(",
"width",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
",",
"height",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
",",
"content",
"=",
"FillControl",
"(",
"'-'",
",",
"token",
... | gets a horiztonal line | [
"gets",
"a",
"horiztonal",
"line"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L288-L293 |
228,768 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | get_descriptions | def get_descriptions(config, exam_lex, lexer):
""" based on the configuration settings determines which windows to include """
if config.BOOLEAN_STATES[config.config.get('Layout', 'command_description')]:
if config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return VSplit([
get_descript(exam_lex),
get_vline(),
get_param(lexer),
])
return get_descript(exam_lex)
if config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return get_param(lexer)
return get_empty() | python | def get_descriptions(config, exam_lex, lexer):
if config.BOOLEAN_STATES[config.config.get('Layout', 'command_description')]:
if config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return VSplit([
get_descript(exam_lex),
get_vline(),
get_param(lexer),
])
return get_descript(exam_lex)
if config.BOOLEAN_STATES[config.config.get('Layout', 'param_description')]:
return get_param(lexer)
return get_empty() | [
"def",
"get_descriptions",
"(",
"config",
",",
"exam_lex",
",",
"lexer",
")",
":",
"if",
"config",
".",
"BOOLEAN_STATES",
"[",
"config",
".",
"config",
".",
"get",
"(",
"'Layout'",
",",
"'command_description'",
")",
"]",
":",
"if",
"config",
".",
"BOOLEAN_... | based on the configuration settings determines which windows to include | [
"based",
"on",
"the",
"configuration",
"settings",
"determines",
"which",
"windows",
"to",
"include"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L304-L316 |
228,769 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | LayoutManager.get_prompt_tokens | def get_prompt_tokens(self, _):
""" returns prompt tokens """
if self.shell_ctx.default_command:
prompt = 'az {}>> '.format(self.shell_ctx.default_command)
else:
prompt = 'az>> '
return [(Token.Az, prompt)] | python | def get_prompt_tokens(self, _):
if self.shell_ctx.default_command:
prompt = 'az {}>> '.format(self.shell_ctx.default_command)
else:
prompt = 'az>> '
return [(Token.Az, prompt)] | [
"def",
"get_prompt_tokens",
"(",
"self",
",",
"_",
")",
":",
"if",
"self",
".",
"shell_ctx",
".",
"default_command",
":",
"prompt",
"=",
"'az {}>> '",
".",
"format",
"(",
"self",
".",
"shell_ctx",
".",
"default_command",
")",
"else",
":",
"prompt",
"=",
... | returns prompt tokens | [
"returns",
"prompt",
"tokens"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L74-L80 |
228,770 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | LayoutManager.create_tutorial_layout | def create_tutorial_layout(self):
""" layout for example tutorial """
lexer, _, _ = get_lexers(self.shell_ctx.lexer, None, None)
layout_full = HSplit([
FloatContainer(
Window(
BufferControl(
input_processors=self.input_processors,
lexer=lexer,
preview_search=Always()),
get_height=get_height),
[
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=MAX_COMPLETION,
scroll_offset=1,
extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
ConditionalContainer(
HSplit([
get_hline(),
get_param(lexer),
get_hline(),
Window(
content=BufferControl(
buffer_name='example_line',
lexer=lexer
),
),
Window(
TokenListControl(
get_tutorial_tokens,
default_char=Char(' ', Token.Toolbar)),
height=LayoutDimension.exact(1)),
]),
filter=~IsDone() & RendererHeightIsKnown()
)
])
return layout_full | python | def create_tutorial_layout(self):
lexer, _, _ = get_lexers(self.shell_ctx.lexer, None, None)
layout_full = HSplit([
FloatContainer(
Window(
BufferControl(
input_processors=self.input_processors,
lexer=lexer,
preview_search=Always()),
get_height=get_height),
[
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=MAX_COMPLETION,
scroll_offset=1,
extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
ConditionalContainer(
HSplit([
get_hline(),
get_param(lexer),
get_hline(),
Window(
content=BufferControl(
buffer_name='example_line',
lexer=lexer
),
),
Window(
TokenListControl(
get_tutorial_tokens,
default_char=Char(' ', Token.Toolbar)),
height=LayoutDimension.exact(1)),
]),
filter=~IsDone() & RendererHeightIsKnown()
)
])
return layout_full | [
"def",
"create_tutorial_layout",
"(",
"self",
")",
":",
"lexer",
",",
"_",
",",
"_",
"=",
"get_lexers",
"(",
"self",
".",
"shell_ctx",
".",
"lexer",
",",
"None",
",",
"None",
")",
"layout_full",
"=",
"HSplit",
"(",
"[",
"FloatContainer",
"(",
"Window",
... | layout for example tutorial | [
"layout",
"for",
"example",
"tutorial"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L82-L120 |
228,771 | Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/layout.py | LayoutManager.create_layout | def create_layout(self, exam_lex, toolbar_lex):
""" creates the layout """
lexer, exam_lex, toolbar_lex = get_lexers(self.shell_ctx.lexer, exam_lex, toolbar_lex)
if not any(isinstance(processor, DefaultPrompt) for processor in self.input_processors):
self.input_processors.append(DefaultPrompt(self.get_prompt_tokens))
layout_lower = ConditionalContainer(
HSplit([
get_anyhline(self.shell_ctx.config),
get_descriptions(self.shell_ctx.config, exam_lex, lexer),
get_examplehline(self.shell_ctx.config),
get_example(self.shell_ctx.config, exam_lex),
ConditionalContainer(
get_hline(),
filter=self.show_default | self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='default_values',
lexer=lexer
)
),
filter=self.show_default
),
ConditionalContainer(
get_hline(),
filter=self.show_default & self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='symbols',
lexer=exam_lex
)
),
filter=self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='progress',
lexer=lexer
)
),
filter=self.show_progress
),
Window(
content=BufferControl(
buffer_name='bottom_toolbar',
lexer=toolbar_lex
),
),
]),
filter=~IsDone() & RendererHeightIsKnown()
)
layout_full = HSplit([
FloatContainer(
Window(
BufferControl(
input_processors=self.input_processors,
lexer=lexer,
preview_search=Always()),
get_height=get_height,
),
[
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=MAX_COMPLETION,
scroll_offset=1,
extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
layout_lower
])
return layout_full | python | def create_layout(self, exam_lex, toolbar_lex):
lexer, exam_lex, toolbar_lex = get_lexers(self.shell_ctx.lexer, exam_lex, toolbar_lex)
if not any(isinstance(processor, DefaultPrompt) for processor in self.input_processors):
self.input_processors.append(DefaultPrompt(self.get_prompt_tokens))
layout_lower = ConditionalContainer(
HSplit([
get_anyhline(self.shell_ctx.config),
get_descriptions(self.shell_ctx.config, exam_lex, lexer),
get_examplehline(self.shell_ctx.config),
get_example(self.shell_ctx.config, exam_lex),
ConditionalContainer(
get_hline(),
filter=self.show_default | self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='default_values',
lexer=lexer
)
),
filter=self.show_default
),
ConditionalContainer(
get_hline(),
filter=self.show_default & self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='symbols',
lexer=exam_lex
)
),
filter=self.show_symbol
),
ConditionalContainer(
Window(
content=BufferControl(
buffer_name='progress',
lexer=lexer
)
),
filter=self.show_progress
),
Window(
content=BufferControl(
buffer_name='bottom_toolbar',
lexer=toolbar_lex
),
),
]),
filter=~IsDone() & RendererHeightIsKnown()
)
layout_full = HSplit([
FloatContainer(
Window(
BufferControl(
input_processors=self.input_processors,
lexer=lexer,
preview_search=Always()),
get_height=get_height,
),
[
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=MAX_COMPLETION,
scroll_offset=1,
extra_filter=(HasFocus(DEFAULT_BUFFER))))]),
layout_lower
])
return layout_full | [
"def",
"create_layout",
"(",
"self",
",",
"exam_lex",
",",
"toolbar_lex",
")",
":",
"lexer",
",",
"exam_lex",
",",
"toolbar_lex",
"=",
"get_lexers",
"(",
"self",
".",
"shell_ctx",
".",
"lexer",
",",
"exam_lex",
",",
"toolbar_lex",
")",
"if",
"not",
"any",
... | creates the layout | [
"creates",
"the",
"layout"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/layout.py#L122-L200 |
228,772 | Azure/azure-cli-extensions | src/dev-spaces/azext_dev_spaces/custom.py | ads_use_dev_spaces | def ads_use_dev_spaces(cluster_name, resource_group_name, update=False, space_name=None, do_not_prompt=False):
"""
Use Azure Dev Spaces with a managed Kubernetes cluster.
:param cluster_name: Name of the managed cluster.
:type cluster_name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param update: Update to the latest Azure Dev Spaces client components.
:type update: bool
:param space_name: Name of the new or existing dev space to select. Defaults to an interactive selection experience.
:type space_name: String
:param do_not_prompt: Do not prompt for confirmation. Requires --space.
:type do_not_prompt: bool
"""
azds_cli = _install_dev_spaces_cli(update)
use_command_arguments = [azds_cli, 'use', '--name', cluster_name,
'--resource-group', resource_group_name]
if space_name is not None:
use_command_arguments.append('--space')
use_command_arguments.append(space_name)
if do_not_prompt:
use_command_arguments.append('-y')
subprocess.call(
use_command_arguments, universal_newlines=True) | python | def ads_use_dev_spaces(cluster_name, resource_group_name, update=False, space_name=None, do_not_prompt=False):
azds_cli = _install_dev_spaces_cli(update)
use_command_arguments = [azds_cli, 'use', '--name', cluster_name,
'--resource-group', resource_group_name]
if space_name is not None:
use_command_arguments.append('--space')
use_command_arguments.append(space_name)
if do_not_prompt:
use_command_arguments.append('-y')
subprocess.call(
use_command_arguments, universal_newlines=True) | [
"def",
"ads_use_dev_spaces",
"(",
"cluster_name",
",",
"resource_group_name",
",",
"update",
"=",
"False",
",",
"space_name",
"=",
"None",
",",
"do_not_prompt",
"=",
"False",
")",
":",
"azds_cli",
"=",
"_install_dev_spaces_cli",
"(",
"update",
")",
"use_command_ar... | Use Azure Dev Spaces with a managed Kubernetes cluster.
:param cluster_name: Name of the managed cluster.
:type cluster_name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param update: Update to the latest Azure Dev Spaces client components.
:type update: bool
:param space_name: Name of the new or existing dev space to select. Defaults to an interactive selection experience.
:type space_name: String
:param do_not_prompt: Do not prompt for confirmation. Requires --space.
:type do_not_prompt: bool | [
"Use",
"Azure",
"Dev",
"Spaces",
"with",
"a",
"managed",
"Kubernetes",
"cluster",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/dev-spaces/azext_dev_spaces/custom.py#L21-L50 |
228,773 | Azure/azure-cli-extensions | src/dev-spaces/azext_dev_spaces/custom.py | ads_remove_dev_spaces | def ads_remove_dev_spaces(cluster_name, resource_group_name, do_not_prompt=False):
"""
Remove Azure Dev Spaces from a managed Kubernetes cluster.
:param cluster_name: Name of the managed cluster.
:type cluster_name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param do_not_prompt: Do not prompt for confirmation.
:type do_not_prompt: bool
"""
azds_cli = _install_dev_spaces_cli(False)
remove_command_arguments = [azds_cli, 'remove', '--name', cluster_name,
'--resource-group', resource_group_name]
if do_not_prompt:
remove_command_arguments.append('-y')
subprocess.call(
remove_command_arguments, universal_newlines=True) | python | def ads_remove_dev_spaces(cluster_name, resource_group_name, do_not_prompt=False):
azds_cli = _install_dev_spaces_cli(False)
remove_command_arguments = [azds_cli, 'remove', '--name', cluster_name,
'--resource-group', resource_group_name]
if do_not_prompt:
remove_command_arguments.append('-y')
subprocess.call(
remove_command_arguments, universal_newlines=True) | [
"def",
"ads_remove_dev_spaces",
"(",
"cluster_name",
",",
"resource_group_name",
",",
"do_not_prompt",
"=",
"False",
")",
":",
"azds_cli",
"=",
"_install_dev_spaces_cli",
"(",
"False",
")",
"remove_command_arguments",
"=",
"[",
"azds_cli",
",",
"'remove'",
",",
"'--... | Remove Azure Dev Spaces from a managed Kubernetes cluster.
:param cluster_name: Name of the managed cluster.
:type cluster_name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param do_not_prompt: Do not prompt for confirmation.
:type do_not_prompt: bool | [
"Remove",
"Azure",
"Dev",
"Spaces",
"from",
"a",
"managed",
"Kubernetes",
"cluster",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/dev-spaces/azext_dev_spaces/custom.py#L53-L73 |
228,774 | Azure/azure-cli-extensions | src/application-insights/azext_applicationinsights/util.py | get_query_targets | def get_query_targets(cli_ctx, apps, resource_group):
"""Produces a list of uniform GUIDs representing applications to query."""
if isinstance(apps, list):
if resource_group:
return [get_id_from_azure_resource(cli_ctx, apps[0], resource_group)]
return list(map(lambda x: get_id_from_azure_resource(cli_ctx, x), apps))
else:
if resource_group:
return [get_id_from_azure_resource(cli_ctx, apps, resource_group)]
return apps | python | def get_query_targets(cli_ctx, apps, resource_group):
if isinstance(apps, list):
if resource_group:
return [get_id_from_azure_resource(cli_ctx, apps[0], resource_group)]
return list(map(lambda x: get_id_from_azure_resource(cli_ctx, x), apps))
else:
if resource_group:
return [get_id_from_azure_resource(cli_ctx, apps, resource_group)]
return apps | [
"def",
"get_query_targets",
"(",
"cli_ctx",
",",
"apps",
",",
"resource_group",
")",
":",
"if",
"isinstance",
"(",
"apps",
",",
"list",
")",
":",
"if",
"resource_group",
":",
"return",
"[",
"get_id_from_azure_resource",
"(",
"cli_ctx",
",",
"apps",
"[",
"0",... | Produces a list of uniform GUIDs representing applications to query. | [
"Produces",
"a",
"list",
"of",
"uniform",
"GUIDs",
"representing",
"applications",
"to",
"query",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/application-insights/azext_applicationinsights/util.py#L22-L31 |
228,775 | Azure/azure-cli-extensions | src/application-insights/azext_applicationinsights/util.py | get_linked_properties | def get_linked_properties(cli_ctx, app, resource_group, read_properties=None, write_properties=None):
"""Maps user-facing role names to strings used to identify them on resources."""
roles = {
"ReadTelemetry": "api",
"WriteAnnotations": "annotations",
"AuthenticateSDKControlChannel": "agentconfig"
}
sub_id = get_subscription_id(cli_ctx)
tmpl = '/subscriptions/{}/resourceGroups/{}/providers/microsoft.insights/components/{}'.format(
sub_id,
resource_group,
app
)
linked_read_properties, linked_write_properties = [], []
if isinstance(read_properties, list):
propLen = len(read_properties)
linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties[i]]) for i in range(propLen)]
else:
linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties])]
if isinstance(write_properties, list):
propLen = len(write_properties)
linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties[i]]) for i in range(propLen)]
else:
linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties])]
return linked_read_properties, linked_write_properties | python | def get_linked_properties(cli_ctx, app, resource_group, read_properties=None, write_properties=None):
roles = {
"ReadTelemetry": "api",
"WriteAnnotations": "annotations",
"AuthenticateSDKControlChannel": "agentconfig"
}
sub_id = get_subscription_id(cli_ctx)
tmpl = '/subscriptions/{}/resourceGroups/{}/providers/microsoft.insights/components/{}'.format(
sub_id,
resource_group,
app
)
linked_read_properties, linked_write_properties = [], []
if isinstance(read_properties, list):
propLen = len(read_properties)
linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties[i]]) for i in range(propLen)]
else:
linked_read_properties = ['{}/{}'.format(tmpl, roles[read_properties])]
if isinstance(write_properties, list):
propLen = len(write_properties)
linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties[i]]) for i in range(propLen)]
else:
linked_write_properties = ['{}/{}'.format(tmpl, roles[write_properties])]
return linked_read_properties, linked_write_properties | [
"def",
"get_linked_properties",
"(",
"cli_ctx",
",",
"app",
",",
"resource_group",
",",
"read_properties",
"=",
"None",
",",
"write_properties",
"=",
"None",
")",
":",
"roles",
"=",
"{",
"\"ReadTelemetry\"",
":",
"\"api\"",
",",
"\"WriteAnnotations\"",
":",
"\"a... | Maps user-facing role names to strings used to identify them on resources. | [
"Maps",
"user",
"-",
"facing",
"role",
"names",
"to",
"strings",
"used",
"to",
"identify",
"them",
"on",
"resources",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/application-insights/azext_applicationinsights/util.py#L48-L74 |
228,776 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | transform_aglistener_output | def transform_aglistener_output(result):
'''
Transforms the result of Availability Group Listener to eliminate unnecessary parameters.
'''
from collections import OrderedDict
from msrestazure.tools import parse_resource_id
try:
resource_group = getattr(result, 'resource_group', None) or parse_resource_id(result.id)['resource_group']
# Create a dictionary with the relevant parameters
output = OrderedDict([('id', result.id),
('name', result.name),
('provisioningState', result.provisioning_state),
('port', result.port),
('resourceGroup', resource_group)])
# Note, wsfcDomainCredentials will not display
if result.load_balancer_configurations is not None:
output['loadBalancerConfigurations'] = format_load_balancer_configuration_list(result.load_balancer_configurations)
return output
except AttributeError:
# Return the response object if the formating fails
return result | python | def transform_aglistener_output(result):
'''
Transforms the result of Availability Group Listener to eliminate unnecessary parameters.
'''
from collections import OrderedDict
from msrestazure.tools import parse_resource_id
try:
resource_group = getattr(result, 'resource_group', None) or parse_resource_id(result.id)['resource_group']
# Create a dictionary with the relevant parameters
output = OrderedDict([('id', result.id),
('name', result.name),
('provisioningState', result.provisioning_state),
('port', result.port),
('resourceGroup', resource_group)])
# Note, wsfcDomainCredentials will not display
if result.load_balancer_configurations is not None:
output['loadBalancerConfigurations'] = format_load_balancer_configuration_list(result.load_balancer_configurations)
return output
except AttributeError:
# Return the response object if the formating fails
return result | [
"def",
"transform_aglistener_output",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"from",
"msrestazure",
".",
"tools",
"import",
"parse_resource_id",
"try",
":",
"resource_group",
"=",
"getattr",
"(",
"result",
",",
"'resource_group'",
"... | Transforms the result of Availability Group Listener to eliminate unnecessary parameters. | [
"Transforms",
"the",
"result",
"of",
"Availability",
"Group",
"Listener",
"to",
"eliminate",
"unnecessary",
"parameters",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L78-L100 |
228,777 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_wsfc_domain_profile | def format_wsfc_domain_profile(result):
'''
Formats the WSFCDomainProfile object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.cluster_bootstrap_account is not None:
order_dict['clusterBootstrapAccount'] = result.cluster_bootstrap_account
if result.domain_fqdn is not None:
order_dict['domainFqdn'] = result.domain_fqdn
if result.ou_path is not None:
order_dict['ouPath'] = result.ou_path
if result.cluster_operator_account is not None:
order_dict['clusterOperatorAccount'] = result.cluster_operator_account
if result.file_share_witness_path is not None:
order_dict['fileShareWitnessPath'] = result.file_share_witness_path
if result.sql_service_account is not None:
order_dict['sqlServiceAccount'] = result.sql_service_account
if result.storage_account_url is not None:
order_dict['storageAccountUrl'] = result.storage_account_url
return order_dict | python | def format_wsfc_domain_profile(result):
'''
Formats the WSFCDomainProfile object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.cluster_bootstrap_account is not None:
order_dict['clusterBootstrapAccount'] = result.cluster_bootstrap_account
if result.domain_fqdn is not None:
order_dict['domainFqdn'] = result.domain_fqdn
if result.ou_path is not None:
order_dict['ouPath'] = result.ou_path
if result.cluster_operator_account is not None:
order_dict['clusterOperatorAccount'] = result.cluster_operator_account
if result.file_share_witness_path is not None:
order_dict['fileShareWitnessPath'] = result.file_share_witness_path
if result.sql_service_account is not None:
order_dict['sqlServiceAccount'] = result.sql_service_account
if result.storage_account_url is not None:
order_dict['storageAccountUrl'] = result.storage_account_url
return order_dict | [
"def",
"format_wsfc_domain_profile",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"cluster_bootstrap_account",
"is",
"not",
"None",
... | Formats the WSFCDomainProfile object removing arguments that are empty | [
"Formats",
"the",
"WSFCDomainProfile",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L110-L132 |
228,778 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_additional_features_server_configurations | def format_additional_features_server_configurations(result):
'''
Formats the AdditionalFeaturesServerConfigurations object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.is_rservices_enabled is not None:
order_dict['isRServicesEnabled'] = result.is_rservices_enabled
if result.backup_permissions_for_azure_backup_svc is not None:
order_dict['backupPermissionsForAzureBackupSvc'] = result.backup_permissions_for_azure_backup_svc
return order_dict | python | def format_additional_features_server_configurations(result):
'''
Formats the AdditionalFeaturesServerConfigurations object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.is_rservices_enabled is not None:
order_dict['isRServicesEnabled'] = result.is_rservices_enabled
if result.backup_permissions_for_azure_backup_svc is not None:
order_dict['backupPermissionsForAzureBackupSvc'] = result.backup_permissions_for_azure_backup_svc
return order_dict | [
"def",
"format_additional_features_server_configurations",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"is_rservices_enabled",
"is",
... | Formats the AdditionalFeaturesServerConfigurations object removing arguments that are empty | [
"Formats",
"the",
"AdditionalFeaturesServerConfigurations",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L135-L147 |
228,779 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_auto_backup_settings | def format_auto_backup_settings(result):
'''
Formats the AutoBackupSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.enable_encryption is not None:
order_dict['enableEncryption'] = result.enable_encryption
if result.retention_period is not None:
order_dict['retentionPeriod'] = result.retention_period
if result.storage_account_url is not None:
order_dict['storageAccountUrl'] = result.storage_account_url
if result.backup_system_dbs is not None:
order_dict['backupSystemDbs'] = result.backup_system_dbs
if result.backup_schedule_type is not None:
order_dict['backupScheduleType'] = result.backup_schedule_type
if result.full_backup_frequency is not None:
order_dict['fullBackupFrequency'] = result.full_backup_frequency
if result.full_backup_start_time is not None:
order_dict['fullBackupStartTime'] = result.full_backup_start_time
if result.full_backup_window_hours is not None:
order_dict['fullBackupWindowHours'] = result.full_backup_window_hours
if result.log_backup_frequency is not None:
order_dict['logBackupFrequency'] = result.log_backup_frequency
return order_dict | python | def format_auto_backup_settings(result):
'''
Formats the AutoBackupSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.enable_encryption is not None:
order_dict['enableEncryption'] = result.enable_encryption
if result.retention_period is not None:
order_dict['retentionPeriod'] = result.retention_period
if result.storage_account_url is not None:
order_dict['storageAccountUrl'] = result.storage_account_url
if result.backup_system_dbs is not None:
order_dict['backupSystemDbs'] = result.backup_system_dbs
if result.backup_schedule_type is not None:
order_dict['backupScheduleType'] = result.backup_schedule_type
if result.full_backup_frequency is not None:
order_dict['fullBackupFrequency'] = result.full_backup_frequency
if result.full_backup_start_time is not None:
order_dict['fullBackupStartTime'] = result.full_backup_start_time
if result.full_backup_window_hours is not None:
order_dict['fullBackupWindowHours'] = result.full_backup_window_hours
if result.log_backup_frequency is not None:
order_dict['logBackupFrequency'] = result.log_backup_frequency
return order_dict | [
"def",
"format_auto_backup_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"enable",
"is",
"not",
"None",
":",
"order_di... | Formats the AutoBackupSettings object removing arguments that are empty | [
"Formats",
"the",
"AutoBackupSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L150-L178 |
228,780 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_auto_patching_settings | def format_auto_patching_settings(result):
'''
Formats the AutoPatchingSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.day_of_week is not None:
order_dict['dayOfWeek'] = result.day_of_week
if result.maintenance_window_starting_hour is not None:
order_dict['maintenanceWindowStartingHour'] = result.maintenance_window_starting_hour
if result.maintenance_window_duration is not None:
order_dict['maintenanceWindowDuration'] = result.maintenance_window_duration
return order_dict | python | def format_auto_patching_settings(result):
'''
Formats the AutoPatchingSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.day_of_week is not None:
order_dict['dayOfWeek'] = result.day_of_week
if result.maintenance_window_starting_hour is not None:
order_dict['maintenanceWindowStartingHour'] = result.maintenance_window_starting_hour
if result.maintenance_window_duration is not None:
order_dict['maintenanceWindowDuration'] = result.maintenance_window_duration
return order_dict | [
"def",
"format_auto_patching_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"enable",
"is",
"not",
"None",
":",
"order_... | Formats the AutoPatchingSettings object removing arguments that are empty | [
"Formats",
"the",
"AutoPatchingSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L181-L197 |
228,781 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_key_vault_credential_settings | def format_key_vault_credential_settings(result):
'''
Formats the KeyVaultCredentialSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.credential_name is not None:
order_dict['credentialName'] = result.credential_name
if result.azure_key_vault_url is not None:
order_dict['azureKeyVaultUrl'] = result.azure_key_vault_url
return order_dict | python | def format_key_vault_credential_settings(result):
'''
Formats the KeyVaultCredentialSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.enable is not None:
order_dict['enable'] = result.enable
if result.credential_name is not None:
order_dict['credentialName'] = result.credential_name
if result.azure_key_vault_url is not None:
order_dict['azureKeyVaultUrl'] = result.azure_key_vault_url
return order_dict | [
"def",
"format_key_vault_credential_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"enable",
"is",
"not",
"None",
":",
... | Formats the KeyVaultCredentialSettings object removing arguments that are empty | [
"Formats",
"the",
"KeyVaultCredentialSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L200-L214 |
228,782 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_load_balancer_configuration | def format_load_balancer_configuration(result):
'''
Formats the LoadBalancerConfiguration object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.private_ip_address is not None:
order_dict['privateIpAddress'] = format_private_ip_address(result.private_ip_address)
if result.public_ip_address_resource_id is not None:
order_dict['publicIpAddressResourceId'] = result.public_ip_address_resource_id
if result.load_balancer_resource_id is not None:
order_dict['loadBalancerResourceId'] = result.load_balancer_resource_id
if result.probe_port is not None:
order_dict['probePort'] = result.probe_port
if result.sql_virtual_machine_instances is not None:
order_dict['sqlVirtualMachineInstances'] = result.sql_virtual_machine_instances
return order_dict | python | def format_load_balancer_configuration(result):
'''
Formats the LoadBalancerConfiguration object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.private_ip_address is not None:
order_dict['privateIpAddress'] = format_private_ip_address(result.private_ip_address)
if result.public_ip_address_resource_id is not None:
order_dict['publicIpAddressResourceId'] = result.public_ip_address_resource_id
if result.load_balancer_resource_id is not None:
order_dict['loadBalancerResourceId'] = result.load_balancer_resource_id
if result.probe_port is not None:
order_dict['probePort'] = result.probe_port
if result.sql_virtual_machine_instances is not None:
order_dict['sqlVirtualMachineInstances'] = result.sql_virtual_machine_instances
return order_dict | [
"def",
"format_load_balancer_configuration",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"private_ip_address",
"is",
"not",
"None",... | Formats the LoadBalancerConfiguration object removing arguments that are empty | [
"Formats",
"the",
"LoadBalancerConfiguration",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L224-L242 |
228,783 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_private_ip_address | def format_private_ip_address(result):
'''
Formats the PrivateIPAddress object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.ip_address is not None:
order_dict['ipAddress'] = result.ip_address
if result.subnet_resource_id is not None:
order_dict['subnetResourceId'] = result.subnet_resource_id
return order_dict | python | def format_private_ip_address(result):
'''
Formats the PrivateIPAddress object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.ip_address is not None:
order_dict['ipAddress'] = result.ip_address
if result.subnet_resource_id is not None:
order_dict['subnetResourceId'] = result.subnet_resource_id
return order_dict | [
"def",
"format_private_ip_address",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"ip_address",
"is",
"not",
"None",
":",
"order_... | Formats the PrivateIPAddress object removing arguments that are empty | [
"Formats",
"the",
"PrivateIPAddress",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L245-L257 |
228,784 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_server_configuration_management_settings | def format_server_configuration_management_settings(result):
'''
Formats the ServerConfigurationsManagementSettings object removing arguments that are empty
'''
from collections import OrderedDict
order_dict = OrderedDict([('sqlConnectivityUpdateSettings',
format_sql_connectivity_update_settings(result.sql_connectivity_update_settings)),
('sqlWorkloadTypeUpdateSettings', format_sql_workload_type_update_settings(result.sql_workload_type_update_settings)),
('sqlStorageUpdateSettings', format_sql_storage_update_settings(result.sql_storage_update_settings)),
('additionalFeaturesServerConfigurations',
format_additional_features_server_configurations(result.additional_features_server_configurations))])
return order_dict | python | def format_server_configuration_management_settings(result):
'''
Formats the ServerConfigurationsManagementSettings object removing arguments that are empty
'''
from collections import OrderedDict
order_dict = OrderedDict([('sqlConnectivityUpdateSettings',
format_sql_connectivity_update_settings(result.sql_connectivity_update_settings)),
('sqlWorkloadTypeUpdateSettings', format_sql_workload_type_update_settings(result.sql_workload_type_update_settings)),
('sqlStorageUpdateSettings', format_sql_storage_update_settings(result.sql_storage_update_settings)),
('additionalFeaturesServerConfigurations',
format_additional_features_server_configurations(result.additional_features_server_configurations))])
return order_dict | [
"def",
"format_server_configuration_management_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"order_dict",
"=",
"OrderedDict",
"(",
"[",
"(",
"'sqlConnectivityUpdateSettings'",
",",
"format_sql_connectivity_update_settings",
"(",
"result"... | Formats the ServerConfigurationsManagementSettings object removing arguments that are empty | [
"Formats",
"the",
"ServerConfigurationsManagementSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L260-L272 |
228,785 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_sql_connectivity_update_settings | def format_sql_connectivity_update_settings(result):
'''
Formats the SqlConnectivityUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.connectivity_type is not None:
order_dict['connectivityType'] = result.connectivity_type
if result.port is not None:
order_dict['port'] = result.port
if result.sql_auth_update_user_name is not None:
order_dict['sqlAuthUpdateUserName'] = result.sql_auth_update_user_name
return order_dict | python | def format_sql_connectivity_update_settings(result):
'''
Formats the SqlConnectivityUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.connectivity_type is not None:
order_dict['connectivityType'] = result.connectivity_type
if result.port is not None:
order_dict['port'] = result.port
if result.sql_auth_update_user_name is not None:
order_dict['sqlAuthUpdateUserName'] = result.sql_auth_update_user_name
return order_dict | [
"def",
"format_sql_connectivity_update_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"connectivity_type",
"is",
"not",
"No... | Formats the SqlConnectivityUpdateSettings object removing arguments that are empty | [
"Formats",
"the",
"SqlConnectivityUpdateSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L275-L289 |
228,786 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_sql_storage_update_settings | def format_sql_storage_update_settings(result):
'''
Formats the SqlStorageUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.disk_count is not None:
order_dict['diskCount'] = result.disk_count
if result.disk_configuration_type is not None:
order_dict['diskConfigurationType'] = result.disk_configuration_type
return order_dict | python | def format_sql_storage_update_settings(result):
'''
Formats the SqlStorageUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.disk_count is not None:
order_dict['diskCount'] = result.disk_count
if result.disk_configuration_type is not None:
order_dict['diskConfigurationType'] = result.disk_configuration_type
return order_dict | [
"def",
"format_sql_storage_update_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"disk_count",
"is",
"not",
"None",
":",
... | Formats the SqlStorageUpdateSettings object removing arguments that are empty | [
"Formats",
"the",
"SqlStorageUpdateSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L292-L304 |
228,787 | Azure/azure-cli-extensions | src/sqlvm-preview/azext_sqlvm_preview/_format.py | format_sql_workload_type_update_settings | def format_sql_workload_type_update_settings(result):
'''
Formats the SqlWorkloadTypeUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.sql_workload_type is not None:
order_dict['sqlWorkloadType'] = result.sql_workload_type
return order_dict | python | def format_sql_workload_type_update_settings(result):
'''
Formats the SqlWorkloadTypeUpdateSettings object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.sql_workload_type is not None:
order_dict['sqlWorkloadType'] = result.sql_workload_type
return order_dict | [
"def",
"format_sql_workload_type_update_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"# Only display parameters that have content",
"order_dict",
"=",
"OrderedDict",
"(",
")",
"if",
"result",
".",
"sql_workload_type",
"is",
"not",
"N... | Formats the SqlWorkloadTypeUpdateSettings object removing arguments that are empty | [
"Formats",
"the",
"SqlWorkloadTypeUpdateSettings",
"object",
"removing",
"arguments",
"that",
"are",
"empty"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/sqlvm-preview/azext_sqlvm_preview/_format.py#L307-L317 |
228,788 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_format.py | aks_upgrades_table_format | def aks_upgrades_table_format(result):
"""Format get-upgrades results as a summary for display with "-o table"."""
# pylint: disable=import-error
from jmespath import compile as compile_jmes, Options
# This expression assumes there is one node pool, and that the master and nodes upgrade in lockstep.
parsed = compile_jmes("""{
name: name,
resourceGroup: resourceGroup,
masterVersion: controlPlaneProfile.kubernetesVersion || `unknown`,
nodePoolVersion: agentPoolProfiles[0].kubernetesVersion || `unknown`,
upgrades: controlPlaneProfile.upgrades || [`None available`] | sort_versions(@) | join(`, `, @)
}""")
# use ordered dicts so headers are predictable
return parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions())) | python | def aks_upgrades_table_format(result):
# pylint: disable=import-error
from jmespath import compile as compile_jmes, Options
# This expression assumes there is one node pool, and that the master and nodes upgrade in lockstep.
parsed = compile_jmes("""{
name: name,
resourceGroup: resourceGroup,
masterVersion: controlPlaneProfile.kubernetesVersion || `unknown`,
nodePoolVersion: agentPoolProfiles[0].kubernetesVersion || `unknown`,
upgrades: controlPlaneProfile.upgrades || [`None available`] | sort_versions(@) | join(`, `, @)
}""")
# use ordered dicts so headers are predictable
return parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions())) | [
"def",
"aks_upgrades_table_format",
"(",
"result",
")",
":",
"# pylint: disable=import-error",
"from",
"jmespath",
"import",
"compile",
"as",
"compile_jmes",
",",
"Options",
"# This expression assumes there is one node pool, and that the master and nodes upgrade in lockstep.",
"parse... | Format get-upgrades results as a summary for display with "-o table". | [
"Format",
"get",
"-",
"upgrades",
"results",
"as",
"a",
"summary",
"for",
"display",
"with",
"-",
"o",
"table",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_format.py#L56-L70 |
228,789 | Azure/azure-cli-extensions | src/aks-preview/azext_aks_preview/_format.py | aks_versions_table_format | def aks_versions_table_format(result):
"""Format get-versions results as a summary for display with "-o table"."""
# pylint: disable=import-error
from jmespath import compile as compile_jmes, Options
parsed = compile_jmes("""orchestrators[].{
kubernetesVersion: orchestratorVersion,
upgrades: upgrades[].orchestratorVersion || [`None available`] | sort_versions(@) | join(`, `, @)
}""")
# use ordered dicts so headers are predictable
results = parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions()))
return sorted(results, key=lambda x: version_to_tuple(x.get('kubernetesVersion')), reverse=True) | python | def aks_versions_table_format(result):
# pylint: disable=import-error
from jmespath import compile as compile_jmes, Options
parsed = compile_jmes("""orchestrators[].{
kubernetesVersion: orchestratorVersion,
upgrades: upgrades[].orchestratorVersion || [`None available`] | sort_versions(@) | join(`, `, @)
}""")
# use ordered dicts so headers are predictable
results = parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions()))
return sorted(results, key=lambda x: version_to_tuple(x.get('kubernetesVersion')), reverse=True) | [
"def",
"aks_versions_table_format",
"(",
"result",
")",
":",
"# pylint: disable=import-error",
"from",
"jmespath",
"import",
"compile",
"as",
"compile_jmes",
",",
"Options",
"parsed",
"=",
"compile_jmes",
"(",
"\"\"\"orchestrators[].{\n kubernetesVersion: orchestratorVer... | Format get-versions results as a summary for display with "-o table". | [
"Format",
"get",
"-",
"versions",
"results",
"as",
"a",
"summary",
"for",
"display",
"with",
"-",
"o",
"table",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/aks-preview/azext_aks_preview/_format.py#L73-L84 |
228,790 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | process_alias_create_namespace | def process_alias_create_namespace(namespace):
"""
Validate input arguments when the user invokes 'az alias create'.
Args:
namespace: argparse namespace object.
"""
namespace = filter_alias_create_namespace(namespace)
_validate_alias_name(namespace.alias_name)
_validate_alias_command(namespace.alias_command)
_validate_alias_command_level(namespace.alias_name, namespace.alias_command)
_validate_pos_args_syntax(namespace.alias_name, namespace.alias_command) | python | def process_alias_create_namespace(namespace):
namespace = filter_alias_create_namespace(namespace)
_validate_alias_name(namespace.alias_name)
_validate_alias_command(namespace.alias_command)
_validate_alias_command_level(namespace.alias_name, namespace.alias_command)
_validate_pos_args_syntax(namespace.alias_name, namespace.alias_command) | [
"def",
"process_alias_create_namespace",
"(",
"namespace",
")",
":",
"namespace",
"=",
"filter_alias_create_namespace",
"(",
"namespace",
")",
"_validate_alias_name",
"(",
"namespace",
".",
"alias_name",
")",
"_validate_alias_command",
"(",
"namespace",
".",
"alias_comman... | Validate input arguments when the user invokes 'az alias create'.
Args:
namespace: argparse namespace object. | [
"Validate",
"input",
"arguments",
"when",
"the",
"user",
"invokes",
"az",
"alias",
"create",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L37-L48 |
228,791 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | process_alias_import_namespace | def process_alias_import_namespace(namespace):
"""
Validate input arguments when the user invokes 'az alias import'.
Args:
namespace: argparse namespace object.
"""
if is_url(namespace.alias_source):
alias_source = retrieve_file_from_url(namespace.alias_source)
_validate_alias_file_content(alias_source, url=namespace.alias_source)
else:
namespace.alias_source = os.path.abspath(namespace.alias_source)
_validate_alias_file_path(namespace.alias_source)
_validate_alias_file_content(namespace.alias_source) | python | def process_alias_import_namespace(namespace):
if is_url(namespace.alias_source):
alias_source = retrieve_file_from_url(namespace.alias_source)
_validate_alias_file_content(alias_source, url=namespace.alias_source)
else:
namespace.alias_source = os.path.abspath(namespace.alias_source)
_validate_alias_file_path(namespace.alias_source)
_validate_alias_file_content(namespace.alias_source) | [
"def",
"process_alias_import_namespace",
"(",
"namespace",
")",
":",
"if",
"is_url",
"(",
"namespace",
".",
"alias_source",
")",
":",
"alias_source",
"=",
"retrieve_file_from_url",
"(",
"namespace",
".",
"alias_source",
")",
"_validate_alias_file_content",
"(",
"alias... | Validate input arguments when the user invokes 'az alias import'.
Args:
namespace: argparse namespace object. | [
"Validate",
"input",
"arguments",
"when",
"the",
"user",
"invokes",
"az",
"alias",
"import",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L51-L65 |
228,792 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | process_alias_export_namespace | def process_alias_export_namespace(namespace):
"""
Validate input arguments when the user invokes 'az alias export'.
Args:
namespace: argparse namespace object.
"""
namespace.export_path = os.path.abspath(namespace.export_path)
if os.path.isfile(namespace.export_path):
raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))
export_path_dir = os.path.dirname(namespace.export_path)
if not os.path.isdir(export_path_dir):
os.makedirs(export_path_dir)
if os.path.isdir(namespace.export_path):
namespace.export_path = os.path.join(namespace.export_path, ALIAS_FILE_NAME) | python | def process_alias_export_namespace(namespace):
namespace.export_path = os.path.abspath(namespace.export_path)
if os.path.isfile(namespace.export_path):
raise CLIError(FILE_ALREADY_EXISTS_ERROR.format(namespace.export_path))
export_path_dir = os.path.dirname(namespace.export_path)
if not os.path.isdir(export_path_dir):
os.makedirs(export_path_dir)
if os.path.isdir(namespace.export_path):
namespace.export_path = os.path.join(namespace.export_path, ALIAS_FILE_NAME) | [
"def",
"process_alias_export_namespace",
"(",
"namespace",
")",
":",
"namespace",
".",
"export_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"namespace",
".",
"export_path",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"namespace",
".",
"export_pa... | Validate input arguments when the user invokes 'az alias export'.
Args:
namespace: argparse namespace object. | [
"Validate",
"input",
"arguments",
"when",
"the",
"user",
"invokes",
"az",
"alias",
"export",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L68-L84 |
228,793 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_alias_name | def _validate_alias_name(alias_name):
"""
Check if the alias name is valid.
Args:
alias_name: The name of the alias to validate.
"""
if not alias_name:
raise CLIError(EMPTY_ALIAS_ERROR)
if not re.match('^[a-zA-Z]', alias_name):
raise CLIError(INVALID_STARTING_CHAR_ERROR.format(alias_name[0])) | python | def _validate_alias_name(alias_name):
if not alias_name:
raise CLIError(EMPTY_ALIAS_ERROR)
if not re.match('^[a-zA-Z]', alias_name):
raise CLIError(INVALID_STARTING_CHAR_ERROR.format(alias_name[0])) | [
"def",
"_validate_alias_name",
"(",
"alias_name",
")",
":",
"if",
"not",
"alias_name",
":",
"raise",
"CLIError",
"(",
"EMPTY_ALIAS_ERROR",
")",
"if",
"not",
"re",
".",
"match",
"(",
"'^[a-zA-Z]'",
",",
"alias_name",
")",
":",
"raise",
"CLIError",
"(",
"INVAL... | Check if the alias name is valid.
Args:
alias_name: The name of the alias to validate. | [
"Check",
"if",
"the",
"alias",
"name",
"is",
"valid",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L87-L98 |
228,794 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_alias_command | def _validate_alias_command(alias_command):
"""
Check if the alias command is valid.
Args:
alias_command: The command to validate.
"""
if not alias_command:
raise CLIError(EMPTY_ALIAS_ERROR)
split_command = shlex.split(alias_command)
boundary_index = len(split_command)
for i, subcommand in enumerate(split_command):
if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
boundary_index = i
break
# Extract possible CLI commands and validate
command_to_validate = ' '.join(split_command[:boundary_index]).lower()
for command in azext_alias.cached_reserved_commands:
if re.match(r'([a-z\-]*\s)*{}($|\s)'.format(command_to_validate), command):
return
_validate_positional_arguments(shlex.split(alias_command)) | python | def _validate_alias_command(alias_command):
if not alias_command:
raise CLIError(EMPTY_ALIAS_ERROR)
split_command = shlex.split(alias_command)
boundary_index = len(split_command)
for i, subcommand in enumerate(split_command):
if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
boundary_index = i
break
# Extract possible CLI commands and validate
command_to_validate = ' '.join(split_command[:boundary_index]).lower()
for command in azext_alias.cached_reserved_commands:
if re.match(r'([a-z\-]*\s)*{}($|\s)'.format(command_to_validate), command):
return
_validate_positional_arguments(shlex.split(alias_command)) | [
"def",
"_validate_alias_command",
"(",
"alias_command",
")",
":",
"if",
"not",
"alias_command",
":",
"raise",
"CLIError",
"(",
"EMPTY_ALIAS_ERROR",
")",
"split_command",
"=",
"shlex",
".",
"split",
"(",
"alias_command",
")",
"boundary_index",
"=",
"len",
"(",
"s... | Check if the alias command is valid.
Args:
alias_command: The command to validate. | [
"Check",
"if",
"the",
"alias",
"command",
"is",
"valid",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L101-L124 |
228,795 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_pos_args_syntax | def _validate_pos_args_syntax(alias_name, alias_command):
"""
Check if the positional argument syntax is valid in alias name and alias command.
Args:
alias_name: The name of the alias to validate.
alias_command: The command to validate.
"""
pos_args_from_alias = get_placeholders(alias_name)
# Split by '|' to extract positional argument name from Jinja filter (e.g. {{ arg_name | upper }})
# Split by '.' to extract positional argument name from function call (e.g. {{ arg_name.split()[0] }})
pos_args_from_command = [x.split('|')[0].split('.')[0].strip() for x in get_placeholders(alias_command)]
if set(pos_args_from_alias) != set(pos_args_from_command):
arg_diff = set(pos_args_from_alias) ^ set(pos_args_from_command)
raise CLIError(INCONSISTENT_ARG_ERROR.format('' if len(arg_diff) == 1 else 's',
arg_diff,
'is' if len(arg_diff) == 1 else 'are')) | python | def _validate_pos_args_syntax(alias_name, alias_command):
pos_args_from_alias = get_placeholders(alias_name)
# Split by '|' to extract positional argument name from Jinja filter (e.g. {{ arg_name | upper }})
# Split by '.' to extract positional argument name from function call (e.g. {{ arg_name.split()[0] }})
pos_args_from_command = [x.split('|')[0].split('.')[0].strip() for x in get_placeholders(alias_command)]
if set(pos_args_from_alias) != set(pos_args_from_command):
arg_diff = set(pos_args_from_alias) ^ set(pos_args_from_command)
raise CLIError(INCONSISTENT_ARG_ERROR.format('' if len(arg_diff) == 1 else 's',
arg_diff,
'is' if len(arg_diff) == 1 else 'are')) | [
"def",
"_validate_pos_args_syntax",
"(",
"alias_name",
",",
"alias_command",
")",
":",
"pos_args_from_alias",
"=",
"get_placeholders",
"(",
"alias_name",
")",
"# Split by '|' to extract positional argument name from Jinja filter (e.g. {{ arg_name | upper }})",
"# Split by '.' to extrac... | Check if the positional argument syntax is valid in alias name and alias command.
Args:
alias_name: The name of the alias to validate.
alias_command: The command to validate. | [
"Check",
"if",
"the",
"positional",
"argument",
"syntax",
"is",
"valid",
"in",
"alias",
"name",
"and",
"alias",
"command",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L127-L144 |
228,796 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_alias_command_level | def _validate_alias_command_level(alias, command):
"""
Make sure that if the alias is a reserved command, the command that the alias points to
in the command tree does not conflict in levels.
e.g. 'dns' -> 'network dns' is valid because dns is a level 2 command and network dns starts at level 1.
However, 'list' -> 'show' is not valid because list and show are both reserved commands at level 2.
Args:
alias: The name of the alias.
command: The command that the alias points to.
"""
alias_collision_table = AliasManager.build_collision_table([alias])
# Alias is not a reserved command, so it can point to any command
if not alias_collision_table:
return
command_collision_table = AliasManager.build_collision_table([command])
alias_collision_levels = alias_collision_table.get(alias.split()[0], [])
command_collision_levels = command_collision_table.get(command.split()[0], [])
# Check if there is a command level conflict
if set(alias_collision_levels) & set(command_collision_levels):
raise CLIError(COMMAND_LVL_ERROR.format(alias, command)) | python | def _validate_alias_command_level(alias, command):
alias_collision_table = AliasManager.build_collision_table([alias])
# Alias is not a reserved command, so it can point to any command
if not alias_collision_table:
return
command_collision_table = AliasManager.build_collision_table([command])
alias_collision_levels = alias_collision_table.get(alias.split()[0], [])
command_collision_levels = command_collision_table.get(command.split()[0], [])
# Check if there is a command level conflict
if set(alias_collision_levels) & set(command_collision_levels):
raise CLIError(COMMAND_LVL_ERROR.format(alias, command)) | [
"def",
"_validate_alias_command_level",
"(",
"alias",
",",
"command",
")",
":",
"alias_collision_table",
"=",
"AliasManager",
".",
"build_collision_table",
"(",
"[",
"alias",
"]",
")",
"# Alias is not a reserved command, so it can point to any command",
"if",
"not",
"alias_... | Make sure that if the alias is a reserved command, the command that the alias points to
in the command tree does not conflict in levels.
e.g. 'dns' -> 'network dns' is valid because dns is a level 2 command and network dns starts at level 1.
However, 'list' -> 'show' is not valid because list and show are both reserved commands at level 2.
Args:
alias: The name of the alias.
command: The command that the alias points to. | [
"Make",
"sure",
"that",
"if",
"the",
"alias",
"is",
"a",
"reserved",
"command",
"the",
"command",
"that",
"the",
"alias",
"points",
"to",
"in",
"the",
"command",
"tree",
"does",
"not",
"conflict",
"in",
"levels",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L147-L171 |
228,797 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_alias_file_path | def _validate_alias_file_path(alias_file_path):
"""
Make sure the alias file path is neither non-existant nor a directory
Args:
The alias file path to import aliases from.
"""
if not os.path.exists(alias_file_path):
raise CLIError(ALIAS_FILE_NOT_FOUND_ERROR)
if os.path.isdir(alias_file_path):
raise CLIError(ALIAS_FILE_DIR_ERROR.format(alias_file_path)) | python | def _validate_alias_file_path(alias_file_path):
if not os.path.exists(alias_file_path):
raise CLIError(ALIAS_FILE_NOT_FOUND_ERROR)
if os.path.isdir(alias_file_path):
raise CLIError(ALIAS_FILE_DIR_ERROR.format(alias_file_path)) | [
"def",
"_validate_alias_file_path",
"(",
"alias_file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"alias_file_path",
")",
":",
"raise",
"CLIError",
"(",
"ALIAS_FILE_NOT_FOUND_ERROR",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"a... | Make sure the alias file path is neither non-existant nor a directory
Args:
The alias file path to import aliases from. | [
"Make",
"sure",
"the",
"alias",
"file",
"path",
"is",
"neither",
"non",
"-",
"existant",
"nor",
"a",
"directory"
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L174-L185 |
228,798 | Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | _validate_alias_file_content | def _validate_alias_file_content(alias_file_path, url=''):
"""
Make sure the alias name and alias command in the alias file is in valid format.
Args:
The alias file path to import aliases from.
"""
alias_table = get_config_parser()
try:
alias_table.read(alias_file_path)
for alias_name, alias_command in reduce_alias_table(alias_table):
_validate_alias_name(alias_name)
_validate_alias_command(alias_command)
_validate_alias_command_level(alias_name, alias_command)
_validate_pos_args_syntax(alias_name, alias_command)
except Exception as exception: # pylint: disable=broad-except
error_msg = CONFIG_PARSING_ERROR % AliasManager.process_exception_message(exception)
error_msg = error_msg.replace(alias_file_path, url or alias_file_path)
raise CLIError(error_msg) | python | def _validate_alias_file_content(alias_file_path, url=''):
alias_table = get_config_parser()
try:
alias_table.read(alias_file_path)
for alias_name, alias_command in reduce_alias_table(alias_table):
_validate_alias_name(alias_name)
_validate_alias_command(alias_command)
_validate_alias_command_level(alias_name, alias_command)
_validate_pos_args_syntax(alias_name, alias_command)
except Exception as exception: # pylint: disable=broad-except
error_msg = CONFIG_PARSING_ERROR % AliasManager.process_exception_message(exception)
error_msg = error_msg.replace(alias_file_path, url or alias_file_path)
raise CLIError(error_msg) | [
"def",
"_validate_alias_file_content",
"(",
"alias_file_path",
",",
"url",
"=",
"''",
")",
":",
"alias_table",
"=",
"get_config_parser",
"(",
")",
"try",
":",
"alias_table",
".",
"read",
"(",
"alias_file_path",
")",
"for",
"alias_name",
",",
"alias_command",
"in... | Make sure the alias name and alias command in the alias file is in valid format.
Args:
The alias file path to import aliases from. | [
"Make",
"sure",
"the",
"alias",
"name",
"and",
"alias",
"command",
"in",
"the",
"alias",
"file",
"is",
"in",
"valid",
"format",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L188-L206 |
228,799 | Azure/azure-cli-extensions | src/application-insights/azext_applicationinsights/custom.py | execute_query | def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
"""Executes a query against the provided Application Insights application."""
from .vendored_sdks.applicationinsights.models import QueryBody
targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:])) | python | def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
from .vendored_sdks.applicationinsights.models import QueryBody
targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:])) | [
"def",
"execute_query",
"(",
"cmd",
",",
"client",
",",
"application",
",",
"analytics_query",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"offset",
"=",
"'1h'",
",",
"resource_group_name",
"=",
"None",
")",
":",
"from",
".",
"vendor... | Executes a query against the provided Application Insights application. | [
"Executes",
"a",
"query",
"against",
"the",
"provided",
"Application",
"Insights",
"application",
"."
] | 3d4854205b0f0d882f688cfa12383d14506c2e35 | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/application-insights/azext_applicationinsights/custom.py#L15-L19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.