INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Coerce value to an JSON - compatible representation. | def _time_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, datetime.time):
value = value.isoformat()
return value |
Maps a field and value to a JSON - safe value. | def _scalar_field_to_json(field, row_value):
"""Maps a field and value to a JSON-safe value.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (any):
Value to ... |
Convert a repeated/ array field to its JSON representation. | def _repeated_field_to_json(field, row_value):
"""Convert a repeated/array field to its JSON representation.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name. The
field mode mus... |
Convert a record/ struct field to its JSON representation. | def _record_field_to_json(fields, row_value):
"""Convert a record/struct field to its JSON representation.
Args:
fields ( \
Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`], \
):
The :class:`~google.cloud.bigquery.schema.SchemaField`s of the
recor... |
Convert a field into JSON - serializable values. | def _field_to_json(field, row_value):
"""Convert a field into JSON-serializable values.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (Union[ \
Sequence[l... |
Convert snake case string to camel case. | def _snake_to_camel_case(value):
"""Convert snake case string to camel case."""
words = value.split("_")
return words[0] + "".join(map(str.capitalize, words[1:])) |
Get a nested value from a dictionary. | def _get_sub_prop(container, keys, default=None):
"""Get a nested value from a dictionary.
This method works like ``dict.get(key)``, but for nested values.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A s... |
Set a nested value in a dictionary. | def _set_sub_prop(container, keys, value):
"""Set a nested value in a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to set the value for. Each item in
the s... |
Remove a nested key fro a dictionary. | def _del_sub_prop(container, keys):
"""Remove a nested key fro a dictionary.
Arguments:
container (dict):
A dictionary which may contain other dictionaries as values.
keys (iterable):
A sequence of keys to attempt to clear the value for. Each item in
the sequ... |
Build a resource based on a _properties dictionary filtered by filter_fields which follow the name of the Python object. | def _build_resource_from_properties(obj, filter_fields):
"""Build a resource based on a ``_properties`` dictionary, filtered by
``filter_fields``, which follow the name of the Python object.
"""
partial = {}
for filter_field in filter_fields:
api_field = obj._PROPERTY_TO_API_FIELD.get(filter... |
Sample ID: go/ samples - tracker/ 1510 | def get_model(client, model_id):
"""Sample ID: go/samples-tracker/1510"""
# [START bigquery_get_model]
from google.cloud import bigquery
# TODO(developer): Construct a BigQuery client object.
# client = bigquery.Client()
# TODO(developer): Set model_id to the ID of the model to fetch.
# m... |
Make sure a Reference database ID is empty. | def _check_database_id(database_id):
"""Make sure a "Reference" database ID is empty.
:type database_id: unicode
:param database_id: The ``database_id`` field from a "Reference" protobuf.
:raises: :exc:`ValueError` if the ``database_id`` is not empty.
"""
if database_id != u"":
msg = _... |
Add the ID or name from an element to a list. | def _add_id_or_name(flat_path, element_pb, empty_allowed):
"""Add the ID or name from an element to a list.
:type flat_path: list
:param flat_path: List of accumulated path parts.
:type element_pb: :class:`._app_engine_key_pb2.Path.Element`
:param element_pb: The element containing ID or name.
... |
Convert a legacy Path protobuf to a flat path. | def _get_flat_path(path_pb):
"""Convert a legacy "Path" protobuf to a flat path.
For example
Element {
type: "parent"
id: 59
}
Element {
type: "child"
name: "naem"
}
would convert to ``('parent', 59, 'child', 'naem')``.
:type pa... |
Convert a tuple of ints and strings in a legacy Path. | def _to_legacy_path(dict_path):
"""Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: ... |
Parses positional arguments into key path with kinds and IDs. | def _parse_path(path_args):
"""Parses positional arguments into key path with kinds and IDs.
:type path_args: tuple
:param path_args: A tuple from positional arguments. Should be
alternating list of kinds (string) and ID/name
parts (int or str... |
Sets protected data by combining raw data set from the constructor. | def _combine_args(self):
"""Sets protected data by combining raw data set from the constructor.
If a ``_parent`` is set, updates the ``_flat_path`` and sets the
``_namespace`` and ``_project`` if not already set.
:rtype: :class:`list` of :class:`dict`
:returns: A list of key pa... |
Duplicates the Key. | def _clone(self):
"""Duplicates the Key.
Most attributes are simple types, so don't require copying. Other
attributes like ``parent`` are long-lived and so we re-use them.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance with the same data as the... |
Creates new key from existing partial key by adding final ID/ name. | def completed_key(self, id_or_name):
"""Creates new key from existing partial key by adding final ID/name.
:type id_or_name: str or integer
:param id_or_name: ID or name to be added to the key.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: A new ``Key`` instance wit... |
Return a protobuf corresponding to the key. | def to_protobuf(self):
"""Return a protobuf corresponding to the key.
:rtype: :class:`.entity_pb2.Key`
:returns: The protobuf representing the key.
"""
key = _entity_pb2.Key()
key.partition_id.project_id = self.project
if self.namespace:
key.partitio... |
Convert to a base64 encode urlsafe string for App Engine. | def to_legacy_urlsafe(self, location_prefix=None):
"""Convert to a base64 encode urlsafe string for App Engine.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). The returned string can be used as the ... |
Convert urlsafe string to: class: ~google. cloud. datastore. key. Key. | def from_legacy_urlsafe(cls, urlsafe):
"""Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). This assumes that ``urlsafe`` was created... |
Creates a parent key for the current path. | def _make_parent(self):
"""Creates a parent key for the current path.
Extracts all but the last element in the key path and creates a new
key, while still matching the namespace and the project.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A ne... |
The parent of the current key. | def parent(self):
"""The parent of the current key.
:rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType`
:returns: A new ``Key`` instance, whose path consists of all but the
last element of current path. If the current key has only
one path el... |
Factory: construct a record set given its API representation | def from_api_repr(cls, resource, zone):
"""Factory: construct a record set given its API representation
:type resource: dict
:param resource: record sets representation returned from the API
:type zone: :class:`google.cloud.dns.zone.ManagedZone`
:param zone: A zone which holds... |
The entry point for the worker thread. | def _thread_main(self):
"""The entry point for the worker thread.
Pulls pending log entries off the queue and writes them in batches to
the Cloud Logger.
"""
_LOGGER.debug("Background thread started.")
quit_ = False
while True:
batch = self._cloud_lo... |
Starts the background thread. | def start(self):
"""Starts the background thread.
Additionally, this registers a handler for process exit to attempt
to send any pending log entries before shutdown.
"""
with self._operational_lock:
if self.is_alive:
return
self._thread =... |
Signals the background thread to stop. | def stop(self, grace_period=None):
"""Signals the background thread to stop.
This does not terminate the background thread. It simply queues the
stop signal. If the main process exits before the background thread
processes the stop signal, it will be terminated without finishing
... |
Callback that attempts to send pending logs before termination. | def _main_thread_terminated(self):
"""Callback that attempts to send pending logs before termination."""
if not self.is_alive:
return
if not self._queue.empty():
print(
"Program shutting down, attempting to send %d queued log "
"entries to... |
Queues a log entry to be written by the background thread. | def enqueue(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
"""Queues a log entry to be written by the background thread.
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type messag... |
Overrides Transport. send (). | def send(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
"""Overrides Transport.send().
:type record: :class:`logging.LogRecord`
:param record: Python log record that the handler was called with.
:type message: str
:param message: The... |
Lex a field path into tokens ( including dots ). | def _tokenize_field_path(path):
"""Lex a field path into tokens (including dots).
Args:
path (str): field path to be lexed.
Returns:
List(str): tokens
"""
pos = 0
get_token = TOKENS_REGEX.match
match = get_token(path)
while match is not None:
type_ = match.lastgr... |
Split a field path into valid elements ( without dots ). | def split_field_path(path):
"""Split a field path into valid elements (without dots).
Args:
path (str): field path to be lexed.
Returns:
List(str): tokens
Raises:
ValueError: if the path does not match the elements-interspersed-
with-dots pattern.
"""
... |
Parse a ** field path ** from into a list of nested field names. | def parse_field_path(api_repr):
"""Parse a **field path** from into a list of nested field names.
See :func:`field_path` for more on **field paths**.
Args:
api_repr (str):
The unique Firestore api representation which consists of
either simple or UTF-8 field names. It canno... |
Create a ** field path ** from a list of nested field names. | def render_field_path(field_names):
"""Create a **field path** from a list of nested field names.
A **field path** is a ``.``-delimited concatenation of the field
names. It is used to represent a nested field. For example,
in the data
.. code-block: python
data = {
'aa': {
... |
Get a ( potentially nested ) value from a dictionary. | def get_nested_value(field_path, data):
"""Get a (potentially nested) value from a dictionary.
If the data is nested, for example:
.. code-block:: python
>>> data
{
'top1': {
'middle2': {
'bottom3': 20,
'bottom4': 22,
... |
Factory: create a FieldPath from the string formatted per the API. | def from_api_repr(cls, api_repr):
"""Factory: create a FieldPath from the string formatted per the API.
Args:
api_repr (str): a string path, with non-identifier elements quoted
It cannot exceed 1500 characters, and cannot be empty.
Returns:
(:class:`FieldPath... |
Factory: create a FieldPath from a unicode string representation. | def from_string(cls, path_string):
"""Factory: create a FieldPath from a unicode string representation.
This method splits on the character `.` and disallows the
characters `~*/[]`. To create a FieldPath whose components have
those characters, call the constructor.
Args:
... |
Check whether other is an ancestor. | def eq_or_parent(self, other):
"""Check whether ``other`` is an ancestor.
Returns:
(bool) True IFF ``other`` is an ancestor or equal to ``self``,
else False.
"""
return self.parts[: len(other.parts)] == other.parts[: len(self.parts)] |
Return field paths for all parents. | def lineage(self):
"""Return field paths for all parents.
Returns: Set[:class:`FieldPath`]
"""
indexes = six.moves.range(1, len(self.parts))
return {FieldPath(*self.parts[:index]) for index in indexes} |
Gets the latest state of a long - running operation. | def get_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Gets the latest state of a long-running operation.
Clients can use this method to poll the operation result at intervals
as recommended by the API service.
Example:
... |
Lists operations that match the specified filter in the request. | def list_operations(
self,
name,
filter_,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
"""
Lists operations that match the specified filter in the request.
Example:
>>> from google.api_core import operations_v1
... |
Starts asynchronous cancellation on a long - running operation. | def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_oper... |
Deletes a long - running operation. | def delete_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Deletes a long-running operation.
This method indicates that the client is no longer interested in the
operation result. It does not cancel the operation.
Example:
... |
Extract the config name from a full resource name. | def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like... |
Extract the variable name from a full resource name. | def variable_name_from_full_name(full_name):
"""Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-con... |
Return the maximum value in this histogram. | def max(self):
"""Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
"""
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(s... |
Return the minimum value in this histogram. | def min(self):
"""Return the minimum value in this histogram.
If there are no values in the histogram at all, return 10.
Returns:
int: The minimum value in the histogram.
"""
if len(self._data) == 0:
return 10
return next(iter(sorted(self._data.k... |
Add the value to this histogram. | def add(self, value):
"""Add the value to this histogram.
Args:
value (int): The value. Values outside of ``10 <= x <= 600``
will be raised to ``10`` or reduced to ``600``.
"""
# If the value is out of bounds, bring it in bounds.
value = int(value)
... |
Return the value that is the Nth precentile in the histogram. | def percentile(self, percent):
"""Return the value that is the Nth precentile in the histogram.
Args:
percent (Union[int, float]): The precentile being sought. The
default consumer implementations use consistently use ``99``.
Returns:
int: The value corr... |
Return a fully - qualified job string. | def job_path(cls, project, location, job):
"""Return a fully-qualified job string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/jobs/{job}",
project=project,
location=location,
job=job,
) |
Creates a job. | def create_job(
self,
parent,
job,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a job.
Example:
>>> from google.cloud import scheduler_v1beta1
... |
A: class: ~google. cloud. bigquery. model. ModelReference pointing to this model. | def reference(self):
"""A :class:`~google.cloud.bigquery.model.ModelReference` pointing to
this model.
Read-only.
Returns:
google.cloud.bigquery.model.ModelReference: pointer to this model.
"""
ref = ModelReference()
ref._proto = self._proto.model_re... |
Union [ datetime. datetime None ]: Datetime at which the model was created (: data: None until set from the server ). | def created(self):
"""Union[datetime.datetime, None]: Datetime at which the model was
created (:data:`None` until set from the server).
Read-only.
"""
value = self._proto.creation_time
if value is not None and value != 0:
# value will be in milliseconds.
... |
Union [ datetime. datetime None ]: Datetime at which the model was last modified (: data: None until set from the server ). | def modified(self):
"""Union[datetime.datetime, None]: Datetime at which the model was last
modified (:data:`None` until set from the server).
Read-only.
"""
value = self._proto.last_modified_time
if value is not None and value != 0:
# value will be in millis... |
Union [ datetime. datetime None ]: The datetime when this model expires. If not present the model will persist indefinitely. Expired models will be deleted and their storage reclaimed. | def expires(self):
"""Union[datetime.datetime, None]: The datetime when this model
expires. If not present, the model will persist indefinitely. Expired
models will be deleted and their storage reclaimed.
"""
value = self._properties.get("expirationTime")
if value is not ... |
Factory: construct a model resource given its API representation | def from_api_repr(cls, resource):
"""Factory: construct a model resource given its API representation
Args:
resource (Dict[str, object]):
Model resource representation from the API
Returns:
google.cloud.bigquery.model.Model: Model parsed from ``resource`... |
str: URL path for the model s APIs. | def path(self):
"""str: URL path for the model's APIs."""
return "/projects/%s/datasets/%s/models/%s" % (
self._proto.project_id,
self._proto.dataset_id,
self._proto.model_id,
) |
Factory: construct a model reference given its API representation | def from_api_repr(cls, resource):
"""Factory: construct a model reference given its API representation
Args:
resource (Dict[str, object]):
Model reference representation returned from the API
Returns:
google.cloud.bigquery.model.ModelReference:
... |
Construct a model reference from model ID string. | def from_string(cls, model_id, default_project=None):
"""Construct a model reference from model ID string.
Args:
model_id (str):
A model ID in standard SQL format. If ``default_project``
is not specified, this must included a project ID, dataset
... |
Leases tasks from a pull queue for lease_duration. | def lease_tasks(
self,
parent,
lease_duration,
max_tasks=None,
response_view=None,
filter_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Leases tasks ... |
Helper to format a LogRecord in in Stackdriver fluentd format. | def format_stackdriver_json(record, message):
"""Helper to format a LogRecord in in Stackdriver fluentd format.
:rtype: str
:returns: JSON str to be written to the log file.
"""
subsecond, second = math.modf(record.created)
payload = {
"message": message,
"timestamp": {... |
Get trace_id from flask request headers. | def get_trace_id_from_flask():
"""Get trace_id from flask request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if flask is None or not flask.request:
return None
header = flask.request.headers.get(_FLASK_TRACE_HEADER)
if header is None:
return None
... |
Get trace_id from webapp2 request headers. | def get_trace_id_from_webapp2():
"""Get trace_id from webapp2 request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
if webapp2 is None:
return None
try:
# get_request() succeeds if we're in the middle of a webapp2
# request, or raises an assertion ... |
Get trace_id from django request headers. | def get_trace_id_from_django():
"""Get trace_id from django request headers.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
request = _get_django_request()
if request is None:
return None
header = request.META.get(_DJANGO_TRACE_HEADER)
if header is None:
re... |
Helper to get trace_id from web application request header. | def get_trace_id():
"""Helper to get trace_id from web application request header.
:rtype: str
:returns: TraceID in HTTP request headers.
"""
checkers = (
get_trace_id_from_django,
get_trace_id_from_flask,
get_trace_id_from_webapp2,
)
for checker in checkers:
... |
Return a fully - qualified group string. | def group_path(cls, project, group):
"""Return a fully-qualified group string."""
return google.api_core.path_template.expand(
"projects/{project}/groups/{group}", project=project, group=group
) |
Lists the existing groups. | def list_groups(
self,
name,
children_of_group=None,
ancestors_of_group=None,
descendants_of_group=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"... |
Returns a list of Voice supported for synthesis. | def list_voices(
self,
language_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.... |
Synthesizes speech synchronously: receive results after all text input has been processed. | def synthesize_speech(
self,
input_,
voice,
audio_config,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Synthesizes speech synchronously: receive results after all text inp... |
Raise AttributeError if the credentials are unsigned. | def ensure_signed_credentials(credentials):
"""Raise AttributeError if the credentials are unsigned.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:raises: :exc:`AttributeError` if ... |
Gets query parameters for creating a signed URL. | def get_signed_query_params_v2(credentials, expiration, string_to_sign):
"""Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expi... |
Convert expiration to a number of seconds in the future. | def get_expiration_seconds_v2(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration is not a valid ... |
Convert expiration to a number of seconds offset from the current time. | def get_expiration_seconds_v4(expiration):
"""Convert 'expiration' to a number of seconds offset from the current time.
:type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
:param expiration: Point in time when the signed URL should expire.
:raises: :exc:`TypeError` when expiration ... |
Canonicalize headers for signing. | def get_canonical_headers(headers):
"""Canonicalize headers for signing.
See:
https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers
:type headers: Union[dict|List(Tuple(str,str))]
:param headers:
(Optional) Additional HTTP headers to be included... |
Canonicalize method resource | def canonicalize(method, resource, query_parameters, headers):
"""Canonicalize method, resource
:type method: str
:param method: The HTTP verb that will be used when requesting the URL.
Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
signature will additio... |
Generate a V2 signed URL to provide query - string auth n to a resource. | def generate_signed_url_v2(
credentials,
resource,
expiration,
api_access_endpoint="",
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
):
"""Generate a V2 signed UR... |
Generate a V4 signed URL to provide query - string auth n to a resource. | def generate_signed_url_v4(
credentials,
resource,
expiration,
api_access_endpoint=DEFAULT_ENDPOINT,
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
_request_timest... |
Return a fully - qualified glossary string. | def glossary_path(cls, project, location, glossary):
"""Return a fully-qualified glossary string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/glossaries/{glossary}",
project=project,
location=location,
glossary=... |
Translates input text and returns translated text. | def translate_text(
self,
contents,
target_language_code,
mime_type=None,
source_language_code=None,
parent=None,
model=None,
glossary_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAU... |
Detects the language of text within a request. | def detect_language(
self,
parent=None,
model=None,
content=None,
mime_type=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Detects the language of text within ... |
Returns a list of supported languages for translation. | def get_supported_languages(
self,
parent=None,
display_language_code=None,
model=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of supported languages ... |
Translates a large volume of text in asynchronous batch mode. This function provides real - time output as the inputs are being processed. If caller cancels a request the partial results ( for an input file it s all or nothing ) may still be available on the specified output location. | def batch_translate_text(
self,
source_language_code,
target_language_codes,
input_configs,
output_config,
parent=None,
models=None,
glossaries=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEF... |
Creates a glossary and returns the long - running operation. Returns NOT \ _FOUND if the project doesn t exist. | def create_glossary(
self,
parent,
glossary,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a glossary and returns the long-running operation. Returns
NOT\_FOUND, if... |
Deletes a glossary or cancels glossary construction if the glossary isn t created yet. Returns NOT \ _FOUND if the glossary doesn t exist. | def delete_glossary(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a glossary, or cancels glossary construction if the glossary
isn't created yet. Returns NOT\_... |
Return a copy of time_series with the points removed. | def _extract_header(time_series):
"""Return a copy of time_series with the points removed."""
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) |
Build the combined resource and metric labels with resource_type. | def _extract_labels(time_series):
"""Build the combined resource and metric labels, with resource_type."""
labels = {"resource_type": time_series.resource.type}
labels.update(time_series.resource.labels)
labels.update(time_series.metric.labels)
return labels |
Build a: mod: pandas dataframe out of time series. | def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER
"""Build a :mod:`pandas` dataframe out of time series.
:type time_series_iterable:
iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries`
:param time_series_iterable:
An iterable (e.g., a q... |
Sort label names putting well - known resource labels first. | def _sorted_resource_labels(labels):
"""Sort label names, putting well-known resource labels first."""
head = [label for label in TOP_RESOURCE_LABELS if label in labels]
tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS)
return head + tail |
Starts a thread and marks it as a daemon thread. | def start_daemon_thread(*args, **kwargs):
"""Starts a thread and marks it as a daemon thread."""
thread = threading.Thread(*args, **kwargs)
thread.daemon = True
thread.start()
return thread |
Invoke a callback swallowing and logging any exceptions. | def safe_invoke_callback(callback, *args, **kwargs):
"""Invoke a callback, swallowing and logging any exceptions."""
# pylint: disable=bare-except
# We intentionally want to swallow all exceptions.
try:
return callback(*args, **kwargs)
except Exception:
_LOGGER.exception("Error while... |
Create a project bound to the current client. | def new_project(self, project_id, name=None, labels=None):
"""Create a project bound to the current client.
Use :meth:`Project.reload() \
<google.cloud.resource_manager.project.Project.reload>` to retrieve
project metadata after creating a
:class:`~google.cloud.resource_manager.... |
Fetch an existing project and it s relevant metadata by ID. | def fetch_project(self, project_id):
"""Fetch an existing project and it's relevant metadata by ID.
.. note::
If the project does not exist, this will raise a
:class:`NotFound <google.cloud.exceptions.NotFound>` error.
:type project_id: str
:param project_id: T... |
List the projects visible to this client. | def list_projects(self, filter_params=None, page_size=None):
"""List the projects visible to this client.
Example::
>>> from google.cloud import resource_manager
>>> client = resource_manager.Client()
>>> for project in client.list_projects():
... pr... |
Return a fully - qualified session string. | def session_path(cls, project, instance, database, session):
"""Return a fully-qualified session string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}/sessions/{session}",
project=project,
instance=instan... |
Creates a new session. A session can be used to perform transactions that read and/ or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. | def create_session(
self,
database,
session=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new session. A session can be used to perform transactions
that re... |
Like ExecuteSql except returns the result set as a stream. Unlike ExecuteSql there is no limit on the size of the returned result set. However no individual row in the result set can exceed 100 MiB and no column value can exceed 10 MiB. | def execute_streaming_sql(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
resume_token=None,
query_mode=None,
partition_token=None,
seqno=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=goo... |
Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with ExecuteSql. | def execute_batch_dml(
self,
session,
transaction,
statements,
seqno,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Executes a batch of SQL DML statements. This met... |
Reads rows from the database using key lookups and scans as a simple key/ value style alternative to ExecuteSql. This method cannot be used to return a result set larger than 10 MiB ; if the read matches more data than that the read fails with a FAILED_PRECONDITION error. | def read(
self,
session,
table,
columns,
key_set,
transaction=None,
index=None,
limit=None,
resume_token=None,
partition_token=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFA... |
Commits a transaction. The request includes the mutations to be applied to rows in the database. | def commit(
self,
session,
mutations,
transaction_id=None,
single_use_transaction=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Commits a transaction. The req... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.