id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
27,900
googleapis/google-cloud-python
api_core/google/api_core/datetime_helpers.py
DatetimeWithNanoseconds.rfc3339
def rfc3339(self): """Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec. """ if self._nanosecond == 0: return to_rfc3339(self) nanos = str(self._nanosecond).rjust(9, '0').rstrip("0") return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
python
def rfc3339(self): """Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec. """ if self._nanosecond == 0: return to_rfc3339(self) nanos = str(self._nanosecond).rjust(9, '0').rstrip("0") return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
[ "def", "rfc3339", "(", "self", ")", ":", "if", "self", ".", "_nanosecond", "==", "0", ":", "return", "to_rfc3339", "(", "self", ")", "nanos", "=", "str", "(", "self", ".", "_nanosecond", ")", ".", "rjust", "(", "9", ",", "'0'", ")", ".", "rstrip", "(", "\"0\"", ")", "return", "\"{}.{}Z\"", ".", "format", "(", "self", ".", "strftime", "(", "_RFC3339_NO_FRACTION", ")", ",", "nanos", ")" ]
Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec.
[ "Return", "an", "RFC", "3339", "-", "compliant", "timestamp", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/datetime_helpers.py#L217-L226
27,901
googleapis/google-cloud-python
api_core/google/api_core/datetime_helpers.py
DatetimeWithNanoseconds.timestamp_pb
def timestamp_pb(self): """Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message """ inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC) delta = inst - _UTC_EPOCH seconds = int(delta.total_seconds()) nanos = self._nanosecond or self.microsecond * 1000 return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
python
def timestamp_pb(self): """Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message """ inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC) delta = inst - _UTC_EPOCH seconds = int(delta.total_seconds()) nanos = self._nanosecond or self.microsecond * 1000 return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
[ "def", "timestamp_pb", "(", "self", ")", ":", "inst", "=", "self", "if", "self", ".", "tzinfo", "is", "not", "None", "else", "self", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "delta", "=", "inst", "-", "_UTC_EPOCH", "seconds", "=", "int", "(", "delta", ".", "total_seconds", "(", ")", ")", "nanos", "=", "self", ".", "_nanosecond", "or", "self", ".", "microsecond", "*", "1000", "return", "timestamp_pb2", ".", "Timestamp", "(", "seconds", "=", "seconds", ",", "nanos", "=", "nanos", ")" ]
Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
[ "Return", "a", "timestamp", "message", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/datetime_helpers.py#L269-L279
27,902
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py
ClusterControllerClient.create_cluster
def create_cluster( self, project_id, region, cluster, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(project_id, region, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster (Union[dict, ~google.cloud.dataproc_v1beta2.types.Cluster]): Required. The cluster to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Cluster` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``CreateClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_cluster" not in self._inner_api_calls: self._inner_api_calls[ "create_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_cluster, default_retry=self._method_configs["CreateCluster"].retry, default_timeout=self._method_configs["CreateCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.CreateClusterRequest( project_id=project_id, region=region, cluster=cluster, request_id=request_id ) operation = self._inner_api_calls["create_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, clusters_pb2.Cluster, metadata_type=proto_operations_pb2.ClusterOperationMetadata, )
python
def create_cluster( self, project_id, region, cluster, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(project_id, region, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster (Union[dict, ~google.cloud.dataproc_v1beta2.types.Cluster]): Required. The cluster to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Cluster` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``CreateClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_cluster" not in self._inner_api_calls: self._inner_api_calls[ "create_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_cluster, default_retry=self._method_configs["CreateCluster"].retry, default_timeout=self._method_configs["CreateCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.CreateClusterRequest( project_id=project_id, region=region, cluster=cluster, request_id=request_id ) operation = self._inner_api_calls["create_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, clusters_pb2.Cluster, metadata_type=proto_operations_pb2.ClusterOperationMetadata, )
[ "def", "create_cluster", "(", "self", ",", "project_id", ",", "region", ",", "cluster", ",", "request_id", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "clusters_pb2", ".", "CreateClusterRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "cluster", "=", "cluster", ",", "request_id", "=", "request_id", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"create_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "clusters_pb2", ".", "Cluster", ",", "metadata_type", "=", "proto_operations_pb2", ".", "ClusterOperationMetadata", ",", ")" ]
Creates a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(project_id, region, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster (Union[dict, ~google.cloud.dataproc_v1beta2.types.Cluster]): Required. The cluster to create. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Cluster` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``CreateClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "cluster", "in", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py#L180-L278
27,903
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py
ClusterControllerClient.delete_cluster
def delete_cluster( self, project_id, region, cluster_name, cluster_uuid=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.delete_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. cluster_uuid (str): Optional. Specifying the ``cluster_uuid`` means the RPC should fail (with error NOT\_FOUND) if cluster with specified UUID does not exist. request_id (str): Optional. A unique id used to identify the request. If the server receives two ``DeleteClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_cluster" not in self._inner_api_calls: self._inner_api_calls[ "delete_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_cluster, default_retry=self._method_configs["DeleteCluster"].retry, default_timeout=self._method_configs["DeleteCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.DeleteClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name, cluster_uuid=cluster_uuid, request_id=request_id, ) operation = self._inner_api_calls["delete_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=proto_operations_pb2.ClusterOperationMetadata, )
python
def delete_cluster( self, project_id, region, cluster_name, cluster_uuid=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.delete_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. cluster_uuid (str): Optional. Specifying the ``cluster_uuid`` means the RPC should fail (with error NOT\_FOUND) if cluster with specified UUID does not exist. request_id (str): Optional. A unique id used to identify the request. If the server receives two ``DeleteClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_cluster" not in self._inner_api_calls: self._inner_api_calls[ "delete_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_cluster, default_retry=self._method_configs["DeleteCluster"].retry, default_timeout=self._method_configs["DeleteCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.DeleteClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name, cluster_uuid=cluster_uuid, request_id=request_id, ) operation = self._inner_api_calls["delete_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=proto_operations_pb2.ClusterOperationMetadata, )
[ "def", "delete_cluster", "(", "self", ",", "project_id", ",", "region", ",", "cluster_name", ",", "cluster_uuid", "=", "None", ",", "request_id", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"delete_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "clusters_pb2", ".", "DeleteClusterRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "cluster_name", "=", "cluster_name", ",", "cluster_uuid", "=", "cluster_uuid", ",", "request_id", "=", "request_id", ",", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"delete_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "empty_pb2", ".", "Empty", ",", "metadata_type", "=", "proto_operations_pb2", ".", "ClusterOperationMetadata", ",", ")" ]
Deletes a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.delete_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. cluster_uuid (str): Optional. Specifying the ``cluster_uuid`` means the RPC should fail (with error NOT\_FOUND) if cluster with specified UUID does not exist. request_id (str): Optional. A unique id used to identify the request. If the server receives two ``DeleteClusterRequest`` requests with the same id, then the second request will be ignored and the first ``google.longrunning.Operation`` created and stored in the backend is returned. It is recommended to always set this value to a `UUID <https://en.wikipedia.org/wiki/Universally_unique_identifier>`__. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (\_), and hyphens (-). The maximum length is 40 characters. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "a", "cluster", "in", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py#L646-L748
27,904
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py
ClusterControllerClient.get_cluster
def get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, default_retry=self._method_configs["GetCluster"].retry, default_timeout=self._method_configs["GetCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.GetClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name ) return self._inner_api_calls["get_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, default_retry=self._method_configs["GetCluster"].retry, default_timeout=self._method_configs["GetCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.GetClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name ) return self._inner_api_calls["get_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_cluster", "(", "self", ",", "project_id", ",", "region", ",", "cluster_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"get_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "clusters_pb2", ".", "GetClusterRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "cluster_name", "=", "cluster_name", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Gets", "the", "resource", "representation", "for", "a", "cluster", "in", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py#L750-L818
27,905
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py
ClusterControllerClient.diagnose_cluster
def diagnose_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets cluster diagnostic information. After the operation completes, the Operation.response field contains ``DiagnoseClusterOutputLocation``. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.diagnose_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "diagnose_cluster" not in self._inner_api_calls: self._inner_api_calls[ "diagnose_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.diagnose_cluster, default_retry=self._method_configs["DiagnoseCluster"].retry, default_timeout=self._method_configs["DiagnoseCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.DiagnoseClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name ) operation = self._inner_api_calls["diagnose_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=clusters_pb2.DiagnoseClusterResults, )
python
def diagnose_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets cluster diagnostic information. After the operation completes, the Operation.response field contains ``DiagnoseClusterOutputLocation``. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.diagnose_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "diagnose_cluster" not in self._inner_api_calls: self._inner_api_calls[ "diagnose_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.diagnose_cluster, default_retry=self._method_configs["DiagnoseCluster"].retry, default_timeout=self._method_configs["DiagnoseCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.DiagnoseClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name ) operation = self._inner_api_calls["diagnose_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, empty_pb2.Empty, metadata_type=clusters_pb2.DiagnoseClusterResults, )
[ "def", "diagnose_cluster", "(", "self", ",", "project_id", ",", "region", ",", "cluster_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"diagnose_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"diagnose_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "diagnose_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DiagnoseCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DiagnoseCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "clusters_pb2", ".", "DiagnoseClusterRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "cluster_name", "=", "cluster_name", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"diagnose_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "empty_pb2", ".", "Empty", ",", "metadata_type", "=", "clusters_pb2", ".", "DiagnoseClusterResults", ",", ")" ]
Gets cluster diagnostic information. After the operation completes, the Operation.response field contains ``DiagnoseClusterOutputLocation``. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.diagnose_cluster(project_id, region, cluster_name) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Gets", "cluster", "diagnostic", "information", ".", "After", "the", "operation", "completes", "the", "Operation", ".", "response", "field", "contains", "DiagnoseClusterOutputLocation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/cluster_controller_client.py#L938-L1022
27,906
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/publisher/_batch/thread.py
Batch.monitor
def monitor(self): """Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit unless the batch has already been committed. """ # NOTE: This blocks; it is up to the calling code to call it # in a separate thread. # Sleep for however long we should be waiting. time.sleep(self._settings.max_latency) _LOGGER.debug("Monitor is waking up") return self._commit()
python
def monitor(self): """Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit unless the batch has already been committed. """ # NOTE: This blocks; it is up to the calling code to call it # in a separate thread. # Sleep for however long we should be waiting. time.sleep(self._settings.max_latency) _LOGGER.debug("Monitor is waking up") return self._commit()
[ "def", "monitor", "(", "self", ")", ":", "# NOTE: This blocks; it is up to the calling code to call it", "# in a separate thread.", "# Sleep for however long we should be waiting.", "time", ".", "sleep", "(", "self", ".", "_settings", ".", "max_latency", ")", "_LOGGER", ".", "debug", "(", "\"Monitor is waking up\"", ")", "return", "self", ".", "_commit", "(", ")" ]
Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit unless the batch has already been committed.
[ "Commit", "this", "batch", "after", "sufficient", "time", "has", "elapsed", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/publisher/_batch/thread.py#L241-L254
27,907
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/publisher/_batch/thread.py
Batch.publish
def publish(self, message): """Publish a single message. Add the given message to this object; this will cause it to be published once the batch either has enough messages or a sufficient period of time has elapsed. This method is called by :meth:`~.PublisherClient.publish`. Args: message (~.pubsub_v1.types.PubsubMessage): The Pub/Sub message. Returns: Optional[~google.api_core.future.Future]: An object conforming to the :class:`~concurrent.futures.Future` interface or :data:`None`. If :data:`None` is returned, that signals that the batch cannot accept a message. """ # Coerce the type, just in case. if not isinstance(message, types.PubsubMessage): message = types.PubsubMessage(**message) future = None with self._state_lock: if not self.will_accept(message): return future new_size = self._size + message.ByteSize() new_count = len(self._messages) + 1 overflow = ( new_size > self.settings.max_bytes or new_count >= self._settings.max_messages ) if not self._messages or not overflow: # Store the actual message in the batch's message queue. self._messages.append(message) self._size = new_size # Track the future on this batch (so that the result of the # future can be set). future = futures.Future(completed=threading.Event()) self._futures.append(future) # Try to commit, but it must be **without** the lock held, since # ``commit()`` will try to obtain the lock. if overflow: self.commit() return future
python
def publish(self, message): """Publish a single message. Add the given message to this object; this will cause it to be published once the batch either has enough messages or a sufficient period of time has elapsed. This method is called by :meth:`~.PublisherClient.publish`. Args: message (~.pubsub_v1.types.PubsubMessage): The Pub/Sub message. Returns: Optional[~google.api_core.future.Future]: An object conforming to the :class:`~concurrent.futures.Future` interface or :data:`None`. If :data:`None` is returned, that signals that the batch cannot accept a message. """ # Coerce the type, just in case. if not isinstance(message, types.PubsubMessage): message = types.PubsubMessage(**message) future = None with self._state_lock: if not self.will_accept(message): return future new_size = self._size + message.ByteSize() new_count = len(self._messages) + 1 overflow = ( new_size > self.settings.max_bytes or new_count >= self._settings.max_messages ) if not self._messages or not overflow: # Store the actual message in the batch's message queue. self._messages.append(message) self._size = new_size # Track the future on this batch (so that the result of the # future can be set). future = futures.Future(completed=threading.Event()) self._futures.append(future) # Try to commit, but it must be **without** the lock held, since # ``commit()`` will try to obtain the lock. if overflow: self.commit() return future
[ "def", "publish", "(", "self", ",", "message", ")", ":", "# Coerce the type, just in case.", "if", "not", "isinstance", "(", "message", ",", "types", ".", "PubsubMessage", ")", ":", "message", "=", "types", ".", "PubsubMessage", "(", "*", "*", "message", ")", "future", "=", "None", "with", "self", ".", "_state_lock", ":", "if", "not", "self", ".", "will_accept", "(", "message", ")", ":", "return", "future", "new_size", "=", "self", ".", "_size", "+", "message", ".", "ByteSize", "(", ")", "new_count", "=", "len", "(", "self", ".", "_messages", ")", "+", "1", "overflow", "=", "(", "new_size", ">", "self", ".", "settings", ".", "max_bytes", "or", "new_count", ">=", "self", ".", "_settings", ".", "max_messages", ")", "if", "not", "self", ".", "_messages", "or", "not", "overflow", ":", "# Store the actual message in the batch's message queue.", "self", ".", "_messages", ".", "append", "(", "message", ")", "self", ".", "_size", "=", "new_size", "# Track the future on this batch (so that the result of the", "# future can be set).", "future", "=", "futures", ".", "Future", "(", "completed", "=", "threading", ".", "Event", "(", ")", ")", "self", ".", "_futures", ".", "append", "(", "future", ")", "# Try to commit, but it must be **without** the lock held, since", "# ``commit()`` will try to obtain the lock.", "if", "overflow", ":", "self", ".", "commit", "(", ")", "return", "future" ]
Publish a single message. Add the given message to this object; this will cause it to be published once the batch either has enough messages or a sufficient period of time has elapsed. This method is called by :meth:`~.PublisherClient.publish`. Args: message (~.pubsub_v1.types.PubsubMessage): The Pub/Sub message. Returns: Optional[~google.api_core.future.Future]: An object conforming to the :class:`~concurrent.futures.Future` interface or :data:`None`. If :data:`None` is returned, that signals that the batch cannot accept a message.
[ "Publish", "a", "single", "message", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/publisher/_batch/thread.py#L256-L307
27,908
googleapis/google-cloud-python
dns/google/cloud/dns/changes.py
Changes.path
def path(self): """URL path for change set APIs. :rtype: str :returns: the path based on project, zone, and change set names. """ return "/projects/%s/managedZones/%s/changes/%s" % ( self.zone.project, self.zone.name, self.name, )
python
def path(self): """URL path for change set APIs. :rtype: str :returns: the path based on project, zone, and change set names. """ return "/projects/%s/managedZones/%s/changes/%s" % ( self.zone.project, self.zone.name, self.name, )
[ "def", "path", "(", "self", ")", ":", "return", "\"/projects/%s/managedZones/%s/changes/%s\"", "%", "(", "self", ".", "zone", ".", "project", ",", "self", ".", "zone", ".", "name", ",", "self", ".", "name", ",", ")" ]
URL path for change set APIs. :rtype: str :returns: the path based on project, zone, and change set names.
[ "URL", "path", "for", "change", "set", "APIs", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/changes.py#L80-L90
27,909
googleapis/google-cloud-python
dns/google/cloud/dns/changes.py
Changes.name
def name(self, value): """Update name of the change set. :type value: str :param value: New name for the changeset. """ if not isinstance(value, six.string_types): raise ValueError("Pass a string") self._properties["id"] = value
python
def name(self, value): """Update name of the change set. :type value: str :param value: New name for the changeset. """ if not isinstance(value, six.string_types): raise ValueError("Pass a string") self._properties["id"] = value
[ "def", "name", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"Pass a string\"", ")", "self", ".", "_properties", "[", "\"id\"", "]", "=", "value" ]
Update name of the change set. :type value: str :param value: New name for the changeset.
[ "Update", "name", "of", "the", "change", "set", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/changes.py#L102-L110
27,910
googleapis/google-cloud-python
dns/google/cloud/dns/changes.py
Changes.add_record_set
def add_record_set(self, record_set): """Append a record set to the 'additions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type. """ if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._additions += (record_set,)
python
def add_record_set(self, record_set): """Append a record set to the 'additions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type. """ if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._additions += (record_set,)
[ "def", "add_record_set", "(", "self", ",", "record_set", ")", ":", "if", "not", "isinstance", "(", "record_set", ",", "ResourceRecordSet", ")", ":", "raise", "ValueError", "(", "\"Pass a ResourceRecordSet\"", ")", "self", ".", "_additions", "+=", "(", "record_set", ",", ")" ]
Append a record set to the 'additions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type.
[ "Append", "a", "record", "set", "to", "the", "additions", "for", "the", "change", "set", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/changes.py#L152-L163
27,911
googleapis/google-cloud-python
dns/google/cloud/dns/changes.py
Changes.delete_record_set
def delete_record_set(self, record_set): """Append a record set to the 'deletions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type. """ if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._deletions += (record_set,)
python
def delete_record_set(self, record_set): """Append a record set to the 'deletions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type. """ if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._deletions += (record_set,)
[ "def", "delete_record_set", "(", "self", ",", "record_set", ")", ":", "if", "not", "isinstance", "(", "record_set", ",", "ResourceRecordSet", ")", ":", "raise", "ValueError", "(", "\"Pass a ResourceRecordSet\"", ")", "self", ".", "_deletions", "+=", "(", "record_set", ",", ")" ]
Append a record set to the 'deletions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_set.ResourceRecordSet` :param record_set: the record set to append. :raises: ``ValueError`` if ``record_set`` is not of the required type.
[ "Append", "a", "record", "set", "to", "the", "deletions", "for", "the", "change", "set", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/changes.py#L165-L176
27,912
googleapis/google-cloud-python
dns/google/cloud/dns/changes.py
Changes._build_resource
def _build_resource(self): """Generate a resource for ``create``.""" additions = [ { "name": added.name, "type": added.record_type, "ttl": str(added.ttl), "rrdatas": added.rrdatas, } for added in self.additions ] deletions = [ { "name": deleted.name, "type": deleted.record_type, "ttl": str(deleted.ttl), "rrdatas": deleted.rrdatas, } for deleted in self.deletions ] return {"additions": additions, "deletions": deletions}
python
def _build_resource(self): """Generate a resource for ``create``.""" additions = [ { "name": added.name, "type": added.record_type, "ttl": str(added.ttl), "rrdatas": added.rrdatas, } for added in self.additions ] deletions = [ { "name": deleted.name, "type": deleted.record_type, "ttl": str(deleted.ttl), "rrdatas": deleted.rrdatas, } for deleted in self.deletions ] return {"additions": additions, "deletions": deletions}
[ "def", "_build_resource", "(", "self", ")", ":", "additions", "=", "[", "{", "\"name\"", ":", "added", ".", "name", ",", "\"type\"", ":", "added", ".", "record_type", ",", "\"ttl\"", ":", "str", "(", "added", ".", "ttl", ")", ",", "\"rrdatas\"", ":", "added", ".", "rrdatas", ",", "}", "for", "added", "in", "self", ".", "additions", "]", "deletions", "=", "[", "{", "\"name\"", ":", "deleted", ".", "name", ",", "\"type\"", ":", "deleted", ".", "record_type", ",", "\"ttl\"", ":", "str", "(", "deleted", ".", "ttl", ")", ",", "\"rrdatas\"", ":", "deleted", ".", "rrdatas", ",", "}", "for", "deleted", "in", "self", ".", "deletions", "]", "return", "{", "\"additions\"", ":", "additions", ",", "\"deletions\"", ":", "deletions", "}" ]
Generate a resource for ``create``.
[ "Generate", "a", "resource", "for", "create", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dns/google/cloud/dns/changes.py#L193-L215
27,913
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.sinks_api
def sinks_api(self): """Helper for log sink-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks """ if self._sinks_api is None: if self._use_grpc: self._sinks_api = _gapic.make_sinks_api(self) else: self._sinks_api = JSONSinksAPI(self) return self._sinks_api
python
def sinks_api(self): """Helper for log sink-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks """ if self._sinks_api is None: if self._use_grpc: self._sinks_api = _gapic.make_sinks_api(self) else: self._sinks_api = JSONSinksAPI(self) return self._sinks_api
[ "def", "sinks_api", "(", "self", ")", ":", "if", "self", ".", "_sinks_api", "is", "None", ":", "if", "self", ".", "_use_grpc", ":", "self", ".", "_sinks_api", "=", "_gapic", ".", "make_sinks_api", "(", "self", ")", "else", ":", "self", ".", "_sinks_api", "=", "JSONSinksAPI", "(", "self", ")", "return", "self", ".", "_sinks_api" ]
Helper for log sink-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks
[ "Helper", "for", "log", "sink", "-", "related", "API", "calls", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L129-L140
27,914
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.metrics_api
def metrics_api(self): """Helper for log metric-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics """ if self._metrics_api is None: if self._use_grpc: self._metrics_api = _gapic.make_metrics_api(self) else: self._metrics_api = JSONMetricsAPI(self) return self._metrics_api
python
def metrics_api(self): """Helper for log metric-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics """ if self._metrics_api is None: if self._use_grpc: self._metrics_api = _gapic.make_metrics_api(self) else: self._metrics_api = JSONMetricsAPI(self) return self._metrics_api
[ "def", "metrics_api", "(", "self", ")", ":", "if", "self", ".", "_metrics_api", "is", "None", ":", "if", "self", ".", "_use_grpc", ":", "self", ".", "_metrics_api", "=", "_gapic", ".", "make_metrics_api", "(", "self", ")", "else", ":", "self", ".", "_metrics_api", "=", "JSONMetricsAPI", "(", "self", ")", "return", "self", ".", "_metrics_api" ]
Helper for log metric-related API calls. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics
[ "Helper", "for", "log", "metric", "-", "related", "API", "calls", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L143-L154
27,915
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.sink
def sink(self, name, filter_=None, destination=None): """Creates a sink bound to the current client. :type name: str :param name: the name of the sink to be constructed. :type filter_: str :param filter_: (optional) the advanced logs filter expression defining the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :type destination: str :param destination: destination URI for the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :rtype: :class:`google.cloud.logging.sink.Sink` :returns: Sink created with the current client. """ return Sink(name, filter_, destination, client=self)
python
def sink(self, name, filter_=None, destination=None): """Creates a sink bound to the current client. :type name: str :param name: the name of the sink to be constructed. :type filter_: str :param filter_: (optional) the advanced logs filter expression defining the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :type destination: str :param destination: destination URI for the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :rtype: :class:`google.cloud.logging.sink.Sink` :returns: Sink created with the current client. """ return Sink(name, filter_, destination, client=self)
[ "def", "sink", "(", "self", ",", "name", ",", "filter_", "=", "None", ",", "destination", "=", "None", ")", ":", "return", "Sink", "(", "name", ",", "filter_", ",", "destination", ",", "client", "=", "self", ")" ]
Creates a sink bound to the current client. :type name: str :param name: the name of the sink to be constructed. :type filter_: str :param filter_: (optional) the advanced logs filter expression defining the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :type destination: str :param destination: destination URI for the entries exported by the sink. If not passed, the instance should already exist, to be refreshed via :meth:`Sink.reload`. :rtype: :class:`google.cloud.logging.sink.Sink` :returns: Sink created with the current client.
[ "Creates", "a", "sink", "bound", "to", "the", "current", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L222-L243
27,916
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.metric
def metric(self, name, filter_=None, description=""): """Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the entries tracked by the metric. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :type description: str :param description: the description of the metric to be constructed. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :rtype: :class:`google.cloud.logging.metric.Metric` :returns: Metric created with the current client. """ return Metric(name, filter_, client=self, description=description)
python
def metric(self, name, filter_=None, description=""): """Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the entries tracked by the metric. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :type description: str :param description: the description of the metric to be constructed. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :rtype: :class:`google.cloud.logging.metric.Metric` :returns: Metric created with the current client. """ return Metric(name, filter_, client=self, description=description)
[ "def", "metric", "(", "self", ",", "name", ",", "filter_", "=", "None", ",", "description", "=", "\"\"", ")", ":", "return", "Metric", "(", "name", ",", "filter_", ",", "client", "=", "self", ",", "description", "=", "description", ")" ]
Creates a metric bound to the current client. :type name: str :param name: the name of the metric to be constructed. :type filter_: str :param filter_: the advanced logs filter expression defining the entries tracked by the metric. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :type description: str :param description: the description of the metric to be constructed. If not passed, the instance should already exist, to be refreshed via :meth:`Metric.reload`. :rtype: :class:`google.cloud.logging.metric.Metric` :returns: Metric created with the current client.
[ "Creates", "a", "metric", "bound", "to", "the", "current", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L272-L292
27,917
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.get_default_handler
def get_default_handler(self, **kw): """Return the default logging handler based on the local environment. :type kw: dict :param kw: keyword args passed to handler constructor :rtype: :class:`logging.Handler` :returns: The default log handler based on the environment """ gke_cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME) if ( _APPENGINE_FLEXIBLE_ENV_VM in os.environ or _APPENGINE_INSTANCE_ID in os.environ ): return AppEngineHandler(self, **kw) elif gke_cluster_name is not None: return ContainerEngineHandler(**kw) else: return CloudLoggingHandler(self, **kw)
python
def get_default_handler(self, **kw): """Return the default logging handler based on the local environment. :type kw: dict :param kw: keyword args passed to handler constructor :rtype: :class:`logging.Handler` :returns: The default log handler based on the environment """ gke_cluster_name = retrieve_metadata_server(_GKE_CLUSTER_NAME) if ( _APPENGINE_FLEXIBLE_ENV_VM in os.environ or _APPENGINE_INSTANCE_ID in os.environ ): return AppEngineHandler(self, **kw) elif gke_cluster_name is not None: return ContainerEngineHandler(**kw) else: return CloudLoggingHandler(self, **kw)
[ "def", "get_default_handler", "(", "self", ",", "*", "*", "kw", ")", ":", "gke_cluster_name", "=", "retrieve_metadata_server", "(", "_GKE_CLUSTER_NAME", ")", "if", "(", "_APPENGINE_FLEXIBLE_ENV_VM", "in", "os", ".", "environ", "or", "_APPENGINE_INSTANCE_ID", "in", "os", ".", "environ", ")", ":", "return", "AppEngineHandler", "(", "self", ",", "*", "*", "kw", ")", "elif", "gke_cluster_name", "is", "not", "None", ":", "return", "ContainerEngineHandler", "(", "*", "*", "kw", ")", "else", ":", "return", "CloudLoggingHandler", "(", "self", ",", "*", "*", "kw", ")" ]
Return the default logging handler based on the local environment. :type kw: dict :param kw: keyword args passed to handler constructor :rtype: :class:`logging.Handler` :returns: The default log handler based on the environment
[ "Return", "the", "default", "logging", "handler", "based", "on", "the", "local", "environment", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L320-L339
27,918
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
Client.setup_logging
def setup_logging( self, log_level=logging.INFO, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, **kw ): """Attach default Stackdriver logging handler to the root logger. This method uses the default log handler, obtained by :meth:`~get_default_handler`, and attaches it to the root Python logger, so that a call such as ``logging.warn``, as well as all child loggers, will report to Stackdriver logging. :type log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. :type excluded_loggers: tuple :param excluded_loggers: (Optional) The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself. :type kw: dict :param kw: keyword args passed to handler constructor """ handler = self.get_default_handler(**kw) setup_logging(handler, log_level=log_level, excluded_loggers=excluded_loggers)
python
def setup_logging( self, log_level=logging.INFO, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, **kw ): """Attach default Stackdriver logging handler to the root logger. This method uses the default log handler, obtained by :meth:`~get_default_handler`, and attaches it to the root Python logger, so that a call such as ``logging.warn``, as well as all child loggers, will report to Stackdriver logging. :type log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. :type excluded_loggers: tuple :param excluded_loggers: (Optional) The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself. :type kw: dict :param kw: keyword args passed to handler constructor """ handler = self.get_default_handler(**kw) setup_logging(handler, log_level=log_level, excluded_loggers=excluded_loggers)
[ "def", "setup_logging", "(", "self", ",", "log_level", "=", "logging", ".", "INFO", ",", "excluded_loggers", "=", "EXCLUDED_LOGGER_DEFAULTS", ",", "*", "*", "kw", ")", ":", "handler", "=", "self", ".", "get_default_handler", "(", "*", "*", "kw", ")", "setup_logging", "(", "handler", ",", "log_level", "=", "log_level", ",", "excluded_loggers", "=", "excluded_loggers", ")" ]
Attach default Stackdriver logging handler to the root logger. This method uses the default log handler, obtained by :meth:`~get_default_handler`, and attaches it to the root Python logger, so that a call such as ``logging.warn``, as well as all child loggers, will report to Stackdriver logging. :type log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. :type excluded_loggers: tuple :param excluded_loggers: (Optional) The loggers to not attach the handler to. This will always include the loggers in the path of the logging client itself. :type kw: dict :param kw: keyword args passed to handler constructor
[ "Attach", "default", "Stackdriver", "logging", "handler", "to", "the", "root", "logger", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L341-L365
27,919
googleapis/google-cloud-python
kms/google/cloud/kms_v1/gapic/key_management_service_client.py
KeyManagementServiceClient.key_ring_path
def key_ring_path(cls, project, location, key_ring): """Return a fully-qualified key_ring string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}", project=project, location=location, key_ring=key_ring, )
python
def key_ring_path(cls, project, location, key_ring): """Return a fully-qualified key_ring string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}", project=project, location=location, key_ring=key_ring, )
[ "def", "key_ring_path", "(", "cls", ",", "project", ",", "location", ",", "key_ring", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/locations/{location}/keyRings/{key_ring}\"", ",", "project", "=", "project", ",", "location", "=", "location", ",", "key_ring", "=", "key_ring", ",", ")" ]
Return a fully-qualified key_ring string.
[ "Return", "a", "fully", "-", "qualified", "key_ring", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/kms/google/cloud/kms_v1/gapic/key_management_service_client.py#L88-L95
27,920
googleapis/google-cloud-python
kms/google/cloud/kms_v1/gapic/key_management_service_client.py
KeyManagementServiceClient.crypto_key_path_path
def crypto_key_path_path(cls, project, location, key_ring, crypto_key_path): """Return a fully-qualified crypto_key_path string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}", project=project, location=location, key_ring=key_ring, crypto_key_path=crypto_key_path, )
python
def crypto_key_path_path(cls, project, location, key_ring, crypto_key_path): """Return a fully-qualified crypto_key_path string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}", project=project, location=location, key_ring=key_ring, crypto_key_path=crypto_key_path, )
[ "def", "crypto_key_path_path", "(", "cls", ",", "project", ",", "location", ",", "key_ring", ",", "crypto_key_path", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}\"", ",", "project", "=", "project", ",", "location", "=", "location", ",", "key_ring", "=", "key_ring", ",", "crypto_key_path", "=", "crypto_key_path", ",", ")" ]
Return a fully-qualified crypto_key_path string.
[ "Return", "a", "fully", "-", "qualified", "crypto_key_path", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/kms/google/cloud/kms_v1/gapic/key_management_service_client.py#L98-L106
27,921
googleapis/google-cloud-python
kms/google/cloud/kms_v1/gapic/key_management_service_client.py
KeyManagementServiceClient.crypto_key_version_path
def crypto_key_version_path( cls, project, location, key_ring, crypto_key, crypto_key_version ): """Return a fully-qualified crypto_key_version string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}", project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, )
python
def crypto_key_version_path( cls, project, location, key_ring, crypto_key, crypto_key_version ): """Return a fully-qualified crypto_key_version string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}", project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, )
[ "def", "crypto_key_version_path", "(", "cls", ",", "project", ",", "location", ",", "key_ring", ",", "crypto_key", ",", "crypto_key_version", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}\"", ",", "project", "=", "project", ",", "location", "=", "location", ",", "key_ring", "=", "key_ring", ",", "crypto_key", "=", "crypto_key", ",", "crypto_key_version", "=", "crypto_key_version", ",", ")" ]
Return a fully-qualified crypto_key_version string.
[ "Return", "a", "fully", "-", "qualified", "crypto_key_version", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/kms/google/cloud/kms_v1/gapic/key_management_service_client.py#L129-L140
27,922
googleapis/google-cloud-python
kms/google/cloud/kms_v1/gapic/key_management_service_client.py
KeyManagementServiceClient.create_key_ring
def create_key_ring( self, parent, key_ring_id, key_ring, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Create a new ``KeyRing`` in a given Project and Location. Example: >>> from google.cloud import kms_v1 >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `key_ring_id`: >>> key_ring_id = '' >>> >>> # TODO: Initialize `key_ring`: >>> key_ring = {} >>> >>> response = client.create_key_ring(parent, key_ring_id, key_ring) Args: parent (str): Required. The resource name of the location associated with the ``KeyRings``, in the format ``projects/*/locations/*``. key_ring_id (str): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` key_ring (Union[dict, ~google.cloud.kms_v1.types.KeyRing]): A ``KeyRing`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.KeyRing` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.KeyRing` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_key_ring" not in self._inner_api_calls: self._inner_api_calls[ "create_key_ring" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_key_ring, default_retry=self._method_configs["CreateKeyRing"].retry, default_timeout=self._method_configs["CreateKeyRing"].timeout, client_info=self._client_info, ) request = service_pb2.CreateKeyRingRequest( parent=parent, key_ring_id=key_ring_id, key_ring=key_ring ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_key_ring"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_key_ring( self, parent, key_ring_id, key_ring, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Create a new ``KeyRing`` in a given Project and Location. Example: >>> from google.cloud import kms_v1 >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `key_ring_id`: >>> key_ring_id = '' >>> >>> # TODO: Initialize `key_ring`: >>> key_ring = {} >>> >>> response = client.create_key_ring(parent, key_ring_id, key_ring) Args: parent (str): Required. The resource name of the location associated with the ``KeyRings``, in the format ``projects/*/locations/*``. key_ring_id (str): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` key_ring (Union[dict, ~google.cloud.kms_v1.types.KeyRing]): A ``KeyRing`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.KeyRing` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.KeyRing` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_key_ring" not in self._inner_api_calls: self._inner_api_calls[ "create_key_ring" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_key_ring, default_retry=self._method_configs["CreateKeyRing"].retry, default_timeout=self._method_configs["CreateKeyRing"].timeout, client_info=self._client_info, ) request = service_pb2.CreateKeyRingRequest( parent=parent, key_ring_id=key_ring_id, key_ring=key_ring ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_key_ring"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_key_ring", "(", "self", ",", "parent", ",", "key_ring_id", ",", "key_ring", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_key_ring\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_key_ring\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_key_ring", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateKeyRing\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateKeyRing\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "service_pb2", ".", "CreateKeyRingRequest", "(", "parent", "=", "parent", ",", "key_ring_id", "=", "key_ring_id", ",", "key_ring", "=", "key_ring", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_key_ring\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Create a new ``KeyRing`` in a given Project and Location. Example: >>> from google.cloud import kms_v1 >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.location_path('[PROJECT]', '[LOCATION]') >>> >>> # TODO: Initialize `key_ring_id`: >>> key_ring_id = '' >>> >>> # TODO: Initialize `key_ring`: >>> key_ring = {} >>> >>> response = client.create_key_ring(parent, key_ring_id, key_ring) Args: parent (str): Required. The resource name of the location associated with the ``KeyRings``, in the format ``projects/*/locations/*``. key_ring_id (str): Required. It must be unique within a location and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` key_ring (Union[dict, ~google.cloud.kms_v1.types.KeyRing]): A ``KeyRing`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.KeyRing` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.KeyRing` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Create", "a", "new", "KeyRing", "in", "a", "given", "Project", "and", "Location", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/kms/google/cloud/kms_v1/gapic/key_management_service_client.py#L763-L847
27,923
googleapis/google-cloud-python
kms/google/cloud/kms_v1/gapic/key_management_service_client.py
KeyManagementServiceClient.create_crypto_key
def create_crypto_key( self, parent, crypto_key_id, crypto_key, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Create a new ``CryptoKey`` within a ``KeyRing``. ``CryptoKey.purpose`` and ``CryptoKey.version_template.algorithm`` are required. Example: >>> from google.cloud import kms_v1 >>> from google.cloud.kms_v1 import enums >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.key_ring_path('[PROJECT]', '[LOCATION]', '[KEY_RING]') >>> crypto_key_id = 'my-app-key' >>> purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT >>> seconds = 2147483647 >>> next_rotation_time = {'seconds': seconds} >>> seconds_2 = 604800 >>> rotation_period = {'seconds': seconds_2} >>> crypto_key = {'purpose': purpose, 'next_rotation_time': next_rotation_time, 'rotation_period': rotation_period} >>> >>> response = client.create_crypto_key(parent, crypto_key_id, crypto_key) Args: parent (str): Required. The ``name`` of the KeyRing associated with the ``CryptoKeys``. crypto_key_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` crypto_key (Union[dict, ~google.cloud.kms_v1.types.CryptoKey]): A ``CryptoKey`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.CryptoKey` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.CryptoKey` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_crypto_key" not in self._inner_api_calls: self._inner_api_calls[ "create_crypto_key" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_crypto_key, default_retry=self._method_configs["CreateCryptoKey"].retry, default_timeout=self._method_configs["CreateCryptoKey"].timeout, client_info=self._client_info, ) request = service_pb2.CreateCryptoKeyRequest( parent=parent, crypto_key_id=crypto_key_id, crypto_key=crypto_key ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_crypto_key"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_crypto_key( self, parent, crypto_key_id, crypto_key, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Create a new ``CryptoKey`` within a ``KeyRing``. ``CryptoKey.purpose`` and ``CryptoKey.version_template.algorithm`` are required. Example: >>> from google.cloud import kms_v1 >>> from google.cloud.kms_v1 import enums >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.key_ring_path('[PROJECT]', '[LOCATION]', '[KEY_RING]') >>> crypto_key_id = 'my-app-key' >>> purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT >>> seconds = 2147483647 >>> next_rotation_time = {'seconds': seconds} >>> seconds_2 = 604800 >>> rotation_period = {'seconds': seconds_2} >>> crypto_key = {'purpose': purpose, 'next_rotation_time': next_rotation_time, 'rotation_period': rotation_period} >>> >>> response = client.create_crypto_key(parent, crypto_key_id, crypto_key) Args: parent (str): Required. The ``name`` of the KeyRing associated with the ``CryptoKeys``. crypto_key_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` crypto_key (Union[dict, ~google.cloud.kms_v1.types.CryptoKey]): A ``CryptoKey`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.CryptoKey` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.CryptoKey` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_crypto_key" not in self._inner_api_calls: self._inner_api_calls[ "create_crypto_key" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_crypto_key, default_retry=self._method_configs["CreateCryptoKey"].retry, default_timeout=self._method_configs["CreateCryptoKey"].timeout, client_info=self._client_info, ) request = service_pb2.CreateCryptoKeyRequest( parent=parent, crypto_key_id=crypto_key_id, crypto_key=crypto_key ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_crypto_key"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_crypto_key", "(", "self", ",", "parent", ",", "crypto_key_id", ",", "crypto_key", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_crypto_key\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_crypto_key\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_crypto_key", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateCryptoKey\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateCryptoKey\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "service_pb2", ".", "CreateCryptoKeyRequest", "(", "parent", "=", "parent", ",", "crypto_key_id", "=", "crypto_key_id", ",", "crypto_key", "=", "crypto_key", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"parent\"", ",", "parent", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_crypto_key\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Create a new ``CryptoKey`` within a ``KeyRing``. ``CryptoKey.purpose`` and ``CryptoKey.version_template.algorithm`` are required. Example: >>> from google.cloud import kms_v1 >>> from google.cloud.kms_v1 import enums >>> >>> client = kms_v1.KeyManagementServiceClient() >>> >>> parent = client.key_ring_path('[PROJECT]', '[LOCATION]', '[KEY_RING]') >>> crypto_key_id = 'my-app-key' >>> purpose = enums.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT >>> seconds = 2147483647 >>> next_rotation_time = {'seconds': seconds} >>> seconds_2 = 604800 >>> rotation_period = {'seconds': seconds_2} >>> crypto_key = {'purpose': purpose, 'next_rotation_time': next_rotation_time, 'rotation_period': rotation_period} >>> >>> response = client.create_crypto_key(parent, crypto_key_id, crypto_key) Args: parent (str): Required. The ``name`` of the KeyRing associated with the ``CryptoKeys``. crypto_key_id (str): Required. It must be unique within a KeyRing and match the regular expression ``[a-zA-Z0-9_-]{1,63}`` crypto_key (Union[dict, ~google.cloud.kms_v1.types.CryptoKey]): A ``CryptoKey`` with initial field values. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.kms_v1.types.CryptoKey` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.kms_v1.types.CryptoKey` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Create", "a", "new", "CryptoKey", "within", "a", "KeyRing", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/kms/google/cloud/kms_v1/gapic/key_management_service_client.py#L849-L938
27,924
googleapis/google-cloud-python
trace/google/cloud/trace_v2/gapic/trace_service_client.py
TraceServiceClient.span_path
def span_path(cls, project, trace, span): """Return a fully-qualified span string.""" return google.api_core.path_template.expand( "projects/{project}/traces/{trace}/spans/{span}", project=project, trace=trace, span=span, )
python
def span_path(cls, project, trace, span): """Return a fully-qualified span string.""" return google.api_core.path_template.expand( "projects/{project}/traces/{trace}/spans/{span}", project=project, trace=trace, span=span, )
[ "def", "span_path", "(", "cls", ",", "project", ",", "trace", ",", "span", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/traces/{trace}/spans/{span}\"", ",", "project", "=", "project", ",", "trace", "=", "trace", ",", "span", "=", "span", ",", ")" ]
Return a fully-qualified span string.
[ "Return", "a", "fully", "-", "qualified", "span", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace_v2/gapic/trace_service_client.py#L88-L95
27,925
googleapis/google-cloud-python
trace/google/cloud/trace_v2/gapic/trace_service_client.py
TraceServiceClient.batch_write_spans
def batch_write_spans( self, name, spans, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sends new spans to new or existing traces. You cannot update existing spans. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `spans`: >>> spans = [] >>> >>> client.batch_write_spans(name, spans) Args: name (str): Required. The name of the project where the spans belong. The format is ``projects/[PROJECT_ID]``. spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing spans, or the results are undefined. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Span` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_write_spans" not in self._inner_api_calls: self._inner_api_calls[ "batch_write_spans" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_write_spans, default_retry=self._method_configs["BatchWriteSpans"].retry, default_timeout=self._method_configs["BatchWriteSpans"].timeout, client_info=self._client_info, ) request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["batch_write_spans"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def batch_write_spans( self, name, spans, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sends new spans to new or existing traces. You cannot update existing spans. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `spans`: >>> spans = [] >>> >>> client.batch_write_spans(name, spans) Args: name (str): Required. The name of the project where the spans belong. The format is ``projects/[PROJECT_ID]``. spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing spans, or the results are undefined. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Span` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_write_spans" not in self._inner_api_calls: self._inner_api_calls[ "batch_write_spans" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_write_spans, default_retry=self._method_configs["BatchWriteSpans"].retry, default_timeout=self._method_configs["BatchWriteSpans"].timeout, client_info=self._client_info, ) request = tracing_pb2.BatchWriteSpansRequest(name=name, spans=spans) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["batch_write_spans"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "batch_write_spans", "(", "self", ",", "name", ",", "spans", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"batch_write_spans\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"batch_write_spans\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "batch_write_spans", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"BatchWriteSpans\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"BatchWriteSpans\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "tracing_pb2", ".", "BatchWriteSpansRequest", "(", "name", "=", "name", ",", "spans", "=", "spans", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"name\"", ",", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "self", ".", "_inner_api_calls", "[", "\"batch_write_spans\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Sends new spans to new or existing traces. You cannot update existing spans. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `spans`: >>> spans = [] >>> >>> client.batch_write_spans(name, spans) Args: name (str): Required. The name of the project where the spans belong. The format is ``projects/[PROJECT_ID]``. spans (list[Union[dict, ~google.cloud.trace_v2.types.Span]]): A list of new spans. The span names must not match existing spans, or the results are undefined. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Span` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Sends", "new", "spans", "to", "new", "or", "existing", "traces", ".", "You", "cannot", "update", "existing", "spans", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace_v2/gapic/trace_service_client.py#L196-L271
27,926
googleapis/google-cloud-python
trace/google/cloud/trace_v2/gapic/trace_service_client.py
TraceServiceClient.create_span
def create_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, status=None, same_process_as_parent_span=None, child_span_count=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]') >>> >>> # TODO: Initialize `span_id`: >>> span_id = '' >>> >>> # TODO: Initialize `display_name`: >>> display_name = {} >>> >>> # TODO: Initialize `start_time`: >>> start_time = {} >>> >>> # TODO: Initialize `end_time`: >>> end_time = {} >>> >>> response = client.create_span(name, span_id, display_name, start_time, end_time) Args: name (str): The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE\_ID] is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. [SPAN\_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. span_id (str): The [SPAN\_ID] portion of the span's resource name. display_name (Union[dict, ~google.cloud.trace_v2.types.TruncatableString]): A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site\_values.console\_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TruncatableString` start_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` end_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` parent_span_id (str): The [SPAN\_ID] of this span's parent span. If this is a root span, then this field must be empty. attributes (Union[dict, ~google.cloud.trace_v2.types.Attributes]): A set of attributes on the span. You can have up to 32 attributes per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Attributes` stack_trace (Union[dict, ~google.cloud.trace_v2.types.StackTrace]): Stack trace captured at the start of the span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.StackTrace` time_events (Union[dict, ~google.cloud.trace_v2.types.TimeEvents]): A set of time events. You can have up to 32 annotations and 128 message events per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TimeEvents` links (Union[dict, ~google.cloud.trace_v2.types.Links]): Links associated with the span. You can have up to 128 links per Span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Links` status (Union[dict, ~google.cloud.trace_v2.types.Status]): An optional final status for this span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Status` same_process_as_parent_span (Union[dict, ~google.cloud.trace_v2.types.BoolValue]): (Optional) Set this parameter to indicate whether this span is in the same process as its parent. If you do not set this parameter, Stackdriver Trace is unable to take advantage of this helpful information. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.BoolValue` child_span_count (Union[dict, ~google.cloud.trace_v2.types.Int32Value]): An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Int32Value` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.trace_v2.types.Span` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_span" not in self._inner_api_calls: self._inner_api_calls[ "create_span" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_span, default_retry=self._method_configs["CreateSpan"].retry, default_timeout=self._method_configs["CreateSpan"].timeout, client_info=self._client_info, ) request = trace_pb2.Span( name=name, span_id=span_id, display_name=display_name, start_time=start_time, end_time=end_time, parent_span_id=parent_span_id, attributes=attributes, stack_trace=stack_trace, time_events=time_events, links=links, status=status, same_process_as_parent_span=same_process_as_parent_span, child_span_count=child_span_count, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_span"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_span( self, name, span_id, display_name, start_time, end_time, parent_span_id=None, attributes=None, stack_trace=None, time_events=None, links=None, status=None, same_process_as_parent_span=None, child_span_count=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]') >>> >>> # TODO: Initialize `span_id`: >>> span_id = '' >>> >>> # TODO: Initialize `display_name`: >>> display_name = {} >>> >>> # TODO: Initialize `start_time`: >>> start_time = {} >>> >>> # TODO: Initialize `end_time`: >>> end_time = {} >>> >>> response = client.create_span(name, span_id, display_name, start_time, end_time) Args: name (str): The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE\_ID] is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. [SPAN\_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. span_id (str): The [SPAN\_ID] portion of the span's resource name. display_name (Union[dict, ~google.cloud.trace_v2.types.TruncatableString]): A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site\_values.console\_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TruncatableString` start_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` end_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` parent_span_id (str): The [SPAN\_ID] of this span's parent span. If this is a root span, then this field must be empty. attributes (Union[dict, ~google.cloud.trace_v2.types.Attributes]): A set of attributes on the span. You can have up to 32 attributes per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Attributes` stack_trace (Union[dict, ~google.cloud.trace_v2.types.StackTrace]): Stack trace captured at the start of the span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.StackTrace` time_events (Union[dict, ~google.cloud.trace_v2.types.TimeEvents]): A set of time events. You can have up to 32 annotations and 128 message events per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TimeEvents` links (Union[dict, ~google.cloud.trace_v2.types.Links]): Links associated with the span. You can have up to 128 links per Span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Links` status (Union[dict, ~google.cloud.trace_v2.types.Status]): An optional final status for this span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Status` same_process_as_parent_span (Union[dict, ~google.cloud.trace_v2.types.BoolValue]): (Optional) Set this parameter to indicate whether this span is in the same process as its parent. If you do not set this parameter, Stackdriver Trace is unable to take advantage of this helpful information. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.BoolValue` child_span_count (Union[dict, ~google.cloud.trace_v2.types.Int32Value]): An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Int32Value` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.trace_v2.types.Span` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_span" not in self._inner_api_calls: self._inner_api_calls[ "create_span" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_span, default_retry=self._method_configs["CreateSpan"].retry, default_timeout=self._method_configs["CreateSpan"].timeout, client_info=self._client_info, ) request = trace_pb2.Span( name=name, span_id=span_id, display_name=display_name, start_time=start_time, end_time=end_time, parent_span_id=parent_span_id, attributes=attributes, stack_trace=stack_trace, time_events=time_events, links=links, status=status, same_process_as_parent_span=same_process_as_parent_span, child_span_count=child_span_count, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_span"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_span", "(", "self", ",", "name", ",", "span_id", ",", "display_name", ",", "start_time", ",", "end_time", ",", "parent_span_id", "=", "None", ",", "attributes", "=", "None", ",", "stack_trace", "=", "None", ",", "time_events", "=", "None", ",", "links", "=", "None", ",", "status", "=", "None", ",", "same_process_as_parent_span", "=", "None", ",", "child_span_count", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"create_span\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_span\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_span", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateSpan\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateSpan\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "trace_pb2", ".", "Span", "(", "name", "=", "name", ",", "span_id", "=", "span_id", ",", "display_name", "=", "display_name", ",", "start_time", "=", "start_time", ",", "end_time", "=", "end_time", ",", "parent_span_id", "=", "parent_span_id", ",", "attributes", "=", "attributes", ",", "stack_trace", "=", "stack_trace", ",", "time_events", "=", "time_events", ",", "links", "=", "links", ",", "status", "=", "status", ",", "same_process_as_parent_span", "=", "same_process_as_parent_span", ",", "child_span_count", "=", "child_span_count", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"name\"", ",", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_span\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new span. Example: >>> from google.cloud import trace_v2 >>> >>> client = trace_v2.TraceServiceClient() >>> >>> name = client.span_path('[PROJECT]', '[TRACE]', '[SPAN]') >>> >>> # TODO: Initialize `span_id`: >>> span_id = '' >>> >>> # TODO: Initialize `display_name`: >>> display_name = {} >>> >>> # TODO: Initialize `start_time`: >>> start_time = {} >>> >>> # TODO: Initialize `end_time`: >>> end_time = {} >>> >>> response = client.create_span(name, span_id, display_name, start_time, end_time) Args: name (str): The resource name of the span in the following format: :: projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] [TRACE\_ID] is a unique identifier for a trace within a project; it is a 32-character hexadecimal encoding of a 16-byte array. [SPAN\_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte array. span_id (str): The [SPAN\_ID] portion of the span's resource name. display_name (Union[dict, ~google.cloud.trace_v2.types.TruncatableString]): A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description in the {% dynamic print site\_values.console\_name %}. For example, the display name can be a qualified method name or a file name and a line number where the operation is called. A best practice is to use the same display name within an application and at the same call point. This makes it easier to correlate spans in different traces. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TruncatableString` start_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The start time of the span. On the client side, this is the time kept by the local machine where the span execution starts. On the server side, this is the time when the server's application handler starts running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` end_time (Union[dict, ~google.cloud.trace_v2.types.Timestamp]): The end time of the span. On the client side, this is the time kept by the local machine where the span execution ends. On the server side, this is the time when the server application handler stops running. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Timestamp` parent_span_id (str): The [SPAN\_ID] of this span's parent span. If this is a root span, then this field must be empty. attributes (Union[dict, ~google.cloud.trace_v2.types.Attributes]): A set of attributes on the span. You can have up to 32 attributes per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Attributes` stack_trace (Union[dict, ~google.cloud.trace_v2.types.StackTrace]): Stack trace captured at the start of the span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.StackTrace` time_events (Union[dict, ~google.cloud.trace_v2.types.TimeEvents]): A set of time events. You can have up to 32 annotations and 128 message events per span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.TimeEvents` links (Union[dict, ~google.cloud.trace_v2.types.Links]): Links associated with the span. You can have up to 128 links per Span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Links` status (Union[dict, ~google.cloud.trace_v2.types.Status]): An optional final status for this span. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Status` same_process_as_parent_span (Union[dict, ~google.cloud.trace_v2.types.BoolValue]): (Optional) Set this parameter to indicate whether this span is in the same process as its parent. If you do not set this parameter, Stackdriver Trace is unable to take advantage of this helpful information. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.BoolValue` child_span_count (Union[dict, ~google.cloud.trace_v2.types.Int32Value]): An optional number of child spans that were generated while this span was active. If set, allows implementation to detect missing child spans. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.trace_v2.types.Int32Value` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.trace_v2.types.Span` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Creates", "a", "new", "span", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace_v2/gapic/trace_service_client.py#L273-L447
27,927
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
_wrap_callback_errors
def _wrap_callback_errors(callback, message): """Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Message]): The user callback. message (~Message): The Pub/Sub message. """ try: callback(message) except Exception: # Note: the likelihood of this failing is extremely low. This just adds # a message to a queue, so if this doesn't work the world is in an # unrecoverable state and this thread should just bail. _LOGGER.exception( "Top-level exception occurred in callback while processing a " "message" ) message.nack()
python
def _wrap_callback_errors(callback, message): """Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Message]): The user callback. message (~Message): The Pub/Sub message. """ try: callback(message) except Exception: # Note: the likelihood of this failing is extremely low. This just adds # a message to a queue, so if this doesn't work the world is in an # unrecoverable state and this thread should just bail. _LOGGER.exception( "Top-level exception occurred in callback while processing a " "message" ) message.nack()
[ "def", "_wrap_callback_errors", "(", "callback", ",", "message", ")", ":", "try", ":", "callback", "(", "message", ")", "except", "Exception", ":", "# Note: the likelihood of this failing is extremely low. This just adds", "# a message to a queue, so if this doesn't work the world is in an", "# unrecoverable state and this thread should just bail.", "_LOGGER", ".", "exception", "(", "\"Top-level exception occurred in callback while processing a \"", "\"message\"", ")", "message", ".", "nack", "(", ")" ]
Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Message]): The user callback. message (~Message): The Pub/Sub message.
[ "Wraps", "a", "user", "callback", "so", "that", "if", "an", "exception", "occurs", "the", "message", "is", "nacked", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L55-L72
27,928
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.ack_deadline
def ack_deadline(self): """Return the current ack deadline based on historical time-to-ack. This method is "sticky". It will only perform the computations to check on the right ack deadline if the histogram has gained a significant amount of new information. Returns: int: The ack deadline. """ target = min([self._last_histogram_size * 2, self._last_histogram_size + 100]) if len(self.ack_histogram) > target: self._ack_deadline = self.ack_histogram.percentile(percent=99) return self._ack_deadline
python
def ack_deadline(self): """Return the current ack deadline based on historical time-to-ack. This method is "sticky". It will only perform the computations to check on the right ack deadline if the histogram has gained a significant amount of new information. Returns: int: The ack deadline. """ target = min([self._last_histogram_size * 2, self._last_histogram_size + 100]) if len(self.ack_histogram) > target: self._ack_deadline = self.ack_histogram.percentile(percent=99) return self._ack_deadline
[ "def", "ack_deadline", "(", "self", ")", ":", "target", "=", "min", "(", "[", "self", ".", "_last_histogram_size", "*", "2", ",", "self", ".", "_last_histogram_size", "+", "100", "]", ")", "if", "len", "(", "self", ".", "ack_histogram", ")", ">", "target", ":", "self", ".", "_ack_deadline", "=", "self", ".", "ack_histogram", ".", "percentile", "(", "percent", "=", "99", ")", "return", "self", ".", "_ack_deadline" ]
Return the current ack deadline based on historical time-to-ack. This method is "sticky". It will only perform the computations to check on the right ack deadline if the histogram has gained a significant amount of new information. Returns: int: The ack deadline.
[ "Return", "the", "current", "ack", "deadline", "based", "on", "historical", "time", "-", "to", "-", "ack", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L161-L174
27,929
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.load
def load(self): """Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values between 0.0 and 1.0 represent how close we are to them. (0.5 means we have exactly half of what the flow control setting allows, for example.) There are (currently) two flow control settings; this property computes how close the manager is to each of them, and returns whichever value is higher. (It does not matter that we have lots of running room on setting A if setting B is over.) Returns: float: The load value. """ if self._leaser is None: return 0 return max( [ self._leaser.message_count / self._flow_control.max_messages, self._leaser.bytes / self._flow_control.max_bytes, ] )
python
def load(self): """Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values between 0.0 and 1.0 represent how close we are to them. (0.5 means we have exactly half of what the flow control setting allows, for example.) There are (currently) two flow control settings; this property computes how close the manager is to each of them, and returns whichever value is higher. (It does not matter that we have lots of running room on setting A if setting B is over.) Returns: float: The load value. """ if self._leaser is None: return 0 return max( [ self._leaser.message_count / self._flow_control.max_messages, self._leaser.bytes / self._flow_control.max_bytes, ] )
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "_leaser", "is", "None", ":", "return", "0", "return", "max", "(", "[", "self", ".", "_leaser", ".", "message_count", "/", "self", ".", "_flow_control", ".", "max_messages", ",", "self", ".", "_leaser", ".", "bytes", "/", "self", ".", "_flow_control", ".", "max_bytes", ",", "]", ")" ]
Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values between 0.0 and 1.0 represent how close we are to them. (0.5 means we have exactly half of what the flow control setting allows, for example.) There are (currently) two flow control settings; this property computes how close the manager is to each of them, and returns whichever value is higher. (It does not matter that we have lots of running room on setting A if setting B is over.) Returns: float: The load value.
[ "Return", "the", "current", "load", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L177-L201
27,930
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.maybe_pause_consumer
def maybe_pause_consumer(self): """Check the current load and pause the consumer if needed.""" if self.load >= 1.0: if self._consumer is not None and not self._consumer.is_paused: _LOGGER.debug("Message backlog over load at %.2f, pausing.", self.load) self._consumer.pause()
python
def maybe_pause_consumer(self): """Check the current load and pause the consumer if needed.""" if self.load >= 1.0: if self._consumer is not None and not self._consumer.is_paused: _LOGGER.debug("Message backlog over load at %.2f, pausing.", self.load) self._consumer.pause()
[ "def", "maybe_pause_consumer", "(", "self", ")", ":", "if", "self", ".", "load", ">=", "1.0", ":", "if", "self", ".", "_consumer", "is", "not", "None", "and", "not", "self", ".", "_consumer", ".", "is_paused", ":", "_LOGGER", ".", "debug", "(", "\"Message backlog over load at %.2f, pausing.\"", ",", "self", ".", "load", ")", "self", ".", "_consumer", ".", "pause", "(", ")" ]
Check the current load and pause the consumer if needed.
[ "Check", "the", "current", "load", "and", "pause", "the", "consumer", "if", "needed", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L211-L216
27,931
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.maybe_resume_consumer
def maybe_resume_consumer(self): """Check the current load and resume the consumer if needed.""" # If we have been paused by flow control, check and see if we are # back within our limits. # # In order to not thrash too much, require us to have passed below # the resume threshold (80% by default) of each flow control setting # before restarting. if self._consumer is None or not self._consumer.is_paused: return if self.load < self.flow_control.resume_threshold: self._consumer.resume() else: _LOGGER.debug("Did not resume, current load is %s", self.load)
python
def maybe_resume_consumer(self): """Check the current load and resume the consumer if needed.""" # If we have been paused by flow control, check and see if we are # back within our limits. # # In order to not thrash too much, require us to have passed below # the resume threshold (80% by default) of each flow control setting # before restarting. if self._consumer is None or not self._consumer.is_paused: return if self.load < self.flow_control.resume_threshold: self._consumer.resume() else: _LOGGER.debug("Did not resume, current load is %s", self.load)
[ "def", "maybe_resume_consumer", "(", "self", ")", ":", "# If we have been paused by flow control, check and see if we are", "# back within our limits.", "#", "# In order to not thrash too much, require us to have passed below", "# the resume threshold (80% by default) of each flow control setting", "# before restarting.", "if", "self", ".", "_consumer", "is", "None", "or", "not", "self", ".", "_consumer", ".", "is_paused", ":", "return", "if", "self", ".", "load", "<", "self", ".", "flow_control", ".", "resume_threshold", ":", "self", ".", "_consumer", ".", "resume", "(", ")", "else", ":", "_LOGGER", ".", "debug", "(", "\"Did not resume, current load is %s\"", ",", "self", ".", "load", ")" ]
Check the current load and resume the consumer if needed.
[ "Check", "the", "current", "load", "and", "resume", "the", "consumer", "if", "needed", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L218-L232
27,932
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager._send_unary_request
def _send_unary_request(self, request): """Send a request using a separate unary request instead of over the stream. Args: request (types.StreamingPullRequest): The stream request to be mapped into unary requests. """ if request.ack_ids: self._client.acknowledge( subscription=self._subscription, ack_ids=list(request.ack_ids) ) if request.modify_deadline_ack_ids: # Send ack_ids with the same deadline seconds together. deadline_to_ack_ids = collections.defaultdict(list) for n, ack_id in enumerate(request.modify_deadline_ack_ids): deadline = request.modify_deadline_seconds[n] deadline_to_ack_ids[deadline].append(ack_id) for deadline, ack_ids in six.iteritems(deadline_to_ack_ids): self._client.modify_ack_deadline( subscription=self._subscription, ack_ids=ack_ids, ack_deadline_seconds=deadline, ) _LOGGER.debug("Sent request(s) over unary RPC.")
python
def _send_unary_request(self, request): """Send a request using a separate unary request instead of over the stream. Args: request (types.StreamingPullRequest): The stream request to be mapped into unary requests. """ if request.ack_ids: self._client.acknowledge( subscription=self._subscription, ack_ids=list(request.ack_ids) ) if request.modify_deadline_ack_ids: # Send ack_ids with the same deadline seconds together. deadline_to_ack_ids = collections.defaultdict(list) for n, ack_id in enumerate(request.modify_deadline_ack_ids): deadline = request.modify_deadline_seconds[n] deadline_to_ack_ids[deadline].append(ack_id) for deadline, ack_ids in six.iteritems(deadline_to_ack_ids): self._client.modify_ack_deadline( subscription=self._subscription, ack_ids=ack_ids, ack_deadline_seconds=deadline, ) _LOGGER.debug("Sent request(s) over unary RPC.")
[ "def", "_send_unary_request", "(", "self", ",", "request", ")", ":", "if", "request", ".", "ack_ids", ":", "self", ".", "_client", ".", "acknowledge", "(", "subscription", "=", "self", ".", "_subscription", ",", "ack_ids", "=", "list", "(", "request", ".", "ack_ids", ")", ")", "if", "request", ".", "modify_deadline_ack_ids", ":", "# Send ack_ids with the same deadline seconds together.", "deadline_to_ack_ids", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "n", ",", "ack_id", "in", "enumerate", "(", "request", ".", "modify_deadline_ack_ids", ")", ":", "deadline", "=", "request", ".", "modify_deadline_seconds", "[", "n", "]", "deadline_to_ack_ids", "[", "deadline", "]", ".", "append", "(", "ack_id", ")", "for", "deadline", ",", "ack_ids", "in", "six", ".", "iteritems", "(", "deadline_to_ack_ids", ")", ":", "self", ".", "_client", ".", "modify_ack_deadline", "(", "subscription", "=", "self", ".", "_subscription", ",", "ack_ids", "=", "ack_ids", ",", "ack_deadline_seconds", "=", "deadline", ",", ")", "_LOGGER", ".", "debug", "(", "\"Sent request(s) over unary RPC.\"", ")" ]
Send a request using a separate unary request instead of over the stream. Args: request (types.StreamingPullRequest): The stream request to be mapped into unary requests.
[ "Send", "a", "request", "using", "a", "separate", "unary", "request", "instead", "of", "over", "the", "stream", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L234-L262
27,933
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.send
def send(self, request): """Queue a request to be sent to the RPC.""" if self._UNARY_REQUESTS: try: self._send_unary_request(request) except exceptions.GoogleAPICallError: _LOGGER.debug( "Exception while sending unary RPC. This is typically " "non-fatal as stream requests are best-effort.", exc_info=True, ) else: self._rpc.send(request)
python
def send(self, request): """Queue a request to be sent to the RPC.""" if self._UNARY_REQUESTS: try: self._send_unary_request(request) except exceptions.GoogleAPICallError: _LOGGER.debug( "Exception while sending unary RPC. This is typically " "non-fatal as stream requests are best-effort.", exc_info=True, ) else: self._rpc.send(request)
[ "def", "send", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_UNARY_REQUESTS", ":", "try", ":", "self", ".", "_send_unary_request", "(", "request", ")", "except", "exceptions", ".", "GoogleAPICallError", ":", "_LOGGER", ".", "debug", "(", "\"Exception while sending unary RPC. This is typically \"", "\"non-fatal as stream requests are best-effort.\"", ",", "exc_info", "=", "True", ",", ")", "else", ":", "self", ".", "_rpc", ".", "send", "(", "request", ")" ]
Queue a request to be sent to the RPC.
[ "Queue", "a", "request", "to", "be", "sent", "to", "the", "RPC", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L264-L276
27,934
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager.heartbeat
def heartbeat(self): """Sends an empty request over the streaming pull RPC. This always sends over the stream, regardless of if ``self._UNARY_REQUESTS`` is set or not. """ if self._rpc is not None and self._rpc.is_active: self._rpc.send(types.StreamingPullRequest())
python
def heartbeat(self): """Sends an empty request over the streaming pull RPC. This always sends over the stream, regardless of if ``self._UNARY_REQUESTS`` is set or not. """ if self._rpc is not None and self._rpc.is_active: self._rpc.send(types.StreamingPullRequest())
[ "def", "heartbeat", "(", "self", ")", ":", "if", "self", ".", "_rpc", "is", "not", "None", "and", "self", ".", "_rpc", ".", "is_active", ":", "self", ".", "_rpc", ".", "send", "(", "types", ".", "StreamingPullRequest", "(", ")", ")" ]
Sends an empty request over the streaming pull RPC. This always sends over the stream, regardless of if ``self._UNARY_REQUESTS`` is set or not.
[ "Sends", "an", "empty", "request", "over", "the", "streaming", "pull", "RPC", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L278-L285
27,935
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager._get_initial_request
def _get_initial_request(self): """Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon opening the subscription. Returns: google.cloud.pubsub_v1.types.StreamingPullRequest: A request suitable for being the first request on the stream (and not suitable for any other purpose). """ # Any ack IDs that are under lease management need to have their # deadline extended immediately. if self._leaser is not None: # Explicitly copy the list, as it could be modified by another # thread. lease_ids = list(self._leaser.ack_ids) else: lease_ids = [] # Put the request together. request = types.StreamingPullRequest( modify_deadline_ack_ids=list(lease_ids), modify_deadline_seconds=[self.ack_deadline] * len(lease_ids), stream_ack_deadline_seconds=self.ack_histogram.percentile(99), subscription=self._subscription, ) # Return the initial request. return request
python
def _get_initial_request(self): """Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon opening the subscription. Returns: google.cloud.pubsub_v1.types.StreamingPullRequest: A request suitable for being the first request on the stream (and not suitable for any other purpose). """ # Any ack IDs that are under lease management need to have their # deadline extended immediately. if self._leaser is not None: # Explicitly copy the list, as it could be modified by another # thread. lease_ids = list(self._leaser.ack_ids) else: lease_ids = [] # Put the request together. request = types.StreamingPullRequest( modify_deadline_ack_ids=list(lease_ids), modify_deadline_seconds=[self.ack_deadline] * len(lease_ids), stream_ack_deadline_seconds=self.ack_histogram.percentile(99), subscription=self._subscription, ) # Return the initial request. return request
[ "def", "_get_initial_request", "(", "self", ")", ":", "# Any ack IDs that are under lease management need to have their", "# deadline extended immediately.", "if", "self", ".", "_leaser", "is", "not", "None", ":", "# Explicitly copy the list, as it could be modified by another", "# thread.", "lease_ids", "=", "list", "(", "self", ".", "_leaser", ".", "ack_ids", ")", "else", ":", "lease_ids", "=", "[", "]", "# Put the request together.", "request", "=", "types", ".", "StreamingPullRequest", "(", "modify_deadline_ack_ids", "=", "list", "(", "lease_ids", ")", ",", "modify_deadline_seconds", "=", "[", "self", ".", "ack_deadline", "]", "*", "len", "(", "lease_ids", ")", ",", "stream_ack_deadline_seconds", "=", "self", ".", "ack_histogram", ".", "percentile", "(", "99", ")", ",", "subscription", "=", "self", ".", "_subscription", ",", ")", "# Return the initial request.", "return", "request" ]
Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon opening the subscription. Returns: google.cloud.pubsub_v1.types.StreamingPullRequest: A request suitable for being the first request on the stream (and not suitable for any other purpose).
[ "Return", "the", "initial", "request", "for", "the", "RPC", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L370-L399
27,936
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
StreamingPullManager._should_recover
def _should_recover(self, exception): """Determine if an error on the RPC stream should be recovered. If the exception is one of the retryable exceptions, this will signal to the consumer thread that it should "recover" from the failure. This will cause the stream to exit when it returns :data:`False`. Returns: bool: Indicates if the caller should recover or shut down. Will be :data:`True` if the ``exception`` is "acceptable", i.e. in a list of retryable / idempotent exceptions. """ exception = _maybe_wrap_exception(exception) # If this is in the list of idempotent exceptions, then we want to # recover. if isinstance(exception, _RETRYABLE_STREAM_ERRORS): _LOGGER.info("Observed recoverable stream error %s", exception) return True _LOGGER.info("Observed non-recoverable stream error %s", exception) return False
python
def _should_recover(self, exception): """Determine if an error on the RPC stream should be recovered. If the exception is one of the retryable exceptions, this will signal to the consumer thread that it should "recover" from the failure. This will cause the stream to exit when it returns :data:`False`. Returns: bool: Indicates if the caller should recover or shut down. Will be :data:`True` if the ``exception`` is "acceptable", i.e. in a list of retryable / idempotent exceptions. """ exception = _maybe_wrap_exception(exception) # If this is in the list of idempotent exceptions, then we want to # recover. if isinstance(exception, _RETRYABLE_STREAM_ERRORS): _LOGGER.info("Observed recoverable stream error %s", exception) return True _LOGGER.info("Observed non-recoverable stream error %s", exception) return False
[ "def", "_should_recover", "(", "self", ",", "exception", ")", ":", "exception", "=", "_maybe_wrap_exception", "(", "exception", ")", "# If this is in the list of idempotent exceptions, then we want to", "# recover.", "if", "isinstance", "(", "exception", ",", "_RETRYABLE_STREAM_ERRORS", ")", ":", "_LOGGER", ".", "info", "(", "\"Observed recoverable stream error %s\"", ",", "exception", ")", "return", "True", "_LOGGER", ".", "info", "(", "\"Observed non-recoverable stream error %s\"", ",", "exception", ")", "return", "False" ]
Determine if an error on the RPC stream should be recovered. If the exception is one of the retryable exceptions, this will signal to the consumer thread that it should "recover" from the failure. This will cause the stream to exit when it returns :data:`False`. Returns: bool: Indicates if the caller should recover or shut down. Will be :data:`True` if the ``exception`` is "acceptable", i.e. in a list of retryable / idempotent exceptions.
[ "Determine", "if", "an", "error", "on", "the", "RPC", "stream", "should", "be", "recovered", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L432-L452
27,937
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/batch.py
WriteBatch.create
def create(self, reference, document_data): """Add a "change" to this batch to create a document. If the document given by ``reference`` already exists, then this batch will fail when :meth:`commit`-ed. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference to be created in this batch. document_data (dict): Property names and values to use for creating a document. """ write_pbs = _helpers.pbs_for_create(reference._document_path, document_data) self._add_write_pbs(write_pbs)
python
def create(self, reference, document_data): """Add a "change" to this batch to create a document. If the document given by ``reference`` already exists, then this batch will fail when :meth:`commit`-ed. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference to be created in this batch. document_data (dict): Property names and values to use for creating a document. """ write_pbs = _helpers.pbs_for_create(reference._document_path, document_data) self._add_write_pbs(write_pbs)
[ "def", "create", "(", "self", ",", "reference", ",", "document_data", ")", ":", "write_pbs", "=", "_helpers", ".", "pbs_for_create", "(", "reference", ".", "_document_path", ",", "document_data", ")", "self", ".", "_add_write_pbs", "(", "write_pbs", ")" ]
Add a "change" to this batch to create a document. If the document given by ``reference`` already exists, then this batch will fail when :meth:`commit`-ed. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference to be created in this batch. document_data (dict): Property names and values to use for creating a document.
[ "Add", "a", "change", "to", "this", "batch", "to", "create", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/batch.py#L50-L63
27,938
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/batch.py
WriteBatch.set
def set(self, reference, document_data, merge=False): """Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will have values set in this batch. document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document. """ if merge is not False: write_pbs = _helpers.pbs_for_set_with_merge( reference._document_path, document_data, merge ) else: write_pbs = _helpers.pbs_for_set_no_merge( reference._document_path, document_data ) self._add_write_pbs(write_pbs)
python
def set(self, reference, document_data, merge=False): """Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will have values set in this batch. document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document. """ if merge is not False: write_pbs = _helpers.pbs_for_set_with_merge( reference._document_path, document_data, merge ) else: write_pbs = _helpers.pbs_for_set_no_merge( reference._document_path, document_data ) self._add_write_pbs(write_pbs)
[ "def", "set", "(", "self", ",", "reference", ",", "document_data", ",", "merge", "=", "False", ")", ":", "if", "merge", "is", "not", "False", ":", "write_pbs", "=", "_helpers", ".", "pbs_for_set_with_merge", "(", "reference", ".", "_document_path", ",", "document_data", ",", "merge", ")", "else", ":", "write_pbs", "=", "_helpers", ".", "pbs_for_set_no_merge", "(", "reference", ".", "_document_path", ",", "document_data", ")", "self", ".", "_add_write_pbs", "(", "write_pbs", ")" ]
Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will have values set in this batch. document_data (dict): Property names and values to use for replacing a document. merge (Optional[bool] or Optional[List<apispec>]): If True, apply merging instead of overwriting the state of the document.
[ "Add", "a", "change", "to", "replace", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/batch.py#L65-L91
27,939
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/batch.py
WriteBatch.update
def update(self, reference, field_updates, option=None): """Add a "change" to update a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.update` for more information on ``field_updates`` and ``option``. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. """ if option.__class__.__name__ == "ExistsOption": raise ValueError("you must not pass an explicit write option to " "update.") write_pbs = _helpers.pbs_for_update( reference._document_path, field_updates, option ) self._add_write_pbs(write_pbs)
python
def update(self, reference, field_updates, option=None): """Add a "change" to update a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.update` for more information on ``field_updates`` and ``option``. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. """ if option.__class__.__name__ == "ExistsOption": raise ValueError("you must not pass an explicit write option to " "update.") write_pbs = _helpers.pbs_for_update( reference._document_path, field_updates, option ) self._add_write_pbs(write_pbs)
[ "def", "update", "(", "self", ",", "reference", ",", "field_updates", ",", "option", "=", "None", ")", ":", "if", "option", ".", "__class__", ".", "__name__", "==", "\"ExistsOption\"", ":", "raise", "ValueError", "(", "\"you must not pass an explicit write option to \"", "\"update.\"", ")", "write_pbs", "=", "_helpers", ".", "pbs_for_update", "(", "reference", ".", "_document_path", ",", "field_updates", ",", "option", ")", "self", ".", "_add_write_pbs", "(", "write_pbs", ")" ]
Add a "change" to update a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.update` for more information on ``field_updates`` and ``option``. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. field_updates (dict): Field names or paths to update and values to update with. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes.
[ "Add", "a", "change", "to", "update", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/batch.py#L93-L114
27,940
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/batch.py
WriteBatch.delete
def delete(self, reference, option=None): """Add a "change" to delete a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.delete` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. """ write_pb = _helpers.pb_for_delete(reference._document_path, option) self._add_write_pbs([write_pb])
python
def delete(self, reference, option=None): """Add a "change" to delete a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.delete` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes. """ write_pb = _helpers.pb_for_delete(reference._document_path, option) self._add_write_pbs([write_pb])
[ "def", "delete", "(", "self", ",", "reference", ",", "option", "=", "None", ")", ":", "write_pb", "=", "_helpers", ".", "pb_for_delete", "(", "reference", ".", "_document_path", ",", "option", ")", "self", ".", "_add_write_pbs", "(", "[", "write_pb", "]", ")" ]
Add a "change" to delete a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.delete` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A document reference that will be deleted in this batch. option (Optional[~.firestore_v1beta1.client.WriteOption]): A write option to make assertions / preconditions on the server state of the document before applying changes.
[ "Add", "a", "change", "to", "delete", "a", "document", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/batch.py#L116-L132
27,941
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/batch.py
WriteBatch.commit
def commit(self): """Commit the changes accumulated in this batch. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes were applied to this batch. A write result contains an ``update_time`` field. """ commit_response = self._client._firestore_api.commit( self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata, ) self._write_pbs = [] self.write_results = results = list(commit_response.write_results) self.commit_time = commit_response.commit_time return results
python
def commit(self): """Commit the changes accumulated in this batch. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes were applied to this batch. A write result contains an ``update_time`` field. """ commit_response = self._client._firestore_api.commit( self._client._database_string, self._write_pbs, transaction=None, metadata=self._client._rpc_metadata, ) self._write_pbs = [] self.write_results = results = list(commit_response.write_results) self.commit_time = commit_response.commit_time return results
[ "def", "commit", "(", "self", ")", ":", "commit_response", "=", "self", ".", "_client", ".", "_firestore_api", ".", "commit", "(", "self", ".", "_client", ".", "_database_string", ",", "self", ".", "_write_pbs", ",", "transaction", "=", "None", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "self", ".", "_write_pbs", "=", "[", "]", "self", ".", "write_results", "=", "results", "=", "list", "(", "commit_response", ".", "write_results", ")", "self", ".", "commit_time", "=", "commit_response", ".", "commit_time", "return", "results" ]
Commit the changes accumulated in this batch. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes were applied to this batch. A write result contains an ``update_time`` field.
[ "Commit", "the", "changes", "accumulated", "in", "this", "batch", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/batch.py#L134-L154
27,942
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_ensure_tuple_or_list
def _ensure_tuple_or_list(arg_name, tuple_or_list): """Ensures an input is a tuple or list. This effectively reduces the iterable types allowed to a very short whitelist: list and tuple. :type arg_name: str :param arg_name: Name of argument to use in error message. :type tuple_or_list: sequence of str :param tuple_or_list: Sequence to be verified. :rtype: list of str :returns: The ``tuple_or_list`` passed in cast to a ``list``. :raises TypeError: if the ``tuple_or_list`` is not a tuple or list. """ if not isinstance(tuple_or_list, (tuple, list)): raise TypeError( "Expected %s to be a tuple or list. " "Received %r" % (arg_name, tuple_or_list) ) return list(tuple_or_list)
python
def _ensure_tuple_or_list(arg_name, tuple_or_list): """Ensures an input is a tuple or list. This effectively reduces the iterable types allowed to a very short whitelist: list and tuple. :type arg_name: str :param arg_name: Name of argument to use in error message. :type tuple_or_list: sequence of str :param tuple_or_list: Sequence to be verified. :rtype: list of str :returns: The ``tuple_or_list`` passed in cast to a ``list``. :raises TypeError: if the ``tuple_or_list`` is not a tuple or list. """ if not isinstance(tuple_or_list, (tuple, list)): raise TypeError( "Expected %s to be a tuple or list. " "Received %r" % (arg_name, tuple_or_list) ) return list(tuple_or_list)
[ "def", "_ensure_tuple_or_list", "(", "arg_name", ",", "tuple_or_list", ")", ":", "if", "not", "isinstance", "(", "tuple_or_list", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"Expected %s to be a tuple or list. \"", "\"Received %r\"", "%", "(", "arg_name", ",", "tuple_or_list", ")", ")", "return", "list", "(", "tuple_or_list", ")" ]
Ensures an input is a tuple or list. This effectively reduces the iterable types allowed to a very short whitelist: list and tuple. :type arg_name: str :param arg_name: Name of argument to use in error message. :type tuple_or_list: sequence of str :param tuple_or_list: Sequence to be verified. :rtype: list of str :returns: The ``tuple_or_list`` passed in cast to a ``list``. :raises TypeError: if the ``tuple_or_list`` is not a tuple or list.
[ "Ensures", "an", "input", "is", "a", "tuple", "or", "list", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L149-L170
27,943
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_microseconds_from_datetime
def _microseconds_from_datetime(value): """Convert non-none datetime to microseconds. :type value: :class:`datetime.datetime` :param value: The timestamp to convert. :rtype: int :returns: The timestamp, in microseconds. """ if not value.tzinfo: value = value.replace(tzinfo=UTC) # Regardless of what timezone is on the value, convert it to UTC. value = value.astimezone(UTC) # Convert the datetime to a microsecond timestamp. return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond
python
def _microseconds_from_datetime(value): """Convert non-none datetime to microseconds. :type value: :class:`datetime.datetime` :param value: The timestamp to convert. :rtype: int :returns: The timestamp, in microseconds. """ if not value.tzinfo: value = value.replace(tzinfo=UTC) # Regardless of what timezone is on the value, convert it to UTC. value = value.astimezone(UTC) # Convert the datetime to a microsecond timestamp. return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond
[ "def", "_microseconds_from_datetime", "(", "value", ")", ":", "if", "not", "value", ".", "tzinfo", ":", "value", "=", "value", ".", "replace", "(", "tzinfo", "=", "UTC", ")", "# Regardless of what timezone is on the value, convert it to UTC.", "value", "=", "value", ".", "astimezone", "(", "UTC", ")", "# Convert the datetime to a microsecond timestamp.", "return", "int", "(", "calendar", ".", "timegm", "(", "value", ".", "timetuple", "(", ")", ")", "*", "1e6", ")", "+", "value", ".", "microsecond" ]
Convert non-none datetime to microseconds. :type value: :class:`datetime.datetime` :param value: The timestamp to convert. :rtype: int :returns: The timestamp, in microseconds.
[ "Convert", "non", "-", "none", "datetime", "to", "microseconds", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L215-L229
27,944
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_time_from_iso8601_time_naive
def _time_from_iso8601_time_naive(value): """Convert a zoneless ISO8601 time string to naive datetime time :type value: str :param value: The time string to convert :rtype: :class:`datetime.time` :returns: A datetime time object created from the string :raises ValueError: if the value does not match a known format. """ if len(value) == 8: # HH:MM:SS fmt = _TIMEONLY_NO_FRACTION elif len(value) == 15: # HH:MM:SS.micros fmt = _TIMEONLY_W_MICROS else: raise ValueError("Unknown time format: {}".format(value)) return datetime.datetime.strptime(value, fmt).time()
python
def _time_from_iso8601_time_naive(value): """Convert a zoneless ISO8601 time string to naive datetime time :type value: str :param value: The time string to convert :rtype: :class:`datetime.time` :returns: A datetime time object created from the string :raises ValueError: if the value does not match a known format. """ if len(value) == 8: # HH:MM:SS fmt = _TIMEONLY_NO_FRACTION elif len(value) == 15: # HH:MM:SS.micros fmt = _TIMEONLY_W_MICROS else: raise ValueError("Unknown time format: {}".format(value)) return datetime.datetime.strptime(value, fmt).time()
[ "def", "_time_from_iso8601_time_naive", "(", "value", ")", ":", "if", "len", "(", "value", ")", "==", "8", ":", "# HH:MM:SS", "fmt", "=", "_TIMEONLY_NO_FRACTION", "elif", "len", "(", "value", ")", "==", "15", ":", "# HH:MM:SS.micros", "fmt", "=", "_TIMEONLY_W_MICROS", "else", ":", "raise", "ValueError", "(", "\"Unknown time format: {}\"", ".", "format", "(", "value", ")", ")", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "fmt", ")", ".", "time", "(", ")" ]
Convert a zoneless ISO8601 time string to naive datetime time :type value: str :param value: The time string to convert :rtype: :class:`datetime.time` :returns: A datetime time object created from the string :raises ValueError: if the value does not match a known format.
[ "Convert", "a", "zoneless", "ISO8601", "time", "string", "to", "naive", "datetime", "time" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L258-L274
27,945
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_rfc3339_to_datetime
def _rfc3339_to_datetime(dt_str): """Convert a microsecond-precision timestamp to a native datetime. :type dt_str: str :param dt_str: The string to convert. :rtype: :class:`datetime.datetime` :returns: The datetime object created from the string. """ return datetime.datetime.strptime(dt_str, _RFC3339_MICROS).replace(tzinfo=UTC)
python
def _rfc3339_to_datetime(dt_str): """Convert a microsecond-precision timestamp to a native datetime. :type dt_str: str :param dt_str: The string to convert. :rtype: :class:`datetime.datetime` :returns: The datetime object created from the string. """ return datetime.datetime.strptime(dt_str, _RFC3339_MICROS).replace(tzinfo=UTC)
[ "def", "_rfc3339_to_datetime", "(", "dt_str", ")", ":", "return", "datetime", ".", "datetime", ".", "strptime", "(", "dt_str", ",", "_RFC3339_MICROS", ")", ".", "replace", "(", "tzinfo", "=", "UTC", ")" ]
Convert a microsecond-precision timestamp to a native datetime. :type dt_str: str :param dt_str: The string to convert. :rtype: :class:`datetime.datetime` :returns: The datetime object created from the string.
[ "Convert", "a", "microsecond", "-", "precision", "timestamp", "to", "a", "native", "datetime", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L277-L286
27,946
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_datetime_to_rfc3339
def _datetime_to_rfc3339(value, ignore_zone=True): """Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime object is ignored. :rtype: str :returns: The string representing the datetime stamp. """ if not ignore_zone and value.tzinfo is not None: # Convert to UTC and remove the time zone info. value = value.replace(tzinfo=None) - value.utcoffset() return value.strftime(_RFC3339_MICROS)
python
def _datetime_to_rfc3339(value, ignore_zone=True): """Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime object is ignored. :rtype: str :returns: The string representing the datetime stamp. """ if not ignore_zone and value.tzinfo is not None: # Convert to UTC and remove the time zone info. value = value.replace(tzinfo=None) - value.utcoffset() return value.strftime(_RFC3339_MICROS)
[ "def", "_datetime_to_rfc3339", "(", "value", ",", "ignore_zone", "=", "True", ")", ":", "if", "not", "ignore_zone", "and", "value", ".", "tzinfo", "is", "not", "None", ":", "# Convert to UTC and remove the time zone info.", "value", "=", "value", ".", "replace", "(", "tzinfo", "=", "None", ")", "-", "value", ".", "utcoffset", "(", ")", "return", "value", ".", "strftime", "(", "_RFC3339_MICROS", ")" ]
Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime object is ignored. :rtype: str :returns: The string representing the datetime stamp.
[ "Convert", "a", "timestamp", "to", "a", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L324-L341
27,947
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_bytes_to_unicode
def _bytes_to_unicode(value): """Converts bytes to a unicode value, if necessary. :type value: bytes :param value: bytes value to attempt string conversion on. :rtype: str :returns: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. :raises ValueError: if the value could not be converted to unicode. """ result = value.decode("utf-8") if isinstance(value, six.binary_type) else value if isinstance(result, six.text_type): return result else: raise ValueError("%r could not be converted to unicode" % (value,))
python
def _bytes_to_unicode(value): """Converts bytes to a unicode value, if necessary. :type value: bytes :param value: bytes value to attempt string conversion on. :rtype: str :returns: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. :raises ValueError: if the value could not be converted to unicode. """ result = value.decode("utf-8") if isinstance(value, six.binary_type) else value if isinstance(result, six.text_type): return result else: raise ValueError("%r could not be converted to unicode" % (value,))
[ "def", "_bytes_to_unicode", "(", "value", ")", ":", "result", "=", "value", ".", "decode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", "else", "value", "if", "isinstance", "(", "result", ",", "six", ".", "text_type", ")", ":", "return", "result", "else", ":", "raise", "ValueError", "(", "\"%r could not be converted to unicode\"", "%", "(", "value", ",", ")", ")" ]
Converts bytes to a unicode value, if necessary. :type value: bytes :param value: bytes value to attempt string conversion on. :rtype: str :returns: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. :raises ValueError: if the value could not be converted to unicode.
[ "Converts", "bytes", "to", "a", "unicode", "value", "if", "necessary", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L373-L389
27,948
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_from_any_pb
def _from_any_pb(pb_type, any_pb): """Converts an Any protobuf to the specified message type Args: pb_type (type): the type of the message that any_pb stores an instance of. any_pb (google.protobuf.any_pb2.Any): the object to be converted. Returns: pb_type: An instance of the pb_type message. Raises: TypeError: if the message could not be converted. """ msg = pb_type() if not any_pb.Unpack(msg): raise TypeError( "Could not convert {} to {}".format( any_pb.__class__.__name__, pb_type.__name__ ) ) return msg
python
def _from_any_pb(pb_type, any_pb): """Converts an Any protobuf to the specified message type Args: pb_type (type): the type of the message that any_pb stores an instance of. any_pb (google.protobuf.any_pb2.Any): the object to be converted. Returns: pb_type: An instance of the pb_type message. Raises: TypeError: if the message could not be converted. """ msg = pb_type() if not any_pb.Unpack(msg): raise TypeError( "Could not convert {} to {}".format( any_pb.__class__.__name__, pb_type.__name__ ) ) return msg
[ "def", "_from_any_pb", "(", "pb_type", ",", "any_pb", ")", ":", "msg", "=", "pb_type", "(", ")", "if", "not", "any_pb", ".", "Unpack", "(", "msg", ")", ":", "raise", "TypeError", "(", "\"Could not convert {} to {}\"", ".", "format", "(", "any_pb", ".", "__class__", ".", "__name__", ",", "pb_type", ".", "__name__", ")", ")", "return", "msg" ]
Converts an Any protobuf to the specified message type Args: pb_type (type): the type of the message that any_pb stores an instance of. any_pb (google.protobuf.any_pb2.Any): the object to be converted. Returns: pb_type: An instance of the pb_type message. Raises: TypeError: if the message could not be converted.
[ "Converts", "an", "Any", "protobuf", "to", "the", "specified", "message", "type" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L392-L414
27,949
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_pb_timestamp_to_datetime
def _pb_timestamp_to_datetime(timestamp_pb): """Convert a Timestamp protobuf to a datetime object. :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp` :param timestamp_pb: A Google returned timestamp protobuf. :rtype: :class:`datetime.datetime` :returns: A UTC datetime object converted from a protobuf timestamp. """ return _EPOCH + datetime.timedelta( seconds=timestamp_pb.seconds, microseconds=(timestamp_pb.nanos / 1000.0) )
python
def _pb_timestamp_to_datetime(timestamp_pb): """Convert a Timestamp protobuf to a datetime object. :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp` :param timestamp_pb: A Google returned timestamp protobuf. :rtype: :class:`datetime.datetime` :returns: A UTC datetime object converted from a protobuf timestamp. """ return _EPOCH + datetime.timedelta( seconds=timestamp_pb.seconds, microseconds=(timestamp_pb.nanos / 1000.0) )
[ "def", "_pb_timestamp_to_datetime", "(", "timestamp_pb", ")", ":", "return", "_EPOCH", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "timestamp_pb", ".", "seconds", ",", "microseconds", "=", "(", "timestamp_pb", ".", "nanos", "/", "1000.0", ")", ")" ]
Convert a Timestamp protobuf to a datetime object. :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp` :param timestamp_pb: A Google returned timestamp protobuf. :rtype: :class:`datetime.datetime` :returns: A UTC datetime object converted from a protobuf timestamp.
[ "Convert", "a", "Timestamp", "protobuf", "to", "a", "datetime", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L417-L428
27,950
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_datetime_to_pb_timestamp
def _datetime_to_pb_timestamp(when): """Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object. """ ms_value = _microseconds_from_datetime(when) seconds, micros = divmod(ms_value, 10 ** 6) nanos = micros * 10 ** 3 return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
python
def _datetime_to_pb_timestamp(when): """Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object. """ ms_value = _microseconds_from_datetime(when) seconds, micros = divmod(ms_value, 10 ** 6) nanos = micros * 10 ** 3 return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
[ "def", "_datetime_to_pb_timestamp", "(", "when", ")", ":", "ms_value", "=", "_microseconds_from_datetime", "(", "when", ")", "seconds", ",", "micros", "=", "divmod", "(", "ms_value", ",", "10", "**", "6", ")", "nanos", "=", "micros", "*", "10", "**", "3", "return", "timestamp_pb2", ".", "Timestamp", "(", "seconds", "=", "seconds", ",", "nanos", "=", "nanos", ")" ]
Convert a datetime object to a Timestamp protobuf. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp` :returns: A timestamp protobuf corresponding to the object.
[ "Convert", "a", "datetime", "object", "to", "a", "Timestamp", "protobuf", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L444-L456
27,951
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_duration_pb_to_timedelta
def _duration_pb_to_timedelta(duration_pb): """Convert a duration protobuf to a Python timedelta object. .. note:: The Python timedelta has a granularity of microseconds while the protobuf duration type has a duration of nanoseconds. :type duration_pb: :class:`google.protobuf.duration_pb2.Duration` :param duration_pb: A protobuf duration object. :rtype: :class:`datetime.timedelta` :returns: The converted timedelta object. """ return datetime.timedelta( seconds=duration_pb.seconds, microseconds=(duration_pb.nanos / 1000.0) )
python
def _duration_pb_to_timedelta(duration_pb): """Convert a duration protobuf to a Python timedelta object. .. note:: The Python timedelta has a granularity of microseconds while the protobuf duration type has a duration of nanoseconds. :type duration_pb: :class:`google.protobuf.duration_pb2.Duration` :param duration_pb: A protobuf duration object. :rtype: :class:`datetime.timedelta` :returns: The converted timedelta object. """ return datetime.timedelta( seconds=duration_pb.seconds, microseconds=(duration_pb.nanos / 1000.0) )
[ "def", "_duration_pb_to_timedelta", "(", "duration_pb", ")", ":", "return", "datetime", ".", "timedelta", "(", "seconds", "=", "duration_pb", ".", "seconds", ",", "microseconds", "=", "(", "duration_pb", ".", "nanos", "/", "1000.0", ")", ")" ]
Convert a duration protobuf to a Python timedelta object. .. note:: The Python timedelta has a granularity of microseconds while the protobuf duration type has a duration of nanoseconds. :type duration_pb: :class:`google.protobuf.duration_pb2.Duration` :param duration_pb: A protobuf duration object. :rtype: :class:`datetime.timedelta` :returns: The converted timedelta object.
[ "Convert", "a", "duration", "protobuf", "to", "a", "Python", "timedelta", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L478-L494
27,952
googleapis/google-cloud-python
core/google/cloud/_helpers.py
_name_from_project_path
def _name_from_project_path(path, project, template): """Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the name. :type project: str :param project: (Optional) The project associated with the request. It is included for validation purposes. If passed as None, disables validation. :type template: str :param template: Template regex describing the expected form of the path. The regex must have two named groups, 'project' and 'name'. :rtype: str :returns: Name parsed from ``path``. :raises ValueError: if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ if isinstance(template, str): template = re.compile(template) match = template.match(path) if not match: raise ValueError( 'path "%s" did not match expected pattern "%s"' % (path, template.pattern) ) if project is not None: found_project = match.group("project") if found_project != project: raise ValueError( "Project from client (%s) should agree with " "project from resource(%s)." % (project, found_project) ) return match.group("name")
python
def _name_from_project_path(path, project, template): """Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the name. :type project: str :param project: (Optional) The project associated with the request. It is included for validation purposes. If passed as None, disables validation. :type template: str :param template: Template regex describing the expected form of the path. The regex must have two named groups, 'project' and 'name'. :rtype: str :returns: Name parsed from ``path``. :raises ValueError: if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ if isinstance(template, str): template = re.compile(template) match = template.match(path) if not match: raise ValueError( 'path "%s" did not match expected pattern "%s"' % (path, template.pattern) ) if project is not None: found_project = match.group("project") if found_project != project: raise ValueError( "Project from client (%s) should agree with " "project from resource(%s)." % (project, found_project) ) return match.group("name")
[ "def", "_name_from_project_path", "(", "path", ",", "project", ",", "template", ")", ":", "if", "isinstance", "(", "template", ",", "str", ")", ":", "template", "=", "re", ".", "compile", "(", "template", ")", "match", "=", "template", ".", "match", "(", "path", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'path \"%s\" did not match expected pattern \"%s\"'", "%", "(", "path", ",", "template", ".", "pattern", ")", ")", "if", "project", "is", "not", "None", ":", "found_project", "=", "match", ".", "group", "(", "\"project\"", ")", "if", "found_project", "!=", "project", ":", "raise", "ValueError", "(", "\"Project from client (%s) should agree with \"", "\"project from resource(%s).\"", "%", "(", "project", ",", "found_project", ")", ")", "return", "match", ".", "group", "(", "\"name\"", ")" ]
Validate a URI path and get the leaf object's name. :type path: str :param path: URI path containing the name. :type project: str :param project: (Optional) The project associated with the request. It is included for validation purposes. If passed as None, disables validation. :type template: str :param template: Template regex describing the expected form of the path. The regex must have two named groups, 'project' and 'name'. :rtype: str :returns: Name parsed from ``path``. :raises ValueError: if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in.
[ "Validate", "a", "URI", "path", "and", "get", "the", "leaf", "object", "s", "name", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L497-L537
27,953
googleapis/google-cloud-python
core/google/cloud/_helpers.py
make_secure_channel
def make_secure_channel(credentials, user_agent, host, extra_options=()): """Makes a secure channel for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options used when creating the channel. :rtype: :class:`grpc._channel.Channel` :returns: gRPC secure channel with credentials attached. """ target = "%s:%d" % (host, http_client.HTTPS_PORT) http_request = google.auth.transport.requests.Request() user_agent_option = ("grpc.primary_user_agent", user_agent) options = (user_agent_option,) + extra_options return google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, target, options=options )
python
def make_secure_channel(credentials, user_agent, host, extra_options=()): """Makes a secure channel for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options used when creating the channel. :rtype: :class:`grpc._channel.Channel` :returns: gRPC secure channel with credentials attached. """ target = "%s:%d" % (host, http_client.HTTPS_PORT) http_request = google.auth.transport.requests.Request() user_agent_option = ("grpc.primary_user_agent", user_agent) options = (user_agent_option,) + extra_options return google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, target, options=options )
[ "def", "make_secure_channel", "(", "credentials", ",", "user_agent", ",", "host", ",", "extra_options", "=", "(", ")", ")", ":", "target", "=", "\"%s:%d\"", "%", "(", "host", ",", "http_client", ".", "HTTPS_PORT", ")", "http_request", "=", "google", ".", "auth", ".", "transport", ".", "requests", ".", "Request", "(", ")", "user_agent_option", "=", "(", "\"grpc.primary_user_agent\"", ",", "user_agent", ")", "options", "=", "(", "user_agent_option", ",", ")", "+", "extra_options", "return", "google", ".", "auth", ".", "transport", ".", "grpc", ".", "secure_authorized_channel", "(", "credentials", ",", "http_request", ",", "target", ",", "options", "=", "options", ")" ]
Makes a secure channel for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options used when creating the channel. :rtype: :class:`grpc._channel.Channel` :returns: gRPC secure channel with credentials attached.
[ "Makes", "a", "secure", "channel", "for", "an", "RPC", "service", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L540-L569
27,954
googleapis/google-cloud-python
core/google/cloud/_helpers.py
make_secure_stub
def make_secure_stub(credentials, user_agent, stub_class, host, extra_options=()): """Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options passed when creating the channel. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API. """ channel = make_secure_channel( credentials, user_agent, host, extra_options=extra_options ) return stub_class(channel)
python
def make_secure_stub(credentials, user_agent, stub_class, host, extra_options=()): """Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options passed when creating the channel. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API. """ channel = make_secure_channel( credentials, user_agent, host, extra_options=extra_options ) return stub_class(channel)
[ "def", "make_secure_stub", "(", "credentials", ",", "user_agent", ",", "stub_class", ",", "host", ",", "extra_options", "=", "(", ")", ")", ":", "channel", "=", "make_secure_channel", "(", "credentials", ",", "user_agent", ",", "host", ",", "extra_options", "=", "extra_options", ")", "return", "stub_class", "(", "channel", ")" ]
Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used with API requests. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. :type extra_options: tuple :param extra_options: (Optional) Extra gRPC options passed when creating the channel. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API.
[ "Makes", "a", "secure", "stub", "for", "an", "RPC", "service", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L572-L600
27,955
googleapis/google-cloud-python
core/google/cloud/_helpers.py
make_insecure_stub
def make_insecure_stub(stub_class, host, port=None): """Makes an insecure stub for an RPC service. Uses / depends on gRPC. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. May also include the port if ``port`` is unspecified. :type port: int :param port: (Optional) The port for the service. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API. """ if port is None: target = host else: # NOTE: This assumes port != http_client.HTTPS_PORT: target = "%s:%d" % (host, port) channel = grpc.insecure_channel(target) return stub_class(channel)
python
def make_insecure_stub(stub_class, host, port=None): """Makes an insecure stub for an RPC service. Uses / depends on gRPC. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. May also include the port if ``port`` is unspecified. :type port: int :param port: (Optional) The port for the service. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API. """ if port is None: target = host else: # NOTE: This assumes port != http_client.HTTPS_PORT: target = "%s:%d" % (host, port) channel = grpc.insecure_channel(target) return stub_class(channel)
[ "def", "make_insecure_stub", "(", "stub_class", ",", "host", ",", "port", "=", "None", ")", ":", "if", "port", "is", "None", ":", "target", "=", "host", "else", ":", "# NOTE: This assumes port != http_client.HTTPS_PORT:", "target", "=", "\"%s:%d\"", "%", "(", "host", ",", "port", ")", "channel", "=", "grpc", ".", "insecure_channel", "(", "target", ")", "return", "stub_class", "(", "channel", ")" ]
Makes an insecure stub for an RPC service. Uses / depends on gRPC. :type stub_class: type :param stub_class: A gRPC stub type for a given service. :type host: str :param host: The host for the service. May also include the port if ``port`` is unspecified. :type port: int :param port: (Optional) The port for the service. :rtype: object, instance of ``stub_class`` :returns: The stub object used to make gRPC requests to a given API.
[ "Makes", "an", "insecure", "stub", "for", "an", "RPC", "service", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/core/google/cloud/_helpers.py#L603-L627
27,956
googleapis/google-cloud-python
vision/google/cloud/vision_helpers/decorators.py
_create_single_feature_method
def _create_single_feature_method(feature): """Return a function that will detect a single feature. Args: feature (enum): A specific feature defined as a member of :class:`~enums.Feature.Type`. Returns: function: A helper function to detect just that feature. """ # Define the function properties. fx_name = feature.name.lower() if "detection" in fx_name: fx_doc = "Perform {0}.".format(fx_name.replace("_", " ")) else: fx_doc = "Return {desc} information.".format(desc=fx_name.replace("_", " ")) # Provide a complete docstring with argument and return value # information. fx_doc += """ Args: image (:class:`~.{module}.types.Image`): The image to analyze. max_results (int): Number of results to return, does not apply for TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS. retry (int): Number of retries to do before giving up. timeout (int): Number of seconds before timing out. kwargs (dict): Additional properties to be set on the :class:`~.{module}.types.AnnotateImageRequest`. Returns: :class:`~.{module}.types.AnnotateImageResponse`: The API response. """ # Get the actual feature value to send. feature_value = {"type": feature} # Define the function to be returned. def inner(self, image, max_results=None, retry=None, timeout=None, **kwargs): """Return a single feature annotation for the given image. Intended for use with functools.partial, to create the particular single-feature methods. """ copied_features = feature_value.copy() if max_results is not None: copied_features["max_results"] = max_results request = dict(image=image, features=[copied_features], **kwargs) response = self.annotate_image(request, retry=retry, timeout=timeout) return response # Set the appropriate function metadata. inner.__name__ = fx_name inner.__doc__ = fx_doc # Return the final function. return inner
python
def _create_single_feature_method(feature): """Return a function that will detect a single feature. Args: feature (enum): A specific feature defined as a member of :class:`~enums.Feature.Type`. Returns: function: A helper function to detect just that feature. """ # Define the function properties. fx_name = feature.name.lower() if "detection" in fx_name: fx_doc = "Perform {0}.".format(fx_name.replace("_", " ")) else: fx_doc = "Return {desc} information.".format(desc=fx_name.replace("_", " ")) # Provide a complete docstring with argument and return value # information. fx_doc += """ Args: image (:class:`~.{module}.types.Image`): The image to analyze. max_results (int): Number of results to return, does not apply for TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS. retry (int): Number of retries to do before giving up. timeout (int): Number of seconds before timing out. kwargs (dict): Additional properties to be set on the :class:`~.{module}.types.AnnotateImageRequest`. Returns: :class:`~.{module}.types.AnnotateImageResponse`: The API response. """ # Get the actual feature value to send. feature_value = {"type": feature} # Define the function to be returned. def inner(self, image, max_results=None, retry=None, timeout=None, **kwargs): """Return a single feature annotation for the given image. Intended for use with functools.partial, to create the particular single-feature methods. """ copied_features = feature_value.copy() if max_results is not None: copied_features["max_results"] = max_results request = dict(image=image, features=[copied_features], **kwargs) response = self.annotate_image(request, retry=retry, timeout=timeout) return response # Set the appropriate function metadata. inner.__name__ = fx_name inner.__doc__ = fx_doc # Return the final function. return inner
[ "def", "_create_single_feature_method", "(", "feature", ")", ":", "# Define the function properties.", "fx_name", "=", "feature", ".", "name", ".", "lower", "(", ")", "if", "\"detection\"", "in", "fx_name", ":", "fx_doc", "=", "\"Perform {0}.\"", ".", "format", "(", "fx_name", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", ")", "else", ":", "fx_doc", "=", "\"Return {desc} information.\"", ".", "format", "(", "desc", "=", "fx_name", ".", "replace", "(", "\"_\"", ",", "\" \"", ")", ")", "# Provide a complete docstring with argument and return value", "# information.", "fx_doc", "+=", "\"\"\"\n\n Args:\n image (:class:`~.{module}.types.Image`): The image to analyze.\n max_results (int):\n Number of results to return, does not apply for\n TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS.\n retry (int): Number of retries to do before giving up.\n timeout (int): Number of seconds before timing out.\n kwargs (dict): Additional properties to be set on the\n :class:`~.{module}.types.AnnotateImageRequest`.\n\n Returns:\n :class:`~.{module}.types.AnnotateImageResponse`: The API response.\n \"\"\"", "# Get the actual feature value to send.", "feature_value", "=", "{", "\"type\"", ":", "feature", "}", "# Define the function to be returned.", "def", "inner", "(", "self", ",", "image", ",", "max_results", "=", "None", ",", "retry", "=", "None", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Return a single feature annotation for the given image.\n\n Intended for use with functools.partial, to create the particular\n single-feature methods.\n \"\"\"", "copied_features", "=", "feature_value", ".", "copy", "(", ")", "if", "max_results", "is", "not", "None", ":", "copied_features", "[", "\"max_results\"", "]", "=", "max_results", "request", "=", "dict", "(", "image", "=", "image", ",", "features", "=", "[", "copied_features", "]", ",", "*", "*", "kwargs", ")", "response", "=", "self", ".", "annotate_image", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ")", "return", "response", "# Set the appropriate function metadata.", "inner", ".", "__name__", "=", "fx_name", "inner", ".", "__doc__", "=", "fx_doc", "# Return the final function.", "return", "inner" ]
Return a function that will detect a single feature. Args: feature (enum): A specific feature defined as a member of :class:`~enums.Feature.Type`. Returns: function: A helper function to detect just that feature.
[ "Return", "a", "function", "that", "will", "detect", "a", "single", "feature", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/vision/google/cloud/vision_helpers/decorators.py#L52-L109
27,957
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/scheduler.py
ThreadScheduler.schedule
def schedule(self, callback, *args, **kwargs): """Schedule the callback to be called asynchronously in a thread pool. Args: callback (Callable): The function to call. args: Positional arguments passed to the function. kwargs: Key-word arguments passed to the function. Returns: None """ self._executor.submit(callback, *args, **kwargs)
python
def schedule(self, callback, *args, **kwargs): """Schedule the callback to be called asynchronously in a thread pool. Args: callback (Callable): The function to call. args: Positional arguments passed to the function. kwargs: Key-word arguments passed to the function. Returns: None """ self._executor.submit(callback, *args, **kwargs)
[ "def", "schedule", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_executor", ".", "submit", "(", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Schedule the callback to be called asynchronously in a thread pool. Args: callback (Callable): The function to call. args: Positional arguments passed to the function. kwargs: Key-word arguments passed to the function. Returns: None
[ "Schedule", "the", "callback", "to", "be", "called", "asynchronously", "in", "a", "thread", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/scheduler.py#L99-L110
27,958
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/scheduler.py
ThreadScheduler.shutdown
def shutdown(self): """Shuts down the scheduler and immediately end all pending callbacks. """ # Drop all pending item from the executor. Without this, the executor # will block until all pending items are complete, which is # undesirable. try: while True: self._executor._work_queue.get(block=False) except queue.Empty: pass self._executor.shutdown()
python
def shutdown(self): """Shuts down the scheduler and immediately end all pending callbacks. """ # Drop all pending item from the executor. Without this, the executor # will block until all pending items are complete, which is # undesirable. try: while True: self._executor._work_queue.get(block=False) except queue.Empty: pass self._executor.shutdown()
[ "def", "shutdown", "(", "self", ")", ":", "# Drop all pending item from the executor. Without this, the executor", "# will block until all pending items are complete, which is", "# undesirable.", "try", ":", "while", "True", ":", "self", ".", "_executor", ".", "_work_queue", ".", "get", "(", "block", "=", "False", ")", "except", "queue", ".", "Empty", ":", "pass", "self", ".", "_executor", ".", "shutdown", "(", ")" ]
Shuts down the scheduler and immediately end all pending callbacks.
[ "Shuts", "down", "the", "scheduler", "and", "immediately", "end", "all", "pending", "callbacks", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/scheduler.py#L112-L123
27,959
googleapis/google-cloud-python
error_reporting/google/cloud/errorreporting_v1beta1/gapic/error_stats_service_client.py
ErrorStatsServiceClient.list_events
def list_events( self, project_name, group_id, service_filter=None, time_range=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists the specified events. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `group_id`: >>> group_id = '' >>> >>> # Iterate over all results >>> for element in client.list_events(project_name, group_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_events(project_name, group_id).pages: ... for element in page: ... # process element ... pass Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. group_id (str): [Required] The group for which events shall be returned. service_filter (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter]): [Optional] List only ErrorGroups which belong to a service context that matches the filter. Data for all service contexts is returned if this field is not specified. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter` time_range (Union[dict, ~google.cloud.errorreporting_v1beta1.types.QueryTimeRange]): [Optional] List only data for the given time range. If not set a default time range is used. The field time\_range\_begin in the response will specify the beginning of this time range. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.QueryTimeRange` page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.errorreporting_v1beta1.types.ErrorEvent` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_events" not in self._inner_api_calls: self._inner_api_calls[ "list_events" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_events, default_retry=self._method_configs["ListEvents"].retry, default_timeout=self._method_configs["ListEvents"].timeout, client_info=self._client_info, ) request = error_stats_service_pb2.ListEventsRequest( project_name=project_name, group_id=group_id, service_filter=service_filter, time_range=time_range, page_size=page_size, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_name", project_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_events"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="error_events", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
python
def list_events( self, project_name, group_id, service_filter=None, time_range=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists the specified events. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `group_id`: >>> group_id = '' >>> >>> # Iterate over all results >>> for element in client.list_events(project_name, group_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_events(project_name, group_id).pages: ... for element in page: ... # process element ... pass Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. group_id (str): [Required] The group for which events shall be returned. service_filter (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter]): [Optional] List only ErrorGroups which belong to a service context that matches the filter. Data for all service contexts is returned if this field is not specified. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter` time_range (Union[dict, ~google.cloud.errorreporting_v1beta1.types.QueryTimeRange]): [Optional] List only data for the given time range. If not set a default time range is used. The field time\_range\_begin in the response will specify the beginning of this time range. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.QueryTimeRange` page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.errorreporting_v1beta1.types.ErrorEvent` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_events" not in self._inner_api_calls: self._inner_api_calls[ "list_events" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_events, default_retry=self._method_configs["ListEvents"].retry, default_timeout=self._method_configs["ListEvents"].timeout, client_info=self._client_info, ) request = error_stats_service_pb2.ListEventsRequest( project_name=project_name, group_id=group_id, service_filter=service_filter, time_range=time_range, page_size=page_size, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_name", project_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_events"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="error_events", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
[ "def", "list_events", "(", "self", ",", "project_name", ",", "group_id", ",", "service_filter", "=", "None", ",", "time_range", "=", "None", ",", "page_size", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"list_events\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"list_events\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "list_events", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ListEvents\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ListEvents\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "error_stats_service_pb2", ".", "ListEventsRequest", "(", "project_name", "=", "project_name", ",", "group_id", "=", "group_id", ",", "service_filter", "=", "service_filter", ",", "time_range", "=", "time_range", ",", "page_size", "=", "page_size", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"project_name\"", ",", "project_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "iterator", "=", "google", ".", "api_core", ".", "page_iterator", ".", "GRPCIterator", "(", "client", "=", "None", ",", "method", "=", "functools", ".", "partial", "(", "self", ".", "_inner_api_calls", "[", "\"list_events\"", "]", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", ",", "request", "=", "request", ",", "items_field", "=", "\"error_events\"", ",", "request_token_field", "=", "\"page_token\"", ",", "response_token_field", "=", "\"next_page_token\"", ",", ")", "return", "iterator" ]
Lists the specified events. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `group_id`: >>> group_id = '' >>> >>> # Iterate over all results >>> for element in client.list_events(project_name, group_id): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_events(project_name, group_id).pages: ... for element in page: ... # process element ... pass Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. group_id (str): [Required] The group for which events shall be returned. service_filter (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter]): [Optional] List only ErrorGroups which belong to a service context that matches the filter. Data for all service contexts is returned if this field is not specified. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.ServiceContextFilter` time_range (Union[dict, ~google.cloud.errorreporting_v1beta1.types.QueryTimeRange]): [Optional] List only data for the given time range. If not set a default time range is used. The field time\_range\_begin in the response will specify the beginning of this time range. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.errorreporting_v1beta1.types.QueryTimeRange` page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.gax.PageIterator` instance. By default, this is an iterable of :class:`~google.cloud.errorreporting_v1beta1.types.ErrorEvent` instances. This object can also be configured to iterate over the pages of the response through the `options` parameter. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Lists", "the", "specified", "events", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/errorreporting_v1beta1/gapic/error_stats_service_client.py#L343-L470
27,960
googleapis/google-cloud-python
error_reporting/google/cloud/errorreporting_v1beta1/gapic/error_stats_service_client.py
ErrorStatsServiceClient.delete_events
def delete_events( self, project_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all error events of a given project. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> response = client.delete_events(project_name) Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_events" not in self._inner_api_calls: self._inner_api_calls[ "delete_events" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_events, default_retry=self._method_configs["DeleteEvents"].retry, default_timeout=self._method_configs["DeleteEvents"].timeout, client_info=self._client_info, ) request = error_stats_service_pb2.DeleteEventsRequest(project_name=project_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_name", project_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["delete_events"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def delete_events( self, project_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all error events of a given project. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> response = client.delete_events(project_name) Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_events" not in self._inner_api_calls: self._inner_api_calls[ "delete_events" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_events, default_retry=self._method_configs["DeleteEvents"].retry, default_timeout=self._method_configs["DeleteEvents"].timeout, client_info=self._client_info, ) request = error_stats_service_pb2.DeleteEventsRequest(project_name=project_name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("project_name", project_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["delete_events"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "delete_events", "(", "self", ",", "project_name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"delete_events\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"delete_events\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "delete_events", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"DeleteEvents\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"DeleteEvents\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "error_stats_service_pb2", ".", "DeleteEventsRequest", "(", "project_name", "=", "project_name", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"project_name\"", ",", "project_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"delete_events\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Deletes all error events of a given project. Example: >>> from google.cloud import errorreporting_v1beta1 >>> >>> client = errorreporting_v1beta1.ErrorStatsServiceClient() >>> >>> project_name = client.project_path('[PROJECT]') >>> >>> response = client.delete_events(project_name) Args: project_name (str): [Required] The resource name of the Google Cloud Platform project. Written as ``projects/`` plus the `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`__. Example: ``projects/my-project-123``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.errorreporting_v1beta1.types.DeleteEventsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Deletes", "all", "error", "events", "of", "a", "given", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/errorreporting_v1beta1/gapic/error_stats_service_client.py#L472-L542
27,961
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
_item_to_document_ref
def _item_to_document_ref(iterator, item): """Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource """ document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1] return iterator.collection.document(document_id)
python
def _item_to_document_ref(iterator, item): """Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource """ document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1] return iterator.collection.document(document_id)
[ "def", "_item_to_document_ref", "(", "iterator", ",", "item", ")", ":", "document_id", "=", "item", ".", "name", ".", "split", "(", "_helpers", ".", "DOCUMENT_PATH_DELIMITER", ")", "[", "-", "1", "]", "return", "iterator", ".", "collection", ".", "document", "(", "document_id", ")" ]
Convert Document resource to document ref. Args: iterator (google.api_core.page_iterator.GRPCIterator): iterator response item (dict): document resource
[ "Convert", "Document", "resource", "to", "document", "ref", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L468-L477
27,962
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.parent
def parent(self): """Document that owns the current collection. Returns: Optional[~.firestore_v1beta1.document.DocumentReference]: The parent document, if the current collection is not a top-level collection. """ if len(self._path) == 1: return None else: parent_path = self._path[:-1] return self._client.document(*parent_path)
python
def parent(self): """Document that owns the current collection. Returns: Optional[~.firestore_v1beta1.document.DocumentReference]: The parent document, if the current collection is not a top-level collection. """ if len(self._path) == 1: return None else: parent_path = self._path[:-1] return self._client.document(*parent_path)
[ "def", "parent", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_path", ")", "==", "1", ":", "return", "None", "else", ":", "parent_path", "=", "self", ".", "_path", "[", ":", "-", "1", "]", "return", "self", ".", "_client", ".", "document", "(", "*", "parent_path", ")" ]
Document that owns the current collection. Returns: Optional[~.firestore_v1beta1.document.DocumentReference]: The parent document, if the current collection is not a top-level collection.
[ "Document", "that", "owns", "the", "current", "collection", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L80-L92
27,963
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.document
def document(self, document_id=None): """Create a sub-document underneath the current collection. Args: document_id (Optional[str]): The document identifier within the current collection. If not provided, will default to a random 20 character string composed of digits, uppercase and lowercase and letters. Returns: ~.firestore_v1beta1.document.DocumentReference: The child document. """ if document_id is None: document_id = _auto_id() child_path = self._path + (document_id,) return self._client.document(*child_path)
python
def document(self, document_id=None): """Create a sub-document underneath the current collection. Args: document_id (Optional[str]): The document identifier within the current collection. If not provided, will default to a random 20 character string composed of digits, uppercase and lowercase and letters. Returns: ~.firestore_v1beta1.document.DocumentReference: The child document. """ if document_id is None: document_id = _auto_id() child_path = self._path + (document_id,) return self._client.document(*child_path)
[ "def", "document", "(", "self", ",", "document_id", "=", "None", ")", ":", "if", "document_id", "is", "None", ":", "document_id", "=", "_auto_id", "(", ")", "child_path", "=", "self", ".", "_path", "+", "(", "document_id", ",", ")", "return", "self", ".", "_client", ".", "document", "(", "*", "child_path", ")" ]
Create a sub-document underneath the current collection. Args: document_id (Optional[str]): The document identifier within the current collection. If not provided, will default to a random 20 character string composed of digits, uppercase and lowercase and letters. Returns: ~.firestore_v1beta1.document.DocumentReference: The child document.
[ "Create", "a", "sub", "-", "document", "underneath", "the", "current", "collection", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L94-L111
27,964
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference._parent_info
def _parent_info(self): """Get fully-qualified parent path and prefix for this collection. Returns: Tuple[str, str]: Pair of * the fully-qualified (with database and project) path to the parent of this collection (will either be the database path or a document path). * the prefix to a document in this collection. """ parent_doc = self.parent if parent_doc is None: parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join( (self._client._database_string, "documents") ) else: parent_path = parent_doc._document_path expected_prefix = _helpers.DOCUMENT_PATH_DELIMITER.join((parent_path, self.id)) return parent_path, expected_prefix
python
def _parent_info(self): """Get fully-qualified parent path and prefix for this collection. Returns: Tuple[str, str]: Pair of * the fully-qualified (with database and project) path to the parent of this collection (will either be the database path or a document path). * the prefix to a document in this collection. """ parent_doc = self.parent if parent_doc is None: parent_path = _helpers.DOCUMENT_PATH_DELIMITER.join( (self._client._database_string, "documents") ) else: parent_path = parent_doc._document_path expected_prefix = _helpers.DOCUMENT_PATH_DELIMITER.join((parent_path, self.id)) return parent_path, expected_prefix
[ "def", "_parent_info", "(", "self", ")", ":", "parent_doc", "=", "self", ".", "parent", "if", "parent_doc", "is", "None", ":", "parent_path", "=", "_helpers", ".", "DOCUMENT_PATH_DELIMITER", ".", "join", "(", "(", "self", ".", "_client", ".", "_database_string", ",", "\"documents\"", ")", ")", "else", ":", "parent_path", "=", "parent_doc", ".", "_document_path", "expected_prefix", "=", "_helpers", ".", "DOCUMENT_PATH_DELIMITER", ".", "join", "(", "(", "parent_path", ",", "self", ".", "id", ")", ")", "return", "parent_path", ",", "expected_prefix" ]
Get fully-qualified parent path and prefix for this collection. Returns: Tuple[str, str]: Pair of * the fully-qualified (with database and project) path to the parent of this collection (will either be the database path or a document path). * the prefix to a document in this collection.
[ "Get", "fully", "-", "qualified", "parent", "path", "and", "prefix", "for", "this", "collection", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L113-L133
27,965
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.add
def add(self, document_data, document_id=None): """Create a document in the Firestore database with the provided data. Args: document_data (dict): Property names and values to use for creating the document. document_id (Optional[str]): The document identifier within the current collection. If not provided, an ID will be automatically assigned by the server (the assigned ID will be a random 20 character string composed of digits, uppercase and lowercase letters). Returns: Tuple[google.protobuf.timestamp_pb2.Timestamp, \ ~.firestore_v1beta1.document.DocumentReference]: Pair of * The ``update_time`` when the document was created (or overwritten). * A document reference for the created document. Raises: ~google.cloud.exceptions.Conflict: If ``document_id`` is provided and the document already exists. """ if document_id is None: parent_path, expected_prefix = self._parent_info() document_pb = document_pb2.Document() created_document_pb = self._client._firestore_api.create_document( parent_path, collection_id=self.id, document_id=None, document=document_pb, mask=None, metadata=self._client._rpc_metadata, ) new_document_id = _helpers.get_doc_id(created_document_pb, expected_prefix) document_ref = self.document(new_document_id) set_result = document_ref.set(document_data) return set_result.update_time, document_ref else: document_ref = self.document(document_id) write_result = document_ref.create(document_data) return write_result.update_time, document_ref
python
def add(self, document_data, document_id=None): """Create a document in the Firestore database with the provided data. Args: document_data (dict): Property names and values to use for creating the document. document_id (Optional[str]): The document identifier within the current collection. If not provided, an ID will be automatically assigned by the server (the assigned ID will be a random 20 character string composed of digits, uppercase and lowercase letters). Returns: Tuple[google.protobuf.timestamp_pb2.Timestamp, \ ~.firestore_v1beta1.document.DocumentReference]: Pair of * The ``update_time`` when the document was created (or overwritten). * A document reference for the created document. Raises: ~google.cloud.exceptions.Conflict: If ``document_id`` is provided and the document already exists. """ if document_id is None: parent_path, expected_prefix = self._parent_info() document_pb = document_pb2.Document() created_document_pb = self._client._firestore_api.create_document( parent_path, collection_id=self.id, document_id=None, document=document_pb, mask=None, metadata=self._client._rpc_metadata, ) new_document_id = _helpers.get_doc_id(created_document_pb, expected_prefix) document_ref = self.document(new_document_id) set_result = document_ref.set(document_data) return set_result.update_time, document_ref else: document_ref = self.document(document_id) write_result = document_ref.create(document_data) return write_result.update_time, document_ref
[ "def", "add", "(", "self", ",", "document_data", ",", "document_id", "=", "None", ")", ":", "if", "document_id", "is", "None", ":", "parent_path", ",", "expected_prefix", "=", "self", ".", "_parent_info", "(", ")", "document_pb", "=", "document_pb2", ".", "Document", "(", ")", "created_document_pb", "=", "self", ".", "_client", ".", "_firestore_api", ".", "create_document", "(", "parent_path", ",", "collection_id", "=", "self", ".", "id", ",", "document_id", "=", "None", ",", "document", "=", "document_pb", ",", "mask", "=", "None", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "new_document_id", "=", "_helpers", ".", "get_doc_id", "(", "created_document_pb", ",", "expected_prefix", ")", "document_ref", "=", "self", ".", "document", "(", "new_document_id", ")", "set_result", "=", "document_ref", ".", "set", "(", "document_data", ")", "return", "set_result", ".", "update_time", ",", "document_ref", "else", ":", "document_ref", "=", "self", ".", "document", "(", "document_id", ")", "write_result", "=", "document_ref", ".", "create", "(", "document_data", ")", "return", "write_result", ".", "update_time", ",", "document_ref" ]
Create a document in the Firestore database with the provided data. Args: document_data (dict): Property names and values to use for creating the document. document_id (Optional[str]): The document identifier within the current collection. If not provided, an ID will be automatically assigned by the server (the assigned ID will be a random 20 character string composed of digits, uppercase and lowercase letters). Returns: Tuple[google.protobuf.timestamp_pb2.Timestamp, \ ~.firestore_v1beta1.document.DocumentReference]: Pair of * The ``update_time`` when the document was created (or overwritten). * A document reference for the created document. Raises: ~google.cloud.exceptions.Conflict: If ``document_id`` is provided and the document already exists.
[ "Create", "a", "document", "in", "the", "Firestore", "database", "with", "the", "provided", "data", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L135-L180
27,966
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.list_documents
def list_documents(self, page_size=None): """List all subdocuments of the current collection. Args: page_size (Optional[int]]): The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.DocumentReference]: iterator of subdocuments of the current collection. If the collection does not exist at the time of `snapshot`, the iterator will be empty """ parent, _ = self._parent_info() iterator = self._client._firestore_api.list_documents( parent, self.id, page_size=page_size, show_missing=True, metadata=self._client._rpc_metadata, ) iterator.collection = self iterator.item_to_value = _item_to_document_ref return iterator
python
def list_documents(self, page_size=None): """List all subdocuments of the current collection. Args: page_size (Optional[int]]): The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.DocumentReference]: iterator of subdocuments of the current collection. If the collection does not exist at the time of `snapshot`, the iterator will be empty """ parent, _ = self._parent_info() iterator = self._client._firestore_api.list_documents( parent, self.id, page_size=page_size, show_missing=True, metadata=self._client._rpc_metadata, ) iterator.collection = self iterator.item_to_value = _item_to_document_ref return iterator
[ "def", "list_documents", "(", "self", ",", "page_size", "=", "None", ")", ":", "parent", ",", "_", "=", "self", ".", "_parent_info", "(", ")", "iterator", "=", "self", ".", "_client", ".", "_firestore_api", ".", "list_documents", "(", "parent", ",", "self", ".", "id", ",", "page_size", "=", "page_size", ",", "show_missing", "=", "True", ",", "metadata", "=", "self", ".", "_client", ".", "_rpc_metadata", ",", ")", "iterator", ".", "collection", "=", "self", "iterator", ".", "item_to_value", "=", "_item_to_document_ref", "return", "iterator" ]
List all subdocuments of the current collection. Args: page_size (Optional[int]]): The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. Returns: Sequence[~.firestore_v1beta1.collection.DocumentReference]: iterator of subdocuments of the current collection. If the collection does not exist at the time of `snapshot`, the iterator will be empty
[ "List", "all", "subdocuments", "of", "the", "current", "collection", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L182-L207
27,967
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.select
def select(self, field_paths): """Create a "select" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.select` for more information on this method. Args: field_paths (Iterable[str, ...]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the query results. Returns: ~.firestore_v1beta1.query.Query: A "projected" query. """ query = query_mod.Query(self) return query.select(field_paths)
python
def select(self, field_paths): """Create a "select" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.select` for more information on this method. Args: field_paths (Iterable[str, ...]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the query results. Returns: ~.firestore_v1beta1.query.Query: A "projected" query. """ query = query_mod.Query(self) return query.select(field_paths)
[ "def", "select", "(", "self", ",", "field_paths", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "select", "(", "field_paths", ")" ]
Create a "select" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.select` for more information on this method. Args: field_paths (Iterable[str, ...]): An iterable of field paths (``.``-delimited list of field names) to use as a projection of document fields in the query results. Returns: ~.firestore_v1beta1.query.Query: A "projected" query.
[ "Create", "a", "select", "query", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L209-L225
27,968
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.where
def where(self, field_path, op_string, value): """Create a "where" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.where` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) for the field to filter on. op_string (str): A comparison operation in the form of a string. Acceptable values are ``<``, ``<=``, ``==``, ``>=`` and ``>``. value (Any): The value to compare the field against in the filter. If ``value`` is :data:`None` or a NaN, then ``==`` is the only allowed operation. Returns: ~.firestore_v1beta1.query.Query: A filtered query. """ query = query_mod.Query(self) return query.where(field_path, op_string, value)
python
def where(self, field_path, op_string, value): """Create a "where" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.where` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) for the field to filter on. op_string (str): A comparison operation in the form of a string. Acceptable values are ``<``, ``<=``, ``==``, ``>=`` and ``>``. value (Any): The value to compare the field against in the filter. If ``value`` is :data:`None` or a NaN, then ``==`` is the only allowed operation. Returns: ~.firestore_v1beta1.query.Query: A filtered query. """ query = query_mod.Query(self) return query.where(field_path, op_string, value)
[ "def", "where", "(", "self", ",", "field_path", ",", "op_string", ",", "value", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "where", "(", "field_path", ",", "op_string", ",", "value", ")" ]
Create a "where" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.where` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) for the field to filter on. op_string (str): A comparison operation in the form of a string. Acceptable values are ``<``, ``<=``, ``==``, ``>=`` and ``>``. value (Any): The value to compare the field against in the filter. If ``value`` is :data:`None` or a NaN, then ``==`` is the only allowed operation. Returns: ~.firestore_v1beta1.query.Query: A filtered query.
[ "Create", "a", "where", "query", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L227-L248
27,969
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.order_by
def order_by(self, field_path, **kwargs): """Create an "order by" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.order_by` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) on which to order the query results. kwargs (Dict[str, Any]): The keyword arguments to pass along to the query. The only supported keyword is ``direction``, see :meth:`~.firestore_v1beta1.query.Query.order_by` for more information. Returns: ~.firestore_v1beta1.query.Query: An "order by" query. """ query = query_mod.Query(self) return query.order_by(field_path, **kwargs)
python
def order_by(self, field_path, **kwargs): """Create an "order by" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.order_by` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) on which to order the query results. kwargs (Dict[str, Any]): The keyword arguments to pass along to the query. The only supported keyword is ``direction``, see :meth:`~.firestore_v1beta1.query.Query.order_by` for more information. Returns: ~.firestore_v1beta1.query.Query: An "order by" query. """ query = query_mod.Query(self) return query.order_by(field_path, **kwargs)
[ "def", "order_by", "(", "self", ",", "field_path", ",", "*", "*", "kwargs", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "order_by", "(", "field_path", ",", "*", "*", "kwargs", ")" ]
Create an "order by" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.order_by` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of field names) on which to order the query results. kwargs (Dict[str, Any]): The keyword arguments to pass along to the query. The only supported keyword is ``direction``, see :meth:`~.firestore_v1beta1.query.Query.order_by` for more information. Returns: ~.firestore_v1beta1.query.Query: An "order by" query.
[ "Create", "an", "order", "by", "query", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L250-L269
27,970
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.limit
def limit(self, count): """Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this method. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited query. """ query = query_mod.Query(self) return query.limit(count)
python
def limit(self, count): """Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this method. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited query. """ query = query_mod.Query(self) return query.limit(count)
[ "def", "limit", "(", "self", ",", "count", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "limit", "(", "count", ")" ]
Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this method. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited query.
[ "Create", "a", "limited", "query", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L271-L286
27,971
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.offset
def offset(self, num_to_skip): """Skip to an offset in a query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.offset` for more information on this method. Args: num_to_skip (int): The number of results to skip at the beginning of query results. (Must be non-negative.) Returns: ~.firestore_v1beta1.query.Query: An offset query. """ query = query_mod.Query(self) return query.offset(num_to_skip)
python
def offset(self, num_to_skip): """Skip to an offset in a query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.offset` for more information on this method. Args: num_to_skip (int): The number of results to skip at the beginning of query results. (Must be non-negative.) Returns: ~.firestore_v1beta1.query.Query: An offset query. """ query = query_mod.Query(self) return query.offset(num_to_skip)
[ "def", "offset", "(", "self", ",", "num_to_skip", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "offset", "(", "num_to_skip", ")" ]
Skip to an offset in a query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.offset` for more information on this method. Args: num_to_skip (int): The number of results to skip at the beginning of query results. (Must be non-negative.) Returns: ~.firestore_v1beta1.query.Query: An offset query.
[ "Skip", "to", "an", "offset", "in", "a", "query", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L288-L303
27,972
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.start_at
def start_at(self, document_fields): """Start query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.start_at(document_fields)
python
def start_at(self, document_fields): """Start query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.start_at(document_fields)
[ "def", "start_at", "(", "self", ",", "document_fields", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "start_at", "(", "document_fields", ")" ]
Start query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor.
[ "Start", "query", "at", "a", "cursor", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L305-L323
27,973
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.start_after
def start_after(self, document_fields): """Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.start_after(document_fields)
python
def start_after(self, document_fields): """Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.start_after(document_fields)
[ "def", "start_after", "(", "self", ",", "document_fields", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "start_after", "(", "document_fields", ")" ]
Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor.
[ "Start", "query", "after", "a", "cursor", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L325-L343
27,974
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.end_before
def end_before(self, document_fields): """End query before a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_before` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.end_before(document_fields)
python
def end_before(self, document_fields): """End query before a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_before` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.end_before(document_fields)
[ "def", "end_before", "(", "self", ",", "document_fields", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "end_before", "(", "document_fields", ")" ]
End query before a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_before` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor.
[ "End", "query", "before", "a", "cursor", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L345-L363
27,975
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.end_at
def end_at(self, document_fields): """End query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.end_at(document_fields)
python
def end_at(self, document_fields): """End query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor. """ query = query_mod.Query(self) return query.end_at(document_fields)
[ "def", "end_at", "(", "self", ",", "document_fields", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "end_at", "(", "document_fields", ")" ]
End query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor.
[ "End", "query", "at", "a", "cursor", "with", "this", "collection", "as", "parent", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L365-L383
27,976
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/collection.py
CollectionReference.stream
def stream(self, transaction=None): """Read the documents in this collection. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlying stream of responses will time out after the ``max_rpc_timeout_millis`` value set in the GAPIC client configuration for the ``RunQuery`` API. Snapshots not consumed from the iterator before that point will be lost. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that the query will run in. Yields: ~.firestore_v1beta1.document.DocumentSnapshot: The next document that fulfills the query. """ query = query_mod.Query(self) return query.stream(transaction=transaction)
python
def stream(self, transaction=None): """Read the documents in this collection. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlying stream of responses will time out after the ``max_rpc_timeout_millis`` value set in the GAPIC client configuration for the ``RunQuery`` API. Snapshots not consumed from the iterator before that point will be lost. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that the query will run in. Yields: ~.firestore_v1beta1.document.DocumentSnapshot: The next document that fulfills the query. """ query = query_mod.Query(self) return query.stream(transaction=transaction)
[ "def", "stream", "(", "self", ",", "transaction", "=", "None", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "stream", "(", "transaction", "=", "transaction", ")" ]
Read the documents in this collection. This sends a ``RunQuery`` RPC and then returns an iterator which consumes each document returned in the stream of ``RunQueryResponse`` messages. .. note:: The underlying stream of responses will time out after the ``max_rpc_timeout_millis`` value set in the GAPIC client configuration for the ``RunQuery`` API. Snapshots not consumed from the iterator before that point will be lost. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed). Args: transaction (Optional[~.firestore_v1beta1.transaction.\ Transaction]): An existing transaction that the query will run in. Yields: ~.firestore_v1beta1.document.DocumentSnapshot: The next document that fulfills the query.
[ "Read", "the", "documents", "in", "this", "collection", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L394-L422
27,977
googleapis/google-cloud-python
translate/google/cloud/translate_v2/client.py
Client.get_languages
def get_languages(self, target_language=None): """Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to localize returned language names. Defaults to the target language on the current client. :rtype: list :returns: List of dictionaries. Each dictionary contains a supported ISO 639-1 language code (using the dictionary key ``language``). If ``target_language`` is passed, each dictionary will also contain the name of each supported language (localized to the target language). """ query_params = {} if target_language is None: target_language = self.target_language if target_language is not None: query_params["target"] = target_language response = self._connection.api_request( method="GET", path="/languages", query_params=query_params ) return response.get("data", {}).get("languages", ())
python
def get_languages(self, target_language=None): """Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to localize returned language names. Defaults to the target language on the current client. :rtype: list :returns: List of dictionaries. Each dictionary contains a supported ISO 639-1 language code (using the dictionary key ``language``). If ``target_language`` is passed, each dictionary will also contain the name of each supported language (localized to the target language). """ query_params = {} if target_language is None: target_language = self.target_language if target_language is not None: query_params["target"] = target_language response = self._connection.api_request( method="GET", path="/languages", query_params=query_params ) return response.get("data", {}).get("languages", ())
[ "def", "get_languages", "(", "self", ",", "target_language", "=", "None", ")", ":", "query_params", "=", "{", "}", "if", "target_language", "is", "None", ":", "target_language", "=", "self", ".", "target_language", "if", "target_language", "is", "not", "None", ":", "query_params", "[", "\"target\"", "]", "=", "target_language", "response", "=", "self", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "\"/languages\"", ",", "query_params", "=", "query_params", ")", "return", "response", ".", "get", "(", "\"data\"", ",", "{", "}", ")", ".", "get", "(", "\"languages\"", ",", "(", ")", ")" ]
Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to localize returned language names. Defaults to the target language on the current client. :rtype: list :returns: List of dictionaries. Each dictionary contains a supported ISO 639-1 language code (using the dictionary key ``language``). If ``target_language`` is passed, each dictionary will also contain the name of each supported language (localized to the target language).
[ "Get", "list", "of", "supported", "languages", "for", "translation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v2/client.py#L67-L95
27,978
googleapis/google-cloud-python
translate/google/cloud/translate_v2/client.py
Client.detect_language
def detect_language(self, values): """Detect the language of a string or list of strings. See https://cloud.google.com/translate/docs/detecting-language :type values: str or list :param values: String or list of strings that will have language detected. :rtype: dict or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys * ``confidence``: The confidence in language detection, a float between 0 and 1. * ``input``: The corresponding input value. * ``language``: The detected language (as an ISO 639-1 language code). though the key ``confidence`` may not always be present. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`ValueError <exceptions.ValueError>` if the number of detections is not equal to the number of values. :class:`ValueError <exceptions.ValueError>` if a value produces a list of detections with 0 or multiple results in it. """ single_value = False if isinstance(values, six.string_types): single_value = True values = [values] data = {"q": values} response = self._connection.api_request( method="POST", path="/detect", data=data ) detections = response.get("data", {}).get("detections", ()) if len(values) != len(detections): raise ValueError( "Expected same number of values and detections", values, detections ) for index, value in enumerate(values): # Empirically, even clearly ambiguous text like "no" only returns # a single detection, so we replace the list of detections with # the single detection contained. if len(detections[index]) == 1: detections[index] = detections[index][0] else: message = ( "Expected a single detection per value, API " "returned %d" ) % (len(detections[index]),) raise ValueError(message, value, detections[index]) detections[index]["input"] = value # The ``isReliable`` field is deprecated. detections[index].pop("isReliable", None) if single_value: return detections[0] else: return detections
python
def detect_language(self, values): """Detect the language of a string or list of strings. See https://cloud.google.com/translate/docs/detecting-language :type values: str or list :param values: String or list of strings that will have language detected. :rtype: dict or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys * ``confidence``: The confidence in language detection, a float between 0 and 1. * ``input``: The corresponding input value. * ``language``: The detected language (as an ISO 639-1 language code). though the key ``confidence`` may not always be present. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`ValueError <exceptions.ValueError>` if the number of detections is not equal to the number of values. :class:`ValueError <exceptions.ValueError>` if a value produces a list of detections with 0 or multiple results in it. """ single_value = False if isinstance(values, six.string_types): single_value = True values = [values] data = {"q": values} response = self._connection.api_request( method="POST", path="/detect", data=data ) detections = response.get("data", {}).get("detections", ()) if len(values) != len(detections): raise ValueError( "Expected same number of values and detections", values, detections ) for index, value in enumerate(values): # Empirically, even clearly ambiguous text like "no" only returns # a single detection, so we replace the list of detections with # the single detection contained. if len(detections[index]) == 1: detections[index] = detections[index][0] else: message = ( "Expected a single detection per value, API " "returned %d" ) % (len(detections[index]),) raise ValueError(message, value, detections[index]) detections[index]["input"] = value # The ``isReliable`` field is deprecated. detections[index].pop("isReliable", None) if single_value: return detections[0] else: return detections
[ "def", "detect_language", "(", "self", ",", "values", ")", ":", "single_value", "=", "False", "if", "isinstance", "(", "values", ",", "six", ".", "string_types", ")", ":", "single_value", "=", "True", "values", "=", "[", "values", "]", "data", "=", "{", "\"q\"", ":", "values", "}", "response", "=", "self", ".", "_connection", ".", "api_request", "(", "method", "=", "\"POST\"", ",", "path", "=", "\"/detect\"", ",", "data", "=", "data", ")", "detections", "=", "response", ".", "get", "(", "\"data\"", ",", "{", "}", ")", ".", "get", "(", "\"detections\"", ",", "(", ")", ")", "if", "len", "(", "values", ")", "!=", "len", "(", "detections", ")", ":", "raise", "ValueError", "(", "\"Expected same number of values and detections\"", ",", "values", ",", "detections", ")", "for", "index", ",", "value", "in", "enumerate", "(", "values", ")", ":", "# Empirically, even clearly ambiguous text like \"no\" only returns", "# a single detection, so we replace the list of detections with", "# the single detection contained.", "if", "len", "(", "detections", "[", "index", "]", ")", "==", "1", ":", "detections", "[", "index", "]", "=", "detections", "[", "index", "]", "[", "0", "]", "else", ":", "message", "=", "(", "\"Expected a single detection per value, API \"", "\"returned %d\"", ")", "%", "(", "len", "(", "detections", "[", "index", "]", ")", ",", ")", "raise", "ValueError", "(", "message", ",", "value", ",", "detections", "[", "index", "]", ")", "detections", "[", "index", "]", "[", "\"input\"", "]", "=", "value", "# The ``isReliable`` field is deprecated.", "detections", "[", "index", "]", ".", "pop", "(", "\"isReliable\"", ",", "None", ")", "if", "single_value", ":", "return", "detections", "[", "0", "]", "else", ":", "return", "detections" ]
Detect the language of a string or list of strings. See https://cloud.google.com/translate/docs/detecting-language :type values: str or list :param values: String or list of strings that will have language detected. :rtype: dict or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys * ``confidence``: The confidence in language detection, a float between 0 and 1. * ``input``: The corresponding input value. * ``language``: The detected language (as an ISO 639-1 language code). though the key ``confidence`` may not always be present. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`ValueError <exceptions.ValueError>` if the number of detections is not equal to the number of values. :class:`ValueError <exceptions.ValueError>` if a value produces a list of detections with 0 or multiple results in it.
[ "Detect", "the", "language", "of", "a", "string", "or", "list", "of", "strings", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v2/client.py#L97-L163
27,979
googleapis/google-cloud-python
translate/google/cloud/translate_v2/client.py
Client.translate
def translate( self, values, target_language=None, format_=None, source_language=None, customization_ids=(), model=None, ): """Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text :type values: str or list :param values: String or list of strings to translate. :type target_language: str :param target_language: The language to translate results into. This is required by the API and defaults to the target language of the current instance. :type format_: str :param format_: (Optional) One of ``text`` or ``html``, to specify if the input text is plain text or HTML. :type source_language: str :param source_language: (Optional) The language of the text to be translated. :type customization_ids: str or list :param customization_ids: (Optional) ID or list of customization IDs for translation. Sets the ``cid`` parameter in the query. :type model: str :param model: (Optional) The model used to translate the text, such as ``'base'`` or ``'nmt'``. :rtype: str or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys (though not all will be present in all cases) * ``detectedSourceLanguage``: The detected language (as an ISO 639-1 language code) of the text. * ``translatedText``: The translation of the text into the target language. * ``input``: The corresponding input value. * ``model``: The model used to translate the text. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`~exceptions.ValueError` if the number of values and translations differ. """ single_value = False if isinstance(values, six.string_types): single_value = True values = [values] if target_language is None: target_language = self.target_language if isinstance(customization_ids, six.string_types): customization_ids = [customization_ids] data = { "target": target_language, "q": values, "cid": customization_ids, "format": format_, "source": source_language, "model": model, } response = self._connection.api_request(method="POST", path="", data=data) translations = response.get("data", {}).get("translations", ()) if len(values) != len(translations): raise ValueError( "Expected iterations to have same length", values, translations ) for value, translation in six.moves.zip(values, translations): translation["input"] = value if single_value: return translations[0] else: return translations
python
def translate( self, values, target_language=None, format_=None, source_language=None, customization_ids=(), model=None, ): """Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text :type values: str or list :param values: String or list of strings to translate. :type target_language: str :param target_language: The language to translate results into. This is required by the API and defaults to the target language of the current instance. :type format_: str :param format_: (Optional) One of ``text`` or ``html``, to specify if the input text is plain text or HTML. :type source_language: str :param source_language: (Optional) The language of the text to be translated. :type customization_ids: str or list :param customization_ids: (Optional) ID or list of customization IDs for translation. Sets the ``cid`` parameter in the query. :type model: str :param model: (Optional) The model used to translate the text, such as ``'base'`` or ``'nmt'``. :rtype: str or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys (though not all will be present in all cases) * ``detectedSourceLanguage``: The detected language (as an ISO 639-1 language code) of the text. * ``translatedText``: The translation of the text into the target language. * ``input``: The corresponding input value. * ``model``: The model used to translate the text. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`~exceptions.ValueError` if the number of values and translations differ. """ single_value = False if isinstance(values, six.string_types): single_value = True values = [values] if target_language is None: target_language = self.target_language if isinstance(customization_ids, six.string_types): customization_ids = [customization_ids] data = { "target": target_language, "q": values, "cid": customization_ids, "format": format_, "source": source_language, "model": model, } response = self._connection.api_request(method="POST", path="", data=data) translations = response.get("data", {}).get("translations", ()) if len(values) != len(translations): raise ValueError( "Expected iterations to have same length", values, translations ) for value, translation in six.moves.zip(values, translations): translation["input"] = value if single_value: return translations[0] else: return translations
[ "def", "translate", "(", "self", ",", "values", ",", "target_language", "=", "None", ",", "format_", "=", "None", ",", "source_language", "=", "None", ",", "customization_ids", "=", "(", ")", ",", "model", "=", "None", ",", ")", ":", "single_value", "=", "False", "if", "isinstance", "(", "values", ",", "six", ".", "string_types", ")", ":", "single_value", "=", "True", "values", "=", "[", "values", "]", "if", "target_language", "is", "None", ":", "target_language", "=", "self", ".", "target_language", "if", "isinstance", "(", "customization_ids", ",", "six", ".", "string_types", ")", ":", "customization_ids", "=", "[", "customization_ids", "]", "data", "=", "{", "\"target\"", ":", "target_language", ",", "\"q\"", ":", "values", ",", "\"cid\"", ":", "customization_ids", ",", "\"format\"", ":", "format_", ",", "\"source\"", ":", "source_language", ",", "\"model\"", ":", "model", ",", "}", "response", "=", "self", ".", "_connection", ".", "api_request", "(", "method", "=", "\"POST\"", ",", "path", "=", "\"\"", ",", "data", "=", "data", ")", "translations", "=", "response", ".", "get", "(", "\"data\"", ",", "{", "}", ")", ".", "get", "(", "\"translations\"", ",", "(", ")", ")", "if", "len", "(", "values", ")", "!=", "len", "(", "translations", ")", ":", "raise", "ValueError", "(", "\"Expected iterations to have same length\"", ",", "values", ",", "translations", ")", "for", "value", ",", "translation", "in", "six", ".", "moves", ".", "zip", "(", "values", ",", "translations", ")", ":", "translation", "[", "\"input\"", "]", "=", "value", "if", "single_value", ":", "return", "translations", "[", "0", "]", "else", ":", "return", "translations" ]
Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text :type values: str or list :param values: String or list of strings to translate. :type target_language: str :param target_language: The language to translate results into. This is required by the API and defaults to the target language of the current instance. :type format_: str :param format_: (Optional) One of ``text`` or ``html``, to specify if the input text is plain text or HTML. :type source_language: str :param source_language: (Optional) The language of the text to be translated. :type customization_ids: str or list :param customization_ids: (Optional) ID or list of customization IDs for translation. Sets the ``cid`` parameter in the query. :type model: str :param model: (Optional) The model used to translate the text, such as ``'base'`` or ``'nmt'``. :rtype: str or list :returns: A list of dictionaries for each queried value. Each dictionary typically contains three keys (though not all will be present in all cases) * ``detectedSourceLanguage``: The detected language (as an ISO 639-1 language code) of the text. * ``translatedText``: The translation of the text into the target language. * ``input``: The corresponding input value. * ``model``: The model used to translate the text. If only a single value is passed, then only a single dictionary will be returned. :raises: :class:`~exceptions.ValueError` if the number of values and translations differ.
[ "Translate", "a", "string", "or", "list", "of", "strings", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/translate/google/cloud/translate_v2/client.py#L165-L252
27,980
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
Leaser.add
def add(self, items): """Add messages to be managed by the leaser.""" for item in items: # Add the ack ID to the set of managed ack IDs, and increment # the size counter. if item.ack_id not in self._leased_messages: self._leased_messages[item.ack_id] = _LeasedMessage( added_time=time.time(), size=item.byte_size ) self._bytes += item.byte_size else: _LOGGER.debug("Message %s is already lease managed", item.ack_id)
python
def add(self, items): """Add messages to be managed by the leaser.""" for item in items: # Add the ack ID to the set of managed ack IDs, and increment # the size counter. if item.ack_id not in self._leased_messages: self._leased_messages[item.ack_id] = _LeasedMessage( added_time=time.time(), size=item.byte_size ) self._bytes += item.byte_size else: _LOGGER.debug("Message %s is already lease managed", item.ack_id)
[ "def", "add", "(", "self", ",", "items", ")", ":", "for", "item", "in", "items", ":", "# Add the ack ID to the set of managed ack IDs, and increment", "# the size counter.", "if", "item", ".", "ack_id", "not", "in", "self", ".", "_leased_messages", ":", "self", ".", "_leased_messages", "[", "item", ".", "ack_id", "]", "=", "_LeasedMessage", "(", "added_time", "=", "time", ".", "time", "(", ")", ",", "size", "=", "item", ".", "byte_size", ")", "self", ".", "_bytes", "+=", "item", ".", "byte_size", "else", ":", "_LOGGER", ".", "debug", "(", "\"Message %s is already lease managed\"", ",", "item", ".", "ack_id", ")" ]
Add messages to be managed by the leaser.
[ "Add", "messages", "to", "be", "managed", "by", "the", "leaser", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py#L65-L76
27,981
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
Leaser.remove
def remove(self, items): """Remove messages from lease management.""" # Remove the ack ID from lease management, and decrement the # byte counter. for item in items: if self._leased_messages.pop(item.ack_id, None) is not None: self._bytes -= item.byte_size else: _LOGGER.debug("Item %s was not managed.", item.ack_id) if self._bytes < 0: _LOGGER.debug("Bytes was unexpectedly negative: %d", self._bytes) self._bytes = 0
python
def remove(self, items): """Remove messages from lease management.""" # Remove the ack ID from lease management, and decrement the # byte counter. for item in items: if self._leased_messages.pop(item.ack_id, None) is not None: self._bytes -= item.byte_size else: _LOGGER.debug("Item %s was not managed.", item.ack_id) if self._bytes < 0: _LOGGER.debug("Bytes was unexpectedly negative: %d", self._bytes) self._bytes = 0
[ "def", "remove", "(", "self", ",", "items", ")", ":", "# Remove the ack ID from lease management, and decrement the", "# byte counter.", "for", "item", "in", "items", ":", "if", "self", ".", "_leased_messages", ".", "pop", "(", "item", ".", "ack_id", ",", "None", ")", "is", "not", "None", ":", "self", ".", "_bytes", "-=", "item", ".", "byte_size", "else", ":", "_LOGGER", ".", "debug", "(", "\"Item %s was not managed.\"", ",", "item", ".", "ack_id", ")", "if", "self", ".", "_bytes", "<", "0", ":", "_LOGGER", ".", "debug", "(", "\"Bytes was unexpectedly negative: %d\"", ",", "self", ".", "_bytes", ")", "self", ".", "_bytes", "=", "0" ]
Remove messages from lease management.
[ "Remove", "messages", "from", "lease", "management", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py#L78-L90
27,982
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
Leaser.maintain_leases
def maintain_leases(self): """Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats. """ while self._manager.is_active and not self._stop_event.is_set(): # Determine the appropriate duration for the lease. This is # based off of how long previous messages have taken to ack, with # a sensible default and within the ranges allowed by Pub/Sub. p99 = self._manager.ack_histogram.percentile(99) _LOGGER.debug("The current p99 value is %d seconds.", p99) # Make a copy of the leased messages. This is needed because it's # possible for another thread to modify the dictionary while # we're iterating over it. leased_messages = copy.copy(self._leased_messages) # Drop any leases that are well beyond max lease time. This # ensures that in the event of a badly behaving actor, we can # drop messages and allow Pub/Sub to resend them. cutoff = time.time() - self._manager.flow_control.max_lease_duration to_drop = [ requests.DropRequest(ack_id, item.size) for ack_id, item in six.iteritems(leased_messages) if item.added_time < cutoff ] if to_drop: _LOGGER.warning( "Dropping %s items because they were leased too long.", len(to_drop) ) self._manager.dispatcher.drop(to_drop) # Remove dropped items from our copy of the leased messages (they # have already been removed from the real one by # self._manager.drop(), which calls self.remove()). for item in to_drop: leased_messages.pop(item.ack_id) # Create a streaming pull request. # We do not actually call `modify_ack_deadline` over and over # because it is more efficient to make a single request. ack_ids = leased_messages.keys() if ack_ids: _LOGGER.debug("Renewing lease for %d ack IDs.", len(ack_ids)) # NOTE: This may not work as expected if ``consumer.active`` # has changed since we checked it. An implementation # without any sort of race condition would require a # way for ``send_request`` to fail when the consumer # is inactive. self._manager.dispatcher.modify_ack_deadline( [requests.ModAckRequest(ack_id, p99) for ack_id in ack_ids] ) # Now wait an appropriate period of time and do this again. # # We determine the appropriate period of time based on a random # period between 0 seconds and 90% of the lease. This use of # jitter (http://bit.ly/2s2ekL7) helps decrease contention in cases # where there are many clients. snooze = random.uniform(0.0, p99 * 0.9) _LOGGER.debug("Snoozing lease management for %f seconds.", snooze) self._stop_event.wait(timeout=snooze) _LOGGER.info("%s exiting.", _LEASE_WORKER_NAME)
python
def maintain_leases(self): """Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats. """ while self._manager.is_active and not self._stop_event.is_set(): # Determine the appropriate duration for the lease. This is # based off of how long previous messages have taken to ack, with # a sensible default and within the ranges allowed by Pub/Sub. p99 = self._manager.ack_histogram.percentile(99) _LOGGER.debug("The current p99 value is %d seconds.", p99) # Make a copy of the leased messages. This is needed because it's # possible for another thread to modify the dictionary while # we're iterating over it. leased_messages = copy.copy(self._leased_messages) # Drop any leases that are well beyond max lease time. This # ensures that in the event of a badly behaving actor, we can # drop messages and allow Pub/Sub to resend them. cutoff = time.time() - self._manager.flow_control.max_lease_duration to_drop = [ requests.DropRequest(ack_id, item.size) for ack_id, item in six.iteritems(leased_messages) if item.added_time < cutoff ] if to_drop: _LOGGER.warning( "Dropping %s items because they were leased too long.", len(to_drop) ) self._manager.dispatcher.drop(to_drop) # Remove dropped items from our copy of the leased messages (they # have already been removed from the real one by # self._manager.drop(), which calls self.remove()). for item in to_drop: leased_messages.pop(item.ack_id) # Create a streaming pull request. # We do not actually call `modify_ack_deadline` over and over # because it is more efficient to make a single request. ack_ids = leased_messages.keys() if ack_ids: _LOGGER.debug("Renewing lease for %d ack IDs.", len(ack_ids)) # NOTE: This may not work as expected if ``consumer.active`` # has changed since we checked it. An implementation # without any sort of race condition would require a # way for ``send_request`` to fail when the consumer # is inactive. self._manager.dispatcher.modify_ack_deadline( [requests.ModAckRequest(ack_id, p99) for ack_id in ack_ids] ) # Now wait an appropriate period of time and do this again. # # We determine the appropriate period of time based on a random # period between 0 seconds and 90% of the lease. This use of # jitter (http://bit.ly/2s2ekL7) helps decrease contention in cases # where there are many clients. snooze = random.uniform(0.0, p99 * 0.9) _LOGGER.debug("Snoozing lease management for %f seconds.", snooze) self._stop_event.wait(timeout=snooze) _LOGGER.info("%s exiting.", _LEASE_WORKER_NAME)
[ "def", "maintain_leases", "(", "self", ")", ":", "while", "self", ".", "_manager", ".", "is_active", "and", "not", "self", ".", "_stop_event", ".", "is_set", "(", ")", ":", "# Determine the appropriate duration for the lease. This is", "# based off of how long previous messages have taken to ack, with", "# a sensible default and within the ranges allowed by Pub/Sub.", "p99", "=", "self", ".", "_manager", ".", "ack_histogram", ".", "percentile", "(", "99", ")", "_LOGGER", ".", "debug", "(", "\"The current p99 value is %d seconds.\"", ",", "p99", ")", "# Make a copy of the leased messages. This is needed because it's", "# possible for another thread to modify the dictionary while", "# we're iterating over it.", "leased_messages", "=", "copy", ".", "copy", "(", "self", ".", "_leased_messages", ")", "# Drop any leases that are well beyond max lease time. This", "# ensures that in the event of a badly behaving actor, we can", "# drop messages and allow Pub/Sub to resend them.", "cutoff", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_manager", ".", "flow_control", ".", "max_lease_duration", "to_drop", "=", "[", "requests", ".", "DropRequest", "(", "ack_id", ",", "item", ".", "size", ")", "for", "ack_id", ",", "item", "in", "six", ".", "iteritems", "(", "leased_messages", ")", "if", "item", ".", "added_time", "<", "cutoff", "]", "if", "to_drop", ":", "_LOGGER", ".", "warning", "(", "\"Dropping %s items because they were leased too long.\"", ",", "len", "(", "to_drop", ")", ")", "self", ".", "_manager", ".", "dispatcher", ".", "drop", "(", "to_drop", ")", "# Remove dropped items from our copy of the leased messages (they", "# have already been removed from the real one by", "# self._manager.drop(), which calls self.remove()).", "for", "item", "in", "to_drop", ":", "leased_messages", ".", "pop", "(", "item", ".", "ack_id", ")", "# Create a streaming pull request.", "# We do not actually call `modify_ack_deadline` over and over", "# because it is more efficient to make a single request.", "ack_ids", "=", "leased_messages", ".", "keys", "(", ")", "if", "ack_ids", ":", "_LOGGER", ".", "debug", "(", "\"Renewing lease for %d ack IDs.\"", ",", "len", "(", "ack_ids", ")", ")", "# NOTE: This may not work as expected if ``consumer.active``", "# has changed since we checked it. An implementation", "# without any sort of race condition would require a", "# way for ``send_request`` to fail when the consumer", "# is inactive.", "self", ".", "_manager", ".", "dispatcher", ".", "modify_ack_deadline", "(", "[", "requests", ".", "ModAckRequest", "(", "ack_id", ",", "p99", ")", "for", "ack_id", "in", "ack_ids", "]", ")", "# Now wait an appropriate period of time and do this again.", "#", "# We determine the appropriate period of time based on a random", "# period between 0 seconds and 90% of the lease. This use of", "# jitter (http://bit.ly/2s2ekL7) helps decrease contention in cases", "# where there are many clients.", "snooze", "=", "random", ".", "uniform", "(", "0.0", ",", "p99", "*", "0.9", ")", "_LOGGER", ".", "debug", "(", "\"Snoozing lease management for %f seconds.\"", ",", "snooze", ")", "self", ".", "_stop_event", ".", "wait", "(", "timeout", "=", "snooze", ")", "_LOGGER", ".", "info", "(", "\"%s exiting.\"", ",", "_LEASE_WORKER_NAME", ")" ]
Maintain all of the leases being managed. This method modifies the ack deadline for all of the managed ack IDs, then waits for most of that time (but with jitter), and repeats.
[ "Maintain", "all", "of", "the", "leases", "being", "managed", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py#L92-L159
27,983
googleapis/google-cloud-python
error_reporting/google/cloud/error_reporting/_gapic.py
make_report_error_api
def make_report_error_api(client): """Create an instance of the gapic Logging API. :type client::class:`google.cloud.error_reporting.Client` :param client: Error Reporting client. :rtype: :class:_ErrorReportingGapicApi :returns: An Error Reporting API instance. """ gax_client = report_errors_service_client.ReportErrorsServiceClient( credentials=client._credentials, client_info=_CLIENT_INFO ) return _ErrorReportingGapicApi(gax_client, client.project)
python
def make_report_error_api(client): """Create an instance of the gapic Logging API. :type client::class:`google.cloud.error_reporting.Client` :param client: Error Reporting client. :rtype: :class:_ErrorReportingGapicApi :returns: An Error Reporting API instance. """ gax_client = report_errors_service_client.ReportErrorsServiceClient( credentials=client._credentials, client_info=_CLIENT_INFO ) return _ErrorReportingGapicApi(gax_client, client.project)
[ "def", "make_report_error_api", "(", "client", ")", ":", "gax_client", "=", "report_errors_service_client", ".", "ReportErrorsServiceClient", "(", "credentials", "=", "client", ".", "_credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "_ErrorReportingGapicApi", "(", "gax_client", ",", "client", ".", "project", ")" ]
Create an instance of the gapic Logging API. :type client::class:`google.cloud.error_reporting.Client` :param client: Error Reporting client. :rtype: :class:_ErrorReportingGapicApi :returns: An Error Reporting API instance.
[ "Create", "an", "instance", "of", "the", "gapic", "Logging", "API", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/_gapic.py#L27-L39
27,984
googleapis/google-cloud-python
error_reporting/google/cloud/error_reporting/_gapic.py
_ErrorReportingGapicApi.report_error_event
def report_error_event(self, error_report): """Uses the gapic client to report the error. :type error_report: dict :param error_report: payload of the error report formatted according to https://cloud.google.com/error-reporting/docs/formatting-error-messages This object should be built using Use :meth:~`google.cloud.error_reporting.client._build_error_report` """ project_name = self._gapic_api.project_path(self._project) error_report_payload = report_errors_service_pb2.ReportedErrorEvent() ParseDict(error_report, error_report_payload) self._gapic_api.report_error_event(project_name, error_report_payload)
python
def report_error_event(self, error_report): """Uses the gapic client to report the error. :type error_report: dict :param error_report: payload of the error report formatted according to https://cloud.google.com/error-reporting/docs/formatting-error-messages This object should be built using Use :meth:~`google.cloud.error_reporting.client._build_error_report` """ project_name = self._gapic_api.project_path(self._project) error_report_payload = report_errors_service_pb2.ReportedErrorEvent() ParseDict(error_report, error_report_payload) self._gapic_api.report_error_event(project_name, error_report_payload)
[ "def", "report_error_event", "(", "self", ",", "error_report", ")", ":", "project_name", "=", "self", ".", "_gapic_api", ".", "project_path", "(", "self", ".", "_project", ")", "error_report_payload", "=", "report_errors_service_pb2", ".", "ReportedErrorEvent", "(", ")", "ParseDict", "(", "error_report", ",", "error_report_payload", ")", "self", ".", "_gapic_api", ".", "report_error_event", "(", "project_name", ",", "error_report_payload", ")" ]
Uses the gapic client to report the error. :type error_report: dict :param error_report: payload of the error report formatted according to https://cloud.google.com/error-reporting/docs/formatting-error-messages This object should be built using Use :meth:~`google.cloud.error_reporting.client._build_error_report`
[ "Uses", "the", "gapic", "client", "to", "report", "the", "error", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/error_reporting/google/cloud/error_reporting/_gapic.py#L57-L71
27,985
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py
BigtableClient.table_path
def table_path(cls, project, instance, table): """Return a fully-qualified table string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/tables/{table}", project=project, instance=instance, table=table, )
python
def table_path(cls, project, instance, table): """Return a fully-qualified table string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/tables/{table}", project=project, instance=instance, table=table, )
[ "def", "table_path", "(", "cls", ",", "project", ",", "instance", ",", "table", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/tables/{table}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", "table", "=", "table", ",", ")" ]
Return a fully-qualified table string.
[ "Return", "a", "fully", "-", "qualified", "table", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py#L70-L77
27,986
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py
BigtableClient.read_rows
def read_rows( self, table_name, app_profile_id=None, rows=None, filter_=None, rows_limit=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to each. Depending on their size, rows and cells may be broken up across multiple responses, but atomicity of each row will still be preserved. See the ReadRowsResponse documentation for details. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> for element in client.read_rows(table_name): ... # process element ... pass Args: table_name (str): The unique name of the table from which to read. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. rows (Union[dict, ~google.cloud.bigtable_v2.types.RowSet]): The row keys and/or ranges to read. If not specified, reads from all rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowSet` filter_ (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to apply to the contents of the specified row(s). If unset, reads the entirety of each row. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` rows_limit (long): The read will terminate after committing to N rows' worth of results. The default (zero) is to return all results. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.ReadRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "read_rows" not in self._inner_api_calls: self._inner_api_calls[ "read_rows" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.read_rows, default_retry=self._method_configs["ReadRows"].retry, default_timeout=self._method_configs["ReadRows"].timeout, client_info=self._client_info, ) request = bigtable_pb2.ReadRowsRequest( table_name=table_name, app_profile_id=app_profile_id, rows=rows, filter=filter_, rows_limit=rows_limit, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["read_rows"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def read_rows( self, table_name, app_profile_id=None, rows=None, filter_=None, rows_limit=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to each. Depending on their size, rows and cells may be broken up across multiple responses, but atomicity of each row will still be preserved. See the ReadRowsResponse documentation for details. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> for element in client.read_rows(table_name): ... # process element ... pass Args: table_name (str): The unique name of the table from which to read. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. rows (Union[dict, ~google.cloud.bigtable_v2.types.RowSet]): The row keys and/or ranges to read. If not specified, reads from all rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowSet` filter_ (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to apply to the contents of the specified row(s). If unset, reads the entirety of each row. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` rows_limit (long): The read will terminate after committing to N rows' worth of results. The default (zero) is to return all results. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.ReadRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "read_rows" not in self._inner_api_calls: self._inner_api_calls[ "read_rows" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.read_rows, default_retry=self._method_configs["ReadRows"].retry, default_timeout=self._method_configs["ReadRows"].timeout, client_info=self._client_info, ) request = bigtable_pb2.ReadRowsRequest( table_name=table_name, app_profile_id=app_profile_id, rows=rows, filter=filter_, rows_limit=rows_limit, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["read_rows"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "read_rows", "(", "self", ",", "table_name", ",", "app_profile_id", "=", "None", ",", "rows", "=", "None", ",", "filter_", "=", "None", ",", "rows_limit", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"read_rows\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"read_rows\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "read_rows", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ReadRows\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ReadRows\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_pb2", ".", "ReadRowsRequest", "(", "table_name", "=", "table_name", ",", "app_profile_id", "=", "app_profile_id", ",", "rows", "=", "rows", ",", "filter", "=", "filter_", ",", "rows_limit", "=", "rows_limit", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"table_name\"", ",", "table_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"read_rows\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to each. Depending on their size, rows and cells may be broken up across multiple responses, but atomicity of each row will still be preserved. See the ReadRowsResponse documentation for details. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> for element in client.read_rows(table_name): ... # process element ... pass Args: table_name (str): The unique name of the table from which to read. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. rows (Union[dict, ~google.cloud.bigtable_v2.types.RowSet]): The row keys and/or ranges to read. If not specified, reads from all rows. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowSet` filter_ (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to apply to the contents of the specified row(s). If unset, reads the entirety of each row. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` rows_limit (long): The read will terminate after committing to N rows' worth of results. The default (zero) is to return all results. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.ReadRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Streams", "back", "the", "contents", "of", "all", "requested", "rows", "in", "key", "order", "optionally", "applying", "the", "same", "Reader", "filter", "to", "each", ".", "Depending", "on", "their", "size", "rows", "and", "cells", "may", "be", "broken", "up", "across", "multiple", "responses", "but", "atomicity", "of", "each", "row", "will", "still", "be", "preserved", ".", "See", "the", "ReadRowsResponse", "documentation", "for", "details", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py#L178-L275
27,987
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py
BigtableClient.mutate_rows
def mutate_rows( self, table_name, entries, app_profile_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire batch is not executed atomically. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> for element in client.mutate_rows(table_name, entries): ... # process element ... pass Args: table_name (str): The unique name of the table to which the mutations should be applied. entries (list[Union[dict, ~google.cloud.bigtable_v2.types.Entry]]): The row keys and corresponding mutations to be applied in bulk. Each entry is applied as an atomic mutation, but the entries may be applied in arbitrary order (even between entries for the same row). At least one entry must be specified, and in total the entries can contain at most 100000 mutations. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Entry` app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.MutateRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "mutate_rows" not in self._inner_api_calls: self._inner_api_calls[ "mutate_rows" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.mutate_rows, default_retry=self._method_configs["MutateRows"].retry, default_timeout=self._method_configs["MutateRows"].timeout, client_info=self._client_info, ) request = bigtable_pb2.MutateRowsRequest( table_name=table_name, entries=entries, app_profile_id=app_profile_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["mutate_rows"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def mutate_rows( self, table_name, entries, app_profile_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire batch is not executed atomically. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> for element in client.mutate_rows(table_name, entries): ... # process element ... pass Args: table_name (str): The unique name of the table to which the mutations should be applied. entries (list[Union[dict, ~google.cloud.bigtable_v2.types.Entry]]): The row keys and corresponding mutations to be applied in bulk. Each entry is applied as an atomic mutation, but the entries may be applied in arbitrary order (even between entries for the same row). At least one entry must be specified, and in total the entries can contain at most 100000 mutations. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Entry` app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.MutateRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "mutate_rows" not in self._inner_api_calls: self._inner_api_calls[ "mutate_rows" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.mutate_rows, default_retry=self._method_configs["MutateRows"].retry, default_timeout=self._method_configs["MutateRows"].timeout, client_info=self._client_info, ) request = bigtable_pb2.MutateRowsRequest( table_name=table_name, entries=entries, app_profile_id=app_profile_id ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["mutate_rows"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "mutate_rows", "(", "self", ",", "table_name", ",", "entries", ",", "app_profile_id", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"mutate_rows\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"mutate_rows\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "mutate_rows", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"MutateRows\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"MutateRows\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_pb2", ".", "MutateRowsRequest", "(", "table_name", "=", "table_name", ",", "entries", "=", "entries", ",", "app_profile_id", "=", "app_profile_id", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"table_name\"", ",", "table_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"mutate_rows\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Mutates multiple rows in a batch. Each individual row is mutated atomically as in MutateRow, but the entire batch is not executed atomically. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `entries`: >>> entries = [] >>> >>> for element in client.mutate_rows(table_name, entries): ... # process element ... pass Args: table_name (str): The unique name of the table to which the mutations should be applied. entries (list[Union[dict, ~google.cloud.bigtable_v2.types.Entry]]): The row keys and corresponding mutations to be applied in bulk. Each entry is applied as an atomic mutation, but the entries may be applied in arbitrary order (even between entries for the same row). At least one entry must be specified, and in total the entries can contain at most 100000 mutations. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Entry` app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: Iterable[~google.cloud.bigtable_v2.types.MutateRowsResponse]. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Mutates", "multiple", "rows", "in", "a", "batch", ".", "Each", "individual", "row", "is", "mutated", "atomically", "as", "in", "MutateRow", "but", "the", "entire", "batch", "is", "not", "executed", "atomically", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py#L452-L540
27,988
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py
BigtableClient.check_and_mutate_row
def check_and_mutate_row( self, table_name, row_key, app_profile_id=None, predicate_filter=None, true_mutations=None, false_mutations=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Mutates a row atomically based on the output of a predicate Reader filter. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `row_key`: >>> row_key = b'' >>> >>> response = client.check_and_mutate_row(table_name, row_key) Args: table_name (str): The unique name of the table to which the conditional mutation should be applied. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. row_key (bytes): The key of the row to which the conditional mutation should be applied. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. predicate_filter (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to be applied to the contents of the specified row. Depending on whether or not any results are yielded, either ``true_mutations`` or ``false_mutations`` will be executed. If unset, checks that the row contains any values at all. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` true_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` yields at least one cell when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``false_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` false_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` does not yield any cells when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``true_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigtable_v2.types.CheckAndMutateRowResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "check_and_mutate_row" not in self._inner_api_calls: self._inner_api_calls[ "check_and_mutate_row" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.check_and_mutate_row, default_retry=self._method_configs["CheckAndMutateRow"].retry, default_timeout=self._method_configs["CheckAndMutateRow"].timeout, client_info=self._client_info, ) request = bigtable_pb2.CheckAndMutateRowRequest( table_name=table_name, row_key=row_key, app_profile_id=app_profile_id, predicate_filter=predicate_filter, true_mutations=true_mutations, false_mutations=false_mutations, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["check_and_mutate_row"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def check_and_mutate_row( self, table_name, row_key, app_profile_id=None, predicate_filter=None, true_mutations=None, false_mutations=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Mutates a row atomically based on the output of a predicate Reader filter. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `row_key`: >>> row_key = b'' >>> >>> response = client.check_and_mutate_row(table_name, row_key) Args: table_name (str): The unique name of the table to which the conditional mutation should be applied. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. row_key (bytes): The key of the row to which the conditional mutation should be applied. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. predicate_filter (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to be applied to the contents of the specified row. Depending on whether or not any results are yielded, either ``true_mutations`` or ``false_mutations`` will be executed. If unset, checks that the row contains any values at all. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` true_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` yields at least one cell when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``false_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` false_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` does not yield any cells when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``true_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigtable_v2.types.CheckAndMutateRowResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "check_and_mutate_row" not in self._inner_api_calls: self._inner_api_calls[ "check_and_mutate_row" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.check_and_mutate_row, default_retry=self._method_configs["CheckAndMutateRow"].retry, default_timeout=self._method_configs["CheckAndMutateRow"].timeout, client_info=self._client_info, ) request = bigtable_pb2.CheckAndMutateRowRequest( table_name=table_name, row_key=row_key, app_profile_id=app_profile_id, predicate_filter=predicate_filter, true_mutations=true_mutations, false_mutations=false_mutations, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("table_name", table_name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["check_and_mutate_row"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "check_and_mutate_row", "(", "self", ",", "table_name", ",", "row_key", ",", "app_profile_id", "=", "None", ",", "predicate_filter", "=", "None", ",", "true_mutations", "=", "None", ",", "false_mutations", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", "=", "None", ",", ")", ":", "# Wrap the transport method to add retry and timeout logic.", "if", "\"check_and_mutate_row\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"check_and_mutate_row\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "check_and_mutate_row", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CheckAndMutateRow\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CheckAndMutateRow\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_pb2", ".", "CheckAndMutateRowRequest", "(", "table_name", "=", "table_name", ",", "row_key", "=", "row_key", ",", "app_profile_id", "=", "app_profile_id", ",", "predicate_filter", "=", "predicate_filter", ",", "true_mutations", "=", "true_mutations", ",", "false_mutations", "=", "false_mutations", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"table_name\"", ",", "table_name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "return", "self", ".", "_inner_api_calls", "[", "\"check_and_mutate_row\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Mutates a row atomically based on the output of a predicate Reader filter. Example: >>> from google.cloud import bigtable_v2 >>> >>> client = bigtable_v2.BigtableClient() >>> >>> table_name = client.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]') >>> >>> # TODO: Initialize `row_key`: >>> row_key = b'' >>> >>> response = client.check_and_mutate_row(table_name, row_key) Args: table_name (str): The unique name of the table to which the conditional mutation should be applied. Values are of the form ``projects/<project>/instances/<instance>/tables/<table>``. row_key (bytes): The key of the row to which the conditional mutation should be applied. app_profile_id (str): This value specifies routing for replication. If not specified, the "default" application profile will be used. predicate_filter (Union[dict, ~google.cloud.bigtable_v2.types.RowFilter]): The filter to be applied to the contents of the specified row. Depending on whether or not any results are yielded, either ``true_mutations`` or ``false_mutations`` will be executed. If unset, checks that the row contains any values at all. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.RowFilter` true_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` yields at least one cell when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``false_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` false_mutations (list[Union[dict, ~google.cloud.bigtable_v2.types.Mutation]]): Changes to be atomically applied to the specified row if ``predicate_filter`` does not yield any cells when applied to ``row_key``. Entries are applied in order, meaning that earlier mutations can be masked by later ones. Must contain at least one entry if ``true_mutations`` is empty, and at most 100000. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_v2.types.Mutation` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigtable_v2.types.CheckAndMutateRowResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "Mutates", "a", "row", "atomically", "based", "on", "the", "output", "of", "a", "predicate", "Reader", "filter", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_v2/gapic/bigtable_client.py#L542-L652
27,989
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.name
def name(self): """Instance name used in requests. .. note:: This property will not change if ``instance_id`` does not, but the return value is not cached. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_instance_name] :end-before: [END bigtable_instance_name] The instance name is of the form ``"projects/{project}/instances/{instance_id}"`` :rtype: str :returns: Return a fully-qualified instance string. """ return self._client.instance_admin_client.instance_path( project=self._client.project, instance=self.instance_id )
python
def name(self): """Instance name used in requests. .. note:: This property will not change if ``instance_id`` does not, but the return value is not cached. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_instance_name] :end-before: [END bigtable_instance_name] The instance name is of the form ``"projects/{project}/instances/{instance_id}"`` :rtype: str :returns: Return a fully-qualified instance string. """ return self._client.instance_admin_client.instance_path( project=self._client.project, instance=self.instance_id )
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_client", ".", "instance_admin_client", ".", "instance_path", "(", "project", "=", "self", ".", "_client", ".", "project", ",", "instance", "=", "self", ".", "instance_id", ")" ]
Instance name used in requests. .. note:: This property will not change if ``instance_id`` does not, but the return value is not cached. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_instance_name] :end-before: [END bigtable_instance_name] The instance name is of the form ``"projects/{project}/instances/{instance_id}"`` :rtype: str :returns: Return a fully-qualified instance string.
[ "Instance", "name", "used", "in", "requests", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L170-L192
27,990
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.exists
def exists(self): """Check whether the instance already exists. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_check_instance_exists] :end-before: [END bigtable_check_instance_exists] :rtype: bool :returns: True if the table exists, else False. """ try: self._client.instance_admin_client.get_instance(name=self.name) return True # NOTE: There could be other exceptions that are returned to the user. except NotFound: return False
python
def exists(self): """Check whether the instance already exists. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_check_instance_exists] :end-before: [END bigtable_check_instance_exists] :rtype: bool :returns: True if the table exists, else False. """ try: self._client.instance_admin_client.get_instance(name=self.name) return True # NOTE: There could be other exceptions that are returned to the user. except NotFound: return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "_client", ".", "instance_admin_client", ".", "get_instance", "(", "name", "=", "self", ".", "name", ")", "return", "True", "# NOTE: There could be other exceptions that are returned to the user.", "except", "NotFound", ":", "return", "False" ]
Check whether the instance already exists. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_check_instance_exists] :end-before: [END bigtable_check_instance_exists] :rtype: bool :returns: True if the table exists, else False.
[ "Check", "whether", "the", "instance", "already", "exists", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L327-L344
27,991
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.get_iam_policy
def get_iam_policy(self): """Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_get_iam_policy] :end-before: [END bigtable_get_iam_policy] :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance """ instance_admin_client = self._client.instance_admin_client resp = instance_admin_client.get_iam_policy(resource=self.name) return Policy.from_pb(resp)
python
def get_iam_policy(self): """Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_get_iam_policy] :end-before: [END bigtable_get_iam_policy] :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance """ instance_admin_client = self._client.instance_admin_client resp = instance_admin_client.get_iam_policy(resource=self.name) return Policy.from_pb(resp)
[ "def", "get_iam_policy", "(", "self", ")", ":", "instance_admin_client", "=", "self", ".", "_client", ".", "instance_admin_client", "resp", "=", "instance_admin_client", ".", "get_iam_policy", "(", "resource", "=", "self", ".", "name", ")", "return", "Policy", ".", "from_pb", "(", "resp", ")" ]
Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_get_iam_policy] :end-before: [END bigtable_get_iam_policy] :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance
[ "Gets", "the", "access", "control", "policy", "for", "an", "instance", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L437-L451
27,992
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.set_iam_policy
def set_iam_policy(self, policy): """Sets the access control policy on an instance resource. Replaces any existing policy. For more information about policy, please see documentation of class `google.cloud.bigtable.policy.Policy` For example: .. literalinclude:: snippets.py :start-after: [START bigtable_set_iam_policy] :end-before: [END bigtable_set_iam_policy] :type policy: :class:`google.cloud.bigtable.policy.Policy` :param policy: A new IAM policy to replace the current IAM policy of this instance :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance. """ instance_admin_client = self._client.instance_admin_client resp = instance_admin_client.set_iam_policy( resource=self.name, policy=policy.to_pb() ) return Policy.from_pb(resp)
python
def set_iam_policy(self, policy): """Sets the access control policy on an instance resource. Replaces any existing policy. For more information about policy, please see documentation of class `google.cloud.bigtable.policy.Policy` For example: .. literalinclude:: snippets.py :start-after: [START bigtable_set_iam_policy] :end-before: [END bigtable_set_iam_policy] :type policy: :class:`google.cloud.bigtable.policy.Policy` :param policy: A new IAM policy to replace the current IAM policy of this instance :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance. """ instance_admin_client = self._client.instance_admin_client resp = instance_admin_client.set_iam_policy( resource=self.name, policy=policy.to_pb() ) return Policy.from_pb(resp)
[ "def", "set_iam_policy", "(", "self", ",", "policy", ")", ":", "instance_admin_client", "=", "self", ".", "_client", ".", "instance_admin_client", "resp", "=", "instance_admin_client", ".", "set_iam_policy", "(", "resource", "=", "self", ".", "name", ",", "policy", "=", "policy", ".", "to_pb", "(", ")", ")", "return", "Policy", ".", "from_pb", "(", "resp", ")" ]
Sets the access control policy on an instance resource. Replaces any existing policy. For more information about policy, please see documentation of class `google.cloud.bigtable.policy.Policy` For example: .. literalinclude:: snippets.py :start-after: [START bigtable_set_iam_policy] :end-before: [END bigtable_set_iam_policy] :type policy: :class:`google.cloud.bigtable.policy.Policy` :param policy: A new IAM policy to replace the current IAM policy of this instance :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The current IAM policy of this instance.
[ "Sets", "the", "access", "control", "policy", "on", "an", "instance", "resource", ".", "Replaces", "any", "existing", "policy", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L453-L477
27,993
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.cluster
def cluster( self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None ): """Factory to create a cluster associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_create_cluster] :type cluster_id: str :param cluster_id: The ID of the cluster. :type instance: :class:`~google.cloud.bigtable.instance.Instance` :param instance: The instance where the cluster resides. :type location_id: str :param location_id: (Creation Only) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. For list of supported locations refer to https://cloud.google.com/bigtable/docs/locations :type serve_nodes: int :param serve_nodes: (Optional) The number of nodes in the cluster. :type default_storage_type: int :param default_storage_type: (Optional) The type of storage Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.StorageType.SSD`. :data:`google.cloud.bigtable.enums.StorageType.SHD`, Defaults to :data:`google.cloud.bigtable.enums.StorageType.UNSPECIFIED`. :rtype: :class:`~google.cloud.bigtable.instance.Cluster` :returns: a cluster owned by this instance. """ return Cluster( cluster_id, self, location_id=location_id, serve_nodes=serve_nodes, default_storage_type=default_storage_type, )
python
def cluster( self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None ): """Factory to create a cluster associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_create_cluster] :type cluster_id: str :param cluster_id: The ID of the cluster. :type instance: :class:`~google.cloud.bigtable.instance.Instance` :param instance: The instance where the cluster resides. :type location_id: str :param location_id: (Creation Only) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. For list of supported locations refer to https://cloud.google.com/bigtable/docs/locations :type serve_nodes: int :param serve_nodes: (Optional) The number of nodes in the cluster. :type default_storage_type: int :param default_storage_type: (Optional) The type of storage Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.StorageType.SSD`. :data:`google.cloud.bigtable.enums.StorageType.SHD`, Defaults to :data:`google.cloud.bigtable.enums.StorageType.UNSPECIFIED`. :rtype: :class:`~google.cloud.bigtable.instance.Cluster` :returns: a cluster owned by this instance. """ return Cluster( cluster_id, self, location_id=location_id, serve_nodes=serve_nodes, default_storage_type=default_storage_type, )
[ "def", "cluster", "(", "self", ",", "cluster_id", ",", "location_id", "=", "None", ",", "serve_nodes", "=", "None", ",", "default_storage_type", "=", "None", ")", ":", "return", "Cluster", "(", "cluster_id", ",", "self", ",", "location_id", "=", "location_id", ",", "serve_nodes", "=", "serve_nodes", ",", "default_storage_type", "=", "default_storage_type", ",", ")" ]
Factory to create a cluster associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_create_cluster] :type cluster_id: str :param cluster_id: The ID of the cluster. :type instance: :class:`~google.cloud.bigtable.instance.Instance` :param instance: The instance where the cluster resides. :type location_id: str :param location_id: (Creation Only) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. For list of supported locations refer to https://cloud.google.com/bigtable/docs/locations :type serve_nodes: int :param serve_nodes: (Optional) The number of nodes in the cluster. :type default_storage_type: int :param default_storage_type: (Optional) The type of storage Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.StorageType.SSD`. :data:`google.cloud.bigtable.enums.StorageType.SHD`, Defaults to :data:`google.cloud.bigtable.enums.StorageType.UNSPECIFIED`. :rtype: :class:`~google.cloud.bigtable.instance.Cluster` :returns: a cluster owned by this instance.
[ "Factory", "to", "create", "a", "cluster", "associated", "with", "this", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L507-L553
27,994
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.list_clusters
def list_clusters(self): """List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_instance] :end-before: [END bigtable_list_clusters_on_instance] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of locations which could not be resolved. """ resp = self._client.instance_admin_client.list_clusters(self.name) clusters = [Cluster.from_pb(cluster, self) for cluster in resp.clusters] return clusters, resp.failed_locations
python
def list_clusters(self): """List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_instance] :end-before: [END bigtable_list_clusters_on_instance] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of locations which could not be resolved. """ resp = self._client.instance_admin_client.list_clusters(self.name) clusters = [Cluster.from_pb(cluster, self) for cluster in resp.clusters] return clusters, resp.failed_locations
[ "def", "list_clusters", "(", "self", ")", ":", "resp", "=", "self", ".", "_client", ".", "instance_admin_client", ".", "list_clusters", "(", "self", ".", "name", ")", "clusters", "=", "[", "Cluster", ".", "from_pb", "(", "cluster", ",", "self", ")", "for", "cluster", "in", "resp", ".", "clusters", "]", "return", "clusters", ",", "resp", ".", "failed_locations" ]
List the clusters in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_clusters_on_instance] :end-before: [END bigtable_list_clusters_on_instance] :rtype: tuple :returns: (clusters, failed_locations), where 'clusters' is list of :class:`google.cloud.bigtable.instance.Cluster`, and 'failed_locations' is a list of locations which could not be resolved.
[ "List", "the", "clusters", "in", "this", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L555-L573
27,995
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.table
def table(self, table_id, mutation_timeout=None, app_profile_id=None): """Factory to create a table associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_table] :end-before: [END bigtable_create_table] :type table_id: str :param table_id: The ID of the table. :type app_profile_id: str :param app_profile_id: (Optional) The unique name of the AppProfile. :rtype: :class:`Table <google.cloud.bigtable.table.Table>` :returns: The table owned by this instance. """ return Table( table_id, self, app_profile_id=app_profile_id, mutation_timeout=mutation_timeout, )
python
def table(self, table_id, mutation_timeout=None, app_profile_id=None): """Factory to create a table associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_table] :end-before: [END bigtable_create_table] :type table_id: str :param table_id: The ID of the table. :type app_profile_id: str :param app_profile_id: (Optional) The unique name of the AppProfile. :rtype: :class:`Table <google.cloud.bigtable.table.Table>` :returns: The table owned by this instance. """ return Table( table_id, self, app_profile_id=app_profile_id, mutation_timeout=mutation_timeout, )
[ "def", "table", "(", "self", ",", "table_id", ",", "mutation_timeout", "=", "None", ",", "app_profile_id", "=", "None", ")", ":", "return", "Table", "(", "table_id", ",", "self", ",", "app_profile_id", "=", "app_profile_id", ",", "mutation_timeout", "=", "mutation_timeout", ",", ")" ]
Factory to create a table associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_table] :end-before: [END bigtable_create_table] :type table_id: str :param table_id: The ID of the table. :type app_profile_id: str :param app_profile_id: (Optional) The unique name of the AppProfile. :rtype: :class:`Table <google.cloud.bigtable.table.Table>` :returns: The table owned by this instance.
[ "Factory", "to", "create", "a", "table", "associated", "with", "this", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L575-L598
27,996
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.list_tables
def list_tables(self): """List the tables in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_tables] :end-before: [END bigtable_list_tables] :rtype: list of :class:`Table <google.cloud.bigtable.table.Table>` :returns: The list of tables owned by the instance. :raises: :class:`ValueError <exceptions.ValueError>` if one of the returned tables has a name that is not of the expected format. """ table_list_pb = self._client.table_admin_client.list_tables(self.name) result = [] for table_pb in table_list_pb: table_prefix = self.name + "/tables/" if not table_pb.name.startswith(table_prefix): raise ValueError( "Table name {} not of expected format".format(table_pb.name) ) table_id = table_pb.name[len(table_prefix) :] result.append(self.table(table_id)) return result
python
def list_tables(self): """List the tables in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_tables] :end-before: [END bigtable_list_tables] :rtype: list of :class:`Table <google.cloud.bigtable.table.Table>` :returns: The list of tables owned by the instance. :raises: :class:`ValueError <exceptions.ValueError>` if one of the returned tables has a name that is not of the expected format. """ table_list_pb = self._client.table_admin_client.list_tables(self.name) result = [] for table_pb in table_list_pb: table_prefix = self.name + "/tables/" if not table_pb.name.startswith(table_prefix): raise ValueError( "Table name {} not of expected format".format(table_pb.name) ) table_id = table_pb.name[len(table_prefix) :] result.append(self.table(table_id)) return result
[ "def", "list_tables", "(", "self", ")", ":", "table_list_pb", "=", "self", ".", "_client", ".", "table_admin_client", ".", "list_tables", "(", "self", ".", "name", ")", "result", "=", "[", "]", "for", "table_pb", "in", "table_list_pb", ":", "table_prefix", "=", "self", ".", "name", "+", "\"/tables/\"", "if", "not", "table_pb", ".", "name", ".", "startswith", "(", "table_prefix", ")", ":", "raise", "ValueError", "(", "\"Table name {} not of expected format\"", ".", "format", "(", "table_pb", ".", "name", ")", ")", "table_id", "=", "table_pb", ".", "name", "[", "len", "(", "table_prefix", ")", ":", "]", "result", ".", "append", "(", "self", ".", "table", "(", "table_id", ")", ")", "return", "result" ]
List the tables in this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_tables] :end-before: [END bigtable_list_tables] :rtype: list of :class:`Table <google.cloud.bigtable.table.Table>` :returns: The list of tables owned by the instance. :raises: :class:`ValueError <exceptions.ValueError>` if one of the returned tables has a name that is not of the expected format.
[ "List", "the", "tables", "in", "this", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L600-L626
27,997
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.app_profile
def app_profile( self, app_profile_id, routing_policy_type=None, description=None, cluster_id=None, allow_transactional_writes=None, ): """Factory to create AppProfile associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_app_profile] :end-before: [END bigtable_create_app_profile] :type app_profile_id: str :param app_profile_id: The ID of the AppProfile. Must be of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``. :type: routing_policy_type: int :param: routing_policy_type: The type of the routing policy. Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.RoutingPolicyType.ANY` :data:`google.cloud.bigtable.enums.RoutingPolicyType.SINGLE` :type: description: str :param: description: (Optional) Long form description of the use case for this AppProfile. :type: cluster_id: str :param: cluster_id: (Optional) Unique cluster_id which is only required when routing_policy_type is ROUTING_POLICY_TYPE_SINGLE. :type: allow_transactional_writes: bool :param: allow_transactional_writes: (Optional) If true, allow transactional writes for ROUTING_POLICY_TYPE_SINGLE. :rtype: :class:`~google.cloud.bigtable.app_profile.AppProfile>` :returns: AppProfile for this instance. """ return AppProfile( app_profile_id, self, routing_policy_type=routing_policy_type, description=description, cluster_id=cluster_id, allow_transactional_writes=allow_transactional_writes, )
python
def app_profile( self, app_profile_id, routing_policy_type=None, description=None, cluster_id=None, allow_transactional_writes=None, ): """Factory to create AppProfile associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_app_profile] :end-before: [END bigtable_create_app_profile] :type app_profile_id: str :param app_profile_id: The ID of the AppProfile. Must be of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``. :type: routing_policy_type: int :param: routing_policy_type: The type of the routing policy. Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.RoutingPolicyType.ANY` :data:`google.cloud.bigtable.enums.RoutingPolicyType.SINGLE` :type: description: str :param: description: (Optional) Long form description of the use case for this AppProfile. :type: cluster_id: str :param: cluster_id: (Optional) Unique cluster_id which is only required when routing_policy_type is ROUTING_POLICY_TYPE_SINGLE. :type: allow_transactional_writes: bool :param: allow_transactional_writes: (Optional) If true, allow transactional writes for ROUTING_POLICY_TYPE_SINGLE. :rtype: :class:`~google.cloud.bigtable.app_profile.AppProfile>` :returns: AppProfile for this instance. """ return AppProfile( app_profile_id, self, routing_policy_type=routing_policy_type, description=description, cluster_id=cluster_id, allow_transactional_writes=allow_transactional_writes, )
[ "def", "app_profile", "(", "self", ",", "app_profile_id", ",", "routing_policy_type", "=", "None", ",", "description", "=", "None", ",", "cluster_id", "=", "None", ",", "allow_transactional_writes", "=", "None", ",", ")", ":", "return", "AppProfile", "(", "app_profile_id", ",", "self", ",", "routing_policy_type", "=", "routing_policy_type", ",", "description", "=", "description", ",", "cluster_id", "=", "cluster_id", ",", "allow_transactional_writes", "=", "allow_transactional_writes", ",", ")" ]
Factory to create AppProfile associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_app_profile] :end-before: [END bigtable_create_app_profile] :type app_profile_id: str :param app_profile_id: The ID of the AppProfile. Must be of the form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``. :type: routing_policy_type: int :param: routing_policy_type: The type of the routing policy. Possible values are represented by the following constants: :data:`google.cloud.bigtable.enums.RoutingPolicyType.ANY` :data:`google.cloud.bigtable.enums.RoutingPolicyType.SINGLE` :type: description: str :param: description: (Optional) Long form description of the use case for this AppProfile. :type: cluster_id: str :param: cluster_id: (Optional) Unique cluster_id which is only required when routing_policy_type is ROUTING_POLICY_TYPE_SINGLE. :type: allow_transactional_writes: bool :param: allow_transactional_writes: (Optional) If true, allow transactional writes for ROUTING_POLICY_TYPE_SINGLE. :rtype: :class:`~google.cloud.bigtable.app_profile.AppProfile>` :returns: AppProfile for this instance.
[ "Factory", "to", "create", "AppProfile", "associated", "with", "this", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L628-L679
27,998
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/instance.py
Instance.list_app_profiles
def list_app_profiles(self): """Lists information about AppProfiles in an instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_app_profiles] :end-before: [END bigtable_list_app_profiles] :rtype: :list:[`~google.cloud.bigtable.app_profile.AppProfile`] :returns: A :list:[`~google.cloud.bigtable.app_profile.AppProfile`]. By default, this is a list of :class:`~google.cloud.bigtable.app_profile.AppProfile` instances. """ resp = self._client.instance_admin_client.list_app_profiles(self.name) return [AppProfile.from_pb(app_profile, self) for app_profile in resp]
python
def list_app_profiles(self): """Lists information about AppProfiles in an instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_app_profiles] :end-before: [END bigtable_list_app_profiles] :rtype: :list:[`~google.cloud.bigtable.app_profile.AppProfile`] :returns: A :list:[`~google.cloud.bigtable.app_profile.AppProfile`]. By default, this is a list of :class:`~google.cloud.bigtable.app_profile.AppProfile` instances. """ resp = self._client.instance_admin_client.list_app_profiles(self.name) return [AppProfile.from_pb(app_profile, self) for app_profile in resp]
[ "def", "list_app_profiles", "(", "self", ")", ":", "resp", "=", "self", ".", "_client", ".", "instance_admin_client", ".", "list_app_profiles", "(", "self", ".", "name", ")", "return", "[", "AppProfile", ".", "from_pb", "(", "app_profile", ",", "self", ")", "for", "app_profile", "in", "resp", "]" ]
Lists information about AppProfiles in an instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_app_profiles] :end-before: [END bigtable_list_app_profiles] :rtype: :list:[`~google.cloud.bigtable.app_profile.AppProfile`] :returns: A :list:[`~google.cloud.bigtable.app_profile.AppProfile`]. By default, this is a list of :class:`~google.cloud.bigtable.app_profile.AppProfile` instances.
[ "Lists", "information", "about", "AppProfiles", "in", "an", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/instance.py#L681-L697
27,999
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/table.py
_row_from_mapping
def _row_from_mapping(mapping, schema): """Convert a mapping to a row tuple using the schema. Args: mapping (Dict[str, object]) Mapping of row data: must contain keys for all required fields in the schema. Keys which do not correspond to a field in the schema are ignored. schema (List[google.cloud.bigquery.schema.SchemaField]): The schema of the table destination for the rows Returns: Tuple[object]: Tuple whose elements are ordered according to the schema. Raises: ValueError: If schema is empty. """ if len(schema) == 0: raise ValueError(_TABLE_HAS_NO_SCHEMA) row = [] for field in schema: if field.mode == "REQUIRED": row.append(mapping[field.name]) elif field.mode == "REPEATED": row.append(mapping.get(field.name, ())) elif field.mode == "NULLABLE": row.append(mapping.get(field.name)) else: raise ValueError("Unknown field mode: {}".format(field.mode)) return tuple(row)
python
def _row_from_mapping(mapping, schema): """Convert a mapping to a row tuple using the schema. Args: mapping (Dict[str, object]) Mapping of row data: must contain keys for all required fields in the schema. Keys which do not correspond to a field in the schema are ignored. schema (List[google.cloud.bigquery.schema.SchemaField]): The schema of the table destination for the rows Returns: Tuple[object]: Tuple whose elements are ordered according to the schema. Raises: ValueError: If schema is empty. """ if len(schema) == 0: raise ValueError(_TABLE_HAS_NO_SCHEMA) row = [] for field in schema: if field.mode == "REQUIRED": row.append(mapping[field.name]) elif field.mode == "REPEATED": row.append(mapping.get(field.name, ())) elif field.mode == "NULLABLE": row.append(mapping.get(field.name)) else: raise ValueError("Unknown field mode: {}".format(field.mode)) return tuple(row)
[ "def", "_row_from_mapping", "(", "mapping", ",", "schema", ")", ":", "if", "len", "(", "schema", ")", "==", "0", ":", "raise", "ValueError", "(", "_TABLE_HAS_NO_SCHEMA", ")", "row", "=", "[", "]", "for", "field", "in", "schema", ":", "if", "field", ".", "mode", "==", "\"REQUIRED\"", ":", "row", ".", "append", "(", "mapping", "[", "field", ".", "name", "]", ")", "elif", "field", ".", "mode", "==", "\"REPEATED\"", ":", "row", ".", "append", "(", "mapping", ".", "get", "(", "field", ".", "name", ",", "(", ")", ")", ")", "elif", "field", ".", "mode", "==", "\"NULLABLE\"", ":", "row", ".", "append", "(", "mapping", ".", "get", "(", "field", ".", "name", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown field mode: {}\"", ".", "format", "(", "field", ".", "mode", ")", ")", "return", "tuple", "(", "row", ")" ]
Convert a mapping to a row tuple using the schema. Args: mapping (Dict[str, object]) Mapping of row data: must contain keys for all required fields in the schema. Keys which do not correspond to a field in the schema are ignored. schema (List[google.cloud.bigquery.schema.SchemaField]): The schema of the table destination for the rows Returns: Tuple[object]: Tuple whose elements are ordered according to the schema. Raises: ValueError: If schema is empty.
[ "Convert", "a", "mapping", "to", "a", "row", "tuple", "using", "the", "schema", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1105-L1136