Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def from_api_repr(cls, resource, zone):
name = resource["name"]
record_type = resource["type"]
ttl = int(resource["ttl"])
rrdatas = resource["rrdatas"]
return cls(name, record_type, ttl, rrdatas, zone=zone) | [
"Factory: construct a record set given its API representation\n\n :type resource: dict\n :param resource: record sets representation returned from the API\n\n :type zone: :class:`google.cloud.dns.zone.ManagedZone`\n :param zone: A zone which holds one or more record sets.\n\n :rt... |
Please provide a description of the function:def _thread_main(self):
_LOGGER.debug("Background thread started.")
quit_ = False
while True:
batch = self._cloud_logger.batch()
items = _get_many(
self._queue,
max_items=self._max_batc... | [
"The entry point for the worker thread.\n\n Pulls pending log entries off the queue and writes them in batches to\n the Cloud Logger.\n "
] |
Please provide a description of the function:def start(self):
with self._operational_lock:
if self.is_alive:
return
self._thread = threading.Thread(
target=self._thread_main, name=_WORKER_THREAD_NAME
)
self._thread.daemon ... | [
"Starts the background thread.\n\n Additionally, this registers a handler for process exit to attempt\n to send any pending log entries before shutdown.\n "
] |
Please provide a description of the function:def stop(self, grace_period=None):
if not self.is_alive:
return True
with self._operational_lock:
self._queue.put_nowait(_WORKER_TERMINATOR)
if grace_period is not None:
print("Waiting up to %d se... | [
"Signals the background thread to stop.\n\n This does not terminate the background thread. It simply queues the\n stop signal. If the main process exits before the background thread\n processes the stop signal, it will be terminated without finishing\n work. The ``grace_period`` paramete... |
Please provide a description of the function:def _main_thread_terminated(self):
if not self.is_alive:
return
if not self._queue.empty():
print(
"Program shutting down, attempting to send %d queued log "
"entries to Stackdriver Logging..."... | [
"Callback that attempts to send pending logs before termination."
] |
Please provide a description of the function:def enqueue(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
self._queue.put_nowait(
{
"info": {"message": message, "python_logger": record.name},
"severity": record.level... | [
"Queues a log entry to be written by the background thread.\n\n :type record: :class:`logging.LogRecord`\n :param record: Python log record that the handler was called with.\n\n :type message: str\n :param message: The message from the ``LogRecord`` after being\n f... |
Please provide a description of the function:def send(
self, record, message, resource=None, labels=None, trace=None, span_id=None
):
self.worker.enqueue(
record,
message,
resource=resource,
labels=labels,
trace=trace,
... | [
"Overrides Transport.send().\n\n :type record: :class:`logging.LogRecord`\n :param record: Python log record that the handler was called with.\n\n :type message: str\n :param message: The message from the ``LogRecord`` after being\n formatted by the associated log ... |
Please provide a description of the function:def _tokenize_field_path(path):
pos = 0
get_token = TOKENS_REGEX.match
match = get_token(path)
while match is not None:
type_ = match.lastgroup
value = match.group(type_)
yield value
pos = match.end()
match = get_t... | [
"Lex a field path into tokens (including dots).\n\n Args:\n path (str): field path to be lexed.\n Returns:\n List(str): tokens\n "
] |
Please provide a description of the function:def split_field_path(path):
if not path:
return []
elements = []
want_dot = False
for element in _tokenize_field_path(path):
if want_dot:
if element != ".":
raise ValueError("Invalid path: {}".format(path))
... | [
"Split a field path into valid elements (without dots).\n\n Args:\n path (str): field path to be lexed.\n Returns:\n List(str): tokens\n Raises:\n ValueError: if the path does not match the elements-interspersed-\n with-dots pattern.\n "
] |
Please provide a description of the function:def parse_field_path(api_repr):
# code dredged back up from
# https://github.com/googleapis/google-cloud-python/pull/5109/files
field_names = []
for field_name in split_field_path(api_repr):
# non-simple field name
if field_name[0] == "`"... | [
"Parse a **field path** from into a list of nested field names.\n\n See :func:`field_path` for more on **field paths**.\n\n Args:\n api_repr (str):\n The unique Firestore api representation which consists of\n either simple or UTF-8 field names. It cannot exceed\n 1500 ... |
Please provide a description of the function:def render_field_path(field_names):
result = []
for field_name in field_names:
match = _SIMPLE_FIELD_NAME.match(field_name)
if match and match.group(0) == field_name:
result.append(field_name)
else:
replaced = fie... | [
"Create a **field path** from a list of nested field names.\n\n A **field path** is a ``.``-delimited concatenation of the field\n names. It is used to represent a nested field. For example,\n in the data\n\n .. code-block: python\n\n data = {\n 'aa': {\n 'bb': {\n ... |
Please provide a description of the function:def get_nested_value(field_path, data):
field_names = parse_field_path(field_path)
nested_data = data
for index, field_name in enumerate(field_names):
if isinstance(nested_data, collections_abc.Mapping):
if field_name in nested_data:
... | [
"Get a (potentially nested) value from a dictionary.\n\n If the data is nested, for example:\n\n .. code-block:: python\n\n >>> data\n {\n 'top1': {\n 'middle2': {\n 'bottom3': 20,\n 'bottom4': 22,\n },\n 'midd... |
Please provide a description of the function:def from_api_repr(cls, api_repr):
api_repr = api_repr.strip()
if not api_repr:
raise ValueError("Field path API representation cannot be empty.")
return cls(*parse_field_path(api_repr)) | [
"Factory: create a FieldPath from the string formatted per the API.\n\n Args:\n api_repr (str): a string path, with non-identifier elements quoted\n It cannot exceed 1500 characters, and cannot be empty.\n Returns:\n (:class:`FieldPath`) An instance parsed from ``api_r... |
Please provide a description of the function:def from_string(cls, path_string):
try:
return cls.from_api_repr(path_string)
except ValueError:
elements = path_string.split(".")
for element in elements:
if not element:
raise ... | [
"Factory: create a FieldPath from a unicode string representation.\n\n This method splits on the character `.` and disallows the\n characters `~*/[]`. To create a FieldPath whose components have\n those characters, call the constructor.\n\n Args:\n path_string (str): A unicode... |
Please provide a description of the function:def eq_or_parent(self, other):
return self.parts[: len(other.parts)] == other.parts[: len(self.parts)] | [
"Check whether ``other`` is an ancestor.\n\n Returns:\n (bool) True IFF ``other`` is an ancestor or equal to ``self``,\n else False.\n "
] |
Please provide a description of the function:def lineage(self):
indexes = six.moves.range(1, len(self.parts))
return {FieldPath(*self.parts[:index]) for index in indexes} | [
"Return field paths for all parents.\n\n Returns: Set[:class:`FieldPath`]\n "
] |
Please provide a description of the function:def get_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
request = operations_pb2.GetOperationRequest(name=name)
return self._get_operation(request, retry=retry, timeout=timeout) | [
"Gets the latest state of a long-running operation.\n\n Clients can use this method to poll the operation result at intervals\n as recommended by the API service.\n\n Example:\n >>> from google.api_core import operations_v1\n >>> api = operations_v1.OperationsClient()\n ... |
Please provide a description of the function:def list_operations(
self,
name,
filter_,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
# Create the request object.
request = operations_pb2.ListOperationsRequest(name=name, filter=fil... | [
"\n Lists operations that match the specified filter in the request.\n\n Example:\n >>> from google.api_core import operations_v1\n >>> api = operations_v1.OperationsClient()\n >>> name = ''\n >>>\n >>> # Iterate over all results\n >>> ... |
Please provide a description of the function:def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
# Create the request object.
request = operations_pb2.CancelOperationRequest(name=name)
self._cancel_operation(request, retry=retr... | [
"Starts asynchronous cancellation on a long-running operation.\n\n The server makes a best effort to cancel the operation, but success is\n not guaranteed. Clients can use :meth:`get_operation` or service-\n specific methods to check whether the cancellation succeeded or whether\n the op... |
Please provide a description of the function:def delete_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
# Create the request object.
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, retry=retr... | [
"Deletes a long-running operation.\n\n This method indicates that the client is no longer interested in the\n operation result. It does not cancel the operation.\n\n Example:\n >>> from google.api_core import operations_v1\n >>> api = operations_v1.OperationsClient()\n ... |
Please provide a description of the function:def config_name_from_full_name(full_name):
projects, _, configs, result = full_name.split("/")
if projects != "projects" or configs != "configs":
raise ValueError(
"Unexpected format of resource",
full_name,
'Expected ... | [
"Extract the config name from a full resource name.\n\n >>> config_name_from_full_name('projects/my-proj/configs/my-config')\n \"my-config\"\n\n :type full_name: str\n :param full_name:\n The full resource name of a config. The full resource name looks like\n ``projects/project-name/co... |
Please provide a description of the function:def variable_name_from_full_name(full_name):
projects, _, configs, _, variables, result = full_name.split("/", 5)
if projects != "projects" or configs != "configs" or variables != "variables":
raise ValueError(
"Unexpected format of resource"... | [
"Extract the variable name from a full resource name.\n\n >>> variable_name_from_full_name(\n 'projects/my-proj/configs/my-config/variables/var-name')\n \"var-name\"\n >>> variable_name_from_full_name(\n 'projects/my-proj/configs/my-config/variables/another/var/name')\n ... |
Please provide a description of the function:def max(self):
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(self._data.keys())))) | [
"Return the maximum value in this histogram.\n\n If there are no values in the histogram at all, return 600.\n\n Returns:\n int: The maximum value in the histogram.\n "
] |
Please provide a description of the function:def min(self):
if len(self._data) == 0:
return 10
return next(iter(sorted(self._data.keys()))) | [
"Return the minimum value in this histogram.\n\n If there are no values in the histogram at all, return 10.\n\n Returns:\n int: The minimum value in the histogram.\n "
] |
Please provide a description of the function:def add(self, value):
# If the value is out of bounds, bring it in bounds.
value = int(value)
if value < 10:
value = 10
if value > 600:
value = 600
# Add the value to the histogram's data dictionary.
... | [
"Add the value to this histogram.\n\n Args:\n value (int): The value. Values outside of ``10 <= x <= 600``\n will be raised to ``10`` or reduced to ``600``.\n "
] |
Please provide a description of the function:def percentile(self, percent):
# Sanity check: Any value over 100 should become 100.
if percent >= 100:
percent = 100
# Determine the actual target number.
target = len(self) - len(self) * (percent / 100)
# Itera... | [
"Return the value that is the Nth precentile in the histogram.\n\n Args:\n percent (Union[int, float]): The precentile being sought. The\n default consumer implementations use consistently use ``99``.\n\n Returns:\n int: The value corresponding to the requested per... |
Please provide a description of the function:def job_path(cls, project, location, job):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/jobs/{job}",
project=project,
location=location,
job=job,
) | [
"Return a fully-qualified job string."
] |
Please provide a description of the function:def create_job(
self,
parent,
job,
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 logi... | [
"\n Creates a job.\n\n Example:\n >>> from google.cloud import scheduler_v1beta1\n >>>\n >>> client = scheduler_v1beta1.CloudSchedulerClient()\n >>>\n >>> parent = client.location_path('[PROJECT]', '[LOCATION]')\n >>>\n >>> #... |
Please provide a description of the function:def reference(self):
ref = ModelReference()
ref._proto = self._proto.model_reference
return ref | [
"A :class:`~google.cloud.bigquery.model.ModelReference` pointing to\n this model.\n\n Read-only.\n\n Returns:\n google.cloud.bigquery.model.ModelReference: pointer to this model.\n "
] |
Please provide a description of the function:def created(self):
value = self._proto.creation_time
if value is not None and value != 0:
# value will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(value)
... | [
"Union[datetime.datetime, None]: Datetime at which the model was\n created (:data:`None` until set from the server).\n\n Read-only.\n "
] |
Please provide a description of the function:def modified(self):
value = self._proto.last_modified_time
if value is not None and value != 0:
# value will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(value)
... | [
"Union[datetime.datetime, None]: Datetime at which the model was last\n modified (:data:`None` until set from the server).\n\n Read-only.\n "
] |
Please provide a description of the function:def expires(self):
value = self._properties.get("expirationTime")
if value is not None:
# value will be in milliseconds.
return google.cloud._helpers._datetime_from_microseconds(
1000.0 * float(value)
... | [
"Union[datetime.datetime, None]: The datetime when this model\n expires. If not present, the model will persist indefinitely. Expired\n models will be deleted and their storage reclaimed.\n "
] |
Please provide a description of the function:def from_api_repr(cls, resource):
this = cls(None)
# Convert from millis-from-epoch to timestamp well-known type.
# TODO: Remove this hack once CL 238585470 hits prod.
resource = copy.deepcopy(resource)
for training_run in re... | [
"Factory: construct a model resource given its API representation\n\n Args:\n resource (Dict[str, object]):\n Model resource representation from the API\n\n Returns:\n google.cloud.bigquery.model.Model: Model parsed from ``resource``.\n "
] |
Please provide a description of the function:def path(self):
return "/projects/%s/datasets/%s/models/%s" % (
self._proto.project_id,
self._proto.dataset_id,
self._proto.model_id,
) | [
"str: URL path for the model's APIs."
] |
Please provide a description of the function:def from_api_repr(cls, resource):
ref = cls()
ref._proto = json_format.ParseDict(resource, types.ModelReference())
return ref | [
"Factory: construct a model reference given its API representation\n\n Args:\n resource (Dict[str, object]):\n Model reference representation returned from the API\n\n Returns:\n google.cloud.bigquery.model.ModelReference:\n Model reference parsed f... |
Please provide a description of the function:def from_string(cls, model_id, default_project=None):
proj, dset, model = _helpers._parse_3_part_id(
model_id, default_project=default_project, property_name="model_id"
)
return cls.from_api_repr(
{"projectId": proj, "... | [
"Construct a model reference from model ID string.\n\n Args:\n model_id (str):\n A model ID in standard SQL format. If ``default_project``\n is not specified, this must included a project ID, dataset\n ID, and model ID, each separated by ``.``.\n ... |
Please provide a description of the function: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=N... | [
"\n Leases tasks from a pull queue for ``lease_duration``.\n\n This method is invoked by the worker to obtain a lease. The worker must\n acknowledge the task via ``AcknowledgeTask`` after they have performed\n the work associated with the task.\n\n The ``payload`` is intended to s... |
Please provide a description of the function:def format_stackdriver_json(record, message):
subsecond, second = math.modf(record.created)
payload = {
"message": message,
"timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)},
"thread": record.thread,
"severity"... | [
"Helper to format a LogRecord in in Stackdriver fluentd format.\n\n :rtype: str\n :returns: JSON str to be written to the log file.\n "
] |
Please provide a description of the function:def get_trace_id_from_flask():
if flask is None or not flask.request:
return None
header = flask.request.headers.get(_FLASK_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | [
"Get trace_id from flask request headers.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n "
] |
Please provide a description of the function:def get_trace_id_from_webapp2():
if webapp2 is None:
return None
try:
# get_request() succeeds if we're in the middle of a webapp2
# request, or raises an assertion error otherwise:
# "Request global variable is not set".
... | [
"Get trace_id from webapp2 request headers.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n "
] |
Please provide a description of the function:def get_trace_id_from_django():
request = _get_django_request()
if request is None:
return None
header = request.META.get(_DJANGO_TRACE_HEADER)
if header is None:
return None
trace_id = header.split("/", 1)[0]
return trace_id | [
"Get trace_id from django request headers.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n "
] |
Please provide a description of the function:def get_trace_id():
checkers = (
get_trace_id_from_django,
get_trace_id_from_flask,
get_trace_id_from_webapp2,
)
for checker in checkers:
trace_id = checker()
if trace_id is not None:
return trace_id
... | [
"Helper to get trace_id from web application request header.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n "
] |
Please provide a description of the function:def group_path(cls, project, group):
return google.api_core.path_template.expand(
"projects/{project}/groups/{group}", project=project, group=group
) | [
"Return a fully-qualified group string."
] |
Please provide a description of the function: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.DEF... | [
"\n Lists the existing groups.\n\n Example:\n >>> from google.cloud import monitoring_v3\n >>>\n >>> client = monitoring_v3.GroupServiceClient()\n >>>\n >>> name = client.project_path('[PROJECT]')\n >>>\n >>> # Iterate over a... |
Please provide a description of the function: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,
):
# Wrap the transport method to add retry and timeout logi... | [
"\n Returns a list of ``Voice`` supported for synthesis.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> response = client.list_voices()\n\n Args:\n... |
Please provide a description of the function: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,
):
# Wrap the transport metho... | [
"\n Synthesizes speech synchronously: receive results after all text input\n has been processed.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> # T... |
Please provide a description of the function:def ensure_signed_credentials(credentials):
if not isinstance(credentials, google.auth.credentials.Signing):
auth_uri = (
"https://google-cloud-python.readthedocs.io/en/latest/"
"core/auth.html?highlight=authentication#setting-up-"
... | [
"Raise AttributeError if the credentials are unsigned.\n\n :type credentials: :class:`google.auth.credentials.Signing`\n :param credentials: The credentials used to create a private key\n for signing text.\n\n :raises: :exc:`AttributeError` if credentials is not an instance\n ... |
Please provide a description of the function:def get_signed_query_params_v2(credentials, expiration, string_to_sign):
ensure_signed_credentials(credentials)
signature_bytes = credentials.sign_bytes(string_to_sign)
signature = base64.b64encode(signature_bytes)
service_account_name = credentials.sign... | [
"Gets query parameters for creating a signed URL.\n\n :type credentials: :class:`google.auth.credentials.Signing`\n :param credentials: The credentials used to create a private key\n for signing text.\n\n :type expiration: int or long\n :param expiration: When the signed URL shoul... |
Please provide a description of the function:def get_expiration_seconds_v2(expiration):
# If it's a timedelta, add it to `now` in UTC.
if isinstance(expiration, datetime.timedelta):
now = NOW().replace(tzinfo=_helpers.UTC)
expiration = now + expiration
# If it's a datetime, convert to ... | [
"Convert 'expiration' to a number of seconds in the future.\n\n :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]\n :param expiration: Point in time when the signed URL should expire.\n\n :raises: :exc:`TypeError` when expiration is not a valid type.\n\n :rtype: int\n :returns: ... |
Please provide a description of the function:def get_expiration_seconds_v4(expiration):
if not isinstance(expiration, _EXPIRATION_TYPES):
raise TypeError(
"Expected an integer timestamp, datetime, or "
"timedelta. Got %s" % type(expiration)
)
now = NOW().replace(tzi... | [
"Convert 'expiration' to a number of seconds offset from the current time.\n\n :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]\n :param expiration: Point in time when the signed URL should expire.\n\n :raises: :exc:`TypeError` when expiration is not a valid type.\n :raises: :exc:... |
Please provide a description of the function:def get_canonical_headers(headers):
if headers is None:
headers = []
elif isinstance(headers, dict):
headers = list(headers.items())
if not headers:
return [], []
normalized = collections.defaultdict(list)
for key, val in he... | [
"Canonicalize headers for signing.\n\n See:\n https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers\n\n :type headers: Union[dict|List(Tuple(str,str))]\n :param headers:\n (Optional) Additional HTTP headers to be included as part of the\n signed... |
Please provide a description of the function:def canonicalize(method, resource, query_parameters, headers):
headers, _ = get_canonical_headers(headers)
if method == "RESUMABLE":
method = "POST"
headers.append("x-goog-resumable:start")
if query_parameters is None:
return _Canon... | [
"Canonicalize method, resource\n\n :type method: str\n :param method: The HTTP verb that will be used when requesting the URL.\n Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the\n signature will additionally contain the `x-goog-resumable`\n hea... |
Please provide a description of the function: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_param... | [
"Generate a V2 signed URL to provide query-string auth'n to a resource.\n\n .. note::\n\n Assumes ``credentials`` implements the\n :class:`google.auth.credentials.Signing` interface. Also assumes\n ``credentials`` has a ``service_account_email`` property which\n identifies the credent... |
Please provide a description of the function: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,
... | [
"Generate a V4 signed URL to provide query-string auth'n to a resource.\n\n .. note::\n\n Assumes ``credentials`` implements the\n :class:`google.auth.credentials.Signing` interface. Also assumes\n ``credentials`` has a ``service_account_email`` property which\n identifies the credent... |
Please provide a description of the function:def glossary_path(cls, project, location, glossary):
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}/glossaries/{glossary}",
project=project,
location=location,
glossary=gl... | [
"Return a fully-qualified glossary string."
] |
Please provide a description of the function: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,
... | [
"\n Translates input text and returns translated text.\n\n Example:\n >>> from google.cloud import translate_v3beta1\n >>>\n >>> client = translate_v3beta1.TranslationServiceClient()\n >>>\n >>> # TODO: Initialize `contents`:\n >>> cont... |
Please provide a description of the function: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,
):
... | [
"\n Detects the language of text within a request.\n\n Example:\n >>> from google.cloud import translate_v3beta1\n >>>\n >>> client = translate_v3beta1.TranslationServiceClient()\n >>>\n >>> response = client.detect_language()\n\n Args:\n ... |
Please provide a description of the function: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,
):
... | [
"\n Returns a list of supported languages for translation.\n\n Example:\n >>> from google.cloud import translate_v3beta1\n >>>\n >>> client = translate_v3beta1.TranslationServiceClient()\n >>>\n >>> response = client.get_supported_languages()\n\n ... |
Please provide a description of the function: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,
... | [
"\n Translates a large volume of text in asynchronous batch mode.\n This function provides real-time output as the inputs are being processed.\n If caller cancels a request, the partial results (for an input file, it's\n all or nothing) may still be available on the specified output loca... |
Please provide a description of the function:def create_glossary(
self,
parent,
glossary,
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 ti... | [
"\n Creates a glossary and returns the long-running operation. Returns\n NOT\\_FOUND, if the project doesn't exist.\n\n Example:\n >>> from google.cloud import translate_v3beta1\n >>>\n >>> client = translate_v3beta1.TranslationServiceClient()\n >>>\n... |
Please provide a description of the function:def delete_glossary(
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.
... | [
"\n Deletes a glossary, or cancels glossary construction if the glossary\n isn't created yet. Returns NOT\\_FOUND, if the glossary doesn't exist.\n\n Example:\n >>> from google.cloud import translate_v3beta1\n >>>\n >>> client = translate_v3beta1.TranslationServ... |
Please provide a description of the function:def _extract_header(time_series):
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) | [
"Return a copy of time_series with the points removed."
] |
Please provide a description of the function:def _extract_labels(time_series):
labels = {"resource_type": time_series.resource.type}
labels.update(time_series.resource.labels)
labels.update(time_series.metric.labels)
return labels | [
"Build the combined resource and metric labels, with resource_type."
] |
Please provide a description of the function:def _build_dataframe(time_series_iterable, label=None, labels=None): # pragma: NO COVER
if pandas is None:
raise RuntimeError("This method requires `pandas` to be installed.")
if label is not None:
if labels:
raise ValueError("Canno... | [
"Build a :mod:`pandas` dataframe out of time series.\n\n :type time_series_iterable:\n iterable over :class:`~google.cloud.monitoring_v3.types.TimeSeries`\n :param time_series_iterable:\n An iterable (e.g., a query object) yielding time series.\n\n :type label: str\n :param label:\n ... |
Please provide a description of the function:def _sorted_resource_labels(labels):
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 | [
"Sort label names, putting well-known resource labels first."
] |
Please provide a description of the function:def start_daemon_thread(*args, **kwargs):
thread = threading.Thread(*args, **kwargs)
thread.daemon = True
thread.start()
return thread | [
"Starts a thread and marks it as a daemon thread."
] |
Please provide a description of the function:def safe_invoke_callback(callback, *args, **kwargs):
# pylint: disable=bare-except
# We intentionally want to swallow all exceptions.
try:
return callback(*args, **kwargs)
except Exception:
_LOGGER.exception("Error while executing Future ... | [
"Invoke a callback, swallowing and logging any exceptions."
] |
Please provide a description of the function:def new_project(self, project_id, name=None, labels=None):
return Project(project_id=project_id, client=self, name=name, labels=labels) | [
"Create a project bound to the current client.\n\n Use :meth:`Project.reload() \\\n <google.cloud.resource_manager.project.Project.reload>` to retrieve\n project metadata after creating a\n :class:`~google.cloud.resource_manager.project.Project` instance.\n\n .. note:\n\n ... |
Please provide a description of the function:def fetch_project(self, project_id):
project = self.new_project(project_id)
project.reload()
return project | [
"Fetch an existing project and it's relevant metadata by ID.\n\n .. note::\n\n If the project does not exist, this will raise a\n :class:`NotFound <google.cloud.exceptions.NotFound>` error.\n\n :type project_id: str\n :param project_id: The ID for this project.\n\n ... |
Please provide a description of the function:def list_projects(self, filter_params=None, page_size=None):
extra_params = {}
if page_size is not None:
extra_params["pageSize"] = page_size
if filter_params is not None:
extra_params["filter"] = [
"... | [
"List the projects visible to this client.\n\n Example::\n\n >>> from google.cloud import resource_manager\n >>> client = resource_manager.Client()\n >>> for project in client.list_projects():\n ... print(project.project_id)\n\n List all projects with la... |
Please provide a description of the function:def session_path(cls, project, instance, database, session):
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}/sessions/{session}",
project=project,
instance=instanc... | [
"Return a fully-qualified session string."
] |
Please provide a description of the function: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,
):
# Wrap the transport method to add retry a... | [
"\n Creates a new session. A session can be used to perform transactions\n that read and/or modify data in a Cloud Spanner database. Sessions are\n meant to be reused for many consecutive transactions.\n\n Sessions can only execute one transaction at a time. To execute multiple\n ... |
Please provide a description of the function: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... | [
"\n Like ``ExecuteSql``, except returns the result set as a stream. Unlike\n ``ExecuteSql``, there is no limit on the size of the returned result\n set. However, no individual row in the result set can exceed 100 MiB,\n and no column value can exceed 10 MiB.\n\n Example:\n ... |
Please provide a description of the function: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,
):
# Wrap... | [
"\n Executes a batch of SQL DML statements. This method allows many\n statements to be run with lower latency than submitting them\n sequentially with ``ExecuteSql``.\n\n Statements are executed in order, sequentially.\n ``ExecuteBatchDmlResponse`` will contain a ``ResultSet`` for... |
Please provide a description of the function: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,
... | [
"\n Reads rows from the database using key lookups and scans, as a simple\n key/value style alternative to ``ExecuteSql``. This method cannot be\n used to return a result set larger than 10 MiB; if the read matches more\n data than that, the read fails with a ``FAILED_PRECONDITION`` erro... |
Please provide a description of the function: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,
):
... | [
"\n Commits a transaction. The request includes the mutations to be applied\n to rows in the database.\n\n ``Commit`` might return an ``ABORTED`` error. This can occur at any\n time; commonly, the cause is conflicts with concurrent transactions.\n However, it can also happen for a... |
Please provide a description of the function:def partition_query(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DE... | [
"\n Creates a set of partition tokens that can be used to execute a query\n operation in parallel. Each of the returned partition tokens can be used\n by ``ExecuteStreamingSql`` to specify a subset of the query result to\n read. The same session and read-only transaction must be used by ... |
Please provide a description of the function:def partition_read(
self,
session,
table,
key_set,
transaction=None,
index=None,
columns=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic... | [
"\n Creates a set of partition tokens that can be used to execute a read\n operation in parallel. Each of the returned partition tokens can be used\n by ``StreamingRead`` to specify a subset of the read result to read. The\n same session and read-only transaction must be used by the\n ... |
Please provide a description of the function:def create_client_event(
self,
parent,
client_event,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
# Wrap the transport method to add retr... | [
"\n Report events issued when end user interacts with customer's application\n that uses Cloud Talent Solution. You may inspect the created events in\n `self service\n tools <https://console.cloud.google.com/talent-solution/overview>`__.\n `Learn\n more <https://cloud.googl... |
Please provide a description of the function:def make_datastore_api(client):
parse_result = six.moves.urllib_parse.urlparse(client._base_url)
host = parse_result.netloc
if parse_result.scheme == "https":
channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host)
else:
... | [
"Create an instance of the GAPIC Datastore API.\n\n :type client: :class:`~google.cloud.datastore.client.Client`\n :param client: The client that holds configuration details.\n\n :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`\n :returns: A datastore API instance with the proper credenti... |
Please provide a description of the function:def default(session):
# Install all test dependencies, then install local packages in-place.
session.install("mock", "pytest", "pytest-cov")
for local_dep in LOCAL_DEPS:
session.install("-e", local_dep)
# Pyarrow does not support Python 3.7
... | [
"Default unit test session.\n\n This is intended to be run **without** an interpreter set, so\n that the current ``python`` (on the ``PATH``) or the version of\n Python corresponding to the ``nox`` binary the ``PATH`` can\n run the tests.\n "
] |
Please provide a description of the function:def snippets(session):
# Sanity check: Only run snippets tests if the environment variable is set.
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
session.skip("Credentials must be set via environment variable.")
# Install all test dep... | [
"Run the snippets test suite."
] |
Please provide a description of the function:def lint(session):
session.install("black", "flake8", *LOCAL_DEPS)
session.install(".")
session.run("flake8", os.path.join("google", "cloud", "bigquery"))
session.run("flake8", "tests")
session.run("flake8", os.path.join("docs", "snippets.py"))
... | [
"Run linters.\n\n Returns a failure if the linters find linting errors or sufficiently\n serious code quality issues.\n "
] |
Please provide a description of the function:def _indent(lines, prefix=" "):
indented = []
for line in lines.split("\n"):
indented.append(prefix + line)
return "\n".join(indented) | [
"Indent some text.\n\n Note that this is present as ``textwrap.indent``, but not in Python 2.\n\n Args:\n lines (str): The newline delimited string to be indented.\n prefix (Optional[str]): The prefix to indent each line with. Default\n to two spaces.\n\n Returns:\n str: The... |
Please provide a description of the function:def publish_time(self):
timestamp = self._message.publish_time
delta = datetime.timedelta(
seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000
)
return datetime_helpers._UTC_EPOCH + delta | [
"Return the time that the message was originally published.\n\n Returns:\n datetime: The date and time that the message was published.\n "
] |
Please provide a description of the function:def ack(self):
time_to_ack = math.ceil(time.time() - self._received_timestamp)
self._request_queue.put(
requests.AckRequest(
ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack
)
) | [
"Acknowledge the given message.\n\n Acknowledging a message in Pub/Sub means that you are done\n with it, and it will not be delivered to this subscription again.\n You should avoid acknowledging messages until you have\n *finished* processing them, so that in the event of a failure,\n ... |
Please provide a description of the function:def drop(self):
self._request_queue.put(
requests.DropRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"Release the message from lease management.\n\n This informs the policy to no longer hold on to the lease for this\n message. Pub/Sub will re-deliver the message if it is not acknowledged\n before the existing lease expires.\n\n .. warning::\n For most use cases, the only reas... |
Please provide a description of the function:def lease(self):
self._request_queue.put(
requests.LeaseRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"Inform the policy to lease this message continually.\n\n .. note::\n This method is called by the constructor, and you should never\n need to call it manually.\n "
] |
Please provide a description of the function:def modify_ack_deadline(self, seconds):
self._request_queue.put(
requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds)
) | [
"Resets the deadline for acknowledgement.\n\n New deadline will be the given value of seconds from now.\n\n The default implementation handles this for you; you should not need\n to manually deal with setting ack deadlines. The exception case is\n if you are implementing your own custom ... |
Please provide a description of the function:def nack(self):
self._request_queue.put(
requests.NackRequest(ack_id=self._ack_id, byte_size=self.size)
) | [
"Decline to acknowldge the given message.\n\n This will cause the message to be re-delivered to the subscription.\n "
] |
Please provide a description of the function:def _run_query(client, query, job_config=None):
start_time = time.time()
query_job = client.query(query, job_config=job_config)
print("Executing query with job ID: {}".format(query_job.job_id))
while True:
print("\rQuery executing: {:0.2f}s".for... | [
"Runs a query while printing status updates\n\n Args:\n client (google.cloud.bigquery.client.Client):\n Client to bundle configuration needed for API requests.\n query (str):\n SQL query to be executed. Defaults to the standard SQL dialect.\n Use the ``job_config`` ... |
Please provide a description of the function:def _cell_magic(line, query):
args = magic_arguments.parse_argstring(_cell_magic, line)
params = []
if args.params is not None:
try:
params = _helpers.to_query_parameters(
ast.literal_eval("".join(args.params))
... | [
"Underlying function for bigquery cell magic\n\n Note:\n This function contains the underlying logic for the 'bigquery' cell\n magic. This function is not meant to be called directly.\n\n Args:\n line (str): \"%%bigquery\" followed by arguments as required\n query (str): SQL query ... |
Please provide a description of the function:def credentials(self):
if self._credentials is None:
self._credentials, _ = google.auth.default()
return self._credentials | [
"google.auth.credentials.Credentials: Credentials to use for queries\n performed through IPython magics\n\n Note:\n These credentials do not need to be explicitly defined if you are\n using Application Default Credentials. If you are not using\n Application Default Cre... |
Please provide a description of the function:def project(self):
if self._project is None:
_, self._project = google.auth.default()
return self._project | [
"str: Default project to use for queries performed through IPython\n magics\n\n Note:\n The project does not need to be explicitly defined if you have an\n environment default project set. If you do not have a default\n project set in your environment, manually assign ... |
Please provide a description of the function:def database_root_path(cls, project, database):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) | [
"Return a fully-qualified database_root string."
] |
Please provide a description of the function:def document_root_path(cls, project, database):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents",
project=project,
database=database,
) | [
"Return a fully-qualified document_root string."
] |
Please provide a description of the function:def document_path_path(cls, project, database, document_path):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,
... | [
"Return a fully-qualified document_path string."
] |
Please provide a description of the function:def any_path_path(cls, project, database, document, any_path):
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document}/{any_path=**}",
project=project,
database=database,
... | [
"Return a fully-qualified any_path string."
] |
Please provide a description of the function:def get_document(
self,
name,
mask=None,
transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
#... | [
"\n Gets a single document.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.FirestoreClient()\n >>>\n >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')\n ... |
Please provide a description of the function:def list_documents(
self,
parent,
collection_id,
page_size=None,
order_by=None,
mask=None,
transaction=None,
read_time=None,
show_missing=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
... | [
"\n Lists documents.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.FirestoreClient()\n >>>\n >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.