INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by ExecuteStreamingSql to specify a subset of the query result to read. The same session and read - only transaction must be used by the PartitionQueryRequest used to create the... | 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.DEFAULT,
metadata=None,
):
... |
Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by StreamingRead to specify a subset of the read result to read. The same session and read - only transaction must be used by the PartitionReadRequest used to create the partitio... | 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_v1.method.DEFAULT,
metadata=None,
... |
Report events issued when end user interacts with customer s application that uses Cloud Talent Solution. You may inspect the created events in self service tools <https:// console. cloud. google. com/ talent - solution/ overview > __. Learn more <https:// cloud. google. com/ talent - solution/ docs/ management - tools... | 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,
):
"""
Report events issued when end user interacts with customer's application
... |
Create an instance of the GAPIC Datastore API. | def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API insta... |
Default unit test session. | def default(session):
"""Default unit test session.
This is intended to be run **without** an interpreter set, so
that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can
run the tests.
"""
# Install all test dependencies, t... |
Run the snippets test suite. | def snippets(session):
"""Run the snippets test suite."""
# 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 dependencies, ... |
Run linters. | def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install("black", "flake8", *LOCAL_DEPS)
session.install(".")
session.run("flake8", os.path.join("google", "cloud", "bigquery"))
session.run("... |
Indent some text. | def _indent(lines, prefix=" "):
"""Indent some text.
Note that this is present as ``textwrap.indent``, but not in Python 2.
Args:
lines (str): The newline delimited string to be indented.
prefix (Optional[str]): The prefix to indent each line with. Default
to two spaces.
... |
Return the time that the message was originally published. | def publish_time(self):
"""Return the time that the message was originally published.
Returns:
datetime: The date and time that the message was published.
"""
timestamp = self._message.publish_time
delta = datetime.timedelta(
seconds=timestamp.seconds, mi... |
Acknowledge the given message. | def ack(self):
"""Acknowledge the given message.
Acknowledging a message in Pub/Sub means that you are done
with it, and it will not be delivered to this subscription again.
You should avoid acknowledging messages until you have
*finished* processing them, so that in the event o... |
Release the message from lease management. | def drop(self):
"""Release the message from lease management.
This informs the policy to no longer hold on to the lease for this
message. Pub/Sub will re-deliver the message if it is not acknowledged
before the existing lease expires.
.. warning::
For most use cases... |
Inform the policy to lease this message continually. | def lease(self):
"""Inform the policy to lease this message continually.
.. note::
This method is called by the constructor, and you should never
need to call it manually.
"""
self._request_queue.put(
requests.LeaseRequest(ack_id=self._ack_id, byte_si... |
Resets the deadline for acknowledgement. | def modify_ack_deadline(self, seconds):
"""Resets the deadline for acknowledgement.
New deadline will be the given value of seconds from now.
The default implementation handles this for you; you should not need
to manually deal with setting ack deadlines. The exception case is
... |
Decline to acknowldge the given message. | def nack(self):
"""Decline to acknowldge the given message.
This will cause the message to be re-delivered to the subscription.
"""
self._request_queue.put(
requests.NackRequest(ack_id=self._ack_id, byte_size=self.size)
) |
Runs a query while printing status updates | def _run_query(client, query, job_config=None):
"""Runs a query while printing status updates
Args:
client (google.cloud.bigquery.client.Client):
Client to bundle configuration needed for API requests.
query (str):
SQL query to be executed. Defaults to the standard SQL d... |
Underlying function for bigquery cell magic | def _cell_magic(line, query):
"""Underlying function for bigquery cell magic
Note:
This function contains the underlying logic for the 'bigquery' cell
magic. This function is not meant to be called directly.
Args:
line (str): "%%bigquery" followed by arguments as required
q... |
google. auth. credentials. Credentials: Credentials to use for queries performed through IPython magics | def credentials(self):
"""google.auth.credentials.Credentials: Credentials to use for queries
performed through IPython magics
Note:
These credentials do not need to be explicitly defined if you are
using Application Default Credentials. If you are not using
... |
str: Default project to use for queries performed through IPython magics | def project(self):
"""str: Default project to use for queries performed through IPython
magics
Note:
The project does not need to be explicitly defined if you have an
environment default project set. If you do not have a default
project set in your environmen... |
Return a fully - qualified database_root string. | def database_root_path(cls, project, database):
"""Return a fully-qualified database_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}",
project=project,
database=database,
) |
Return a fully - qualified document_root string. | def document_root_path(cls, project, database):
"""Return a fully-qualified document_root string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents",
project=project,
database=database,
) |
Return a fully - qualified document_path string. | def document_path_path(cls, project, database, document_path):
"""Return a fully-qualified document_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,... |
Return a fully - qualified any_path string. | def any_path_path(cls, project, database, document, any_path):
"""Return a fully-qualified any_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document}/{any_path=**}",
project=project,
database=database... |
Gets a single document. | 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,
):
"""
Gets a single document.
Example:
... |
Lists documents. | 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,
timeout=google.api_core.gapic_v1.method.D... |
Creates a new document. | def create_document(
self,
parent,
collection_id,
document_id,
document,
mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new document.
... |
Updates or inserts a document. | def update_document(
self,
document,
update_mask,
mask=None,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates or inserts a document.
... |
Deletes a document. | def delete_document(
self,
name,
current_document=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a document.
Example:
>>> from google.cloud import... |
Gets multiple documents. | def batch_get_documents(
self,
database,
documents,
mask=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... |
Starts a new transaction. | def begin_transaction(
self,
database,
options_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Starts a new transaction.
Example:
>>> from google.cloud im... |
Runs a query. | def run_query(
self,
parent,
structured_query=None,
transaction=None,
new_transaction=None,
read_time=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Ru... |
Streams batches of document updates and deletes in order. | def write(
self,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Streams batches of document updates and deletes, in order.
EXPERIMENTAL: This method interface might chang... |
Return a fully - qualified log string. | def log_path(cls, project, log):
"""Return a fully-qualified log string."""
return google.api_core.path_template.expand(
"projects/{project}/logs/{log}", project=project, log=log
) |
Deletes all the log entries in a log. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. | def delete_log(
self,
log_name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes all the log entries in a log.
The log reappears if it receives new entries.
Log entrie... |
Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used directly or indirectly by the Logging agent ( fluentd ) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources ( projects or... | def write_log_entries(
self,
entries,
log_name=None,
resource=None,
labels=None,
partial_success=None,
dry_run=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
... |
Lists log entries. Use this method to retrieve log entries from Logging. For ways to export log entries see Exporting Logs <https:// cloud. google. com/ logging/ docs/ export > __. | def list_log_entries(
self,
resource_names,
project_ids=None,
filter_=None,
order_by=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Lis... |
Expand a matched variable with its value. | def _expand_variable_match(positional_vars, named_vars, match):
"""Expand a matched variable with its value.
Args:
positional_vars (list): A list of positonal variables. This list will
be modified.
named_vars (dict): A dictionary of named variables.
match (re.Match): A regul... |
Expand a path template with the given variables. | def expand(tmpl, *args, **kwargs):
"""Expand a path template with the given variables.
..code-block:: python
>>> expand('users/*/messages/*', 'me', '123')
users/me/messages/123
>>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3')
/v1/shelves/1/books/3
Args:... |
Replace a variable match with a pattern that can be used to validate it. | def _replace_variable_with_pattern(match):
"""Replace a variable match with a pattern that can be used to validate it.
Args:
match (re.Match): A regular expression match
Returns:
str: A regular expression pattern that can be used to validate the
variable in an expanded path.
... |
Validate a path against the path template. | def validate(tmpl, path):
"""Validate a path against the path template.
.. code-block:: python
>>> validate('users/*/messages/*', 'users/me/messages/123')
True
>>> validate('users/*/messages/*', 'users/me/drafts/123')
False
>>> validate('/v1/{name=shelves/*/books/*}', /... |
Default unit test session. | def default(session):
"""Default unit test session.
This is intended to be run **without** an interpreter set, so
that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can
run the tests.
"""
# Install all test dependencies, t... |
Create and return a gRPC channel object. | def create_channel(cls, address="firestore.googleapis.com:443", credentials=None):
"""Create and return a gRPC channel object.
Args:
address (str): The host for the channel to use.
credentials (~.Credentials): The
authorization credentials to attach to requests. ... |
AppProfile name used in requests. | def name(self):
"""AppProfile name used in requests.
.. note::
This property will not change if ``app_profile_id`` does not, but
the return value is not cached.
The AppProfile name is of the form
``"projects/../instances/../app_profile/{app_profile_id}"``
... |
Creates an instance app_profile from a protobuf. | def from_pb(cls, app_profile_pb, instance):
"""Creates an instance app_profile from a protobuf.
:type app_profile_pb: :class:`instance_pb2.app_profile_pb`
:param app_profile_pb: An instance protobuf object.
:type instance: :class:`google.cloud.bigtable.instance.Instance`
:param... |
Refresh self from the server - provided protobuf. Helper for: meth: from_pb and: meth: reload. | def _update_from_pb(self, app_profile_pb):
"""Refresh self from the server-provided protobuf.
Helper for :meth:`from_pb` and :meth:`reload`.
"""
self.routing_policy_type = None
self.allow_transactional_writes = None
self.cluster_id = None
self.description = app_p... |
Create an AppProfile proto buff message for API calls: rtype:: class:. instance_pb2. AppProfile: returns: The converted current object. | def _to_pb(self):
"""Create an AppProfile proto buff message for API calls
:rtype: :class:`.instance_pb2.AppProfile`
:returns: The converted current object.
:raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile
routing_policy_type is not set
"""... |
Reload the metadata for this cluster | def reload(self):
"""Reload the metadata for this cluster"""
app_profile_pb = self.instance_admin_client.get_app_profile(self.name)
# NOTE: _update_from_pb does not check that the project and
# app_profile ID on the response match the request.
self._update_from_pb(app_pro... |
Check whether the AppProfile already exists. | def exists(self):
"""Check whether the AppProfile already exists.
:rtype: bool
:returns: True if the AppProfile exists, else False.
"""
try:
self.instance_admin_client.get_app_profile(self.name)
return True
# NOTE: There could be other exceptions ... |
Create this AppProfile. | def create(self, ignore_warnings=None):
"""Create this AppProfile.
.. note::
Uses the ``instance`` and ``app_profile_id`` on the current
:class:`AppProfile` in addition to the ``routing_policy_type``,
``description``, ``cluster_id`` and ``allow_transactional_writes`... |
Update this app_profile. | def update(self, ignore_warnings=None):
"""Update this app_profile.
.. note::
Update any or all of the following values:
``routing_policy_type``
``description``
``cluster_id``
``allow_transactional_writes``
"""
update_mask_pb... |
Return a fully - qualified sink string. | def sink_path(cls, project, sink):
"""Return a fully-qualified sink string."""
return google.api_core.path_template.expand(
"projects/{project}/sinks/{sink}", project=project, sink=sink
) |
Return a fully - qualified exclusion string. | def exclusion_path(cls, project, exclusion):
"""Return a fully-qualified exclusion string."""
return google.api_core.path_template.expand(
"projects/{project}/exclusions/{exclusion}",
project=project,
exclusion=exclusion,
) |
Creates a sink that exports specified log entries to a destination. The export of newly - ingested log entries begins immediately unless the sink s writer_identity is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink. | def create_sink(
self,
parent,
sink,
unique_writer_identity=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a sink that exports specified log entries to a desti... |
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination and filter. The updated sink might also have a new writer_identity ; see the unique_writer_identity field. | def update_sink(
self,
sink_name,
sink,
unique_writer_identity=None,
update_mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates a sink. This method rep... |
Creates a new exclusion in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource. | def create_exclusion(
self,
parent,
exclusion,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a new exclusion in a specified parent resource.
Only log entries belong... |
Helper for: func: _make_list_value_pbs. | def _make_value_pb(value):
"""Helper for :func:`_make_list_value_pbs`.
:type value: scalar value
:param value: value to convert
:rtype: :class:`~google.protobuf.struct_pb2.Value`
:returns: value protobufs
:raises ValueError: if value is not of a known scalar type.
"""
if value is None:... |
Convert a Value protobuf to cell data. | def _parse_value_pb(value_pb, field_type):
"""Convert a Value protobuf to cell data.
:type value_pb: :class:`~google.protobuf.struct_pb2.Value`
:param value_pb: protobuf to convert
:type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type`
:param field_type: type code for the value
... |
Convert a list of ListValue protobufs into a list of list of cell data. | def _parse_list_value_pbs(rows, row_type):
"""Convert a list of ListValue protobufs into a list of list of cell data.
:type rows: list of :class:`~google.protobuf.struct_pb2.ListValue`
:param rows: row data returned from a read/query
:type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Stru... |
Exports assets with time and resource types to a given Cloud Storage location. The output format is newline - delimited JSON. This API implements the google. longrunning. Operation API allowing you to keep track of the export. | def export_assets(
self,
parent,
output_config,
read_time=None,
asset_types=None,
content_type=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Exports a... |
Batch gets the update history of assets that overlap a time window. For RESOURCE content this API outputs history with asset in both non - delete or deleted status. For IAM \ _POLICY content this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a ... | def batch_get_assets_history(
self,
parent,
content_type,
read_time_window,
asset_names=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Batch gets the update hi... |
Extract and parse Avro schema from a read session. | def _avro_schema(read_session):
"""Extract and parse Avro schema from a read session.
Args:
read_session ( \
~google.cloud.bigquery_storage_v1beta1.types.ReadSession \
):
The read session associated with this read rows stream. This
contains the schema, which ... |
Parse all rows in a stream block. | def _avro_rows(block, avro_schema):
"""Parse all rows in a stream block.
Args:
block ( \
~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \
):
A block containing Avro bytes to parse into rows.
avro_schema (fastavro.schema):
A parsed Avro ... |
Copy a StreamPosition. | def _copy_stream_position(position):
"""Copy a StreamPosition.
Args:
position (Union[ \
dict, \
~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \
]):
StreamPostion (or dictionary in StreamPosition format) to copy.
Returns:
~google.clo... |
Reconnect to the ReadRows stream using the most recent offset. | def _reconnect(self):
"""Reconnect to the ReadRows stream using the most recent offset."""
self._wrapped = self._client.read_rows(
_copy_stream_position(self._position), **self._read_rows_kwargs
) |
Create a: class: pandas. DataFrame of all rows in the stream. | def to_dataframe(self, read_session, dtypes=None):
"""Create a :class:`pandas.DataFrame` of all rows in the stream.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. T... |
A generator of all pages in the stream. | def pages(self):
"""A generator of all pages in the stream.
Returns:
types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]:
A generator of pages.
"""
# Each page is an iterator of rows. But also has num_items, remaining,
# and to_dat... |
Create a: class: pandas. DataFrame of all rows in the stream. | def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of all rows in the stream.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. They are curren... |
Parse metadata and rows from the block only once. | def _parse_block(self):
"""Parse metadata and rows from the block only once."""
if self._iter_rows is not None:
return
rows = _avro_rows(self._block, self._avro_schema)
self._num_items = self._block.avro_rows.row_count
self._remaining = self._block.avro_rows.row_coun... |
Get the next row in the page. | def next(self):
"""Get the next row in the page."""
self._parse_block()
if self._remaining > 0:
self._remaining -= 1
return six.next(self._iter_rows) |
Create a: class: pandas. DataFrame of rows in the page. | def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of rows in the page.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. They are currently pa... |
Return a fully - qualified instance_config string. | def instance_config_path(cls, project, instance_config):
"""Return a fully-qualified instance_config string."""
return google.api_core.path_template.expand(
"projects/{project}/instanceConfigs/{instance_config}",
project=project,
instance_config=instance_config,
... |
Creates an instance and begins preparing it to begin serving. The returned long - running operation can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists CreateInstance returns ALREADY_EXISTS. | def create_instance(
self,
parent,
instance_id,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates an instance and begins preparing it to begin serving. The
... |
Updates an instance and begins allocating or releasing resources as requested. The returned long - running operation can be used to track the progress of updating the instance. If the named instance does not exist returns NOT_FOUND. | def update_instance(
self,
instance,
field_mask,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates an instance, and begins allocating or releasing resources as
requeste... |
Return a fully - qualified finding string. | def finding_path(cls, project, scan_config, scan_run, finding):
"""Return a fully-qualified finding string."""
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}",
project=project,
scan_con... |
Return a fully - qualified scan_config string. | def scan_config_path(cls, project, scan_config):
"""Return a fully-qualified scan_config string."""
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}",
project=project,
scan_config=scan_config,
) |
Return a fully - qualified scan_run string. | def scan_run_path(cls, project, scan_config, scan_run):
"""Return a fully-qualified scan_run string."""
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}",
project=project,
scan_config=scan_config,
... |
Helper for session - related API calls. | def instance_admin_api(self):
"""Helper for session-related API calls."""
if self._instance_admin_api is None:
self._instance_admin_api = InstanceAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._instance_admin_api |
Helper for session - related API calls. | def database_admin_api(self):
"""Helper for session-related API calls."""
if self._database_admin_api is None:
self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._database_admin_api |
Make a copy of this client. | def copy(self):
"""Make a copy of this client.
Copies the local data stored as simple types but does not copy the
current state of any open connections with the Cloud Bigtable API.
:rtype: :class:`.Client`
:returns: A copy of the current client.
"""
return self.... |
List available instance configurations for the client s project. | def list_instance_configs(self, page_size=None, page_token=None):
"""List available instance configurations for the client's project.
.. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\
google.spanner.admin.instance.v1#google.spanner.admin.\
i... |
Factory to create a instance associated with this client. | def instance(
self,
instance_id,
configuration_name=None,
display_name=None,
node_count=DEFAULT_NODE_COUNT,
):
"""Factory to create a instance associated with this client.
:type instance_id: str
:param instance_id: The ID of the instance.
:ty... |
List instances for the client s project. | def list_instances(self, filter_="", page_size=None, page_token=None):
"""List instances for the client's project.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances
:type filter_: string
... |
Predicate for determining when to retry. | def _should_retry(exc):
"""Predicate for determining when to retry.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'.
"""
if not hasattr(exc, "errors"):
return False
if len(exc.errors) == 0:
# Check for unstructured error returns, e.g. from GFE
... |
Default unit test session. | def default(session, django_dep=('django',)):
"""Default unit test session.
"""
# Install all test dependencies, then install this package in-place.
deps = UNIT_TEST_DEPS
deps += django_dep
session.install(*deps)
for local_dep in LOCAL_DEPS:
session.install('-e', local_dep)
ses... |
Run the unit test suite. | def unit(session):
"""Run the unit test suite."""
# Testing multiple version of django
# See https://www.djangoproject.com/download/ for supported version
django_deps_27 = [
('django==1.8.19',),
('django >= 1.11.0, < 2.0.0dev',),
]
if session.virtualenv.interpreter == '2.7':
... |
Run the system test suite. | def system(session):
"""Run the system test suite."""
# Sanity check: Only run system tests if the environment variable is set.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
session.skip('Credentials must be set via environment variable.')
# Use pre-release gRPC for system tests... |
Detect correct entry type from resource and instantiate. | def entry_from_resource(resource, client, loggers):
"""Detect correct entry type from resource and instantiate.
:type resource: dict
:param resource: One entry resource from API response.
:type client: :class:`~google.cloud.logging.client.Client`
:param client: Client that owns the log entry.
... |
Retrieve the metadata key in the metadata server. | def retrieve_metadata_server(metadata_key):
"""Retrieve the metadata key in the metadata server.
See: https://cloud.google.com/compute/docs/storing-retrieving-metadata
:type metadata_key: str
:param metadata_key: Key of the metadata which will form the url. You can
also supply... |
Define loss of TF graph: param y: correct labels: param model: output of the model: param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch: return: return mean of loss if True otherwise return vector with per sample loss | def model_loss(y, model, mean=True):
"""
Define loss of TF graph
:param y: correct labels
:param model: output of the model
:param mean: boolean indicating whether should return mean of loss
or vector of losses for each input of the batch
:return: return mean of loss if True, otherwise return... |
Only initializes the variables of a TensorFlow session that were not already initialized.: param sess: the TensorFlow session: return: | def initialize_uninitialized_global_variables(sess):
"""
Only initializes the variables of a TensorFlow session that were not
already initialized.
:param sess: the TensorFlow session
:return:
"""
# List all global variables
global_vars = tf.global_variables()
# Find initialized status for all variabl... |
Train a TF graph. This function is deprecated. Prefer cleverhans. train. train when possible. cleverhans. train. train supports multiple GPUs but this function is still needed to support legacy models that do not support calling fprop more than once. | def train(sess, loss, x, y, X_train, Y_train, save=False,
init_all=False, evaluate=None, feed=None, args=None,
rng=None, var_list=None, fprop_args=None, optimizer=None):
"""
Train a TF graph.
This function is deprecated. Prefer cleverhans.train.train when possible.
cleverhans.train.train sup... |
Compute the accuracy of a TF model on some data: param sess: TF session to use: param x: input placeholder: param y: output placeholder ( for labels ): param predictions: model output predictions: param X_test: numpy array with training inputs: param Y_test: numpy array with training outputs: param feed: An optional di... | def model_eval(sess, x, y, predictions, X_test=None, Y_test=None,
feed=None, args=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:par... |
Wrapper around deprecated function. | def batch_eval(*args, **kwargs):
"""
Wrapper around deprecated function.
"""
# Inside function to avoid circular import
from cleverhans.evaluation import batch_eval as new_batch_eval
warnings.warn("batch_eval has moved to cleverhans.evaluation. "
"batch_eval will be removed from utils_tf on ... |
Helper function that computes the current class prediction: param sess: TF session: param x: the input placeholder: param predictions: the model s symbolic output: param samples: numpy array with input samples ( dims must match x ): param feed: An optional dictionary that is appended to the feeding dictionary before th... | def model_argmax(sess, x, predictions, samples, feed=None):
"""
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed:... |
Helper function to normalize a batch of vectors.: param x: the input placeholder: param epsilon: stabilizes division: return: the batch of l2 normalized vector | def l2_batch_normalize(x, epsilon=1e-12, scope=None):
"""
Helper function to normalize a batch of vectors.
:param x: the input placeholder
:param epsilon: stabilizes division
:return: the batch of l2 normalized vector
"""
with tf.name_scope(scope, "l2_batch_normalize") as name_scope:
x_shape = tf.shap... |
Helper function to compute kl - divergence KL ( p || q ) | def kl_with_logits(p_logits, q_logits, scope=None,
loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES):
"""Helper function to compute kl-divergence KL(p || q)
"""
with tf.name_scope(scope, "kl_divergence") as name:
p = tf.nn.softmax(p_logits)
p_log = tf.nn.log_softmax(p_logits)
q_lo... |
Helper function to clip the perturbation to epsilon norm ball.: param eta: A tensor with the current perturbation.: param ord: Order of the norm ( mimics Numpy ). Possible values: np. inf 1 or 2.: param eps: Epsilon bound of the perturbation. | def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
# Clipping p... |
Returns the list of devices that multi - replica code should use.: param devices: list of string device names e. g. [/ GPU: 0 ] If the user specifies this infer_devices checks that it is valid and then uses this user - specified list. If the user does not specify this infer_devices uses: - All available GPUs if there a... | def infer_devices(devices=None):
"""
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not spec... |
Returns a list of string names of all available GPUs | def get_available_gpus():
"""
Returns a list of string names of all available GPUs
"""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU'] |
A wrapper for clip_by_value that casts the clipping range if needed. | def clip_by_value(t, clip_value_min, clip_value_max, name=None):
"""
A wrapper for clip_by_value that casts the clipping range if needed.
"""
def cast_clip(clip):
"""
Cast clipping range argument if needed.
"""
if t.dtype in (tf.float32, tf.float64):
if hasattr(clip, 'dtype'):
# Co... |
A wrapper around tf multiplication that does more automatic casting of the input. | def mul(a, b):
"""
A wrapper around tf multiplication that does more automatic casting of
the input.
"""
def multiply(a, b):
"""Multiplication"""
return a * b
return op_with_scalar_cast(a, b, multiply) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.