repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_item_to_entry
def _item_to_entry(iterator, entry_pb, loggers): """Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be patched with a mutable ``loggers`` argument that can be updated on subsequent calls. For an example, see how the method is used above in :meth:`_LoggingAPI.list_entries`. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type entry_pb: :class:`.log_entry_pb2.LogEntry` :param entry_pb: Log entry protobuf returned from the API. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The next log entry in the page. """ resource = _parse_log_entry(entry_pb) return entry_from_resource(resource, iterator.client, loggers)
python
def _item_to_entry(iterator, entry_pb, loggers): """Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be patched with a mutable ``loggers`` argument that can be updated on subsequent calls. For an example, see how the method is used above in :meth:`_LoggingAPI.list_entries`. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type entry_pb: :class:`.log_entry_pb2.LogEntry` :param entry_pb: Log entry protobuf returned from the API. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The next log entry in the page. """ resource = _parse_log_entry(entry_pb) return entry_from_resource(resource, iterator.client, loggers)
[ "def", "_item_to_entry", "(", "iterator", ",", "entry_pb", ",", "loggers", ")", ":", "resource", "=", "_parse_log_entry", "(", "entry_pb", ")", "return", "entry_from_resource", "(", "resource", ",", "iterator", ".", "client", ",", "loggers", ")" ]
Convert a log entry protobuf to the native object. .. note:: This method does not have the correct signature to be used as the ``item_to_value`` argument to :class:`~google.api_core.page_iterator.Iterator`. It is intended to be patched with a mutable ``loggers`` argument that can be updated on subsequent calls. For an example, see how the method is used above in :meth:`_LoggingAPI.list_entries`. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type entry_pb: :class:`.log_entry_pb2.LogEntry` :param entry_pb: Log entry protobuf returned from the API. :type loggers: dict :param loggers: A mapping of logger fullnames -> loggers. If the logger that owns the entry is not in ``loggers``, the entry will have a newly-created logger. :rtype: :class:`~google.cloud.logging.entries._BaseEntry` :returns: The next log entry in the page.
[ "Convert", "a", "log", "entry", "protobuf", "to", "the", "native", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L468-L496
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_item_to_sink
def _item_to_sink(iterator, log_sink_pb): """Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :class:`~google.cloud.logging.sink.Sink` :returns: The next sink in the page. """ # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_sink_pb) return Sink.from_api_repr(resource, iterator.client)
python
def _item_to_sink(iterator, log_sink_pb): """Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :class:`~google.cloud.logging.sink.Sink` :returns: The next sink in the page. """ # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_sink_pb) return Sink.from_api_repr(resource, iterator.client)
[ "def", "_item_to_sink", "(", "iterator", ",", "log_sink_pb", ")", ":", "# NOTE: LogSink message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "resource", "=", "MessageToDict", "(", "log_sink_pb", ")", "return", "Sink", ".", "from_api_repr", "(", "resource", ",", "iterator", ".", "client", ")" ]
Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :class:`~google.cloud.logging.sink.Sink` :returns: The next sink in the page.
[ "Convert", "a", "sink", "protobuf", "to", "the", "native", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L499-L515
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_item_to_metric
def _item_to_metric(iterator, log_metric_pb): """Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. :rtype: :class:`~google.cloud.logging.metric.Metric` :returns: The next metric in the page. """ # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_metric_pb) return Metric.from_api_repr(resource, iterator.client)
python
def _item_to_metric(iterator, log_metric_pb): """Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. :rtype: :class:`~google.cloud.logging.metric.Metric` :returns: The next metric in the page. """ # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. resource = MessageToDict(log_metric_pb) return Metric.from_api_repr(resource, iterator.client)
[ "def", "_item_to_metric", "(", "iterator", ",", "log_metric_pb", ")", ":", "# NOTE: LogMetric message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "resource", "=", "MessageToDict", "(", "log_metric_pb", ")", "return", "Metric", ".", "from_api_repr", "(", "resource", ",", "iterator", ".", "client", ")" ]
Convert a metric protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_metric_pb: :class:`.logging_metrics_pb2.LogMetric` :param log_metric_pb: Metric protobuf returned from the API. :rtype: :class:`~google.cloud.logging.metric.Metric` :returns: The next metric in the page.
[ "Convert", "a", "metric", "protobuf", "to", "the", "native", "object", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L518-L534
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
make_logging_api
def make_logging_api(client): """Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_LoggingAPI` :returns: A metrics API instance with the proper credentials. """ generated = LoggingServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _LoggingAPI(generated, client)
python
def make_logging_api(client): """Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_LoggingAPI` :returns: A metrics API instance with the proper credentials. """ generated = LoggingServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _LoggingAPI(generated, client)
[ "def", "make_logging_api", "(", "client", ")", ":", "generated", "=", "LoggingServiceV2Client", "(", "credentials", "=", "client", ".", "_credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "_LoggingAPI", "(", "generated", ",", "client", ")" ]
Create an instance of the Logging API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_LoggingAPI` :returns: A metrics API instance with the proper credentials.
[ "Create", "an", "instance", "of", "the", "Logging", "API", "adapter", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L537-L549
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
make_metrics_api
def make_metrics_api(client): """Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials. """ generated = MetricsServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _MetricsAPI(generated, client)
python
def make_metrics_api(client): """Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials. """ generated = MetricsServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _MetricsAPI(generated, client)
[ "def", "make_metrics_api", "(", "client", ")", ":", "generated", "=", "MetricsServiceV2Client", "(", "credentials", "=", "client", ".", "_credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "_MetricsAPI", "(", "generated", ",", "client", ")" ]
Create an instance of the Metrics API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials.
[ "Create", "an", "instance", "of", "the", "Metrics", "API", "adapter", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L552-L564
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
make_sinks_api
def make_sinks_api(client): """Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials. """ generated = ConfigServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _SinksAPI(generated, client)
python
def make_sinks_api(client): """Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials. """ generated = ConfigServiceV2Client( credentials=client._credentials, client_info=_CLIENT_INFO ) return _SinksAPI(generated, client)
[ "def", "make_sinks_api", "(", "client", ")", ":", "generated", "=", "ConfigServiceV2Client", "(", "credentials", "=", "client", ".", "_credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "_SinksAPI", "(", "generated", ",", "client", ")" ]
Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_SinksAPI` :returns: A metrics API instance with the proper credentials.
[ "Create", "an", "instance", "of", "the", "Sinks", "API", "adapter", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L567-L579
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_LoggingAPI.list_entries
def list_entries( self, projects, filter_="", order_by="", page_size=0, page_token=None ): """Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the API's client. :type filter_: str :param filter_: a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters :type order_by: str :param order_by: One of :data:`~google.cloud.logging.ASCENDING` or :data:`~google.cloud.logging.DESCENDING`. :type page_size: int :param page_size: maximum number of entries to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of entries. If not passed, the API will return the first page of entries. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.entries._BaseEntry` accessible to the current API. """ page_iter = self._gapic_api.list_log_entries( [], project_ids=projects, filter_=filter_, order_by=order_by, page_size=page_size, ) page_iter.client = self._client page_iter.next_page_token = page_token # We attach a mutable loggers dictionary so that as Logger # objects are created by entry_from_resource, they can be # re-used by other log entries from the same logger. loggers = {} page_iter.item_to_value = functools.partial(_item_to_entry, loggers=loggers) return page_iter
python
def list_entries( self, projects, filter_="", order_by="", page_size=0, page_token=None ): """Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the API's client. :type filter_: str :param filter_: a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters :type order_by: str :param order_by: One of :data:`~google.cloud.logging.ASCENDING` or :data:`~google.cloud.logging.DESCENDING`. :type page_size: int :param page_size: maximum number of entries to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of entries. If not passed, the API will return the first page of entries. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.entries._BaseEntry` accessible to the current API. """ page_iter = self._gapic_api.list_log_entries( [], project_ids=projects, filter_=filter_, order_by=order_by, page_size=page_size, ) page_iter.client = self._client page_iter.next_page_token = page_token # We attach a mutable loggers dictionary so that as Logger # objects are created by entry_from_resource, they can be # re-used by other log entries from the same logger. loggers = {} page_iter.item_to_value = functools.partial(_item_to_entry, loggers=loggers) return page_iter
[ "def", "list_entries", "(", "self", ",", "projects", ",", "filter_", "=", "\"\"", ",", "order_by", "=", "\"\"", ",", "page_size", "=", "0", ",", "page_token", "=", "None", ")", ":", "page_iter", "=", "self", ".", "_gapic_api", ".", "list_log_entries", "(", "[", "]", ",", "project_ids", "=", "projects", ",", "filter_", "=", "filter_", ",", "order_by", "=", "order_by", ",", "page_size", "=", "page_size", ",", ")", "page_iter", ".", "client", "=", "self", ".", "_client", "page_iter", ".", "next_page_token", "=", "page_token", "# We attach a mutable loggers dictionary so that as Logger", "# objects are created by entry_from_resource, they can be", "# re-used by other log entries from the same logger.", "loggers", "=", "{", "}", "page_iter", ".", "item_to_value", "=", "functools", ".", "partial", "(", "_item_to_entry", ",", "loggers", "=", "loggers", ")", "return", "page_iter" ]
Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the API's client. :type filter_: str :param filter_: a filter expression. See https://cloud.google.com/logging/docs/view/advanced_filters :type order_by: str :param order_by: One of :data:`~google.cloud.logging.ASCENDING` or :data:`~google.cloud.logging.DESCENDING`. :type page_size: int :param page_size: maximum number of entries to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of entries. If not passed, the API will return the first page of entries. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.entries._BaseEntry` accessible to the current API.
[ "Return", "a", "page", "of", "log", "entry", "resources", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L58-L104
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_LoggingAPI.write_entries
def write_entries(self, entries, logger_name=None, resource=None, labels=None): """API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may override. :type resource: mapping :param resource: default resource to associate with entries; individual entries may override. :type labels: mapping :param labels: default labels to associate with entries; individual entries may override. """ partial_success = False entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries] self._gapic_api.write_log_entries( entry_pbs, log_name=logger_name, resource=resource, labels=labels, partial_success=partial_success, )
python
def write_entries(self, entries, logger_name=None, resource=None, labels=None): """API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may override. :type resource: mapping :param resource: default resource to associate with entries; individual entries may override. :type labels: mapping :param labels: default labels to associate with entries; individual entries may override. """ partial_success = False entry_pbs = [_log_entry_mapping_to_pb(entry) for entry in entries] self._gapic_api.write_log_entries( entry_pbs, log_name=logger_name, resource=resource, labels=labels, partial_success=partial_success, )
[ "def", "write_entries", "(", "self", ",", "entries", ",", "logger_name", "=", "None", ",", "resource", "=", "None", ",", "labels", "=", "None", ")", ":", "partial_success", "=", "False", "entry_pbs", "=", "[", "_log_entry_mapping_to_pb", "(", "entry", ")", "for", "entry", "in", "entries", "]", "self", ".", "_gapic_api", ".", "write_log_entries", "(", "entry_pbs", ",", "log_name", "=", "logger_name", ",", "resource", "=", "resource", ",", "labels", "=", "labels", ",", "partial_success", "=", "partial_success", ",", ")" ]
API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may override. :type resource: mapping :param resource: default resource to associate with entries; individual entries may override. :type labels: mapping :param labels: default labels to associate with entries; individual entries may override.
[ "API", "call", ":", "log", "an", "entry", "resource", "via", "a", "POST", "request" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L106-L132
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_LoggingAPI.logger_delete
def logger_delete(self, project, logger_name): """API call: delete all entries in a logger via a DELETE request :type project: str :param project: ID of project containing the log entries to delete :type logger_name: str :param logger_name: name of logger containing the log entries to delete """ path = "projects/%s/logs/%s" % (project, logger_name) self._gapic_api.delete_log(path)
python
def logger_delete(self, project, logger_name): """API call: delete all entries in a logger via a DELETE request :type project: str :param project: ID of project containing the log entries to delete :type logger_name: str :param logger_name: name of logger containing the log entries to delete """ path = "projects/%s/logs/%s" % (project, logger_name) self._gapic_api.delete_log(path)
[ "def", "logger_delete", "(", "self", ",", "project", ",", "logger_name", ")", ":", "path", "=", "\"projects/%s/logs/%s\"", "%", "(", "project", ",", "logger_name", ")", "self", ".", "_gapic_api", ".", "delete_log", "(", "path", ")" ]
API call: delete all entries in a logger via a DELETE request :type project: str :param project: ID of project containing the log entries to delete :type logger_name: str :param logger_name: name of logger containing the log entries to delete
[ "API", "call", ":", "delete", "all", "entries", "in", "a", "logger", "via", "a", "DELETE", "request" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L134-L144
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_SinksAPI.list_sinks
def list_sinks(self, project, page_size=0, page_token=None): """List sinks for the project associated with this client. :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of sinks. If not passed, the API will return the first page of sinks. :rtype: tuple, (list, str) :returns: list of mappings, plus a "next page token" string: if not None, indicates that more sinks can be retrieved with another call (pass that value as ``page_token``). """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_sinks(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_sink return page_iter
python
def list_sinks(self, project, page_size=0, page_token=None): """List sinks for the project associated with this client. :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of sinks. If not passed, the API will return the first page of sinks. :rtype: tuple, (list, str) :returns: list of mappings, plus a "next page token" string: if not None, indicates that more sinks can be retrieved with another call (pass that value as ``page_token``). """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_sinks(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_sink return page_iter
[ "def", "list_sinks", "(", "self", ",", "project", ",", "page_size", "=", "0", ",", "page_token", "=", "None", ")", ":", "path", "=", "\"projects/%s\"", "%", "(", "project", ",", ")", "page_iter", "=", "self", ".", "_gapic_api", ".", "list_sinks", "(", "path", ",", "page_size", "=", "page_size", ")", "page_iter", ".", "client", "=", "self", ".", "_client", "page_iter", ".", "next_page_token", "=", "page_token", "page_iter", ".", "item_to_value", "=", "_item_to_sink", "return", "page_iter" ]
List sinks for the project associated with this client. :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of sinks. If not passed, the API will return the first page of sinks. :rtype: tuple, (list, str) :returns: list of mappings, plus a "next page token" string: if not None, indicates that more sinks can be retrieved with another call (pass that value as ``page_token``).
[ "List", "sinks", "for", "the", "project", "associated", "with", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L162-L187
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_SinksAPI.sink_create
def sink_create( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: create a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type project: str :param project: ID of the project in which to create the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary). """ parent = "projects/%s" % (project,) sink_pb = LogSink(name=sink_name, filter=filter_, destination=destination) created_pb = self._gapic_api.create_sink( parent, sink_pb, unique_writer_identity=unique_writer_identity ) return MessageToDict(created_pb)
python
def sink_create( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: create a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type project: str :param project: ID of the project in which to create the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary). """ parent = "projects/%s" % (project,) sink_pb = LogSink(name=sink_name, filter=filter_, destination=destination) created_pb = self._gapic_api.create_sink( parent, sink_pb, unique_writer_identity=unique_writer_identity ) return MessageToDict(created_pb)
[ "def", "sink_create", "(", "self", ",", "project", ",", "sink_name", ",", "filter_", ",", "destination", ",", "unique_writer_identity", "=", "False", ")", ":", "parent", "=", "\"projects/%s\"", "%", "(", "project", ",", ")", "sink_pb", "=", "LogSink", "(", "name", "=", "sink_name", ",", "filter", "=", "filter_", ",", "destination", "=", "destination", ")", "created_pb", "=", "self", ".", "_gapic_api", ".", "create_sink", "(", "parent", ",", "sink_pb", ",", "unique_writer_identity", "=", "unique_writer_identity", ")", "return", "MessageToDict", "(", "created_pb", ")" ]
API call: create a sink resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create :type project: str :param project: ID of the project in which to create the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary).
[ "API", "call", ":", "create", "a", "sink", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L189-L225
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_SinksAPI.sink_get
def sink_get(self, project, sink_name): """API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The sink object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = self._gapic_api.get_sink(path) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
python
def sink_get(self, project, sink_name): """API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The sink object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = self._gapic_api.get_sink(path) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
[ "def", "sink_get", "(", "self", ",", "project", ",", "sink_name", ")", ":", "path", "=", "\"projects/%s/sinks/%s\"", "%", "(", "project", ",", "sink_name", ")", "sink_pb", "=", "self", ".", "_gapic_api", ".", "get_sink", "(", "path", ")", "# NOTE: LogSink message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "return", "MessageToDict", "(", "sink_pb", ")" ]
API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The sink object returned from the API (converted from a protobuf to a dictionary).
[ "API", "call", ":", "retrieve", "a", "sink", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L227-L244
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_SinksAPI.sink_update
def sink_update( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: update a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = LogSink(name=path, filter=filter_, destination=destination) sink_pb = self._gapic_api.update_sink( path, sink_pb, unique_writer_identity=unique_writer_identity ) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
python
def sink_update( self, project, sink_name, filter_, destination, unique_writer_identity=False ): """API call: update a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/sinks/%s" % (project, sink_name) sink_pb = LogSink(name=path, filter=filter_, destination=destination) sink_pb = self._gapic_api.update_sink( path, sink_pb, unique_writer_identity=unique_writer_identity ) # NOTE: LogSink message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(sink_pb)
[ "def", "sink_update", "(", "self", ",", "project", ",", "sink_name", ",", "filter_", ",", "destination", ",", "unique_writer_identity", "=", "False", ")", ":", "path", "=", "\"projects/%s/sinks/%s\"", "%", "(", "project", ",", "sink_name", ")", "sink_pb", "=", "LogSink", "(", "name", "=", "path", ",", "filter", "=", "filter_", ",", "destination", "=", "destination", ")", "sink_pb", "=", "self", ".", "_gapic_api", ".", "update_sink", "(", "path", ",", "sink_pb", ",", "unique_writer_identity", "=", "unique_writer_identity", ")", "# NOTE: LogSink message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "return", "MessageToDict", "(", "sink_pb", ")" ]
API call: update a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the sink. :type destination: str :param destination: destination URI for the entries exported by the sink. :type unique_writer_identity: bool :param unique_writer_identity: (Optional) determines the kind of IAM identity returned as writer_identity in the new sink. :rtype: dict :returns: The sink resource returned from the API (converted from a protobuf to a dictionary).
[ "API", "call", ":", "update", "a", "sink", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L246-L281
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_SinksAPI.sink_delete
def sink_delete(self, project, sink_name): """API call: delete a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink """ path = "projects/%s/sinks/%s" % (project, sink_name) self._gapic_api.delete_sink(path)
python
def sink_delete(self, project, sink_name): """API call: delete a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink """ path = "projects/%s/sinks/%s" % (project, sink_name) self._gapic_api.delete_sink(path)
[ "def", "sink_delete", "(", "self", ",", "project", ",", "sink_name", ")", ":", "path", "=", "\"projects/%s/sinks/%s\"", "%", "(", "project", ",", "sink_name", ")", "self", ".", "_gapic_api", ".", "delete_sink", "(", "path", ")" ]
API call: delete a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink
[ "API", "call", ":", "delete", "a", "sink", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L283-L293
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_MetricsAPI.list_metrics
def list_metrics(self, project, page_size=0, page_token=None): """List metrics for the project associated with this client. :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: maximum number of metrics to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of metrics. If not passed, the API will return the first page of metrics. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.metric.Metric` accessible to the current API. """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_log_metrics(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_metric return page_iter
python
def list_metrics(self, project, page_size=0, page_token=None): """List metrics for the project associated with this client. :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: maximum number of metrics to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of metrics. If not passed, the API will return the first page of metrics. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.metric.Metric` accessible to the current API. """ path = "projects/%s" % (project,) page_iter = self._gapic_api.list_log_metrics(path, page_size=page_size) page_iter.client = self._client page_iter.next_page_token = page_token page_iter.item_to_value = _item_to_metric return page_iter
[ "def", "list_metrics", "(", "self", ",", "project", ",", "page_size", "=", "0", ",", "page_token", "=", "None", ")", ":", "path", "=", "\"projects/%s\"", "%", "(", "project", ",", ")", "page_iter", "=", "self", ".", "_gapic_api", ".", "list_log_metrics", "(", "path", ",", "page_size", "=", "page_size", ")", "page_iter", ".", "client", "=", "self", ".", "_client", "page_iter", ".", "next_page_token", "=", "page_token", "page_iter", ".", "item_to_value", "=", "_item_to_metric", "return", "page_iter" ]
List metrics for the project associated with this client. :type project: str :param project: ID of the project whose metrics are to be listed. :type page_size: int :param page_size: maximum number of metrics to return, If not passed, defaults to a value set by the API. :type page_token: str :param page_token: opaque marker for the next "page" of metrics. If not passed, the API will return the first page of metrics. :rtype: :class:`~google.api_core.page_iterator.Iterator` :returns: Iterator of :class:`~google.cloud.logging.metric.Metric` accessible to the current API.
[ "List", "metrics", "for", "the", "project", "associated", "with", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L312-L337
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_MetricsAPI.metric_create
def metric_create(self, project, metric_name, filter_, description): """API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. """ parent = "projects/%s" % (project,) metric_pb = LogMetric(name=metric_name, filter=filter_, description=description) self._gapic_api.create_log_metric(parent, metric_pb)
python
def metric_create(self, project, metric_name, filter_, description): """API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. """ parent = "projects/%s" % (project,) metric_pb = LogMetric(name=metric_name, filter=filter_, description=description) self._gapic_api.create_log_metric(parent, metric_pb)
[ "def", "metric_create", "(", "self", ",", "project", ",", "metric_name", ",", "filter_", ",", "description", ")", ":", "parent", "=", "\"projects/%s\"", "%", "(", "project", ",", ")", "metric_pb", "=", "LogMetric", "(", "name", "=", "metric_name", ",", "filter", "=", "filter_", ",", "description", "=", "description", ")", "self", ".", "_gapic_api", ".", "create_log_metric", "(", "parent", ",", "metric_pb", ")" ]
API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric.
[ "API", "call", ":", "create", "a", "metric", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L339-L360
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_MetricsAPI.metric_get
def metric_get(self, project, metric_name): """API call: retrieve a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = self._gapic_api.get_log_metric(path) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
python
def metric_get(self, project, metric_name): """API call: retrieve a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = self._gapic_api.get_log_metric(path) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
[ "def", "metric_get", "(", "self", ",", "project", ",", "metric_name", ")", ":", "path", "=", "\"projects/%s/metrics/%s\"", "%", "(", "project", ",", "metric_name", ")", "metric_pb", "=", "self", ".", "_gapic_api", ".", "get_log_metric", "(", "path", ")", "# NOTE: LogMetric message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "return", "MessageToDict", "(", "metric_pb", ")" ]
API call: retrieve a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary).
[ "API", "call", ":", "retrieve", "a", "metric", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L362-L379
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_MetricsAPI.metric_update
def metric_update(self, project, metric_name, filter_, description): """API call: update a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = LogMetric(name=path, filter=filter_, description=description) metric_pb = self._gapic_api.update_log_metric(path, metric_pb) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
python
def metric_update(self, project, metric_name, filter_, description): """API call: update a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary). """ path = "projects/%s/metrics/%s" % (project, metric_name) metric_pb = LogMetric(name=path, filter=filter_, description=description) metric_pb = self._gapic_api.update_log_metric(path, metric_pb) # NOTE: LogMetric message type does not have an ``Any`` field # so `MessageToDict`` can safely be used. return MessageToDict(metric_pb)
[ "def", "metric_update", "(", "self", ",", "project", ",", "metric_name", ",", "filter_", ",", "description", ")", ":", "path", "=", "\"projects/%s/metrics/%s\"", "%", "(", "project", ",", "metric_name", ")", "metric_pb", "=", "LogMetric", "(", "name", "=", "path", ",", "filter", "=", "filter_", ",", "description", "=", "description", ")", "metric_pb", "=", "self", ".", "_gapic_api", ".", "update_log_metric", "(", "path", ",", "metric_pb", ")", "# NOTE: LogMetric message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "return", "MessageToDict", "(", "metric_pb", ")" ]
API call: update a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric :type filter_: str :param filter_: the advanced logs filter expression defining the entries exported by the metric. :type description: str :param description: description of the metric. :rtype: dict :returns: The metric object returned from the API (converted from a protobuf to a dictionary).
[ "API", "call", ":", "update", "a", "metric", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L381-L406
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
_MetricsAPI.metric_delete
def metric_delete(self, project, metric_name): """API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric """ path = "projects/%s/metrics/%s" % (project, metric_name) self._gapic_api.delete_log_metric(path)
python
def metric_delete(self, project, metric_name): """API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric """ path = "projects/%s/metrics/%s" % (project, metric_name) self._gapic_api.delete_log_metric(path)
[ "def", "metric_delete", "(", "self", ",", "project", ",", "metric_name", ")", ":", "path", "=", "\"projects/%s/metrics/%s\"", "%", "(", "project", ",", "metric_name", ")", "self", ".", "_gapic_api", ".", "delete_log_metric", "(", "path", ")" ]
API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric
[ "API", "call", ":", "delete", "a", "metric", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L408-L418
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py
TenantServiceClient.tenant_path
def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}", project=project, tenant=tenant )
python
def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}", project=project, tenant=tenant )
[ "def", "tenant_path", "(", "cls", ",", "project", ",", "tenant", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/tenants/{tenant}\"", ",", "project", "=", "project", ",", "tenant", "=", "tenant", ")" ]
Return a fully-qualified tenant string.
[ "Return", "a", "fully", "-", "qualified", "tenant", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py#L100-L104
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py
TenantServiceClient.create_tenant
def create_tenant( self, parent, tenant, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new tenant entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.create_tenant(parent, tenant) Args: parent (str): Required. Resource name of the project under which the tenant is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "create_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_tenant, default_retry=self._method_configs["CreateTenant"].retry, default_timeout=self._method_configs["CreateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.CreateTenantRequest(parent=parent, tenant=tenant) return self._inner_api_calls["create_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_tenant( self, parent, tenant, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new tenant entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.create_tenant(parent, tenant) Args: parent (str): Required. Resource name of the project under which the tenant is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "create_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_tenant, default_retry=self._method_configs["CreateTenant"].retry, default_timeout=self._method_configs["CreateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.CreateTenantRequest(parent=parent, tenant=tenant) return self._inner_api_calls["create_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_tenant", "(", "self", ",", "parent", ",", "tenant", ",", "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_tenant\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_tenant\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_tenant", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateTenant\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateTenant\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "tenant_service_pb2", ".", "CreateTenantRequest", "(", "parent", "=", "parent", ",", "tenant", "=", "tenant", ")", "return", "self", ".", "_inner_api_calls", "[", "\"create_tenant\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a new tenant entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.create_tenant(parent, tenant) Args: parent (str): Required. Resource name of the project under which the tenant is created. The format is "projects/{project\_id}", for example, "projects/api-test-project". tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` 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.talent_v4beta1.types.Tenant` 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", "tenant", "entity", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py#L205-L274
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py
TenantServiceClient.get_tenant
def get_tenant( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> name = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> response = client.get_tenant(name) Args: name (str): Required. The resource name of the tenant to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}", for example, "projects/api-test-project/tenants/foo". 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "get_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_tenant, default_retry=self._method_configs["GetTenant"].retry, default_timeout=self._method_configs["GetTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.GetTenantRequest(name=name) return self._inner_api_calls["get_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def get_tenant( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> name = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> response = client.get_tenant(name) Args: name (str): Required. The resource name of the tenant to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}", for example, "projects/api-test-project/tenants/foo". 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.talent_v4beta1.types.Tenant` 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_tenant" not in self._inner_api_calls: self._inner_api_calls[ "get_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_tenant, default_retry=self._method_configs["GetTenant"].retry, default_timeout=self._method_configs["GetTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.GetTenantRequest(name=name) return self._inner_api_calls["get_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "get_tenant", "(", "self", ",", "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_tenant\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"get_tenant\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "get_tenant", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"GetTenant\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"GetTenant\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "tenant_service_pb2", ".", "GetTenantRequest", "(", "name", "=", "name", ")", "return", "self", ".", "_inner_api_calls", "[", "\"get_tenant\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> name = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> response = client.get_tenant(name) Args: name (str): Required. The resource name of the tenant to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}", for example, "projects/api-test-project/tenants/foo". 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.talent_v4beta1.types.Tenant` 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.
[ "Retrieves", "specified", "tenant", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py#L276-L335
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py
TenantServiceClient.update_tenant
def update_tenant( self, tenant, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.update_tenant(tenant) Args: tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``tenant`` are updated. Otherwise all the fields are updated. A field mask to specify the tenant fields to be updated. Only top level fields of ``Tenant`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` 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.talent_v4beta1.types.Tenant` 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 "update_tenant" not in self._inner_api_calls: self._inner_api_calls[ "update_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_tenant, default_retry=self._method_configs["UpdateTenant"].retry, default_timeout=self._method_configs["UpdateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.UpdateTenantRequest( tenant=tenant, update_mask=update_mask ) return self._inner_api_calls["update_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_tenant( self, tenant, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.update_tenant(tenant) Args: tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``tenant`` are updated. Otherwise all the fields are updated. A field mask to specify the tenant fields to be updated. Only top level fields of ``Tenant`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` 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.talent_v4beta1.types.Tenant` 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 "update_tenant" not in self._inner_api_calls: self._inner_api_calls[ "update_tenant" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_tenant, default_retry=self._method_configs["UpdateTenant"].retry, default_timeout=self._method_configs["UpdateTenant"].timeout, client_info=self._client_info, ) request = tenant_service_pb2.UpdateTenantRequest( tenant=tenant, update_mask=update_mask ) return self._inner_api_calls["update_tenant"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_tenant", "(", "self", ",", "tenant", ",", "update_mask", "=", "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", "\"update_tenant\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_tenant\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_tenant", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateTenant\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateTenant\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "tenant_service_pb2", ".", "UpdateTenantRequest", "(", "tenant", "=", "tenant", ",", "update_mask", "=", "update_mask", ")", "return", "self", ".", "_inner_api_calls", "[", "\"update_tenant\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates specified tenant. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.TenantServiceClient() >>> >>> # TODO: Initialize `tenant`: >>> tenant = {} >>> >>> response = client.update_tenant(tenant) Args: tenant (Union[dict, ~google.cloud.talent_v4beta1.types.Tenant]): Required. The tenant resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Tenant` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``tenant`` are updated. Otherwise all the fields are updated. A field mask to specify the tenant fields to be updated. Only top level fields of ``Tenant`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` 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.talent_v4beta1.types.Tenant` 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.
[ "Updates", "specified", "tenant", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/tenant_service_client.py#L337-L410
train
googleapis/google-cloud-python
api_core/google/api_core/gapic_v1/method.py
_apply_decorators
def _apply_decorators(func, decorators): """Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which will be ignored. """ decorators = filter(_is_not_none_or_false, reversed(decorators)) for decorator in decorators: func = decorator(func) return func
python
def _apply_decorators(func, decorators): """Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which will be ignored. """ decorators = filter(_is_not_none_or_false, reversed(decorators)) for decorator in decorators: func = decorator(func) return func
[ "def", "_apply_decorators", "(", "func", ",", "decorators", ")", ":", "decorators", "=", "filter", "(", "_is_not_none_or_false", ",", "reversed", "(", "decorators", ")", ")", "for", "decorator", "in", "decorators", ":", "func", "=", "decorator", "(", "func", ")", "return", "func" ]
Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which will be ignored.
[ "Apply", "a", "list", "of", "decorators", "to", "a", "given", "function", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/method.py#L36-L47
train
googleapis/google-cloud-python
api_core/google/api_core/gapic_v1/method.py
_determine_timeout
def _determine_timeout(default_timeout, specified_timeout, retry): """Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be set to the ``default_timeout``. retry (Optional[Retry]): The retry specified at invocation time. Returns: Optional[Timeout]: The timeout to apply to the method or ``None``. """ if specified_timeout is DEFAULT: specified_timeout = default_timeout if specified_timeout is default_timeout: # If timeout is the default and the default timeout is exponential and # a non-default retry is specified, make sure the timeout's deadline # matches the retry's. This handles the case where the user leaves # the timeout default but specifies a lower deadline via the retry. if ( retry and retry is not DEFAULT and isinstance(default_timeout, timeout.ExponentialTimeout) ): return default_timeout.with_deadline(retry._deadline) else: return default_timeout # If timeout is specified as a number instead of a Timeout instance, # convert it to a ConstantTimeout. if isinstance(specified_timeout, (int, float)): return timeout.ConstantTimeout(specified_timeout) else: return specified_timeout
python
def _determine_timeout(default_timeout, specified_timeout, retry): """Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be set to the ``default_timeout``. retry (Optional[Retry]): The retry specified at invocation time. Returns: Optional[Timeout]: The timeout to apply to the method or ``None``. """ if specified_timeout is DEFAULT: specified_timeout = default_timeout if specified_timeout is default_timeout: # If timeout is the default and the default timeout is exponential and # a non-default retry is specified, make sure the timeout's deadline # matches the retry's. This handles the case where the user leaves # the timeout default but specifies a lower deadline via the retry. if ( retry and retry is not DEFAULT and isinstance(default_timeout, timeout.ExponentialTimeout) ): return default_timeout.with_deadline(retry._deadline) else: return default_timeout # If timeout is specified as a number instead of a Timeout instance, # convert it to a ConstantTimeout. if isinstance(specified_timeout, (int, float)): return timeout.ConstantTimeout(specified_timeout) else: return specified_timeout
[ "def", "_determine_timeout", "(", "default_timeout", ",", "specified_timeout", ",", "retry", ")", ":", "if", "specified_timeout", "is", "DEFAULT", ":", "specified_timeout", "=", "default_timeout", "if", "specified_timeout", "is", "default_timeout", ":", "# If timeout is the default and the default timeout is exponential and", "# a non-default retry is specified, make sure the timeout's deadline", "# matches the retry's. This handles the case where the user leaves", "# the timeout default but specifies a lower deadline via the retry.", "if", "(", "retry", "and", "retry", "is", "not", "DEFAULT", "and", "isinstance", "(", "default_timeout", ",", "timeout", ".", "ExponentialTimeout", ")", ")", ":", "return", "default_timeout", ".", "with_deadline", "(", "retry", ".", "_deadline", ")", "else", ":", "return", "default_timeout", "# If timeout is specified as a number instead of a Timeout instance,", "# convert it to a ConstantTimeout.", "if", "isinstance", "(", "specified_timeout", ",", "(", "int", ",", "float", ")", ")", ":", "return", "timeout", ".", "ConstantTimeout", "(", "specified_timeout", ")", "else", ":", "return", "specified_timeout" ]
Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be set to the ``default_timeout``. retry (Optional[Retry]): The retry specified at invocation time. Returns: Optional[Timeout]: The timeout to apply to the method or ``None``.
[ "Determines", "how", "timeout", "should", "be", "applied", "to", "a", "wrapped", "method", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/method.py#L50-L86
train
googleapis/google-cloud-python
api_core/google/api_core/gapic_v1/method.py
wrap_method
def wrap_method( func, default_retry=None, default_timeout=None, client_info=client_info.DEFAULT_CLIENT_INFO, ): """Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method. """ func = grpc_helpers.wrap_errors(func) if client_info is not None: user_agent_metadata = [client_info.to_grpc_metadata()] else: user_agent_metadata = None return general_helpers.wraps(func)( _GapicCallable( func, default_retry, default_timeout, metadata=user_agent_metadata ) )
python
def wrap_method( func, default_retry=None, default_timeout=None, client_info=client_info.DEFAULT_CLIENT_INFO, ): """Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method. """ func = grpc_helpers.wrap_errors(func) if client_info is not None: user_agent_metadata = [client_info.to_grpc_metadata()] else: user_agent_metadata = None return general_helpers.wraps(func)( _GapicCallable( func, default_retry, default_timeout, metadata=user_agent_metadata ) )
[ "def", "wrap_method", "(", "func", ",", "default_retry", "=", "None", ",", "default_timeout", "=", "None", ",", "client_info", "=", "client_info", ".", "DEFAULT_CLIENT_INFO", ",", ")", ":", "func", "=", "grpc_helpers", ".", "wrap_errors", "(", "func", ")", "if", "client_info", "is", "not", "None", ":", "user_agent_metadata", "=", "[", "client_info", ".", "to_grpc_metadata", "(", ")", "]", "else", ":", "user_agent_metadata", "=", "None", "return", "general_helpers", ".", "wraps", "(", "func", ")", "(", "_GapicCallable", "(", "func", ",", "default_retry", ",", "default_timeout", ",", "metadata", "=", "user_agent_metadata", ")", ")" ]
Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method.
[ "Wrap", "an", "RPC", "method", "with", "common", "behavior", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/gapic_v1/method.py#L146-L242
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_validate_name
def _validate_name(name): """Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. """ if name is None: return # The first and las characters must be alphanumeric. if not all([name[0].isalnum(), name[-1].isalnum()]): raise ValueError("Bucket names must start and end with a number or letter.") return name
python
def _validate_name(name): """Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid. """ if name is None: return # The first and las characters must be alphanumeric. if not all([name[0].isalnum(), name[-1].isalnum()]): raise ValueError("Bucket names must start and end with a number or letter.") return name
[ "def", "_validate_name", "(", "name", ")", ":", "if", "name", "is", "None", ":", "return", "# The first and las characters must be alphanumeric.", "if", "not", "all", "(", "[", "name", "[", "0", "]", ".", "isalnum", "(", ")", ",", "name", "[", "-", "1", "]", ".", "isalnum", "(", ")", "]", ")", ":", "raise", "ValueError", "(", "\"Bucket names must start and end with a number or letter.\"", ")", "return", "name" ]
Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`NoneType` :returns: ``name`` if valid.
[ "Pre", "-", "flight", "Bucket", "name", "validation", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L24-L39
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_scalar_property
def _scalar_property(fieldname): """Create a property descriptor around the :class:`_PropertyMixin` helpers. """ def _getter(self): """Scalar property getter.""" return self._properties.get(fieldname) def _setter(self, value): """Scalar property setter.""" self._patch_property(fieldname, value) return property(_getter, _setter)
python
def _scalar_property(fieldname): """Create a property descriptor around the :class:`_PropertyMixin` helpers. """ def _getter(self): """Scalar property getter.""" return self._properties.get(fieldname) def _setter(self, value): """Scalar property setter.""" self._patch_property(fieldname, value) return property(_getter, _setter)
[ "def", "_scalar_property", "(", "fieldname", ")", ":", "def", "_getter", "(", "self", ")", ":", "\"\"\"Scalar property getter.\"\"\"", "return", "self", ".", "_properties", ".", "get", "(", "fieldname", ")", "def", "_setter", "(", "self", ",", "value", ")", ":", "\"\"\"Scalar property setter.\"\"\"", "self", ".", "_patch_property", "(", "fieldname", ",", "value", ")", "return", "property", "(", "_getter", ",", "_setter", ")" ]
Create a property descriptor around the :class:`_PropertyMixin` helpers.
[ "Create", "a", "property", "descriptor", "around", "the", ":", "class", ":", "_PropertyMixin", "helpers", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L216-L228
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_write_buffer_to_hash
def _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192): """Read blocks from a buffer and update a hash with them. :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to update a hash object. :type hash_obj: object that implements update :param hash_obj: A hash object (MD5 or CRC32-C). :type digest_block_size: int :param digest_block_size: The block size to write to the hash. Defaults to 8192. """ block = buffer_object.read(digest_block_size) while len(block) > 0: hash_obj.update(block) # Update the block for the next iteration. block = buffer_object.read(digest_block_size)
python
def _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192): """Read blocks from a buffer and update a hash with them. :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to update a hash object. :type hash_obj: object that implements update :param hash_obj: A hash object (MD5 or CRC32-C). :type digest_block_size: int :param digest_block_size: The block size to write to the hash. Defaults to 8192. """ block = buffer_object.read(digest_block_size) while len(block) > 0: hash_obj.update(block) # Update the block for the next iteration. block = buffer_object.read(digest_block_size)
[ "def", "_write_buffer_to_hash", "(", "buffer_object", ",", "hash_obj", ",", "digest_block_size", "=", "8192", ")", ":", "block", "=", "buffer_object", ".", "read", "(", "digest_block_size", ")", "while", "len", "(", "block", ")", ">", "0", ":", "hash_obj", ".", "update", "(", "block", ")", "# Update the block for the next iteration.", "block", "=", "buffer_object", ".", "read", "(", "digest_block_size", ")" ]
Read blocks from a buffer and update a hash with them. :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to update a hash object. :type hash_obj: object that implements update :param hash_obj: A hash object (MD5 or CRC32-C). :type digest_block_size: int :param digest_block_size: The block size to write to the hash. Defaults to 8192.
[ "Read", "blocks", "from", "a", "buffer", "and", "update", "a", "hash", "with", "them", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L231-L249
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_base64_md5hash
def _base64_md5hash(buffer_object): """Get MD5 hash of bytes (as base64). :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to compute an MD5 hash (as base64). :rtype: str :returns: A base64 encoded digest of the MD5 hash. """ hash_obj = md5() _write_buffer_to_hash(buffer_object, hash_obj) digest_bytes = hash_obj.digest() return base64.b64encode(digest_bytes)
python
def _base64_md5hash(buffer_object): """Get MD5 hash of bytes (as base64). :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to compute an MD5 hash (as base64). :rtype: str :returns: A base64 encoded digest of the MD5 hash. """ hash_obj = md5() _write_buffer_to_hash(buffer_object, hash_obj) digest_bytes = hash_obj.digest() return base64.b64encode(digest_bytes)
[ "def", "_base64_md5hash", "(", "buffer_object", ")", ":", "hash_obj", "=", "md5", "(", ")", "_write_buffer_to_hash", "(", "buffer_object", ",", "hash_obj", ")", "digest_bytes", "=", "hash_obj", ".", "digest", "(", ")", "return", "base64", ".", "b64encode", "(", "digest_bytes", ")" ]
Get MD5 hash of bytes (as base64). :type buffer_object: bytes buffer :param buffer_object: Buffer containing bytes used to compute an MD5 hash (as base64). :rtype: str :returns: A base64 encoded digest of the MD5 hash.
[ "Get", "MD5", "hash", "of", "bytes", "(", "as", "base64", ")", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L252-L265
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_PropertyMixin.reload
def reload(self, client=None): """Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass only '?projection=noAcl' here because 'acl' and related # are handled via custom endpoints. query_params["projection"] = "noAcl" api_response = client._connection.api_request( method="GET", path=self.path, query_params=query_params, headers=self._encryption_headers(), _target_object=self, ) self._set_properties(api_response)
python
def reload(self, client=None): """Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass only '?projection=noAcl' here because 'acl' and related # are handled via custom endpoints. query_params["projection"] = "noAcl" api_response = client._connection.api_request( method="GET", path=self.path, query_params=query_params, headers=self._encryption_headers(), _target_object=self, ) self._set_properties(api_response)
[ "def", "reload", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "self", ".", "_query_params", "# Pass only '?projection=noAcl' here because 'acl' and related", "# are handled via custom endpoints.", "query_params", "[", "\"projection\"", "]", "=", "\"noAcl\"", "api_response", "=", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "self", ".", "path", ",", "query_params", "=", "query_params", ",", "headers", "=", "self", ".", "_encryption_headers", "(", ")", ",", "_target_object", "=", "self", ",", ")", "self", ".", "_set_properties", "(", "api_response", ")" ]
Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object.
[ "Reload", "properties", "from", "Cloud", "Storage", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L110-L132
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_PropertyMixin._patch_property
def _patch_property(self, name, value): """Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param name: The field name to update. :type value: object :param value: The value being updated. """ self._changes.add(name) self._properties[name] = value
python
def _patch_property(self, name, value): """Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param name: The field name to update. :type value: object :param value: The value being updated. """ self._changes.add(name) self._properties[name] = value
[ "def", "_patch_property", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_changes", ".", "add", "(", "name", ")", "self", ".", "_properties", "[", "name", "]", "=", "value" ]
Update field of this object's properties. This method will only update the field provided and will not touch the other fields. It **will not** reload the properties from the server. The behavior is local only and syncing occurs via :meth:`patch`. :type name: str :param name: The field name to update. :type value: object :param value: The value being updated.
[ "Update", "field", "of", "this", "object", "s", "properties", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L134-L150
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_PropertyMixin.patch
def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass '?projection=full' here because 'PATCH' documented not # to work properly w/ 'noAcl'. query_params["projection"] = "full" update_properties = {key: self._properties[key] for key in self._changes} # Make the API call. api_response = client._connection.api_request( method="PATCH", path=self.path, data=update_properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
python
def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params # Pass '?projection=full' here because 'PATCH' documented not # to work properly w/ 'noAcl'. query_params["projection"] = "full" update_properties = {key: self._properties[key] for key in self._changes} # Make the API call. api_response = client._connection.api_request( method="PATCH", path=self.path, data=update_properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
[ "def", "patch", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "self", ".", "_query_params", "# Pass '?projection=full' here because 'PATCH' documented not", "# to work properly w/ 'noAcl'.", "query_params", "[", "\"projection\"", "]", "=", "\"full\"", "update_properties", "=", "{", "key", ":", "self", ".", "_properties", "[", "key", "]", "for", "key", "in", "self", ".", "_changes", "}", "# Make the API call.", "api_response", "=", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"PATCH\"", ",", "path", "=", "self", ".", "path", ",", "data", "=", "update_properties", ",", "query_params", "=", "query_params", ",", "_target_object", "=", "self", ",", ")", "self", ".", "_set_properties", "(", "api_response", ")" ]
Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object.
[ "Sends", "all", "changed", "properties", "in", "a", "PATCH", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L162-L189
train
googleapis/google-cloud-python
storage/google/cloud/storage/_helpers.py
_PropertyMixin.update
def update(self, client=None): """Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params query_params["projection"] = "full" api_response = client._connection.api_request( method="PUT", path=self.path, data=self._properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
python
def update(self, client=None): """Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object. """ client = self._require_client(client) query_params = self._query_params query_params["projection"] = "full" api_response = client._connection.api_request( method="PUT", path=self.path, data=self._properties, query_params=query_params, _target_object=self, ) self._set_properties(api_response)
[ "def", "update", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "self", ".", "_query_params", "query_params", "[", "\"projection\"", "]", "=", "\"full\"", "api_response", "=", "client", ".", "_connection", ".", "api_request", "(", "method", "=", "\"PUT\"", ",", "path", "=", "self", ".", "path", ",", "data", "=", "self", ".", "_properties", ",", "query_params", "=", "query_params", ",", "_target_object", "=", "self", ",", ")", "self", ".", "_set_properties", "(", "api_response", ")" ]
Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ``client`` stored on the current object.
[ "Sends", "all", "properties", "in", "a", "PUT", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/_helpers.py#L191-L213
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.start
def start(self): """Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`. """ with self._operational_lock: if self._thread is not None: raise ValueError("Dispatcher is already running.") flow_control = self._manager.flow_control worker = helper_threads.QueueCallbackWorker( self._queue, self.dispatch_callback, max_items=flow_control.max_request_batch_size, max_latency=flow_control.max_request_batch_latency, ) # Create and start the helper thread. thread = threading.Thread(name=_CALLBACK_WORKER_NAME, target=worker) thread.daemon = True thread.start() _LOGGER.debug("Started helper thread %s", thread.name) self._thread = thread
python
def start(self): """Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`. """ with self._operational_lock: if self._thread is not None: raise ValueError("Dispatcher is already running.") flow_control = self._manager.flow_control worker = helper_threads.QueueCallbackWorker( self._queue, self.dispatch_callback, max_items=flow_control.max_request_batch_size, max_latency=flow_control.max_request_batch_latency, ) # Create and start the helper thread. thread = threading.Thread(name=_CALLBACK_WORKER_NAME, target=worker) thread.daemon = True thread.start() _LOGGER.debug("Started helper thread %s", thread.name) self._thread = thread
[ "def", "start", "(", "self", ")", ":", "with", "self", ".", "_operational_lock", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Dispatcher is already running.\"", ")", "flow_control", "=", "self", ".", "_manager", ".", "flow_control", "worker", "=", "helper_threads", ".", "QueueCallbackWorker", "(", "self", ".", "_queue", ",", "self", ".", "dispatch_callback", ",", "max_items", "=", "flow_control", ".", "max_request_batch_size", ",", "max_latency", "=", "flow_control", ".", "max_request_batch_latency", ",", ")", "# Create and start the helper thread.", "thread", "=", "threading", ".", "Thread", "(", "name", "=", "_CALLBACK_WORKER_NAME", ",", "target", "=", "worker", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")", "_LOGGER", ".", "debug", "(", "\"Started helper thread %s\"", ",", "thread", ".", "name", ")", "self", ".", "_thread", "=", "thread" ]
Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`.
[ "Start", "a", "thread", "to", "dispatch", "requests", "queued", "up", "by", "callbacks", ".", "Spawns", "a", "thread", "to", "run", ":", "meth", ":", "dispatch_callback", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L37-L57
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.dispatch_callback
def dispatch_callback(self, items): """Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack". """ if not self._manager.is_active: return batched_commands = collections.defaultdict(list) for item in items: batched_commands[item.__class__].append(item) _LOGGER.debug("Handling %d batched requests", len(items)) if batched_commands[requests.LeaseRequest]: self.lease(batched_commands.pop(requests.LeaseRequest)) if batched_commands[requests.ModAckRequest]: self.modify_ack_deadline(batched_commands.pop(requests.ModAckRequest)) # Note: Drop and ack *must* be after lease. It's possible to get both # the lease the and ack/drop request in the same batch. if batched_commands[requests.AckRequest]: self.ack(batched_commands.pop(requests.AckRequest)) if batched_commands[requests.NackRequest]: self.nack(batched_commands.pop(requests.NackRequest)) if batched_commands[requests.DropRequest]: self.drop(batched_commands.pop(requests.DropRequest))
python
def dispatch_callback(self, items): """Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack". """ if not self._manager.is_active: return batched_commands = collections.defaultdict(list) for item in items: batched_commands[item.__class__].append(item) _LOGGER.debug("Handling %d batched requests", len(items)) if batched_commands[requests.LeaseRequest]: self.lease(batched_commands.pop(requests.LeaseRequest)) if batched_commands[requests.ModAckRequest]: self.modify_ack_deadline(batched_commands.pop(requests.ModAckRequest)) # Note: Drop and ack *must* be after lease. It's possible to get both # the lease the and ack/drop request in the same batch. if batched_commands[requests.AckRequest]: self.ack(batched_commands.pop(requests.AckRequest)) if batched_commands[requests.NackRequest]: self.nack(batched_commands.pop(requests.NackRequest)) if batched_commands[requests.DropRequest]: self.drop(batched_commands.pop(requests.DropRequest))
[ "def", "dispatch_callback", "(", "self", ",", "items", ")", ":", "if", "not", "self", ".", "_manager", ".", "is_active", ":", "return", "batched_commands", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "item", "in", "items", ":", "batched_commands", "[", "item", ".", "__class__", "]", ".", "append", "(", "item", ")", "_LOGGER", ".", "debug", "(", "\"Handling %d batched requests\"", ",", "len", "(", "items", ")", ")", "if", "batched_commands", "[", "requests", ".", "LeaseRequest", "]", ":", "self", ".", "lease", "(", "batched_commands", ".", "pop", "(", "requests", ".", "LeaseRequest", ")", ")", "if", "batched_commands", "[", "requests", ".", "ModAckRequest", "]", ":", "self", ".", "modify_ack_deadline", "(", "batched_commands", ".", "pop", "(", "requests", ".", "ModAckRequest", ")", ")", "# Note: Drop and ack *must* be after lease. It's possible to get both", "# the lease the and ack/drop request in the same batch.", "if", "batched_commands", "[", "requests", ".", "AckRequest", "]", ":", "self", ".", "ack", "(", "batched_commands", ".", "pop", "(", "requests", ".", "AckRequest", ")", ")", "if", "batched_commands", "[", "requests", ".", "NackRequest", "]", ":", "self", ".", "nack", "(", "batched_commands", ".", "pop", "(", "requests", ".", "NackRequest", ")", ")", "if", "batched_commands", "[", "requests", ".", "DropRequest", "]", ":", "self", ".", "drop", "(", "batched_commands", ".", "pop", "(", "requests", ".", "DropRequest", ")", ")" ]
Map the callback request to the appropriate gRPC request. Args: action (str): The method to be invoked. kwargs (Dict[str, Any]): The keyword arguments for the method specified by ``action``. Raises: ValueError: If ``action`` isn't one of the expected actions "ack", "drop", "lease", "modify_ack_deadline" or "nack".
[ "Map", "the", "callback", "request", "to", "the", "appropriate", "gRPC", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L68-L101
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.ack
def ack(self, items): """Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge. """ # If we got timing information, add it to the histogram. for item in items: time_to_ack = item.time_to_ack if time_to_ack is not None: self._manager.ack_histogram.add(time_to_ack) ack_ids = [item.ack_id for item in items] request = types.StreamingPullRequest(ack_ids=ack_ids) self._manager.send(request) # Remove the message from lease management. self.drop(items)
python
def ack(self, items): """Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge. """ # If we got timing information, add it to the histogram. for item in items: time_to_ack = item.time_to_ack if time_to_ack is not None: self._manager.ack_histogram.add(time_to_ack) ack_ids = [item.ack_id for item in items] request = types.StreamingPullRequest(ack_ids=ack_ids) self._manager.send(request) # Remove the message from lease management. self.drop(items)
[ "def", "ack", "(", "self", ",", "items", ")", ":", "# If we got timing information, add it to the histogram.", "for", "item", "in", "items", ":", "time_to_ack", "=", "item", ".", "time_to_ack", "if", "time_to_ack", "is", "not", "None", ":", "self", ".", "_manager", ".", "ack_histogram", ".", "add", "(", "time_to_ack", ")", "ack_ids", "=", "[", "item", ".", "ack_id", "for", "item", "in", "items", "]", "request", "=", "types", ".", "StreamingPullRequest", "(", "ack_ids", "=", "ack_ids", ")", "self", ".", "_manager", ".", "send", "(", "request", ")", "# Remove the message from lease management.", "self", ".", "drop", "(", "items", ")" ]
Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge.
[ "Acknowledge", "the", "given", "messages", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L103-L120
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.drop
def drop(self, items): """Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop. """ self._manager.leaser.remove(items) self._manager.maybe_resume_consumer()
python
def drop(self, items): """Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop. """ self._manager.leaser.remove(items) self._manager.maybe_resume_consumer()
[ "def", "drop", "(", "self", ",", "items", ")", ":", "self", ".", "_manager", ".", "leaser", ".", "remove", "(", "items", ")", "self", ".", "_manager", ".", "maybe_resume_consumer", "(", ")" ]
Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to drop.
[ "Remove", "the", "given", "messages", "from", "lease", "management", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L122-L129
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.lease
def lease(self, items): """Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease. """ self._manager.leaser.add(items) self._manager.maybe_pause_consumer()
python
def lease(self, items): """Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease. """ self._manager.leaser.add(items) self._manager.maybe_pause_consumer()
[ "def", "lease", "(", "self", ",", "items", ")", ":", "self", ".", "_manager", ".", "leaser", ".", "add", "(", "items", ")", "self", ".", "_manager", ".", "maybe_pause_consumer", "(", ")" ]
Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to lease.
[ "Add", "the", "given", "messages", "to", "lease", "management", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L131-L138
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.modify_ack_deadline
def modify_ack_deadline(self, items): """Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify. """ ack_ids = [item.ack_id for item in items] seconds = [item.seconds for item in items] request = types.StreamingPullRequest( modify_deadline_ack_ids=ack_ids, modify_deadline_seconds=seconds ) self._manager.send(request)
python
def modify_ack_deadline(self, items): """Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify. """ ack_ids = [item.ack_id for item in items] seconds = [item.seconds for item in items] request = types.StreamingPullRequest( modify_deadline_ack_ids=ack_ids, modify_deadline_seconds=seconds ) self._manager.send(request)
[ "def", "modify_ack_deadline", "(", "self", ",", "items", ")", ":", "ack_ids", "=", "[", "item", ".", "ack_id", "for", "item", "in", "items", "]", "seconds", "=", "[", "item", ".", "seconds", "for", "item", "in", "items", "]", "request", "=", "types", ".", "StreamingPullRequest", "(", "modify_deadline_ack_ids", "=", "ack_ids", ",", "modify_deadline_seconds", "=", "seconds", ")", "self", ".", "_manager", ".", "send", "(", "request", ")" ]
Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify.
[ "Modify", "the", "ack", "deadline", "for", "the", "given", "messages", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L140-L152
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py
Dispatcher.nack
def nack(self, items): """Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny. """ self.modify_ack_deadline( [requests.ModAckRequest(ack_id=item.ack_id, seconds=0) for item in items] ) self.drop([requests.DropRequest(*item) for item in items])
python
def nack(self, items): """Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny. """ self.modify_ack_deadline( [requests.ModAckRequest(ack_id=item.ack_id, seconds=0) for item in items] ) self.drop([requests.DropRequest(*item) for item in items])
[ "def", "nack", "(", "self", ",", "items", ")", ":", "self", ".", "modify_ack_deadline", "(", "[", "requests", ".", "ModAckRequest", "(", "ack_id", "=", "item", ".", "ack_id", ",", "seconds", "=", "0", ")", "for", "item", "in", "items", "]", ")", "self", ".", "drop", "(", "[", "requests", ".", "DropRequest", "(", "*", "item", ")", "for", "item", "in", "items", "]", ")" ]
Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny.
[ "Explicitly", "deny", "receipt", "of", "messages", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L154-L163
train
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py
JobControllerClient.submit_job
def submit_job( self, project_id, region, job, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> response = client.submit_job(project_id, region, job) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The job resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` 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.Job` 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 "submit_job" not in self._inner_api_calls: self._inner_api_calls[ "submit_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.submit_job, default_retry=self._method_configs["SubmitJob"].retry, default_timeout=self._method_configs["SubmitJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.SubmitJobRequest( project_id=project_id, region=region, job=job, request_id=request_id ) return self._inner_api_calls["submit_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def submit_job( self, project_id, region, job, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> response = client.submit_job(project_id, region, job) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The job resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` 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.Job` 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 "submit_job" not in self._inner_api_calls: self._inner_api_calls[ "submit_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.submit_job, default_retry=self._method_configs["SubmitJob"].retry, default_timeout=self._method_configs["SubmitJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.SubmitJobRequest( project_id=project_id, region=region, job=job, request_id=request_id ) return self._inner_api_calls["submit_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "submit_job", "(", "self", ",", "project_id", ",", "region", ",", "job", ",", "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", "\"submit_job\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"submit_job\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "submit_job", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"SubmitJob\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"SubmitJob\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "jobs_pb2", ".", "SubmitJobRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "job", "=", "job", ",", "request_id", "=", "request_id", ")", "return", "self", ".", "_inner_api_calls", "[", "\"submit_job\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> response = client.submit_job(project_id, region, job) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The job resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` request_id (str): Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` 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.Job` 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.
[ "Submits", "a", "job", "to", "a", "cluster", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py#L175-L257
train
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py
JobControllerClient.update_job
def update_job( self, project_id, region, job_id, job, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_job(project_id, region, job_id, job, update_mask) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The changes to the job. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` update_mask (Union[dict, ~google.cloud.dataproc_v1beta2.types.FieldMask]): Required. Specifies the path, relative to Job, of the field to update. For example, to update the labels of a Job the update\_mask parameter would be specified as labels, and the ``PATCH`` request body would specify the new value. Note: Currently, labels is the only field that can be updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.FieldMask` 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.Job` 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 "update_job" not in self._inner_api_calls: self._inner_api_calls[ "update_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_job, default_retry=self._method_configs["UpdateJob"].retry, default_timeout=self._method_configs["UpdateJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.UpdateJobRequest( project_id=project_id, region=region, job_id=job_id, job=job, update_mask=update_mask, ) return self._inner_api_calls["update_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_job( self, project_id, region, job_id, job, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_job(project_id, region, job_id, job, update_mask) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The changes to the job. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` update_mask (Union[dict, ~google.cloud.dataproc_v1beta2.types.FieldMask]): Required. Specifies the path, relative to Job, of the field to update. For example, to update the labels of a Job the update\_mask parameter would be specified as labels, and the ``PATCH`` request body would specify the new value. Note: Currently, labels is the only field that can be updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.FieldMask` 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.Job` 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 "update_job" not in self._inner_api_calls: self._inner_api_calls[ "update_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_job, default_retry=self._method_configs["UpdateJob"].retry, default_timeout=self._method_configs["UpdateJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.UpdateJobRequest( project_id=project_id, region=region, job_id=job_id, job=job, update_mask=update_mask, ) return self._inner_api_calls["update_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_job", "(", "self", ",", "project_id", ",", "region", ",", "job_id", ",", "job", ",", "update_mask", ",", "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", "\"update_job\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_job\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_job", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateJob\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateJob\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "jobs_pb2", ".", "UpdateJobRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "job_id", "=", "job_id", ",", "job", "=", "job", ",", "update_mask", "=", "update_mask", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"update_job\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> # TODO: Initialize `job`: >>> job = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_job(project_id, region, job_id, job, update_mask) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. job (Union[dict, ~google.cloud.dataproc_v1beta2.types.Job]): Required. The changes to the job. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.Job` update_mask (Union[dict, ~google.cloud.dataproc_v1beta2.types.FieldMask]): Required. Specifies the path, relative to Job, of the field to update. For example, to update the labels of a Job the update\_mask parameter would be specified as labels, and the ``PATCH`` request body would specify the new value. Note: Currently, labels is the only field that can be updated. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.dataproc_v1beta2.types.FieldMask` 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.Job` 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.
[ "Updates", "a", "job", "in", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py#L454-L546
train
googleapis/google-cloud-python
dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py
JobControllerClient.cancel_job
def cancel_job( self, project_id, region, job_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get>`__. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> response = client.cancel_job(project_id, region, job_id) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. 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.Job` 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 "cancel_job" not in self._inner_api_calls: self._inner_api_calls[ "cancel_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.cancel_job, default_retry=self._method_configs["CancelJob"].retry, default_timeout=self._method_configs["CancelJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.CancelJobRequest( project_id=project_id, region=region, job_id=job_id ) return self._inner_api_calls["cancel_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def cancel_job( self, project_id, region, job_id, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get>`__. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> response = client.cancel_job(project_id, region, job_id) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. 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.Job` 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 "cancel_job" not in self._inner_api_calls: self._inner_api_calls[ "cancel_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.cancel_job, default_retry=self._method_configs["CancelJob"].retry, default_timeout=self._method_configs["CancelJob"].timeout, client_info=self._client_info, ) request = jobs_pb2.CancelJobRequest( project_id=project_id, region=region, job_id=job_id ) return self._inner_api_calls["cancel_job"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "cancel_job", "(", "self", ",", "project_id", ",", "region", ",", "job_id", ",", "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", "\"cancel_job\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"cancel_job\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "cancel_job", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CancelJob\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CancelJob\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "jobs_pb2", ".", "CancelJobRequest", "(", "project_id", "=", "project_id", ",", "region", "=", "region", ",", "job_id", "=", "job_id", ")", "return", "self", ".", "_inner_api_calls", "[", "\"cancel_job\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Starts a job cancellation request. To access the job resource after cancellation, call `regions/{region}/jobs.list <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list>`__ or `regions/{region}/jobs.get <https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get>`__. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `job_id`: >>> job_id = '' >>> >>> response = client.cancel_job(project_id, region, job_id) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the job belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. job_id (str): Required. The job ID. 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.Job` 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.
[ "Starts", "a", "job", "cancellation", "request", ".", "To", "access", "the", "job", "resource", "after", "cancellation", "call", "regions", "/", "{", "region", "}", "/", "jobs", ".", "list", "<https", ":", "//", "cloud", ".", "google", ".", "com", "/", "dataproc", "/", "docs", "/", "reference", "/", "rest", "/", "v1beta2", "/", "projects", ".", "regions", ".", "jobs", "/", "list", ">", "__", "or", "regions", "/", "{", "region", "}", "/", "jobs", ".", "get", "<https", ":", "//", "cloud", ".", "google", ".", "com", "/", "dataproc", "/", "docs", "/", "reference", "/", "rest", "/", "v1beta2", "/", "projects", ".", "regions", ".", "jobs", "/", "get", ">", "__", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/dataproc/google/cloud/dataproc_v1beta2/gapic/job_controller_client.py#L548-L620
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.instance_path
def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, )
python
def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, )
[ "def", "instance_path", "(", "cls", ",", "project", ",", "instance", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", ")" ]
Return a fully-qualified instance string.
[ "Return", "a", "fully", "-", "qualified", "instance", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L93-L99
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.app_profile_path
def app_profile_path(cls, project, instance, app_profile): """Return a fully-qualified app_profile string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/appProfiles/{app_profile}", project=project, instance=instance, app_profile=app_profile, )
python
def app_profile_path(cls, project, instance, app_profile): """Return a fully-qualified app_profile string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/appProfiles/{app_profile}", project=project, instance=instance, app_profile=app_profile, )
[ "def", "app_profile_path", "(", "cls", ",", "project", ",", "instance", ",", "app_profile", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/appProfiles/{app_profile}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", "app_profile", "=", "app_profile", ",", ")" ]
Return a fully-qualified app_profile string.
[ "Return", "a", "fully", "-", "qualified", "app_profile", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L102-L109
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.cluster_path
def cluster_path(cls, project, instance, cluster): """Return a fully-qualified cluster string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/clusters/{cluster}", project=project, instance=instance, cluster=cluster, )
python
def cluster_path(cls, project, instance, cluster): """Return a fully-qualified cluster string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}/clusters/{cluster}", project=project, instance=instance, cluster=cluster, )
[ "def", "cluster_path", "(", "cls", ",", "project", ",", "instance", ",", "cluster", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}/clusters/{cluster}\"", ",", "project", "=", "project", ",", "instance", "=", "instance", ",", "cluster", "=", "cluster", ",", ")" ]
Return a fully-qualified cluster string.
[ "Return", "a", "fully", "-", "qualified", "cluster", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L112-L119
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.list_instances
def list_instances( self, parent, page_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.list_instances(parent) Args: parent (str): The unique name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_token (str): DEPRECATED: This field is unused and ignored. 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_admin_v2.types.ListInstancesResponse` 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 "list_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.ListInstancesRequest( parent=parent, page_token=page_token ) 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["list_instances"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def list_instances( self, parent, page_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.list_instances(parent) Args: parent (str): The unique name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_token (str): DEPRECATED: This field is unused and ignored. 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_admin_v2.types.ListInstancesResponse` 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 "list_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.ListInstancesRequest( parent=parent, page_token=page_token ) 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["list_instances"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "list_instances", "(", "self", ",", "parent", ",", "page_token", "=", "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_instances\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"list_instances\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "list_instances", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ListInstances\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ListInstances\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_instance_admin_pb2", ".", "ListInstancesRequest", "(", "parent", "=", "parent", ",", "page_token", "=", "page_token", ")", "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", "[", "\"list_instances\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Lists information about instances in a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> response = client.list_instances(parent) Args: parent (str): The unique name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_token (str): DEPRECATED: This field is unused and ignored. 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_admin_v2.types.ListInstancesResponse` 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.
[ "Lists", "information", "about", "instances", "in", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L413-L485
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.update_instance
def update_instance( self, name, display_name, type_, labels, state=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> from google.cloud.bigtable_admin_v2 import enums >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `display_name`: >>> display_name = '' >>> >>> # TODO: Initialize `type_`: >>> type_ = enums.Instance.Type.TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `labels`: >>> labels = {} >>> >>> response = client.update_instance(name, display_name, type_, labels) Args: name (str): (``OutputOnly``) The unique name of the instance. Values are of the form ``projects/<project>/instances/[a-z][a-z0-9\\-]+[a-z0-9]``. display_name (str): The descriptive name for this instance as it appears in UIs. Can be changed at any time, but should be kept globally unique to avoid confusion. type_ (~google.cloud.bigtable_admin_v2.types.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (dict[str -> str]): Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. They can be used to filter resources and aggregate metrics. - Label keys must be between 1 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. - Label values must be between 0 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}``. - No more than 64 labels can be associated with a given resource. - Keys and values must both be under 128 bytes. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the instance. 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_admin_v2.types.Instance` 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 "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = instance_pb2.Instance( name=name, display_name=display_name, type=type_, labels=labels, state=state ) 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["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def update_instance( self, name, display_name, type_, labels, state=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> from google.cloud.bigtable_admin_v2 import enums >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `display_name`: >>> display_name = '' >>> >>> # TODO: Initialize `type_`: >>> type_ = enums.Instance.Type.TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `labels`: >>> labels = {} >>> >>> response = client.update_instance(name, display_name, type_, labels) Args: name (str): (``OutputOnly``) The unique name of the instance. Values are of the form ``projects/<project>/instances/[a-z][a-z0-9\\-]+[a-z0-9]``. display_name (str): The descriptive name for this instance as it appears in UIs. Can be changed at any time, but should be kept globally unique to avoid confusion. type_ (~google.cloud.bigtable_admin_v2.types.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (dict[str -> str]): Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. They can be used to filter resources and aggregate metrics. - Label keys must be between 1 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. - Label values must be between 0 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}``. - No more than 64 labels can be associated with a given resource. - Keys and values must both be under 128 bytes. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the instance. 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_admin_v2.types.Instance` 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 "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = instance_pb2.Instance( name=name, display_name=display_name, type=type_, labels=labels, state=state ) 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["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "update_instance", "(", "self", ",", "name", ",", "display_name", ",", "type_", ",", "labels", ",", "state", "=", "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", "\"update_instance\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_instance\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_instance", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateInstance\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateInstance\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "instance_pb2", ".", "Instance", "(", "name", "=", "name", ",", "display_name", "=", "display_name", ",", "type", "=", "type_", ",", "labels", "=", "labels", ",", "state", "=", "state", ")", "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", "[", "\"update_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> from google.cloud.bigtable_admin_v2 import enums >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `display_name`: >>> display_name = '' >>> >>> # TODO: Initialize `type_`: >>> type_ = enums.Instance.Type.TYPE_UNSPECIFIED >>> >>> # TODO: Initialize `labels`: >>> labels = {} >>> >>> response = client.update_instance(name, display_name, type_, labels) Args: name (str): (``OutputOnly``) The unique name of the instance. Values are of the form ``projects/<project>/instances/[a-z][a-z0-9\\-]+[a-z0-9]``. display_name (str): The descriptive name for this instance as it appears in UIs. Can be changed at any time, but should be kept globally unique to avoid confusion. type_ (~google.cloud.bigtable_admin_v2.types.Type): The type of the instance. Defaults to ``PRODUCTION``. labels (dict[str -> str]): Labels are a flexible and lightweight mechanism for organizing cloud resources into groups that reflect a customer's organizational needs and deployment strategies. They can be used to filter resources and aggregate metrics. - Label keys must be between 1 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. - Label values must be between 0 and 63 characters long and must conform to the regular expression: ``[\p{Ll}\p{Lo}\p{N}_-]{0,63}``. - No more than 64 labels can be associated with a given resource. - Keys and values must both be under 128 bytes. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the instance. 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_admin_v2.types.Instance` 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.
[ "Updates", "an", "instance", "within", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L487-L588
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.partial_update_instance
def partial_update_instance( self, instance, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.partial_update_instance(instance, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.bigtable_admin_v2.types.Instance]): The Instance which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Instance` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of Instance fields which should be replaced. Must be explicitly set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` 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_admin_v2.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 "partial_update_instance" not in self._inner_api_calls: self._inner_api_calls[ "partial_update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partial_update_instance, default_retry=self._method_configs["PartialUpdateInstance"].retry, default_timeout=self._method_configs["PartialUpdateInstance"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.PartialUpdateInstanceRequest( instance=instance, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["partial_update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Instance, metadata_type=bigtable_instance_admin_pb2.UpdateInstanceMetadata, )
python
def partial_update_instance( self, instance, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.partial_update_instance(instance, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.bigtable_admin_v2.types.Instance]): The Instance which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Instance` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of Instance fields which should be replaced. Must be explicitly set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` 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_admin_v2.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 "partial_update_instance" not in self._inner_api_calls: self._inner_api_calls[ "partial_update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partial_update_instance, default_retry=self._method_configs["PartialUpdateInstance"].retry, default_timeout=self._method_configs["PartialUpdateInstance"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.PartialUpdateInstanceRequest( instance=instance, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["partial_update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Instance, metadata_type=bigtable_instance_admin_pb2.UpdateInstanceMetadata, )
[ "def", "partial_update_instance", "(", "self", ",", "instance", ",", "update_mask", ",", "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", "\"partial_update_instance\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"partial_update_instance\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "partial_update_instance", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"PartialUpdateInstance\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"PartialUpdateInstance\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_instance_admin_pb2", ".", "PartialUpdateInstanceRequest", "(", "instance", "=", "instance", ",", "update_mask", "=", "update_mask", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"instance.name\"", ",", "instance", ".", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"partial_update_instance\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "instance_pb2", ".", "Instance", ",", "metadata_type", "=", "bigtable_instance_admin_pb2", ".", "UpdateInstanceMetadata", ",", ")" ]
Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.partial_update_instance(instance, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.bigtable_admin_v2.types.Instance]): The Instance which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Instance` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of Instance fields which should be replaced. Must be explicitly set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` 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_admin_v2.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.
[ "Partially", "updates", "an", "instance", "within", "a", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L590-L687
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.create_cluster
def create_cluster( self, parent, cluster_id, cluster, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(parent, cluster_id, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the new cluster. Values are of the form ``projects/<project>/instances/<instance>``. cluster_id (str): The ID to be used when referring to the new cluster within its instance, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. cluster (Union[dict, ~google.cloud.bigtable_admin_v2.types.Cluster]): The cluster to be created. Fields marked ``OutputOnly`` must be left blank. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Cluster` 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_admin_v2.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 = bigtable_instance_admin_pb2.CreateClusterRequest( parent=parent, cluster_id=cluster_id, cluster=cluster ) 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) 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, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.CreateClusterMetadata, )
python
def create_cluster( self, parent, cluster_id, cluster, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(parent, cluster_id, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the new cluster. Values are of the form ``projects/<project>/instances/<instance>``. cluster_id (str): The ID to be used when referring to the new cluster within its instance, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. cluster (Union[dict, ~google.cloud.bigtable_admin_v2.types.Cluster]): The cluster to be created. Fields marked ``OutputOnly`` must be left blank. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Cluster` 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_admin_v2.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 = bigtable_instance_admin_pb2.CreateClusterRequest( parent=parent, cluster_id=cluster_id, cluster=cluster ) 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) 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, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.CreateClusterMetadata, )
[ "def", "create_cluster", "(", "self", ",", "parent", ",", "cluster_id", ",", "cluster", ",", "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", "=", "bigtable_instance_admin_pb2", ".", "CreateClusterRequest", "(", "parent", "=", "parent", ",", "cluster_id", "=", "cluster_id", ",", "cluster", "=", "cluster", ")", "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", ")", "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", ",", "instance_pb2", ".", "Cluster", ",", "metadata_type", "=", "bigtable_instance_admin_pb2", ".", "CreateClusterMetadata", ",", ")" ]
Creates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `cluster_id`: >>> cluster_id = '' >>> >>> # TODO: Initialize `cluster`: >>> cluster = {} >>> >>> response = client.create_cluster(parent, cluster_id, cluster) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): The unique name of the instance in which to create the new cluster. Values are of the form ``projects/<project>/instances/<instance>``. cluster_id (str): The ID to be used when referring to the new cluster within its instance, e.g., just ``mycluster`` rather than ``projects/myproject/instances/myinstance/clusters/mycluster``. cluster (Union[dict, ~google.cloud.bigtable_admin_v2.types.Cluster]): The cluster to be created. Fields marked ``OutputOnly`` must be left blank. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.Cluster` 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_admin_v2.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", "within", "an", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L756-L857
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.update_cluster
def update_cluster( self, name, serve_nodes, location=None, state=None, default_storage_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTER]') >>> >>> # TODO: Initialize `serve_nodes`: >>> serve_nodes = 0 >>> >>> response = client.update_cluster(name, serve_nodes) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): (``OutputOnly``) The unique name of the cluster. Values are of the form ``projects/<project>/instances/<instance>/clusters/[a-z][-a-z0-9]*``. serve_nodes (int): The number of nodes allocated to this cluster. More nodes enable higher throughput and more consistent performance. location (str): (``CreationOnly``) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. Currently only zones are supported, so values should be of the form ``projects/<project>/locations/<zone>``. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the cluster. default_storage_type (~google.cloud.bigtable_admin_v2.types.StorageType): (``CreationOnly``) The type of storage used by this cluster to serve its parent instance's tables, unless explicitly overridden. 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_admin_v2.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 "update_cluster" not in self._inner_api_calls: self._inner_api_calls[ "update_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_cluster, default_retry=self._method_configs["UpdateCluster"].retry, default_timeout=self._method_configs["UpdateCluster"].timeout, client_info=self._client_info, ) request = instance_pb2.Cluster( name=name, serve_nodes=serve_nodes, location=location, state=state, default_storage_type=default_storage_type, ) 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) operation = self._inner_api_calls["update_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.UpdateClusterMetadata, )
python
def update_cluster( self, name, serve_nodes, location=None, state=None, default_storage_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTER]') >>> >>> # TODO: Initialize `serve_nodes`: >>> serve_nodes = 0 >>> >>> response = client.update_cluster(name, serve_nodes) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): (``OutputOnly``) The unique name of the cluster. Values are of the form ``projects/<project>/instances/<instance>/clusters/[a-z][-a-z0-9]*``. serve_nodes (int): The number of nodes allocated to this cluster. More nodes enable higher throughput and more consistent performance. location (str): (``CreationOnly``) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. Currently only zones are supported, so values should be of the form ``projects/<project>/locations/<zone>``. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the cluster. default_storage_type (~google.cloud.bigtable_admin_v2.types.StorageType): (``CreationOnly``) The type of storage used by this cluster to serve its parent instance's tables, unless explicitly overridden. 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_admin_v2.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 "update_cluster" not in self._inner_api_calls: self._inner_api_calls[ "update_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_cluster, default_retry=self._method_configs["UpdateCluster"].retry, default_timeout=self._method_configs["UpdateCluster"].timeout, client_info=self._client_info, ) request = instance_pb2.Cluster( name=name, serve_nodes=serve_nodes, location=location, state=state, default_storage_type=default_storage_type, ) 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) operation = self._inner_api_calls["update_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.Cluster, metadata_type=bigtable_instance_admin_pb2.UpdateClusterMetadata, )
[ "def", "update_cluster", "(", "self", ",", "name", ",", "serve_nodes", ",", "location", "=", "None", ",", "state", "=", "None", ",", "default_storage_type", "=", "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", "\"update_cluster\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_cluster\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_cluster", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateCluster\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateCluster\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "instance_pb2", ".", "Cluster", "(", "name", "=", "name", ",", "serve_nodes", "=", "serve_nodes", ",", "location", "=", "location", ",", "state", "=", "state", ",", "default_storage_type", "=", "default_storage_type", ",", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"update_cluster\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "instance_pb2", ".", "Cluster", ",", "metadata_type", "=", "bigtable_instance_admin_pb2", ".", "UpdateClusterMetadata", ",", ")" ]
Updates a cluster within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> name = client.cluster_path('[PROJECT]', '[INSTANCE]', '[CLUSTER]') >>> >>> # TODO: Initialize `serve_nodes`: >>> serve_nodes = 0 >>> >>> response = client.update_cluster(name, serve_nodes) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): (``OutputOnly``) The unique name of the cluster. Values are of the form ``projects/<project>/instances/<instance>/clusters/[a-z][-a-z0-9]*``. serve_nodes (int): The number of nodes allocated to this cluster. More nodes enable higher throughput and more consistent performance. location (str): (``CreationOnly``) The location where this cluster's nodes and storage reside. For best performance, clients should be located as close as possible to this cluster. Currently only zones are supported, so values should be of the form ``projects/<project>/locations/<zone>``. state (~google.cloud.bigtable_admin_v2.types.State): (``OutputOnly``) The current state of the cluster. default_storage_type (~google.cloud.bigtable_admin_v2.types.StorageType): (``CreationOnly``) The type of storage used by this cluster to serve its parent instance's tables, unless explicitly overridden. 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_admin_v2.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.
[ "Updates", "a", "cluster", "within", "an", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L1006-L1111
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.create_app_profile
def create_app_profile( self, parent, app_profile_id, app_profile, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `app_profile_id`: >>> app_profile_id = '' >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> response = client.create_app_profile(parent, app_profile_id, app_profile) Args: parent (str): The unique name of the instance in which to create the new app profile. Values are of the form ``projects/<project>/instances/<instance>``. app_profile_id (str): The ID to be used when referring to the new app profile within its instance, e.g., just ``myprofile`` rather than ``projects/myproject/instances/myinstance/appProfiles/myprofile``. app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile to be created. Fields marked ``OutputOnly`` will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` ignore_warnings (bool): If true, ignore safety checks when creating the app profile. 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_admin_v2.types.AppProfile` 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_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "create_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_app_profile, default_retry=self._method_configs["CreateAppProfile"].retry, default_timeout=self._method_configs["CreateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.CreateAppProfileRequest( parent=parent, app_profile_id=app_profile_id, app_profile=app_profile, ignore_warnings=ignore_warnings, ) 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_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_app_profile( self, parent, app_profile_id, app_profile, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `app_profile_id`: >>> app_profile_id = '' >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> response = client.create_app_profile(parent, app_profile_id, app_profile) Args: parent (str): The unique name of the instance in which to create the new app profile. Values are of the form ``projects/<project>/instances/<instance>``. app_profile_id (str): The ID to be used when referring to the new app profile within its instance, e.g., just ``myprofile`` rather than ``projects/myproject/instances/myinstance/appProfiles/myprofile``. app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile to be created. Fields marked ``OutputOnly`` will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` ignore_warnings (bool): If true, ignore safety checks when creating the app profile. 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_admin_v2.types.AppProfile` 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_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "create_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_app_profile, default_retry=self._method_configs["CreateAppProfile"].retry, default_timeout=self._method_configs["CreateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.CreateAppProfileRequest( parent=parent, app_profile_id=app_profile_id, app_profile=app_profile, ignore_warnings=ignore_warnings, ) 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_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_app_profile", "(", "self", ",", "parent", ",", "app_profile_id", ",", "app_profile", ",", "ignore_warnings", "=", "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_app_profile\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_app_profile\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_app_profile", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateAppProfile\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateAppProfile\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_instance_admin_pb2", ".", "CreateAppProfileRequest", "(", "parent", "=", "parent", ",", "app_profile_id", "=", "app_profile_id", ",", "app_profile", "=", "app_profile", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")", "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_app_profile\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> # TODO: Initialize `app_profile_id`: >>> app_profile_id = '' >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> response = client.create_app_profile(parent, app_profile_id, app_profile) Args: parent (str): The unique name of the instance in which to create the new app profile. Values are of the form ``projects/<project>/instances/<instance>``. app_profile_id (str): The ID to be used when referring to the new app profile within its instance, e.g., just ``myprofile`` rather than ``projects/myproject/instances/myinstance/appProfiles/myprofile``. app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile to be created. Fields marked ``OutputOnly`` will be ignored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` ignore_warnings (bool): If true, ignore safety checks when creating the app profile. 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_admin_v2.types.AppProfile` 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", "an", "app", "profile", "within", "an", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L1180-L1271
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py
BigtableInstanceAdminClient.update_app_profile
def update_app_profile( self, app_profile, update_mask, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_app_profile(app_profile, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of app profile fields which should be replaced. If unset, all fields will be replaced. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` ignore_warnings (bool): If true, ignore safety checks when updating the app profile. 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_admin_v2.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 "update_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "update_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_app_profile, default_retry=self._method_configs["UpdateAppProfile"].retry, default_timeout=self._method_configs["UpdateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.UpdateAppProfileRequest( app_profile=app_profile, update_mask=update_mask, ignore_warnings=ignore_warnings, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("app_profile.name", app_profile.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.AppProfile, metadata_type=bigtable_instance_admin_pb2.UpdateAppProfileMetadata, )
python
def update_app_profile( self, app_profile, update_mask, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_app_profile(app_profile, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of app profile fields which should be replaced. If unset, all fields will be replaced. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` ignore_warnings (bool): If true, ignore safety checks when updating the app profile. 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_admin_v2.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 "update_app_profile" not in self._inner_api_calls: self._inner_api_calls[ "update_app_profile" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_app_profile, default_retry=self._method_configs["UpdateAppProfile"].retry, default_timeout=self._method_configs["UpdateAppProfile"].timeout, client_info=self._client_info, ) request = bigtable_instance_admin_pb2.UpdateAppProfileRequest( app_profile=app_profile, update_mask=update_mask, ignore_warnings=ignore_warnings, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("app_profile.name", app_profile.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_app_profile"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instance_pb2.AppProfile, metadata_type=bigtable_instance_admin_pb2.UpdateAppProfileMetadata, )
[ "def", "update_app_profile", "(", "self", ",", "app_profile", ",", "update_mask", ",", "ignore_warnings", "=", "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", "\"update_app_profile\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"update_app_profile\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "update_app_profile", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"UpdateAppProfile\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"UpdateAppProfile\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "bigtable_instance_admin_pb2", ".", "UpdateAppProfileRequest", "(", "app_profile", "=", "app_profile", ",", "update_mask", "=", "update_mask", ",", "ignore_warnings", "=", "ignore_warnings", ",", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"app_profile.name\"", ",", "app_profile", ".", "name", ")", "]", "except", "AttributeError", ":", "pass", "else", ":", "routing_metadata", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "routing_header", ")", "metadata", ".", "append", "(", "routing_metadata", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"update_app_profile\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "instance_pb2", ".", "AppProfile", ",", "metadata_type", "=", "bigtable_instance_admin_pb2", ".", "UpdateAppProfileMetadata", ",", ")" ]
Updates an app profile within an instance. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `app_profile`: >>> app_profile = {} >>> >>> # TODO: Initialize `update_mask`: >>> update_mask = {} >>> >>> response = client.update_app_profile(app_profile, update_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: app_profile (Union[dict, ~google.cloud.bigtable_admin_v2.types.AppProfile]): The app profile which will (partially) replace the current value. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.AppProfile` update_mask (Union[dict, ~google.cloud.bigtable_admin_v2.types.FieldMask]): The subset of app profile fields which should be replaced. If unset, all fields will be replaced. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigtable_admin_v2.types.FieldMask` ignore_warnings (bool): If true, ignore safety checks when updating the app profile. 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_admin_v2.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.
[ "Updates", "an", "app", "profile", "within", "an", "instance", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable_admin_v2/gapic/bigtable_instance_admin_client.py#L1447-L1548
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.annotation_spec_set_path
def annotation_spec_set_path(cls, project, annotation_spec_set): """Return a fully-qualified annotation_spec_set string.""" return google.api_core.path_template.expand( "projects/{project}/annotationSpecSets/{annotation_spec_set}", project=project, annotation_spec_set=annotation_spec_set, )
python
def annotation_spec_set_path(cls, project, annotation_spec_set): """Return a fully-qualified annotation_spec_set string.""" return google.api_core.path_template.expand( "projects/{project}/annotationSpecSets/{annotation_spec_set}", project=project, annotation_spec_set=annotation_spec_set, )
[ "def", "annotation_spec_set_path", "(", "cls", ",", "project", ",", "annotation_spec_set", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/annotationSpecSets/{annotation_spec_set}\"", ",", "project", "=", "project", ",", "annotation_spec_set", "=", "annotation_spec_set", ",", ")" ]
Return a fully-qualified annotation_spec_set string.
[ "Return", "a", "fully", "-", "qualified", "annotation_spec_set", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L93-L99
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.dataset_path
def dataset_path(cls, project, dataset): """Return a fully-qualified dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}", project=project, dataset=dataset )
python
def dataset_path(cls, project, dataset): """Return a fully-qualified dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}", project=project, dataset=dataset )
[ "def", "dataset_path", "(", "cls", ",", "project", ",", "dataset", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/datasets/{dataset}\"", ",", "project", "=", "project", ",", "dataset", "=", "dataset", ")" ]
Return a fully-qualified dataset string.
[ "Return", "a", "fully", "-", "qualified", "dataset", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L102-L106
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.annotated_dataset_path
def annotated_dataset_path(cls, project, dataset, annotated_dataset): """Return a fully-qualified annotated_dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, )
python
def annotated_dataset_path(cls, project, dataset, annotated_dataset): """Return a fully-qualified annotated_dataset string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, )
[ "def", "annotated_dataset_path", "(", "cls", ",", "project", ",", "dataset", ",", "annotated_dataset", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}\"", ",", "project", "=", "project", ",", "dataset", "=", "dataset", ",", "annotated_dataset", "=", "annotated_dataset", ",", ")" ]
Return a fully-qualified annotated_dataset string.
[ "Return", "a", "fully", "-", "qualified", "annotated_dataset", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L109-L116
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.example_path
def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, )
python
def example_path(cls, project, dataset, annotated_dataset, example): """Return a fully-qualified example string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}", project=project, dataset=dataset, annotated_dataset=annotated_dataset, example=example, )
[ "def", "example_path", "(", "cls", ",", "project", ",", "dataset", ",", "annotated_dataset", ",", "example", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}\"", ",", "project", "=", "project", ",", "dataset", "=", "dataset", ",", "annotated_dataset", "=", "annotated_dataset", ",", "example", "=", "example", ",", ")" ]
Return a fully-qualified example string.
[ "Return", "a", "fully", "-", "qualified", "example", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L119-L127
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.data_item_path
def data_item_path(cls, project, dataset, data_item): """Return a fully-qualified data_item string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/dataItems/{data_item}", project=project, dataset=dataset, data_item=data_item, )
python
def data_item_path(cls, project, dataset, data_item): """Return a fully-qualified data_item string.""" return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}/dataItems/{data_item}", project=project, dataset=dataset, data_item=data_item, )
[ "def", "data_item_path", "(", "cls", ",", "project", ",", "dataset", ",", "data_item", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/datasets/{dataset}/dataItems/{data_item}\"", ",", "project", "=", "project", ",", "dataset", "=", "dataset", ",", "data_item", "=", "data_item", ",", ")" ]
Return a fully-qualified data_item string.
[ "Return", "a", "fully", "-", "qualified", "data_item", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L130-L137
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.instruction_path
def instruction_path(cls, project, instruction): """Return a fully-qualified instruction string.""" return google.api_core.path_template.expand( "projects/{project}/instructions/{instruction}", project=project, instruction=instruction, )
python
def instruction_path(cls, project, instruction): """Return a fully-qualified instruction string.""" return google.api_core.path_template.expand( "projects/{project}/instructions/{instruction}", project=project, instruction=instruction, )
[ "def", "instruction_path", "(", "cls", ",", "project", ",", "instruction", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instructions/{instruction}\"", ",", "project", "=", "project", ",", "instruction", "=", "instruction", ",", ")" ]
Return a fully-qualified instruction string.
[ "Return", "a", "fully", "-", "qualified", "instruction", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L140-L146
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.export_data
def export_data( self, name, annotated_dataset, output_config, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `annotated_dataset`: >>> annotated_dataset = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_data(name, annotated_dataset, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): Required. Dataset resource name, format: projects/{project\_id}/datasets/{dataset\_id} annotated_dataset (str): Required. Annotated dataset resource name. DataItem in Dataset and their annotations in specified annotated dataset will be exported. It's in format of projects/{project\_id}/datasets/{dataset\_id}/annotatedDatasets/ {annotated\_dataset\_id} output_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.OutputConfig]): Required. Specify the output destination. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.OutputConfig` filter_ (str): Optional. Filter is not supported at this moment. 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.datalabeling_v1beta1.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 "export_data" not in self._inner_api_calls: self._inner_api_calls[ "export_data" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_data, default_retry=self._method_configs["ExportData"].retry, default_timeout=self._method_configs["ExportData"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.ExportDataRequest( name=name, annotated_dataset=annotated_dataset, output_config=output_config, filter=filter_, ) 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) operation = self._inner_api_calls["export_data"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, proto_operations_pb2.ExportDataOperationResponse, metadata_type=proto_operations_pb2.ExportDataOperationMetadata, )
python
def export_data( self, name, annotated_dataset, output_config, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `annotated_dataset`: >>> annotated_dataset = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_data(name, annotated_dataset, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): Required. Dataset resource name, format: projects/{project\_id}/datasets/{dataset\_id} annotated_dataset (str): Required. Annotated dataset resource name. DataItem in Dataset and their annotations in specified annotated dataset will be exported. It's in format of projects/{project\_id}/datasets/{dataset\_id}/annotatedDatasets/ {annotated\_dataset\_id} output_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.OutputConfig]): Required. Specify the output destination. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.OutputConfig` filter_ (str): Optional. Filter is not supported at this moment. 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.datalabeling_v1beta1.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 "export_data" not in self._inner_api_calls: self._inner_api_calls[ "export_data" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.export_data, default_retry=self._method_configs["ExportData"].retry, default_timeout=self._method_configs["ExportData"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.ExportDataRequest( name=name, annotated_dataset=annotated_dataset, output_config=output_config, filter=filter_, ) 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) operation = self._inner_api_calls["export_data"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, proto_operations_pb2.ExportDataOperationResponse, metadata_type=proto_operations_pb2.ExportDataOperationMetadata, )
[ "def", "export_data", "(", "self", ",", "name", ",", "annotated_dataset", ",", "output_config", ",", "filter_", "=", "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", "\"export_data\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"export_data\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "export_data", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"ExportData\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"ExportData\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "data_labeling_service_pb2", ".", "ExportDataRequest", "(", "name", "=", "name", ",", "annotated_dataset", "=", "annotated_dataset", ",", "output_config", "=", "output_config", ",", "filter", "=", "filter_", ",", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"export_data\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "proto_operations_pb2", ".", "ExportDataOperationResponse", ",", "metadata_type", "=", "proto_operations_pb2", ".", "ExportDataOperationMetadata", ",", ")" ]
Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `annotated_dataset`: >>> annotated_dataset = '' >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.export_data(name, annotated_dataset, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: name (str): Required. Dataset resource name, format: projects/{project\_id}/datasets/{dataset\_id} annotated_dataset (str): Required. Annotated dataset resource name. DataItem in Dataset and their annotations in specified annotated dataset will be exported. It's in format of projects/{project\_id}/datasets/{dataset\_id}/annotatedDatasets/ {annotated\_dataset\_id} output_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.OutputConfig]): Required. Specify the output destination. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.OutputConfig` filter_ (str): Optional. Filter is not supported at this moment. 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.datalabeling_v1beta1.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.
[ "Exports", "data", "and", "annotations", "from", "dataset", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L667-L774
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.label_image
def label_image( self, parent, basic_config, feature, image_classification_config=None, bounding_poly_config=None, polyline_config=None, segmentation_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for image. The type of image labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelImageRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_image(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of image labeling task. image_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig]): Configuration for image classification task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig` bounding_poly_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig]): Configuration for bounding box and bounding poly task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig` polyline_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.PolylineConfig]): Configuration for polyline task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.PolylineConfig` segmentation_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.SegmentationConfig]): Configuration for segmentation task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.SegmentationConfig` 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.datalabeling_v1beta1.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 "label_image" not in self._inner_api_calls: self._inner_api_calls[ "label_image" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_image, default_retry=self._method_configs["LabelImage"].retry, default_timeout=self._method_configs["LabelImage"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_config, ) request = data_labeling_service_pb2.LabelImageRequest( parent=parent, basic_config=basic_config, feature=feature, image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_config, ) 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) operation = self._inner_api_calls["label_image"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
python
def label_image( self, parent, basic_config, feature, image_classification_config=None, bounding_poly_config=None, polyline_config=None, segmentation_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for image. The type of image labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelImageRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_image(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of image labeling task. image_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig]): Configuration for image classification task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig` bounding_poly_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig]): Configuration for bounding box and bounding poly task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig` polyline_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.PolylineConfig]): Configuration for polyline task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.PolylineConfig` segmentation_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.SegmentationConfig]): Configuration for segmentation task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.SegmentationConfig` 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.datalabeling_v1beta1.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 "label_image" not in self._inner_api_calls: self._inner_api_calls[ "label_image" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_image, default_retry=self._method_configs["LabelImage"].retry, default_timeout=self._method_configs["LabelImage"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_config, ) request = data_labeling_service_pb2.LabelImageRequest( parent=parent, basic_config=basic_config, feature=feature, image_classification_config=image_classification_config, bounding_poly_config=bounding_poly_config, polyline_config=polyline_config, segmentation_config=segmentation_config, ) 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) operation = self._inner_api_calls["label_image"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
[ "def", "label_image", "(", "self", ",", "parent", ",", "basic_config", ",", "feature", ",", "image_classification_config", "=", "None", ",", "bounding_poly_config", "=", "None", ",", "polyline_config", "=", "None", ",", "segmentation_config", "=", "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", "\"label_image\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"label_image\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "label_image", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"LabelImage\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"LabelImage\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "image_classification_config", "=", "image_classification_config", ",", "bounding_poly_config", "=", "bounding_poly_config", ",", "polyline_config", "=", "polyline_config", ",", "segmentation_config", "=", "segmentation_config", ",", ")", "request", "=", "data_labeling_service_pb2", ".", "LabelImageRequest", "(", "parent", "=", "parent", ",", "basic_config", "=", "basic_config", ",", "feature", "=", "feature", ",", "image_classification_config", "=", "image_classification_config", ",", "bounding_poly_config", "=", "bounding_poly_config", ",", "polyline_config", "=", "polyline_config", ",", "segmentation_config", "=", "segmentation_config", ",", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"label_image\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "dataset_pb2", ".", "AnnotatedDataset", ",", "metadata_type", "=", "proto_operations_pb2", ".", "LabelOperationMetadata", ",", ")" ]
Starts a labeling task for image. The type of image labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelImageRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_image(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of image labeling task. image_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig]): Configuration for image classification task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ImageClassificationConfig` bounding_poly_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig]): Configuration for bounding box and bounding poly task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.BoundingPolyConfig` polyline_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.PolylineConfig]): Configuration for polyline task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.PolylineConfig` segmentation_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.SegmentationConfig]): Configuration for segmentation task. One of image\_classification\_config, bounding\_poly\_config, polyline\_config and segmentation\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.SegmentationConfig` 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.datalabeling_v1beta1.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.
[ "Starts", "a", "labeling", "task", "for", "image", ".", "The", "type", "of", "image", "labeling", "task", "is", "configured", "by", "feature", "in", "the", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L1131-L1274
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.label_video
def label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for video. The type of video labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelVideoRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_video(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of video labeling task. video_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig]): Configuration for video classification task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig` object_detection_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig]): Configuration for video object detection task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig` object_tracking_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig]): Configuration for video object tracking task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig` event_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.EventConfig]): Configuration for video event task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.EventConfig` 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.datalabeling_v1beta1.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 "label_video" not in self._inner_api_calls: self._inner_api_calls[ "label_video" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_video, default_retry=self._method_configs["LabelVideo"].retry, default_timeout=self._method_configs["LabelVideo"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_config, ) request = data_labeling_service_pb2.LabelVideoRequest( parent=parent, basic_config=basic_config, feature=feature, video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_config, ) 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) operation = self._inner_api_calls["label_video"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
python
def label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for video. The type of video labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelVideoRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_video(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of video labeling task. video_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig]): Configuration for video classification task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig` object_detection_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig]): Configuration for video object detection task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig` object_tracking_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig]): Configuration for video object tracking task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig` event_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.EventConfig]): Configuration for video event task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.EventConfig` 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.datalabeling_v1beta1.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 "label_video" not in self._inner_api_calls: self._inner_api_calls[ "label_video" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_video, default_retry=self._method_configs["LabelVideo"].retry, default_timeout=self._method_configs["LabelVideo"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_config, ) request = data_labeling_service_pb2.LabelVideoRequest( parent=parent, basic_config=basic_config, feature=feature, video_classification_config=video_classification_config, object_detection_config=object_detection_config, object_tracking_config=object_tracking_config, event_config=event_config, ) 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) operation = self._inner_api_calls["label_video"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
[ "def", "label_video", "(", "self", ",", "parent", ",", "basic_config", ",", "feature", ",", "video_classification_config", "=", "None", ",", "object_detection_config", "=", "None", ",", "object_tracking_config", "=", "None", ",", "event_config", "=", "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", "\"label_video\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"label_video\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "label_video", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"LabelVideo\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"LabelVideo\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "video_classification_config", "=", "video_classification_config", ",", "object_detection_config", "=", "object_detection_config", ",", "object_tracking_config", "=", "object_tracking_config", ",", "event_config", "=", "event_config", ",", ")", "request", "=", "data_labeling_service_pb2", ".", "LabelVideoRequest", "(", "parent", "=", "parent", ",", "basic_config", "=", "basic_config", ",", "feature", "=", "feature", ",", "video_classification_config", "=", "video_classification_config", ",", "object_detection_config", "=", "object_detection_config", ",", "object_tracking_config", "=", "object_tracking_config", ",", "event_config", "=", "event_config", ",", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"label_video\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "dataset_pb2", ".", "AnnotatedDataset", ",", "metadata_type", "=", "proto_operations_pb2", ".", "LabelOperationMetadata", ",", ")" ]
Starts a labeling task for video. The type of video labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelVideoRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_video(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the dataset to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of video labeling task. video_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig]): Configuration for video classification task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.VideoClassificationConfig` object_detection_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig]): Configuration for video object detection task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectDetectionConfig` object_tracking_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig]): Configuration for video object tracking task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.ObjectTrackingConfig` event_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.EventConfig]): Configuration for video event task. One of video\_classification\_config, object\_detection\_config, object\_tracking\_config and event\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.EventConfig` 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.datalabeling_v1beta1.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.
[ "Starts", "a", "labeling", "task", "for", "video", ".", "The", "type", "of", "video", "labeling", "task", "is", "configured", "by", "feature", "in", "the", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L1276-L1419
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.label_text
def label_text( self, parent, basic_config, feature, text_classification_config=None, text_entity_extraction_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for text. The type of text labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelTextRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_text(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the data set to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of text labeling task. text_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig]): Configuration for text classification task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig` text_entity_extraction_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig]): Configuration for entity extraction task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig` 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.datalabeling_v1beta1.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 "label_text" not in self._inner_api_calls: self._inner_api_calls[ "label_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_text, default_retry=self._method_configs["LabelText"].retry, default_timeout=self._method_configs["LabelText"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_config, ) request = data_labeling_service_pb2.LabelTextRequest( parent=parent, basic_config=basic_config, feature=feature, text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_config, ) 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) operation = self._inner_api_calls["label_text"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
python
def label_text( self, parent, basic_config, feature, text_classification_config=None, text_entity_extraction_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Starts a labeling task for text. The type of text labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelTextRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_text(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the data set to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of text labeling task. text_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig]): Configuration for text classification task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig` text_entity_extraction_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig]): Configuration for entity extraction task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig` 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.datalabeling_v1beta1.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 "label_text" not in self._inner_api_calls: self._inner_api_calls[ "label_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.label_text, default_retry=self._method_configs["LabelText"].retry, default_timeout=self._method_configs["LabelText"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof( text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_config, ) request = data_labeling_service_pb2.LabelTextRequest( parent=parent, basic_config=basic_config, feature=feature, text_classification_config=text_classification_config, text_entity_extraction_config=text_entity_extraction_config, ) 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) operation = self._inner_api_calls["label_text"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, dataset_pb2.AnnotatedDataset, metadata_type=proto_operations_pb2.LabelOperationMetadata, )
[ "def", "label_text", "(", "self", ",", "parent", ",", "basic_config", ",", "feature", ",", "text_classification_config", "=", "None", ",", "text_entity_extraction_config", "=", "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", "\"label_text\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"label_text\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "label_text", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"LabelText\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"LabelText\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "text_classification_config", "=", "text_classification_config", ",", "text_entity_extraction_config", "=", "text_entity_extraction_config", ",", ")", "request", "=", "data_labeling_service_pb2", ".", "LabelTextRequest", "(", "parent", "=", "parent", ",", "basic_config", "=", "basic_config", ",", "feature", "=", "feature", ",", "text_classification_config", "=", "text_classification_config", ",", "text_entity_extraction_config", "=", "text_entity_extraction_config", ",", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"label_text\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "dataset_pb2", ".", "AnnotatedDataset", ",", "metadata_type", "=", "proto_operations_pb2", ".", "LabelOperationMetadata", ",", ")" ]
Starts a labeling task for text. The type of text labeling task is configured by feature in the request. Example: >>> from google.cloud import datalabeling_v1beta1 >>> from google.cloud.datalabeling_v1beta1 import enums >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.dataset_path('[PROJECT]', '[DATASET]') >>> >>> # TODO: Initialize `basic_config`: >>> basic_config = {} >>> >>> # TODO: Initialize `feature`: >>> feature = enums.LabelTextRequest.Feature.FEATURE_UNSPECIFIED >>> >>> response = client.label_text(parent, basic_config, feature) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Name of the data set to request labeling task, format: projects/{project\_id}/datasets/{dataset\_id} basic_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig]): Required. Basic human annotation config. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.HumanAnnotationConfig` feature (~google.cloud.datalabeling_v1beta1.types.Feature): Required. The type of text labeling task. text_classification_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig]): Configuration for text classification task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextClassificationConfig` text_entity_extraction_config (Union[dict, ~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig]): Configuration for entity extraction task. One of text\_classification\_config and text\_entity\_extraction\_config is required. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.TextEntityExtractionConfig` 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.datalabeling_v1beta1.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.
[ "Starts", "a", "labeling", "task", "for", "text", ".", "The", "type", "of", "text", "labeling", "task", "is", "configured", "by", "feature", "in", "the", "request", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L1421-L1546
train
googleapis/google-cloud-python
datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py
DataLabelingServiceClient.create_instruction
def create_instruction( self, parent, instruction, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instruction for how data should be labeled. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instruction`: >>> instruction = {} >>> >>> response = client.create_instruction(parent, instruction) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Instruction resource parent, format: projects/{project\_id} instruction (Union[dict, ~google.cloud.datalabeling_v1beta1.types.Instruction]): Required. Instruction of how to perform the labeling task. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.Instruction` 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.datalabeling_v1beta1.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_instruction" not in self._inner_api_calls: self._inner_api_calls[ "create_instruction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instruction, default_retry=self._method_configs["CreateInstruction"].retry, default_timeout=self._method_configs["CreateInstruction"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.CreateInstructionRequest( parent=parent, instruction=instruction ) 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) operation = self._inner_api_calls["create_instruction"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instruction_pb2.Instruction, metadata_type=proto_operations_pb2.CreateInstructionMetadata, )
python
def create_instruction( self, parent, instruction, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instruction for how data should be labeled. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instruction`: >>> instruction = {} >>> >>> response = client.create_instruction(parent, instruction) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Instruction resource parent, format: projects/{project\_id} instruction (Union[dict, ~google.cloud.datalabeling_v1beta1.types.Instruction]): Required. Instruction of how to perform the labeling task. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.Instruction` 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.datalabeling_v1beta1.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_instruction" not in self._inner_api_calls: self._inner_api_calls[ "create_instruction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instruction, default_retry=self._method_configs["CreateInstruction"].retry, default_timeout=self._method_configs["CreateInstruction"].timeout, client_info=self._client_info, ) request = data_labeling_service_pb2.CreateInstructionRequest( parent=parent, instruction=instruction ) 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) operation = self._inner_api_calls["create_instruction"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, instruction_pb2.Instruction, metadata_type=proto_operations_pb2.CreateInstructionMetadata, )
[ "def", "create_instruction", "(", "self", ",", "parent", ",", "instruction", ",", "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_instruction\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_instruction\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_instruction", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateInstruction\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateInstruction\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "data_labeling_service_pb2", ".", "CreateInstructionRequest", "(", "parent", "=", "parent", ",", "instruction", "=", "instruction", ")", "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", ")", "operation", "=", "self", ".", "_inner_api_calls", "[", "\"create_instruction\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")", "return", "google", ".", "api_core", ".", "operation", ".", "from_gapic", "(", "operation", ",", "self", ".", "transport", ".", "_operations_client", ",", "instruction_pb2", ".", "Instruction", ",", "metadata_type", "=", "proto_operations_pb2", ".", "CreateInstructionMetadata", ",", ")" ]
Creates an instruction for how data should be labeled. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instruction`: >>> instruction = {} >>> >>> response = client.create_instruction(parent, instruction) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. Instruction resource parent, format: projects/{project\_id} instruction (Union[dict, ~google.cloud.datalabeling_v1beta1.types.Instruction]): Required. Instruction of how to perform the labeling task. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.datalabeling_v1beta1.types.Instruction` 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.datalabeling_v1beta1.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", "an", "instruction", "for", "how", "data", "should", "be", "labeled", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L2157-L2249
train
googleapis/google-cloud-python
runtimeconfig/google/cloud/runtimeconfig/variable.py
Variable.from_api_repr
def from_api_repr(cls, resource, config): """Factory: construct a Variable given its API representation :type resource: dict :param resource: change set representation returned from the API. :type config: :class:`google.cloud.runtimeconfig.config.Config` :param config: The config to which this variable belongs. :rtype: :class:`google.cloud.runtimeconfig.variable.Variable` :returns: Variable parsed from ``resource``. """ name = variable_name_from_full_name(resource.get("name")) variable = cls(name=name, config=config) variable._set_properties(resource=resource) return variable
python
def from_api_repr(cls, resource, config): """Factory: construct a Variable given its API representation :type resource: dict :param resource: change set representation returned from the API. :type config: :class:`google.cloud.runtimeconfig.config.Config` :param config: The config to which this variable belongs. :rtype: :class:`google.cloud.runtimeconfig.variable.Variable` :returns: Variable parsed from ``resource``. """ name = variable_name_from_full_name(resource.get("name")) variable = cls(name=name, config=config) variable._set_properties(resource=resource) return variable
[ "def", "from_api_repr", "(", "cls", ",", "resource", ",", "config", ")", ":", "name", "=", "variable_name_from_full_name", "(", "resource", ".", "get", "(", "\"name\"", ")", ")", "variable", "=", "cls", "(", "name", "=", "name", ",", "config", "=", "config", ")", "variable", ".", "_set_properties", "(", "resource", "=", "resource", ")", "return", "variable" ]
Factory: construct a Variable given its API representation :type resource: dict :param resource: change set representation returned from the API. :type config: :class:`google.cloud.runtimeconfig.config.Config` :param config: The config to which this variable belongs. :rtype: :class:`google.cloud.runtimeconfig.variable.Variable` :returns: Variable parsed from ``resource``.
[ "Factory", ":", "construct", "a", "Variable", "given", "its", "API", "representation" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/variable.py#L73-L88
train
googleapis/google-cloud-python
runtimeconfig/google/cloud/runtimeconfig/variable.py
Variable.full_name
def full_name(self): """Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config/variables/my-var`` :rtype: str :returns: The full name based on config and variable names. :raises: :class:`ValueError` if the variable is missing a name. """ if not self.name: raise ValueError("Missing variable name.") return "%s/variables/%s" % (self.config.full_name, self.name)
python
def full_name(self): """Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config/variables/my-var`` :rtype: str :returns: The full name based on config and variable names. :raises: :class:`ValueError` if the variable is missing a name. """ if not self.name: raise ValueError("Missing variable name.") return "%s/variables/%s" % (self.config.full_name, self.name)
[ "def", "full_name", "(", "self", ")", ":", "if", "not", "self", ".", "name", ":", "raise", "ValueError", "(", "\"Missing variable name.\"", ")", "return", "\"%s/variables/%s\"", "%", "(", "self", ".", "config", ".", "full_name", ",", "self", ".", "name", ")" ]
Fully-qualified name of this variable. Example: ``projects/my-project/configs/my-config/variables/my-var`` :rtype: str :returns: The full name based on config and variable names. :raises: :class:`ValueError` if the variable is missing a name.
[ "Fully", "-", "qualified", "name", "of", "this", "variable", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/variable.py#L91-L104
train
googleapis/google-cloud-python
runtimeconfig/google/cloud/runtimeconfig/variable.py
Variable.value
def value(self): """Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: bytes or ``NoneType`` :returns: The value of the variable or ``None`` if the property is not set locally. """ value = self._properties.get("value") if value is not None: value = base64.b64decode(value) return value
python
def value(self): """Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: bytes or ``NoneType`` :returns: The value of the variable or ``None`` if the property is not set locally. """ value = self._properties.get("value") if value is not None: value = base64.b64decode(value) return value
[ "def", "value", "(", "self", ")", ":", "value", "=", "self", ".", "_properties", ".", "get", "(", "\"value\"", ")", "if", "value", "is", "not", "None", ":", "value", "=", "base64", ".", "b64decode", "(", "value", ")", "return", "value" ]
Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: bytes or ``NoneType`` :returns: The value of the variable or ``None`` if the property is not set locally.
[ "Value", "of", "the", "variable", "as", "bytes", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/variable.py#L121-L134
train
googleapis/google-cloud-python
runtimeconfig/google/cloud/runtimeconfig/variable.py
Variable.update_time
def update_time(self): """Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables Returns: :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`, :class:`datetime.datetime` or ``NoneType``: Datetime object parsed from RFC3339 valid timestamp, or ``None`` if the property is not set locally. Raises: ValueError: if value is not a valid RFC3339 timestamp """ value = self._properties.get("updateTime") if value is not None: try: value = datetime.datetime.strptime( value, datetime_helpers._RFC3339_MICROS ) except ValueError: DatetimeNS = datetime_helpers.DatetimeWithNanoseconds value = DatetimeNS.from_rfc3339(value) naive = value.tzinfo is None or value.tzinfo.utcoffset(value) is None if naive: value = pytz.utc.localize(value) return value
python
def update_time(self): """Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables Returns: :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`, :class:`datetime.datetime` or ``NoneType``: Datetime object parsed from RFC3339 valid timestamp, or ``None`` if the property is not set locally. Raises: ValueError: if value is not a valid RFC3339 timestamp """ value = self._properties.get("updateTime") if value is not None: try: value = datetime.datetime.strptime( value, datetime_helpers._RFC3339_MICROS ) except ValueError: DatetimeNS = datetime_helpers.DatetimeWithNanoseconds value = DatetimeNS.from_rfc3339(value) naive = value.tzinfo is None or value.tzinfo.utcoffset(value) is None if naive: value = pytz.utc.localize(value) return value
[ "def", "update_time", "(", "self", ")", ":", "value", "=", "self", ".", "_properties", ".", "get", "(", "\"updateTime\"", ")", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "datetime_helpers", ".", "_RFC3339_MICROS", ")", "except", "ValueError", ":", "DatetimeNS", "=", "datetime_helpers", ".", "DatetimeWithNanoseconds", "value", "=", "DatetimeNS", ".", "from_rfc3339", "(", "value", ")", "naive", "=", "value", ".", "tzinfo", "is", "None", "or", "value", ".", "tzinfo", ".", "utcoffset", "(", "value", ")", "is", "None", "if", "naive", ":", "value", "=", "pytz", ".", "utc", ".", "localize", "(", "value", ")", "return", "value" ]
Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables Returns: :class:`~api_core.datetime_helpers.DatetimeWithNanoseconds`, :class:`datetime.datetime` or ``NoneType``: Datetime object parsed from RFC3339 valid timestamp, or ``None`` if the property is not set locally. Raises: ValueError: if value is not a valid RFC3339 timestamp
[ "Retrieve", "the", "timestamp", "at", "which", "the", "variable", "was", "updated", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/variable.py#L151-L178
train
googleapis/google-cloud-python
runtimeconfig/google/cloud/runtimeconfig/variable.py
Variable._set_properties
def _set_properties(self, resource): """Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API. """ self._properties.clear() cleaned = resource.copy() if "name" in cleaned: self.name = variable_name_from_full_name(cleaned.pop("name")) self._properties.update(cleaned)
python
def _set_properties(self, resource): """Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API. """ self._properties.clear() cleaned = resource.copy() if "name" in cleaned: self.name = variable_name_from_full_name(cleaned.pop("name")) self._properties.update(cleaned)
[ "def", "_set_properties", "(", "self", ",", "resource", ")", ":", "self", ".", "_properties", ".", "clear", "(", ")", "cleaned", "=", "resource", ".", "copy", "(", ")", "if", "\"name\"", "in", "cleaned", ":", "self", ".", "name", "=", "variable_name_from_full_name", "(", "cleaned", ".", "pop", "(", "\"name\"", ")", ")", "self", ".", "_properties", ".", "update", "(", "cleaned", ")" ]
Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API.
[ "Update", "properties", "from", "resource", "in", "body", "of", "api_response" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/runtimeconfig/google/cloud/runtimeconfig/variable.py#L195-L205
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_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() # Unwrap proto-plus wrapped messages. if callable(getattr(pb_type, "pb", None)): msg_pb = pb_type.pb(msg) else: msg_pb = msg # Unpack the Any object and populate the protobuf message instance. if not any_pb.Unpack(msg_pb): raise TypeError( "Could not convert {} to {}".format( any_pb.__class__.__name__, pb_type.__name__ ) ) # Done; return the message. 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() # Unwrap proto-plus wrapped messages. if callable(getattr(pb_type, "pb", None)): msg_pb = pb_type.pb(msg) else: msg_pb = msg # Unpack the Any object and populate the protobuf message instance. if not any_pb.Unpack(msg_pb): raise TypeError( "Could not convert {} to {}".format( any_pb.__class__.__name__, pb_type.__name__ ) ) # Done; return the message. return msg
[ "def", "from_any_pb", "(", "pb_type", ",", "any_pb", ")", ":", "msg", "=", "pb_type", "(", ")", "# Unwrap proto-plus wrapped messages.", "if", "callable", "(", "getattr", "(", "pb_type", ",", "\"pb\"", ",", "None", ")", ")", ":", "msg_pb", "=", "pb_type", ".", "pb", "(", "msg", ")", "else", ":", "msg_pb", "=", "msg", "# Unpack the Any object and populate the protobuf message instance.", "if", "not", "any_pb", ".", "Unpack", "(", "msg_pb", ")", ":", "raise", "TypeError", "(", "\"Could not convert {} to {}\"", ".", "format", "(", "any_pb", ".", "__class__", ".", "__name__", ",", "pb_type", ".", "__name__", ")", ")", "# Done; return the message.", "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/api_core/google/api_core/protobuf_helpers.py#L43-L74
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
get_messages
def get_messages(module): """Discovers all protobuf Message classes in a given import module. Args: module (module): A Python module; :func:`dir` will be run against this module to find Message subclasses. Returns: dict[str, google.protobuf.message.Message]: A dictionary with the Message class names as keys, and the Message subclasses themselves as values. """ answer = collections.OrderedDict() for name in dir(module): candidate = getattr(module, name) if inspect.isclass(candidate) and issubclass(candidate, message.Message): answer[name] = candidate return answer
python
def get_messages(module): """Discovers all protobuf Message classes in a given import module. Args: module (module): A Python module; :func:`dir` will be run against this module to find Message subclasses. Returns: dict[str, google.protobuf.message.Message]: A dictionary with the Message class names as keys, and the Message subclasses themselves as values. """ answer = collections.OrderedDict() for name in dir(module): candidate = getattr(module, name) if inspect.isclass(candidate) and issubclass(candidate, message.Message): answer[name] = candidate return answer
[ "def", "get_messages", "(", "module", ")", ":", "answer", "=", "collections", ".", "OrderedDict", "(", ")", "for", "name", "in", "dir", "(", "module", ")", ":", "candidate", "=", "getattr", "(", "module", ",", "name", ")", "if", "inspect", ".", "isclass", "(", "candidate", ")", "and", "issubclass", "(", "candidate", ",", "message", ".", "Message", ")", ":", "answer", "[", "name", "]", "=", "candidate", "return", "answer" ]
Discovers all protobuf Message classes in a given import module. Args: module (module): A Python module; :func:`dir` will be run against this module to find Message subclasses. Returns: dict[str, google.protobuf.message.Message]: A dictionary with the Message class names as keys, and the Message subclasses themselves as values.
[ "Discovers", "all", "protobuf", "Message", "classes", "in", "a", "given", "import", "module", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L99-L116
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
_resolve_subkeys
def _resolve_subkeys(key, separator="."): """Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s). """ parts = key.split(separator, 1) if len(parts) > 1: return parts else: return parts[0], None
python
def _resolve_subkeys(key, separator="."): """Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s). """ parts = key.split(separator, 1) if len(parts) > 1: return parts else: return parts[0], None
[ "def", "_resolve_subkeys", "(", "key", ",", "separator", "=", "\".\"", ")", ":", "parts", "=", "key", ".", "split", "(", "separator", ",", "1", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "return", "parts", "else", ":", "return", "parts", "[", "0", "]", ",", "None" ]
Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on the first instance of the subkey:: >>> _resolve_subkeys('a.b.c') ('a', 'b.c') >>> _resolve_subkeys('d|e|f', separator='|') ('d', 'e|f') If not, the subkey will be :data:`None`:: >>> _resolve_subkeys('foo') ('foo', None) Args: key (str): A string that may or may not contain the separator. separator (str): The namespace separator. Defaults to `.`. Returns: Tuple[str, str]: The key and subkey(s).
[ "Resolve", "a", "potentially", "nested", "key", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L119-L147
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
get
def get(msg_or_dict, key, default=_SENTINEL): """Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not present on the object, and a default is set, returns that default instead. A type-appropriate falsy default is generally recommended, as protobuf messages almost always have default values for unset values and it is not always possible to tell the difference between a falsy value and an unset one. If no default is set then :class:`KeyError` will be raised if the key is not present in the object. Returns: Any: The return value from the underlying Message or dict. Raises: KeyError: If the key is not found. Note that, for unset values, messages and dictionaries may not have consistent behavior. TypeError: If ``msg_or_dict`` is not a Message or Mapping. """ # We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know about. # If we get something else, complain. if isinstance(msg_or_dict, message.Message): answer = getattr(msg_or_dict, key, default) elif isinstance(msg_or_dict, collections_abc.Mapping): answer = msg_or_dict.get(key, default) else: raise TypeError( "get() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # If the object we got back is our sentinel, raise KeyError; this is # a "not found" case. if answer is _SENTINEL: raise KeyError(key) # If a subkey exists, call this method recursively against the answer. if subkey is not None and answer is not default: return get(answer, subkey, default=default) return answer
python
def get(msg_or_dict, key, default=_SENTINEL): """Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not present on the object, and a default is set, returns that default instead. A type-appropriate falsy default is generally recommended, as protobuf messages almost always have default values for unset values and it is not always possible to tell the difference between a falsy value and an unset one. If no default is set then :class:`KeyError` will be raised if the key is not present in the object. Returns: Any: The return value from the underlying Message or dict. Raises: KeyError: If the key is not found. Note that, for unset values, messages and dictionaries may not have consistent behavior. TypeError: If ``msg_or_dict`` is not a Message or Mapping. """ # We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know about. # If we get something else, complain. if isinstance(msg_or_dict, message.Message): answer = getattr(msg_or_dict, key, default) elif isinstance(msg_or_dict, collections_abc.Mapping): answer = msg_or_dict.get(key, default) else: raise TypeError( "get() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # If the object we got back is our sentinel, raise KeyError; this is # a "not found" case. if answer is _SENTINEL: raise KeyError(key) # If a subkey exists, call this method recursively against the answer. if subkey is not None and answer is not default: return get(answer, subkey, default=default) return answer
[ "def", "get", "(", "msg_or_dict", ",", "key", ",", "default", "=", "_SENTINEL", ")", ":", "# We may need to get a nested key. Resolve this.", "key", ",", "subkey", "=", "_resolve_subkeys", "(", "key", ")", "# Attempt to get the value from the two types of objects we know about.", "# If we get something else, complain.", "if", "isinstance", "(", "msg_or_dict", ",", "message", ".", "Message", ")", ":", "answer", "=", "getattr", "(", "msg_or_dict", ",", "key", ",", "default", ")", "elif", "isinstance", "(", "msg_or_dict", ",", "collections_abc", ".", "Mapping", ")", ":", "answer", "=", "msg_or_dict", ".", "get", "(", "key", ",", "default", ")", "else", ":", "raise", "TypeError", "(", "\"get() expected a dict or protobuf message, got {!r}.\"", ".", "format", "(", "type", "(", "msg_or_dict", ")", ")", ")", "# If the object we got back is our sentinel, raise KeyError; this is", "# a \"not found\" case.", "if", "answer", "is", "_SENTINEL", ":", "raise", "KeyError", "(", "key", ")", "# If a subkey exists, call this method recursively against the answer.", "if", "subkey", "is", "not", "None", "and", "answer", "is", "not", "default", ":", "return", "get", "(", "answer", ",", "subkey", ",", "default", "=", "default", ")", "return", "answer" ]
Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object. default (Any): If the key is not present on the object, and a default is set, returns that default instead. A type-appropriate falsy default is generally recommended, as protobuf messages almost always have default values for unset values and it is not always possible to tell the difference between a falsy value and an unset one. If no default is set then :class:`KeyError` will be raised if the key is not present in the object. Returns: Any: The return value from the underlying Message or dict. Raises: KeyError: If the key is not found. Note that, for unset values, messages and dictionaries may not have consistent behavior. TypeError: If ``msg_or_dict`` is not a Message or Mapping.
[ "Retrieve", "a", "key", "s", "value", "from", "a", "protobuf", "Message", "or", "dictionary", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L150-L198
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
_set_field_on_message
def _set_field_on_message(msg, key, value): """Set helper for protobuf Messages.""" # Attempt to set the value on the types of objects we know how to deal # with. if isinstance(value, (collections_abc.MutableSequence, tuple)): # Clear the existing repeated protobuf message of any elements # currently inside it. while getattr(msg, key): getattr(msg, key).pop() # Write our new elements to the repeated field. for item in value: if isinstance(item, collections_abc.Mapping): getattr(msg, key).add(**item) else: # protobuf's RepeatedCompositeContainer doesn't support # append. getattr(msg, key).extend([item]) elif isinstance(value, collections_abc.Mapping): # Assign the dictionary values to the protobuf message. for item_key, item_value in value.items(): set(getattr(msg, key), item_key, item_value) elif isinstance(value, message.Message): getattr(msg, key).CopyFrom(value) else: setattr(msg, key, value)
python
def _set_field_on_message(msg, key, value): """Set helper for protobuf Messages.""" # Attempt to set the value on the types of objects we know how to deal # with. if isinstance(value, (collections_abc.MutableSequence, tuple)): # Clear the existing repeated protobuf message of any elements # currently inside it. while getattr(msg, key): getattr(msg, key).pop() # Write our new elements to the repeated field. for item in value: if isinstance(item, collections_abc.Mapping): getattr(msg, key).add(**item) else: # protobuf's RepeatedCompositeContainer doesn't support # append. getattr(msg, key).extend([item]) elif isinstance(value, collections_abc.Mapping): # Assign the dictionary values to the protobuf message. for item_key, item_value in value.items(): set(getattr(msg, key), item_key, item_value) elif isinstance(value, message.Message): getattr(msg, key).CopyFrom(value) else: setattr(msg, key, value)
[ "def", "_set_field_on_message", "(", "msg", ",", "key", ",", "value", ")", ":", "# Attempt to set the value on the types of objects we know how to deal", "# with.", "if", "isinstance", "(", "value", ",", "(", "collections_abc", ".", "MutableSequence", ",", "tuple", ")", ")", ":", "# Clear the existing repeated protobuf message of any elements", "# currently inside it.", "while", "getattr", "(", "msg", ",", "key", ")", ":", "getattr", "(", "msg", ",", "key", ")", ".", "pop", "(", ")", "# Write our new elements to the repeated field.", "for", "item", "in", "value", ":", "if", "isinstance", "(", "item", ",", "collections_abc", ".", "Mapping", ")", ":", "getattr", "(", "msg", ",", "key", ")", ".", "add", "(", "*", "*", "item", ")", "else", ":", "# protobuf's RepeatedCompositeContainer doesn't support", "# append.", "getattr", "(", "msg", ",", "key", ")", ".", "extend", "(", "[", "item", "]", ")", "elif", "isinstance", "(", "value", ",", "collections_abc", ".", "Mapping", ")", ":", "# Assign the dictionary values to the protobuf message.", "for", "item_key", ",", "item_value", "in", "value", ".", "items", "(", ")", ":", "set", "(", "getattr", "(", "msg", ",", "key", ")", ",", "item_key", ",", "item_value", ")", "elif", "isinstance", "(", "value", ",", "message", ".", "Message", ")", ":", "getattr", "(", "msg", ",", "key", ")", ".", "CopyFrom", "(", "value", ")", "else", ":", "setattr", "(", "msg", ",", "key", ",", "value", ")" ]
Set helper for protobuf Messages.
[ "Set", "helper", "for", "protobuf", "Messages", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L201-L226
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
set
def set(msg_or_dict, key, value): """Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ # Sanity check: Is our target object valid? if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)): raise TypeError( "set() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # We may be setting a nested key. Resolve this. basekey, subkey = _resolve_subkeys(key) # If a subkey exists, then get that object and call this method # recursively against it using the subkey. if subkey is not None: if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict.setdefault(basekey, {}) set(get(msg_or_dict, basekey), subkey, value) return if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict[key] = value else: _set_field_on_message(msg_or_dict, key, value)
python
def set(msg_or_dict, key, value): """Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ # Sanity check: Is our target object valid? if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)): raise TypeError( "set() expected a dict or protobuf message, got {!r}.".format( type(msg_or_dict) ) ) # We may be setting a nested key. Resolve this. basekey, subkey = _resolve_subkeys(key) # If a subkey exists, then get that object and call this method # recursively against it using the subkey. if subkey is not None: if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict.setdefault(basekey, {}) set(get(msg_or_dict, basekey), subkey, value) return if isinstance(msg_or_dict, collections_abc.MutableMapping): msg_or_dict[key] = value else: _set_field_on_message(msg_or_dict, key, value)
[ "def", "set", "(", "msg_or_dict", ",", "key", ",", "value", ")", ":", "# Sanity check: Is our target object valid?", "if", "not", "isinstance", "(", "msg_or_dict", ",", "(", "collections_abc", ".", "MutableMapping", ",", "message", ".", "Message", ")", ")", ":", "raise", "TypeError", "(", "\"set() expected a dict or protobuf message, got {!r}.\"", ".", "format", "(", "type", "(", "msg_or_dict", ")", ")", ")", "# We may be setting a nested key. Resolve this.", "basekey", ",", "subkey", "=", "_resolve_subkeys", "(", "key", ")", "# If a subkey exists, then get that object and call this method", "# recursively against it using the subkey.", "if", "subkey", "is", "not", "None", ":", "if", "isinstance", "(", "msg_or_dict", ",", "collections_abc", ".", "MutableMapping", ")", ":", "msg_or_dict", ".", "setdefault", "(", "basekey", ",", "{", "}", ")", "set", "(", "get", "(", "msg_or_dict", ",", "basekey", ")", ",", "subkey", ",", "value", ")", "return", "if", "isinstance", "(", "msg_or_dict", ",", "collections_abc", ".", "MutableMapping", ")", ":", "msg_or_dict", "[", "key", "]", "=", "value", "else", ":", "_set_field_on_message", "(", "msg_or_dict", ",", "key", ",", "value", ")" ]
Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to set. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary.
[ "Set", "a", "key", "s", "value", "on", "a", "protobuf", "Message", "or", "dictionary", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L229-L263
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
setdefault
def setdefault(msg_or_dict, key, value): """Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well (by design), this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ if not get(msg_or_dict, key, default=None): set(msg_or_dict, key, value)
python
def setdefault(msg_or_dict, key, value): """Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well (by design), this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary. """ if not get(msg_or_dict, key, default=None): set(msg_or_dict, key, value)
[ "def", "setdefault", "(", "msg_or_dict", ",", "key", ",", "value", ")", ":", "if", "not", "get", "(", "msg_or_dict", ",", "key", ",", "default", "=", "None", ")", ":", "set", "(", "msg_or_dict", ",", "key", ",", "value", ")" ]
Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Messages do not distinguish between unset values and falsy ones particularly well (by design), this method treats any falsy value (e.g. 0, empty list) as a target to be overwritten, on both Messages and dictionaries. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key on the object in question. value (Any): The value to set. Raises: TypeError: If ``msg_or_dict`` is not a Message or dictionary.
[ "Set", "the", "key", "on", "a", "protobuf", "Message", "or", "dictionary", "to", "a", "given", "value", "if", "the", "current", "value", "is", "falsy", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L266-L285
train
googleapis/google-cloud-python
api_core/google/api_core/protobuf_helpers.py
field_mask
def field_mask(original, modified): """Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message): the modified message. If set to None, this field will be interpretted as an empty message. Returns: google.protobuf.field_mask_pb2.FieldMask: field mask that contains the list of field names that have different values between the two messages. If the messages are equivalent, then the field mask is empty. Raises: ValueError: If the ``original`` or ``modified`` are not the same type. """ if original is None and modified is None: return field_mask_pb2.FieldMask() if original is None and modified is not None: original = copy.deepcopy(modified) original.Clear() if modified is None and original is not None: modified = copy.deepcopy(original) modified.Clear() if type(original) != type(modified): raise ValueError( "expected that both original and modified should be of the " 'same type, received "{!r}" and "{!r}".'.format( type(original), type(modified) ) ) return field_mask_pb2.FieldMask(paths=_field_mask_helper(original, modified))
python
def field_mask(original, modified): """Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message): the modified message. If set to None, this field will be interpretted as an empty message. Returns: google.protobuf.field_mask_pb2.FieldMask: field mask that contains the list of field names that have different values between the two messages. If the messages are equivalent, then the field mask is empty. Raises: ValueError: If the ``original`` or ``modified`` are not the same type. """ if original is None and modified is None: return field_mask_pb2.FieldMask() if original is None and modified is not None: original = copy.deepcopy(modified) original.Clear() if modified is None and original is not None: modified = copy.deepcopy(original) modified.Clear() if type(original) != type(modified): raise ValueError( "expected that both original and modified should be of the " 'same type, received "{!r}" and "{!r}".'.format( type(original), type(modified) ) ) return field_mask_pb2.FieldMask(paths=_field_mask_helper(original, modified))
[ "def", "field_mask", "(", "original", ",", "modified", ")", ":", "if", "original", "is", "None", "and", "modified", "is", "None", ":", "return", "field_mask_pb2", ".", "FieldMask", "(", ")", "if", "original", "is", "None", "and", "modified", "is", "not", "None", ":", "original", "=", "copy", ".", "deepcopy", "(", "modified", ")", "original", ".", "Clear", "(", ")", "if", "modified", "is", "None", "and", "original", "is", "not", "None", ":", "modified", "=", "copy", ".", "deepcopy", "(", "original", ")", "modified", ".", "Clear", "(", ")", "if", "type", "(", "original", ")", "!=", "type", "(", "modified", ")", ":", "raise", "ValueError", "(", "\"expected that both original and modified should be of the \"", "'same type, received \"{!r}\" and \"{!r}\".'", ".", "format", "(", "type", "(", "original", ")", ",", "type", "(", "modified", ")", ")", ")", "return", "field_mask_pb2", ".", "FieldMask", "(", "paths", "=", "_field_mask_helper", "(", "original", ",", "modified", ")", ")" ]
Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message): the original message. If set to None, this field will be interpretted as an empty message. modified (~google.protobuf.message.Message): the modified message. If set to None, this field will be interpretted as an empty message. Returns: google.protobuf.field_mask_pb2.FieldMask: field mask that contains the list of field names that have different values between the two messages. If the messages are equivalent, then the field mask is empty. Raises: ValueError: If the ``original`` or ``modified`` are not the same type.
[ "Create", "a", "field", "mask", "by", "comparing", "two", "messages", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/api_core/google/api_core/protobuf_helpers.py#L288-L326
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py
SubscriberClient.topic_path
def topic_path(cls, project, topic): """Return a fully-qualified topic string.""" return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
python
def topic_path(cls, project, topic): """Return a fully-qualified topic string.""" return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
[ "def", "topic_path", "(", "cls", ",", "project", ",", "topic", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/topics/{topic}\"", ",", "project", "=", "project", ",", "topic", "=", "topic", ")" ]
Return a fully-qualified topic string.
[ "Return", "a", "fully", "-", "qualified", "topic", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py#L98-L102
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py
SubscriberClient.snapshot_path
def snapshot_path(cls, project, snapshot): """Return a fully-qualified snapshot string.""" return google.api_core.path_template.expand( "projects/{project}/snapshots/{snapshot}", project=project, snapshot=snapshot, )
python
def snapshot_path(cls, project, snapshot): """Return a fully-qualified snapshot string.""" return google.api_core.path_template.expand( "projects/{project}/snapshots/{snapshot}", project=project, snapshot=snapshot, )
[ "def", "snapshot_path", "(", "cls", ",", "project", ",", "snapshot", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/snapshots/{snapshot}\"", ",", "project", "=", "project", ",", "snapshot", "=", "snapshot", ",", ")" ]
Return a fully-qualified snapshot string.
[ "Return", "a", "fully", "-", "qualified", "snapshot", "string", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py#L112-L118
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py
SubscriberClient.create_subscription
def create_subscription( self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, expiration_policy=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns ``ALREADY_EXISTS``. If the corresponding topic doesn't exist, returns ``NOT_FOUND``. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the `resource name format <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic) Args: name (str): The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"` topic (str): The name of the topic from which this subscription is receiving messages. Format is ``projects/{project}/topics/{topic}``. The value of this field will be ``_deleted-topic_`` if the topic has been deleted. push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is used to configure it. An empty ``pushConfig`` signifies that the subscriber will pull and ack messages using API methods. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.PushConfig` ack_deadline_seconds (int): The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using non-streaming pull or send the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the ``message_retention_duration`` window. This must be true if you would like to Seek to a timestamp. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Duration` labels (dict[str -> str]): See <a href="https://cloud.google.com/pubsub/docs/labels"> Creating and managing labels</a>. enable_message_ordering (bool): If true, messages published with the same ``ordering_key`` in ``PubsubMessage`` will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. expiration_policy (Union[dict, ~google.cloud.pubsub_v1.types.ExpirationPolicy]): A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If ``expiration_policy`` is not set, a *default policy* with ``ttl`` of 31 days will be used. The minimum allowed value for ``expiration_policy.ttl`` is 1 day. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.ExpirationPolicy` 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.pubsub_v1.types.Subscription` 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_subscription" not in self._inner_api_calls: self._inner_api_calls[ "create_subscription" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_subscription, default_retry=self._method_configs["CreateSubscription"].retry, default_timeout=self._method_configs["CreateSubscription"].timeout, client_info=self._client_info, ) request = pubsub_pb2.Subscription( name=name, topic=topic, push_config=push_config, ack_deadline_seconds=ack_deadline_seconds, retain_acked_messages=retain_acked_messages, message_retention_duration=message_retention_duration, labels=labels, enable_message_ordering=enable_message_ordering, expiration_policy=expiration_policy, ) 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_subscription"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def create_subscription( self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None, enable_message_ordering=None, expiration_policy=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns ``ALREADY_EXISTS``. If the corresponding topic doesn't exist, returns ``NOT_FOUND``. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the `resource name format <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic) Args: name (str): The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"` topic (str): The name of the topic from which this subscription is receiving messages. Format is ``projects/{project}/topics/{topic}``. The value of this field will be ``_deleted-topic_`` if the topic has been deleted. push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is used to configure it. An empty ``pushConfig`` signifies that the subscriber will pull and ack messages using API methods. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.PushConfig` ack_deadline_seconds (int): The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using non-streaming pull or send the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the ``message_retention_duration`` window. This must be true if you would like to Seek to a timestamp. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Duration` labels (dict[str -> str]): See <a href="https://cloud.google.com/pubsub/docs/labels"> Creating and managing labels</a>. enable_message_ordering (bool): If true, messages published with the same ``ordering_key`` in ``PubsubMessage`` will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. expiration_policy (Union[dict, ~google.cloud.pubsub_v1.types.ExpirationPolicy]): A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If ``expiration_policy`` is not set, a *default policy* with ``ttl`` of 31 days will be used. The minimum allowed value for ``expiration_policy.ttl`` is 1 day. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.ExpirationPolicy` 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.pubsub_v1.types.Subscription` 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_subscription" not in self._inner_api_calls: self._inner_api_calls[ "create_subscription" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_subscription, default_retry=self._method_configs["CreateSubscription"].retry, default_timeout=self._method_configs["CreateSubscription"].timeout, client_info=self._client_info, ) request = pubsub_pb2.Subscription( name=name, topic=topic, push_config=push_config, ack_deadline_seconds=ack_deadline_seconds, retain_acked_messages=retain_acked_messages, message_retention_duration=message_retention_duration, labels=labels, enable_message_ordering=enable_message_ordering, expiration_policy=expiration_policy, ) 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_subscription"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "create_subscription", "(", "self", ",", "name", ",", "topic", ",", "push_config", "=", "None", ",", "ack_deadline_seconds", "=", "None", ",", "retain_acked_messages", "=", "None", ",", "message_retention_duration", "=", "None", ",", "labels", "=", "None", ",", "enable_message_ordering", "=", "None", ",", "expiration_policy", "=", "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_subscription\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"create_subscription\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "create_subscription", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CreateSubscription\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CreateSubscription\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "pubsub_pb2", ".", "Subscription", "(", "name", "=", "name", ",", "topic", "=", "topic", ",", "push_config", "=", "push_config", ",", "ack_deadline_seconds", "=", "ack_deadline_seconds", ",", "retain_acked_messages", "=", "retain_acked_messages", ",", "message_retention_duration", "=", "message_retention_duration", ",", "labels", "=", "labels", ",", "enable_message_ordering", "=", "enable_message_ordering", ",", "expiration_policy", "=", "expiration_policy", ",", ")", "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_subscription\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Creates a subscription to a given topic. See the resource name rules. If the subscription already exists, returns ``ALREADY_EXISTS``. If the corresponding topic doesn't exist, returns ``NOT_FOUND``. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic, conforming to the `resource name format <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. The generated name is populated in the returned Subscription object. Note that for REST API requests, you must specify a name in the request. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> topic = client.topic_path('[PROJECT]', '[TOPIC]') >>> >>> response = client.create_subscription(name, topic) Args: name (str): The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"` topic (str): The name of the topic from which this subscription is receiving messages. Format is ``projects/{project}/topics/{topic}``. The value of this field will be ``_deleted-topic_`` if the topic has been deleted. push_config (Union[dict, ~google.cloud.pubsub_v1.types.PushConfig]): If push delivery is used with this subscription, this field is used to configure it. An empty ``pushConfig`` signifies that the subscriber will pull and ack messages using API methods. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.PushConfig` ack_deadline_seconds (int): The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to acknowledge receipt before resending the message. In the interval after the message is delivered and before it is acknowledged, it is considered to be outstanding. During that time period, the message will not be redelivered (on a best-effort basis). For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using non-streaming pull or send the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if using streaming pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is used. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then messages are not expunged from the subscription's backlog, even if they are acknowledged, until they fall out of the ``message_retention_duration`` window. This must be true if you would like to Seek to a timestamp. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. message_retention_duration (Union[dict, ~google.cloud.pubsub_v1.types.Duration]): How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If ``retain_acked_messages`` is true, then this also configures the retention of acknowledged messages, and thus configures how far back in time a ``Seek`` can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Duration` labels (dict[str -> str]): See <a href="https://cloud.google.com/pubsub/docs/labels"> Creating and managing labels</a>. enable_message_ordering (bool): If true, messages published with the same ``ordering_key`` in ``PubsubMessage`` will be delivered to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise, they may be delivered in any order. EXPERIMENTAL: This feature is part of a closed alpha release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. expiration_policy (Union[dict, ~google.cloud.pubsub_v1.types.ExpirationPolicy]): A policy that specifies the conditions for this subscription's expiration. A subscription is considered active as long as any connected subscriber is successfully consuming messages from the subscription or is issuing operations on the subscription. If ``expiration_policy`` is not set, a *default policy* with ``ttl`` of 31 days will be used. The minimum allowed value for ``expiration_policy.ttl`` is 1 day. BETA: This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.ExpirationPolicy` 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.pubsub_v1.types.Subscription` 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", "subscription", "to", "a", "given", "topic", ".", "See", "the", "resource", "name", "rules", ".", "If", "the", "subscription", "already", "exists", "returns", "ALREADY_EXISTS", ".", "If", "the", "corresponding", "topic", "doesn", "t", "exist", "returns", "NOT_FOUND", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py#L219-L389
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py
SubscriberClient.seek
def seek( self, subscription, time=None, snapshot=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.<br><br> <b>BETA:</b> This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription) Args: subscription (str): The subscription to affect. time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of ``message_retention_duration`` and ``retain_acked_messages``). For example, if ``time`` corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Timestamp` snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is ``projects/{project}/snapshots/{snap}``. 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.pubsub_v1.types.SeekResponse` 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 "seek" not in self._inner_api_calls: self._inner_api_calls["seek"] = google.api_core.gapic_v1.method.wrap_method( self.transport.seek, default_retry=self._method_configs["Seek"].retry, default_timeout=self._method_configs["Seek"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(time=time, snapshot=snapshot) request = pubsub_pb2.SeekRequest( subscription=subscription, time=time, snapshot=snapshot ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("subscription", subscription)] 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["seek"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def seek( self, subscription, time=None, snapshot=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.<br><br> <b>BETA:</b> This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription) Args: subscription (str): The subscription to affect. time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of ``message_retention_duration`` and ``retain_acked_messages``). For example, if ``time`` corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Timestamp` snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is ``projects/{project}/snapshots/{snap}``. 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.pubsub_v1.types.SeekResponse` 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 "seek" not in self._inner_api_calls: self._inner_api_calls["seek"] = google.api_core.gapic_v1.method.wrap_method( self.transport.seek, default_retry=self._method_configs["Seek"].retry, default_timeout=self._method_configs["Seek"].timeout, client_info=self._client_info, ) # Sanity check: We have some fields which are mutually exclusive; # raise ValueError if more than one is sent. google.api_core.protobuf_helpers.check_oneof(time=time, snapshot=snapshot) request = pubsub_pb2.SeekRequest( subscription=subscription, time=time, snapshot=snapshot ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("subscription", subscription)] 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["seek"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "seek", "(", "self", ",", "subscription", ",", "time", "=", "None", ",", "snapshot", "=", "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", "\"seek\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"seek\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "seek", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"Seek\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"Seek\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "# Sanity check: We have some fields which are mutually exclusive;", "# raise ValueError if more than one is sent.", "google", ".", "api_core", ".", "protobuf_helpers", ".", "check_oneof", "(", "time", "=", "time", ",", "snapshot", "=", "snapshot", ")", "request", "=", "pubsub_pb2", ".", "SeekRequest", "(", "subscription", "=", "subscription", ",", "time", "=", "time", ",", "snapshot", "=", "snapshot", ")", "if", "metadata", "is", "None", ":", "metadata", "=", "[", "]", "metadata", "=", "list", "(", "metadata", ")", "try", ":", "routing_header", "=", "[", "(", "\"subscription\"", ",", "subscription", ")", "]", "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", "[", "\"seek\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Seeks an existing subscription to a point in time or to a given snapshot, whichever is provided in the request. Snapshots are used in <a href="https://cloud.google.com/pubsub/docs/replay-overview">Seek</a> operations, which allow you to manage message acknowledgments in bulk. That is, you can set the acknowledgment state of messages in an existing subscription to the state captured by a snapshot. Note that both the subscription and the snapshot must be on the same topic.<br><br> <b>BETA:</b> This feature is part of a beta release. This API might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. Example: >>> from google.cloud import pubsub_v1 >>> >>> client = pubsub_v1.SubscriberClient() >>> >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]') >>> >>> response = client.seek(subscription) Args: subscription (str): The subscription to affect. time (Union[dict, ~google.cloud.pubsub_v1.types.Timestamp]): The time to seek to. Messages retained in the subscription that were published before this time are marked as acknowledged, and messages retained in the subscription that were published after this time are marked as unacknowledged. Note that this operation affects only those messages retained in the subscription (configured by the combination of ``message_retention_duration`` and ``retain_acked_messages``). For example, if ``time`` corresponds to a point before the message retention window (or to a point before the system's notion of the subscription creation time), only retained messages will be marked as unacknowledged, and already-expunged messages will not be restored. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.pubsub_v1.types.Timestamp` snapshot (str): The snapshot to seek to. The snapshot's topic must be the same as that of the provided subscription. Format is ``projects/{project}/snapshots/{snap}``. 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.pubsub_v1.types.SeekResponse` 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.
[ "Seeks", "an", "existing", "subscription", "to", "a", "point", "in", "time", "or", "to", "a", "given", "snapshot", "whichever", "is", "provided", "in", "the", "request", ".", "Snapshots", "are", "used", "in", "<a", "href", "=", "https", ":", "//", "cloud", ".", "google", ".", "com", "/", "pubsub", "/", "docs", "/", "replay", "-", "overview", ">", "Seek<", "/", "a", ">", "operations", "which", "allow", "you", "to", "manage", "message", "acknowledgments", "in", "bulk", ".", "That", "is", "you", "can", "set", "the", "acknowledgment", "state", "of", "messages", "in", "an", "existing", "subscription", "to", "the", "state", "captured", "by", "a", "snapshot", ".", "Note", "that", "both", "the", "subscription", "and", "the", "snapshot", "must", "be", "on", "the", "same", "topic", ".", "<br", ">", "<br", ">", "<b", ">", "BETA", ":", "<", "/", "b", ">", "This", "feature", "is", "part", "of", "a", "beta", "release", ".", "This", "API", "might", "be", "changed", "in", "backward", "-", "incompatible", "ways", "and", "is", "not", "recommended", "for", "production", "use", ".", "It", "is", "not", "subject", "to", "any", "SLA", "or", "deprecation", "policy", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/gapic/subscriber_client.py#L1527-L1626
train
googleapis/google-cloud-python
talent/google/cloud/talent_v4beta1/gapic/completion_client.py
CompletionClient.complete_query
def complete_query( self, name, query, page_size, language_codes=None, company_name=None, scope=None, type_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompletionClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `query`: >>> query = '' >>> >>> # TODO: Initialize `page_size`: >>> page_size = 0 >>> >>> response = client.complete_query(name, query, page_size) Args: name (str): Required. Resource name of project the completion is performed within. The format is "projects/{project\_id}", for example, "projects/api-test-project". query (str): Required. The query used to generate suggestions. The maximum number of allowed characters is 255. page_size (int): Required. Completion result count. The maximum allowed page size is 10. language_codes (list[str]): Optional. The list of languages of the query. This is the BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see `Tags for Identifying Languages <https://tools.ietf.org/html/bcp47>`__. For ``CompletionType.JOB_TITLE`` type, only open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMPANY_NAME`` type, only companies having open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMBINED`` type, only open jobs with the same ``language_codes`` or companies having open jobs with the same ``language_codes`` are returned. The maximum number of allowed characters is 255. company_name (str): Optional. If provided, restricts completion to specified company. The format is "projects/{project\_id}/companies/{company\_id}", for example, "projects/api-test-project/companies/foo". scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional. The scope of the completion. The defaults is ``CompletionScope.PUBLIC``. type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional. The completion topic. The default is ``CompletionType.COMBINED``. 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.talent_v4beta1.types.CompleteQueryResponse` 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 "complete_query" not in self._inner_api_calls: self._inner_api_calls[ "complete_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.complete_query, default_retry=self._method_configs["CompleteQuery"].retry, default_timeout=self._method_configs["CompleteQuery"].timeout, client_info=self._client_info, ) request = completion_service_pb2.CompleteQueryRequest( name=name, query=query, page_size=page_size, language_codes=language_codes, company_name=company_name, scope=scope, type=type_, ) return self._inner_api_calls["complete_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
python
def complete_query( self, name, query, page_size, language_codes=None, company_name=None, scope=None, type_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompletionClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `query`: >>> query = '' >>> >>> # TODO: Initialize `page_size`: >>> page_size = 0 >>> >>> response = client.complete_query(name, query, page_size) Args: name (str): Required. Resource name of project the completion is performed within. The format is "projects/{project\_id}", for example, "projects/api-test-project". query (str): Required. The query used to generate suggestions. The maximum number of allowed characters is 255. page_size (int): Required. Completion result count. The maximum allowed page size is 10. language_codes (list[str]): Optional. The list of languages of the query. This is the BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see `Tags for Identifying Languages <https://tools.ietf.org/html/bcp47>`__. For ``CompletionType.JOB_TITLE`` type, only open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMPANY_NAME`` type, only companies having open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMBINED`` type, only open jobs with the same ``language_codes`` or companies having open jobs with the same ``language_codes`` are returned. The maximum number of allowed characters is 255. company_name (str): Optional. If provided, restricts completion to specified company. The format is "projects/{project\_id}/companies/{company\_id}", for example, "projects/api-test-project/companies/foo". scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional. The scope of the completion. The defaults is ``CompletionScope.PUBLIC``. type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional. The completion topic. The default is ``CompletionType.COMBINED``. 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.talent_v4beta1.types.CompleteQueryResponse` 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 "complete_query" not in self._inner_api_calls: self._inner_api_calls[ "complete_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.complete_query, default_retry=self._method_configs["CompleteQuery"].retry, default_timeout=self._method_configs["CompleteQuery"].timeout, client_info=self._client_info, ) request = completion_service_pb2.CompleteQueryRequest( name=name, query=query, page_size=page_size, language_codes=language_codes, company_name=company_name, scope=scope, type=type_, ) return self._inner_api_calls["complete_query"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "def", "complete_query", "(", "self", ",", "name", ",", "query", ",", "page_size", ",", "language_codes", "=", "None", ",", "company_name", "=", "None", ",", "scope", "=", "None", ",", "type_", "=", "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", "\"complete_query\"", "not", "in", "self", ".", "_inner_api_calls", ":", "self", ".", "_inner_api_calls", "[", "\"complete_query\"", "]", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "wrap_method", "(", "self", ".", "transport", ".", "complete_query", ",", "default_retry", "=", "self", ".", "_method_configs", "[", "\"CompleteQuery\"", "]", ".", "retry", ",", "default_timeout", "=", "self", ".", "_method_configs", "[", "\"CompleteQuery\"", "]", ".", "timeout", ",", "client_info", "=", "self", ".", "_client_info", ",", ")", "request", "=", "completion_service_pb2", ".", "CompleteQueryRequest", "(", "name", "=", "name", ",", "query", "=", "query", ",", "page_size", "=", "page_size", ",", "language_codes", "=", "language_codes", ",", "company_name", "=", "company_name", ",", "scope", "=", "scope", ",", "type", "=", "type_", ",", ")", "return", "self", ".", "_inner_api_calls", "[", "\"complete_query\"", "]", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ")" ]
Completes the specified prefix with keyword suggestions. Intended for use by a job search auto-complete search box. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.CompletionClient() >>> >>> name = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `query`: >>> query = '' >>> >>> # TODO: Initialize `page_size`: >>> page_size = 0 >>> >>> response = client.complete_query(name, query, page_size) Args: name (str): Required. Resource name of project the completion is performed within. The format is "projects/{project\_id}", for example, "projects/api-test-project". query (str): Required. The query used to generate suggestions. The maximum number of allowed characters is 255. page_size (int): Required. Completion result count. The maximum allowed page size is 10. language_codes (list[str]): Optional. The list of languages of the query. This is the BCP-47 language code, such as "en-US" or "sr-Latn". For more information, see `Tags for Identifying Languages <https://tools.ietf.org/html/bcp47>`__. For ``CompletionType.JOB_TITLE`` type, only open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMPANY_NAME`` type, only companies having open jobs with the same ``language_codes`` are returned. For ``CompletionType.COMBINED`` type, only open jobs with the same ``language_codes`` or companies having open jobs with the same ``language_codes`` are returned. The maximum number of allowed characters is 255. company_name (str): Optional. If provided, restricts completion to specified company. The format is "projects/{project\_id}/companies/{company\_id}", for example, "projects/api-test-project/companies/foo". scope (~google.cloud.talent_v4beta1.types.CompletionScope): Optional. The scope of the completion. The defaults is ``CompletionScope.PUBLIC``. type_ (~google.cloud.talent_v4beta1.types.CompletionType): Optional. The completion topic. The default is ``CompletionType.COMBINED``. 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.talent_v4beta1.types.CompleteQueryResponse` 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.
[ "Completes", "the", "specified", "prefix", "with", "keyword", "suggestions", ".", "Intended", "for", "use", "by", "a", "job", "search", "auto", "-", "complete", "search", "box", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/talent/google/cloud/talent_v4beta1/gapic/completion_client.py#L179-L298
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
AbstractSessionPool._new_session
def _new_session(self): """Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. """ if self.labels: return self._database.session(labels=self.labels) return self._database.session()
python
def _new_session(self): """Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. """ if self.labels: return self._database.session(labels=self.labels) return self._database.session()
[ "def", "_new_session", "(", "self", ")", ":", "if", "self", ".", "labels", ":", "return", "self", ".", "_database", ".", "session", "(", "labels", "=", "self", ".", "labels", ")", "return", "self", ".", "_database", ".", "session", "(", ")" ]
Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance.
[ "Helper", "for", "concrete", "methods", "creating", "session", "instances", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L102-L110
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
FixedSizePool.bind
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database while not self._sessions.full(): session = self._new_session() session.create() self._sessions.put(session)
python
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database while not self._sessions.full(): session = self._new_session() session.create() self._sessions.put(session)
[ "def", "bind", "(", "self", ",", "database", ")", ":", "self", ".", "_database", "=", "database", "while", "not", "self", ".", "_sessions", ".", "full", "(", ")", ":", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "self", ".", "_sessions", ".", "put", "(", "session", ")" ]
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
[ "Associate", "the", "pool", "with", "a", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L162-L174
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
FixedSizePool.get
def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout session = self._sessions.get(block=True, timeout=timeout) if not session.exists(): session = self._database.session() session.create() return session
python
def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout session = self._sessions.get(block=True, timeout=timeout) if not session.exists(): session = self._database.session() session.create() return session
[ "def", "get", "(", "self", ",", "timeout", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "default_timeout", "session", "=", "self", ".", "_sessions", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "timeout", ")", "if", "not", "session", ".", "exists", "(", ")", ":", "session", "=", "self", ".", "_database", ".", "session", "(", ")", "session", ".", "create", "(", ")", "return", "session" ]
Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty.
[ "Check", "a", "session", "out", "from", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L176-L196
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
FixedSizePool.clear
def clear(self): """Delete all sessions in the pool.""" while True: try: session = self._sessions.get(block=False) except queue.Empty: break else: session.delete()
python
def clear(self): """Delete all sessions in the pool.""" while True: try: session = self._sessions.get(block=False) except queue.Empty: break else: session.delete()
[ "def", "clear", "(", "self", ")", ":", "while", "True", ":", "try", ":", "session", "=", "self", ".", "_sessions", ".", "get", "(", "block", "=", "False", ")", "except", "queue", ".", "Empty", ":", "break", "else", ":", "session", ".", "delete", "(", ")" ]
Delete all sessions in the pool.
[ "Delete", "all", "sessions", "in", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L210-L219
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
BurstyPool.get
def get(self): """Check a session out from the pool. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. """ try: session = self._sessions.get_nowait() except queue.Empty: session = self._new_session() session.create() else: if not session.exists(): session = self._new_session() session.create() return session
python
def get(self): """Check a session out from the pool. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. """ try: session = self._sessions.get_nowait() except queue.Empty: session = self._new_session() session.create() else: if not session.exists(): session = self._new_session() session.create() return session
[ "def", "get", "(", "self", ")", ":", "try", ":", "session", "=", "self", ".", "_sessions", ".", "get_nowait", "(", ")", "except", "queue", ".", "Empty", ":", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "else", ":", "if", "not", "session", ".", "exists", "(", ")", ":", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "return", "session" ]
Check a session out from the pool. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session.
[ "Check", "a", "session", "out", "from", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L257-L273
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
BurstyPool.put
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, the returned session is discarded. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. """ try: self._sessions.put_nowait(session) except queue.Full: try: session.delete() except NotFound: pass
python
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, the returned session is discarded. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. """ try: self._sessions.put_nowait(session) except queue.Full: try: session.delete() except NotFound: pass
[ "def", "put", "(", "self", ",", "session", ")", ":", "try", ":", "self", ".", "_sessions", ".", "put_nowait", "(", "session", ")", "except", "queue", ".", "Full", ":", "try", ":", "session", ".", "delete", "(", ")", "except", "NotFound", ":", "pass" ]
Return a session to the pool. Never blocks: if the pool is full, the returned session is discarded. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned.
[ "Return", "a", "session", "to", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L275-L290
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
PingingPool.bind
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database for _ in xrange(self.size): session = self._new_session() session.create() self.put(session)
python
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ self._database = database for _ in xrange(self.size): session = self._new_session() session.create() self.put(session)
[ "def", "bind", "(", "self", ",", "database", ")", ":", "self", ".", "_database", "=", "database", "for", "_", "in", "xrange", "(", "self", ".", "size", ")", ":", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "self", ".", "put", "(", "session", ")" ]
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
[ "Associate", "the", "pool", "with", "a", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L346-L358
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
PingingPool.get
def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout ping_after, session = self._sessions.get(block=True, timeout=timeout) if _NOW() > ping_after: if not session.exists(): session = self._new_session() session.create() return session
python
def get(self, timeout=None): # pylint: disable=arguments-differ """Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. """ if timeout is None: timeout = self.default_timeout ping_after, session = self._sessions.get(block=True, timeout=timeout) if _NOW() > ping_after: if not session.exists(): session = self._new_session() session.create() return session
[ "def", "get", "(", "self", ",", "timeout", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "default_timeout", "ping_after", ",", "session", "=", "self", ".", "_sessions", ".", "get", "(", "block", "=", "True", ",", "timeout", "=", "timeout", ")", "if", "_NOW", "(", ")", ">", "ping_after", ":", "if", "not", "session", ".", "exists", "(", ")", ":", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "return", "session" ]
Check a session out from the pool. :type timeout: int :param timeout: seconds to block waiting for an available session :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty.
[ "Check", "a", "session", "out", "from", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L360-L381
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
PingingPool.put
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ self._sessions.put_nowait((_NOW() + self._delta, session))
python
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ self._sessions.put_nowait((_NOW() + self._delta, session))
[ "def", "put", "(", "self", ",", "session", ")", ":", "self", ".", "_sessions", ".", "put_nowait", "(", "(", "_NOW", "(", ")", "+", "self", ".", "_delta", ",", "session", ")", ")" ]
Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full.
[ "Return", "a", "session", "to", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L383-L393
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
PingingPool.ping
def ping(self): """Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an event loop. """ while True: try: ping_after, session = self._sessions.get(block=False) except queue.Empty: # all sessions in use break if ping_after > _NOW(): # oldest session is fresh # Re-add to queue with existing expiration self._sessions.put((ping_after, session)) break if not session.exists(): # stale session = self._new_session() session.create() # Re-add to queue with new expiration self.put(session)
python
def ping(self): """Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an event loop. """ while True: try: ping_after, session = self._sessions.get(block=False) except queue.Empty: # all sessions in use break if ping_after > _NOW(): # oldest session is fresh # Re-add to queue with existing expiration self._sessions.put((ping_after, session)) break if not session.exists(): # stale session = self._new_session() session.create() # Re-add to queue with new expiration self.put(session)
[ "def", "ping", "(", "self", ")", ":", "while", "True", ":", "try", ":", "ping_after", ",", "session", "=", "self", ".", "_sessions", ".", "get", "(", "block", "=", "False", ")", "except", "queue", ".", "Empty", ":", "# all sessions in use", "break", "if", "ping_after", ">", "_NOW", "(", ")", ":", "# oldest session is fresh", "# Re-add to queue with existing expiration", "self", ".", "_sessions", ".", "put", "(", "(", "ping_after", ",", "session", ")", ")", "break", "if", "not", "session", ".", "exists", "(", ")", ":", "# stale", "session", "=", "self", ".", "_new_session", "(", ")", "session", ".", "create", "(", ")", "# Re-add to queue with new expiration", "self", ".", "put", "(", "session", ")" ]
Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an event loop.
[ "Refresh", "maybe", "-", "expired", "sessions", "in", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L405-L424
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
TransactionPingingPool.bind
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ super(TransactionPingingPool, self).bind(database) self.begin_pending_transactions()
python
def bind(self, database): """Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ super(TransactionPingingPool, self).bind(database) self.begin_pending_transactions()
[ "def", "bind", "(", "self", ",", "database", ")", ":", "super", "(", "TransactionPingingPool", ",", "self", ")", ".", "bind", "(", "database", ")", "self", ".", "begin_pending_transactions", "(", ")" ]
Associate the pool with a database. :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed.
[ "Associate", "the", "pool", "with", "a", "database", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L463-L471
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
TransactionPingingPool.put
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ if self._sessions.full(): raise queue.Full txn = session._transaction if txn is None or txn.committed() or txn._rolled_back: session.transaction() self._pending_sessions.put(session) else: super(TransactionPingingPool, self).put(session)
python
def put(self, session): """Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. """ if self._sessions.full(): raise queue.Full txn = session._transaction if txn is None or txn.committed() or txn._rolled_back: session.transaction() self._pending_sessions.put(session) else: super(TransactionPingingPool, self).put(session)
[ "def", "put", "(", "self", ",", "session", ")", ":", "if", "self", ".", "_sessions", ".", "full", "(", ")", ":", "raise", "queue", ".", "Full", "txn", "=", "session", ".", "_transaction", "if", "txn", "is", "None", "or", "txn", ".", "committed", "(", ")", "or", "txn", ".", "_rolled_back", ":", "session", ".", "transaction", "(", ")", "self", ".", "_pending_sessions", ".", "put", "(", "session", ")", "else", ":", "super", "(", "TransactionPingingPool", ",", "self", ")", ".", "put", "(", "session", ")" ]
Return a session to the pool. Never blocks: if the pool is full, raises. :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full.
[ "Return", "a", "session", "to", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L473-L491
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
TransactionPingingPool.begin_pending_transactions
def begin_pending_transactions(self): """Begin all transactions for sessions added to the pool.""" while not self._pending_sessions.empty(): session = self._pending_sessions.get() session._transaction.begin() super(TransactionPingingPool, self).put(session)
python
def begin_pending_transactions(self): """Begin all transactions for sessions added to the pool.""" while not self._pending_sessions.empty(): session = self._pending_sessions.get() session._transaction.begin() super(TransactionPingingPool, self).put(session)
[ "def", "begin_pending_transactions", "(", "self", ")", ":", "while", "not", "self", ".", "_pending_sessions", ".", "empty", "(", ")", ":", "session", "=", "self", ".", "_pending_sessions", ".", "get", "(", ")", "session", ".", "_transaction", ".", "begin", "(", ")", "super", "(", "TransactionPingingPool", ",", "self", ")", ".", "put", "(", "session", ")" ]
Begin all transactions for sessions added to the pool.
[ "Begin", "all", "transactions", "for", "sessions", "added", "to", "the", "pool", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L493-L498
train
googleapis/google-cloud-python
logging/google/cloud/logging/handlers/handlers.py
setup_logging
def setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ): """Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler to attach to the global handler :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 log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. Example: .. code-block:: python import logging import google.cloud.logging from google.cloud.logging.handlers import CloudLoggingHandler client = google.cloud.logging.Client() handler = CloudLoggingHandler(client) google.cloud.logging.handlers.setup_logging(handler) logging.getLogger().setLevel(logging.DEBUG) logging.error('bad news') # API call """ all_excluded_loggers = set(excluded_loggers + EXCLUDED_LOGGER_DEFAULTS) logger = logging.getLogger() logger.setLevel(log_level) logger.addHandler(handler) logger.addHandler(logging.StreamHandler()) for logger_name in all_excluded_loggers: logger = logging.getLogger(logger_name) logger.propagate = False logger.addHandler(logging.StreamHandler())
python
def setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ): """Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler to attach to the global handler :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 log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. Example: .. code-block:: python import logging import google.cloud.logging from google.cloud.logging.handlers import CloudLoggingHandler client = google.cloud.logging.Client() handler = CloudLoggingHandler(client) google.cloud.logging.handlers.setup_logging(handler) logging.getLogger().setLevel(logging.DEBUG) logging.error('bad news') # API call """ all_excluded_loggers = set(excluded_loggers + EXCLUDED_LOGGER_DEFAULTS) logger = logging.getLogger() logger.setLevel(log_level) logger.addHandler(handler) logger.addHandler(logging.StreamHandler()) for logger_name in all_excluded_loggers: logger = logging.getLogger(logger_name) logger.propagate = False logger.addHandler(logging.StreamHandler())
[ "def", "setup_logging", "(", "handler", ",", "excluded_loggers", "=", "EXCLUDED_LOGGER_DEFAULTS", ",", "log_level", "=", "logging", ".", "INFO", ")", ":", "all_excluded_loggers", "=", "set", "(", "excluded_loggers", "+", "EXCLUDED_LOGGER_DEFAULTS", ")", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "setLevel", "(", "log_level", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", ")", ")", "for", "logger_name", "in", "all_excluded_loggers", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "propagate", "=", "False", "logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", ")", ")" ]
Attach a logging handler to the Python root logger Excludes loggers that this library itself uses to avoid infinite recursion. :type handler: :class:`logging.handler` :param handler: the handler to attach to the global handler :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 log_level: int :param log_level: (Optional) Python logging log level. Defaults to :const:`logging.INFO`. Example: .. code-block:: python import logging import google.cloud.logging from google.cloud.logging.handlers import CloudLoggingHandler client = google.cloud.logging.Client() handler = CloudLoggingHandler(client) google.cloud.logging.handlers.setup_logging(handler) logging.getLogger().setLevel(logging.DEBUG) logging.error('bad news') # API call
[ "Attach", "a", "logging", "handler", "to", "the", "Python", "root", "logger" ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/handlers.py#L112-L156
train
googleapis/google-cloud-python
logging/google/cloud/logging/handlers/handlers.py
CloudLoggingHandler.emit
def emit(self, record): """Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged. """ message = super(CloudLoggingHandler, self).format(record) self.transport.send(record, message, resource=self.resource, labels=self.labels)
python
def emit(self, record): """Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged. """ message = super(CloudLoggingHandler, self).format(record) self.transport.send(record, message, resource=self.resource, labels=self.labels)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "message", "=", "super", "(", "CloudLoggingHandler", ",", "self", ")", ".", "format", "(", "record", ")", "self", ".", "transport", ".", "send", "(", "record", ",", "message", ",", "resource", "=", "self", ".", "resource", ",", "labels", "=", "self", ".", "labels", ")" ]
Actually log the specified logging record. Overrides the default emit behavior of ``StreamHandler``. See https://docs.python.org/2/library/logging.html#handler-objects :type record: :class:`logging.LogRecord` :param record: The record to be logged.
[ "Actually", "log", "the", "specified", "logging", "record", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/handlers/handlers.py#L98-L109
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/query.py
_query_param_from_api_repr
def _query_param_from_api_repr(resource): """Helper: construct concrete query parameter from JSON resource.""" qp_type = resource["parameterType"] if "arrayType" in qp_type: klass = ArrayQueryParameter elif "structTypes" in qp_type: klass = StructQueryParameter else: klass = ScalarQueryParameter return klass.from_api_repr(resource)
python
def _query_param_from_api_repr(resource): """Helper: construct concrete query parameter from JSON resource.""" qp_type = resource["parameterType"] if "arrayType" in qp_type: klass = ArrayQueryParameter elif "structTypes" in qp_type: klass = StructQueryParameter else: klass = ScalarQueryParameter return klass.from_api_repr(resource)
[ "def", "_query_param_from_api_repr", "(", "resource", ")", ":", "qp_type", "=", "resource", "[", "\"parameterType\"", "]", "if", "\"arrayType\"", "in", "qp_type", ":", "klass", "=", "ArrayQueryParameter", "elif", "\"structTypes\"", "in", "qp_type", ":", "klass", "=", "StructQueryParameter", "else", ":", "klass", "=", "ScalarQueryParameter", "return", "klass", ".", "from_api_repr", "(", "resource", ")" ]
Helper: construct concrete query parameter from JSON resource.
[ "Helper", ":", "construct", "concrete", "query", "parameter", "from", "JSON", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/query.py#L616-L625
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/query.py
ScalarQueryParameter.from_api_repr
def from_api_repr(cls, resource): """Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance """ name = resource.get("name") type_ = resource["parameterType"]["type"] value = resource["parameterValue"]["value"] converted = _QUERY_PARAMS_FROM_JSON[type_](value, None) return cls(name, type_, converted)
python
def from_api_repr(cls, resource): """Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance """ name = resource.get("name") type_ = resource["parameterType"]["type"] value = resource["parameterValue"]["value"] converted = _QUERY_PARAMS_FROM_JSON[type_](value, None) return cls(name, type_, converted)
[ "def", "from_api_repr", "(", "cls", ",", "resource", ")", ":", "name", "=", "resource", ".", "get", "(", "\"name\"", ")", "type_", "=", "resource", "[", "\"parameterType\"", "]", "[", "\"type\"", "]", "value", "=", "resource", "[", "\"parameterValue\"", "]", "[", "\"value\"", "]", "converted", "=", "_QUERY_PARAMS_FROM_JSON", "[", "type_", "]", "(", "value", ",", "None", ")", "return", "cls", "(", "name", ",", "type_", ",", "converted", ")" ]
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance
[ "Factory", ":", "construct", "parameter", "from", "JSON", "resource", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/query.py#L118-L131
train