INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 :par...
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 h...
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.
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. """ ha...
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 ...
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 pass...
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...
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 :me...
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`` :par...
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 ...
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:...
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 ...
Start a thread to dispatch requests queued up by callbacks. Spawns a thread to run :meth:`dispatch_callback`.
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...
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...
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: Valu...
Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge.
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...
Remove the given messages from lease management. Args: items(Sequence[DropRequest]): The items to 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()
Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]): The items to modify.
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.Strea...
Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]): The items to deny.
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.Dro...
Add the given messages to lease management. Args: items(Sequence[LeaseRequest]): The items to 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()
Submits a job to a cluster. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO:...
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: ...
Updates a job in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.JobControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO:...
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. Examp...
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...
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 ...
Return a fully-qualified instance string.
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, )
Return a fully-qualified app_profile string.
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, ...
Return a fully-qualified cluster string.
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...
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]') >>> >>> ...
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: >>> f...
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.insta...
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...
Partially updates an instance within a project. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableInstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> 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: ...
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]') >>> ...
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: >>>...
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]') >>> ...
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 c...
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]') >>> ...
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...
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 = {} ...
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. ...
Return a fully-qualified annotation_spec_set string.
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...
Return a fully-qualified dataset string.
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 )
Return a fully-qualified annotated_dataset string.
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, ...
Return a fully-qualified example string.
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, ...
Return a fully-qualified data_item string.
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=d...
Return a fully-qualified instruction string.
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, )
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_v1b...
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_...
Exports data and annotations from dataset. Example: >>> from google.cloud import datalabeling_v1beta1 >>> >>> client = datalabeling_v1beta1.DataLabelingServiceClient() >>> >>> name = client.dataset_path('[PROJECT]', '[DATASET]') >>> ...
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...
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_v1b...
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.gap...
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_v1bet...
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, ): ...
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]') >>> ...
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: ...
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: ...
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 con...
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.
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. ...
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.
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 ...
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.dateti...
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`, ...
Update properties from resource in body of ``api_response`` :type resource: dict :param resource: variable representation returned from the API.
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: ...
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: ...
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 insta...
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 name...
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 t...
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...
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='|') ...
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 se...
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 p...
Set helper for protobuf Messages.
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 ...
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.
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...
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 ...
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, emp...
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 ...
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)...
Return a fully-qualified topic string.
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 )
Return a fully-qualified snapshot string.
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, )
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 thi...
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.ap...
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, yo...
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 snapsh...
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.p...
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, ): ...
Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance.
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._dat...
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.
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 ...
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: ...
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 fr...
Delete all sessions in the pool.
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()
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.
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 que...
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.
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...
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.
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 ...
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: ...
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 fr...
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.
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. ...
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.
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) ...
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.
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)...
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.
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. ...
Begin all transactions for sessions added to the pool.
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)
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) ...
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...
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.
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. ...
Helper: construct concrete query parameter from JSON resource.
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 =...
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ScalarQueryParameter` :returns: instance
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("n...
Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping
def to_api_repr(self): """Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping """ value = self.value converter = _SCALAR_VALUE_TO_JSON_PARAM.get(self.type_) if converter is not None: value = converter(value) ...
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ArrayQueryParameter` :returns: instance
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.ArrayQueryParameter` :returns: instance """ array_type = resource["...
Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping
def to_api_repr(self): """Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping """ values = self.values if self.array_type == "RECORD" or self.array_type == "STRUCT": reprs = [value.to_api_repr() for value in values] ...
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.StructQueryParameter` :returns: instance
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.StructQueryParameter` :returns: instance """ name = resource.get("n...
Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping
def to_api_repr(self): """Construct JSON API representation for the parameter. :rtype: dict :returns: JSON mapping """ s_types = {} values = {} for name, value in self.struct_values.items(): type_ = self.struct_types[name] if type_ in ("ST...
Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call
def _set_properties(self, api_response): """Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call """ job_id_present = ( "jobReference" in api_response and "jobId" in a...
Format the message into JSON expected by fluentd. :type record: :class:`~logging.LogRecord` :param record: the log record :rtype: str :returns: A JSON string formatted for GKE fluentd.
def format(self, record): """Format the message into JSON expected by fluentd. :type record: :class:`~logging.LogRecord` :param record: the log record :rtype: str :returns: A JSON string formatted for GKE fluentd. """ message = super(ContainerEngineHandler, self...
Analyzes the sentiment of the provided text. Example: >>> from google.cloud import language_v1 >>> >>> client = language_v1.LanguageServiceClient() >>> >>> # TODO: Initialize `document`: >>> document = {} >>> >>> re...
def analyze_sentiment( self, document, encoding_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Analyzes the sentiment of the provided text. Example: ...
Call ``Commit`` on the GAPIC client with retry / sleep. Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level retry is handled by the underlying GAPICd client, but in this case it doesn't because ``Commit`` is not always idempotent. But here we know it is "idempotent"-like because it has a ...
def _commit_with_retry(client, write_pbs, transaction_id): """Call ``Commit`` on the GAPIC client with retry / sleep. Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level retry is handled by the underlying GAPICd client, but in this case it doesn't because ``Commit`` is not always idempote...
Sleep and produce a new sleep time. .. _Exponential Backoff And Jitter: https://www.awsarchitectureblog.com/\ 2015/03/backoff.html Select a duration between zero and ``current_sleep``. It might seem counterintuitive to have so much jitter, but `Exponential Backo...
def _sleep(current_sleep, max_sleep=_MAX_SLEEP, multiplier=_MULTIPLIER): """Sleep and produce a new sleep time. .. _Exponential Backoff And Jitter: https://www.awsarchitectureblog.com/\ 2015/03/backoff.html Select a duration between zero and ``current_sleep``. It mi...
Add `Write`` protobufs to this transaction. Args: write_pbs (List[google.cloud.proto.firestore.v1beta1.\ write_pb2.Write]): A list of write protobufs to be added. Raises: ValueError: If this transaction is read-only.
def _add_write_pbs(self, write_pbs): """Add `Write`` protobufs to this transaction. Args: write_pbs (List[google.cloud.proto.firestore.v1beta1.\ write_pb2.Write]): A list of write protobufs to be added. Raises: ValueError: If this transaction is read-onl...
Convert the current object to protobuf. The ``retry_id`` value is used when retrying a transaction that failed (e.g. due to contention). It is intended to be the "first" transaction that failed (i.e. if multiple retries are needed). Args: retry_id (Union[bytes, NoneType]): ...
def _options_protobuf(self, retry_id): """Convert the current object to protobuf. The ``retry_id`` value is used when retrying a transaction that failed (e.g. due to contention). It is intended to be the "first" transaction that failed (i.e. if multiple retries are needed). Arg...
Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun.
def _begin(self, retry_id=None): """Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun. """ if self.in_progress: ...
Roll back the transaction. Raises: ValueError: If no transaction is in progress.
def _rollback(self): """Roll back the transaction. Raises: ValueError: If no transaction is in progress. """ if not self.in_progress: raise ValueError(_CANT_ROLLBACK) try: # NOTE: The response is just ``google.protobuf.Empty``. se...
Transactionally commit the changes accumulated. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes were applied to this transact...
def _commit(self): """Transactionally commit the changes accumulated. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes...
Begin transaction and call the wrapped callable. If the callable raises an exception, the transaction will be rolled back. If not, the transaction will be "ready" for ``Commit`` (i.e. it will have staged writes). Args: transaction (~.firestore_v1beta1.transaction.Transactio...
def _pre_commit(self, transaction, *args, **kwargs): """Begin transaction and call the wrapped callable. If the callable raises an exception, the transaction will be rolled back. If not, the transaction will be "ready" for ``Commit`` (i.e. it will have staged writes). Args: ...
Try to commit the transaction. If the transaction is read-write and the ``Commit`` fails with the ``ABORTED`` status code, it will be retried. Any other failure will not be caught. Args: transaction (~.firestore_v1beta1.transaction.Transaction): The transact...
def _maybe_commit(self, transaction): """Try to commit the transaction. If the transaction is read-write and the ``Commit`` fails with the ``ABORTED`` status code, it will be retried. Any other failure will not be caught. Args: transaction (~.firestore_v1beta1.trans...
Return a fully-qualified profile string.
def profile_path(cls, project, tenant, profile): """Return a fully-qualified profile string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}/profiles/{profile}", project=project, tenant=tenant, profile=profile, ...
Creates and returns a new profile. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ProfileServiceClient() >>> >>> parent = client.tenant_path('[PROJECT]', '[TENANT]') >>> >>> # TODO: Initial...
def create_profile( self, parent, profile, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates and returns a new profile. Example: >>> from google.cloud impo...
Gets the specified profile. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ProfileServiceClient() >>> >>> name = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]') >>> >>> response =...
def get_profile( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the specified profile. Example: >>> from google.cloud import talent_v4beta1 ...
Updates the specified profile and returns the updated result. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ProfileServiceClient() >>> >>> # TODO: Initialize `profile`: >>> profile = {} >>...
def update_profile( self, profile, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates the specified profile and returns the updated result. Example: ...
Searches for profiles within a tenant. For example, search by raw queries "software engineer in Mountain View" or search by structured filters (location filter, education filter, etc.). See ``SearchProfilesRequest`` for more information. Example: >>> from google.cl...
def search_profiles( self, parent, request_metadata, profile_query=None, page_size=None, offset=None, disable_spell_check=None, order_by=None, case_sensitive_sort=None, histogram_queries=None, retry=google.api_core.gapic_v1.method.D...
Perform an online prediction. The prediction result will be directly returned in the response. Available for following ML problems, and their expected request payloads: - Image Classification - Image in .JPEG, .GIF or .PNG format, image\_bytes up to 30MB. - Image Object Det...
def predict( self, name, payload, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Perform an online prediction. The prediction result will be directly re...
Perform a batch prediction. Unlike the online ``Predict``, batch prediction result won't be immediately available in the response. Instead, a long running operation object is returned. User can poll the operation result via ``GetOperation`` method. Once the operation is done, ``BatchPred...
def batch_predict( self, name, input_config, output_config, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Perform a batch prediction. Unlike the online...
Factory to retrieve JSON credentials while creating client. :type json_credentials_path: str :param json_credentials_path: The path to a private key file (this file was given to you when you created the service account). This f...
def from_service_account_json(cls, json_credentials_path, *args, **kwargs): """Factory to retrieve JSON credentials while creating client. :type json_credentials_path: str :param json_credentials_path: The path to a private key file (this file was given to ...
Getter for object used for HTTP transport. :rtype: :class:`~requests.Session` :returns: An HTTP object.
def _http(self): """Getter for object used for HTTP transport. :rtype: :class:`~requests.Session` :returns: An HTTP object. """ if self._http_internal is None: self._http_internal = google.auth.transport.requests.AuthorizedSession( self._credentials ...
Return a fully-qualified alert_policy string.
def alert_policy_path(cls, project, alert_policy): """Return a fully-qualified alert_policy string.""" return google.api_core.path_template.expand( "projects/{project}/alertPolicies/{alert_policy}", project=project, alert_policy=alert_policy, )
Return a fully-qualified alert_policy_condition string.
def alert_policy_condition_path(cls, project, alert_policy, condition): """Return a fully-qualified alert_policy_condition string.""" return google.api_core.path_template.expand( "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}", project=project, ...