INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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
query (str): SQL query to run
Ret... | 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
Note:
These credentials do not need to be explicitly defined if you are
using Application Default Credentials. If you are not using
Application Default Credentials, m... | 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
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 environment, manually assign the project... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> ... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> # TODO: Initialize `document`:
>>> document = {}
>>>
>>> # TODO: In... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>>... | 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.
Documents returned by this method are not guaranteed to be returned in the
same order that they were requested.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> response = c... | 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.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
>>> for... | 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.
EXPERIMENTAL: This method interface might change in the future.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> da... | 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.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.LoggingServi... | 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
... | 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>`__.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.Loggin... | 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.
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 regular expression match.
Returns:
str: The expanded variable t... | 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.
..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:
tmpl (str): The path template.
... | 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.
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.
Raises:
ValueError: If an unexpected te... | 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.
.. code-block:: python
>>> validate('users/*/messages/*', 'users/me/messages/123')
True
>>> validate('users/*/messages/*', 'users/me/drafts/123')
False
>>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3)
Tru... | 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.
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. | 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.
Args:
address (str): The host for the channel to use.
credentials (~.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
... | 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.
.. 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}"``
:rtype: str
:re... | 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.
: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 instance: The instance that owns the cluster.
... | 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.
:raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile
routing_policy_type is not set | 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.
:rtype: bool
:returns: True if the AppProfile exists, else False. | 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.
.. 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``.
To change them before creating, rese... | 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.
.. note::
Update any or all of the following values:
``routing_policy_type``
``description``
``cluster_id``
``allow_transactional_writes`` | 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.
Exam... | 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.
Example:
>>> from google.cloud... | 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.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.ConfigServiceV2Cl... | 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`.
: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. | 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 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.StructType`
:param row_type: row schema specificat... | 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... |
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
:rtype: varies on field_type
:returns: valu... | 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
... |
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.
Example:
>>> from google.cloud import asset_v1
... | 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
gap... | 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.
Args:
read_session ( \
~google.cloud.bigquery_storage_v1beta1.types.ReadSession \
):
The read session associated with this read rows stream. This
contains the schema, which is required to parse the data
... | 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.
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 schema, used to deserialized the bytes in t... | 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.
Args:
position (Union[ \
dict, \
~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \
]):
StreamPostion (or dictionary in StreamPosition format) to copy.
Returns:
~google.cloud.bigquery_storage_v1beta1.types.StreamPosi... | 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.
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 parsed as
strings in the fastavr... | 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.
Returns:
types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]:
A generator of pages. | 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.
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 parsed as
strings in the fastavr... | 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.
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 parsed as
strings in the fastavro libr... | 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_E... | 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``.
Immediately upon completion of this request:
... | 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 |
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. | 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.... |
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 |
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.\
instance.v1.InstanceAdmin.ListInstanceConfigs
See `RPC docs`_.
... | 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.
:type instance_id: str
:param instance_id: The ID of the instance.
:type configuration_name: string
:param configuration_name:
(Optional) Name of the instance configuration used to set up the
instance's clu... | 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.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances
:type filter_: string
:param filter_: (Optional) Filter to select instances listed. See
... | 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.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'. | 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.
: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.
:type loggers: dict
:param loggers:
A mapping ... | 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.
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 query parameters after the metadata key.
... | 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.
:param sess: TF session to use when training the graph
:para... | 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... | 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
d... | 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:
-... | 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) |
A wrapper around tf division that does more automatic casting of
the input. | def div(a, b):
"""
A wrapper around tf division that does more automatic casting of
the input.
"""
def divide(a, b):
"""Division"""
return a / b
return op_with_scalar_cast(a, b, divide) |
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar | def op_with_scalar_cast(a, b, f):
"""
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
""... |
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return: | def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"""
# This fun... |
Augment an adversary's substitute training set using the Jacobian
of a substitute model to generate new synthetic inputs.
See https://arxiv.org/abs/1602.02697 for more details.
See cleverhans_tutorials/mnist_blackbox.py for example use case
:param sess: TF session in which the substitute model is defined
:par... | def jacobian_augmentation(sess,
x,
X_sub_prev,
Y_sub,
grads,
lmbda,
aug_batch_size=512,
feed=None):
"""
Augment an adversary's substit... |
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param batch_size: size o... | def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
"""
Run evaluation on a saved model
:param filepath: path to model to evaluate
:param train_start: index of first ... |
Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary. | def set_input(self, X_batch=None):
"""
Preprocessing the inputs before calling session.run()
:param X_batch: A dictionary of inputs to the first sub-graph
:return: A tuple, `(fetches, fd)`, with `fetches` being a list of
Tensors to be fetches and `fd` the feed dictionary.
"""
input... |
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-graph. | def proc_fvals(self, fvals):
"""
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-g... |
Helper method to write images from single batch into datastore. | def _write_single_batch_images_internal(self, batch_id, client_batch):
"""Helper method to write images from single batch into datastore."""
client = self._datastore_client
batch_key = client.key(self._entity_kind_batches, batch_id)
for img_id, img in iteritems(self._data[batch_id]['images']):
img... |
Writes all image batches to the datastore. | def write_to_datastore(self):
"""Writes all image batches to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
for batch_id, batch_data in iteritems(self._data):
batch_key = client.key(self._entity_kind_batches, batch_id)
batch_entity = ... |
Writes only images from one batch to the datastore. | def write_single_batch_images_to_datastore(self, batch_id):
"""Writes only images from one batch to the datastore."""
client = self._datastore_client
with client.no_transact_batch() as client_batch:
self._write_single_batch_images_internal(batch_id, client_batch) |
Initializes batches by reading from the datastore. | def init_from_datastore(self):
"""Initializes batches by reading from the datastore."""
self._data = {}
for entity in self._datastore_client.query_fetch(
kind=self._entity_kind_batches):
batch_id = entity.key.flat_path[-1]
self._data[batch_id] = dict(entity)
self._data[batch_id]['i... |
Adds batch with give ID and list of properties. | def add_batch(self, batch_id, batch_properties=None):
"""Adds batch with give ID and list of properties."""
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError('batch_properties has to be dict, however it was: '
+ ... |
Adds image to given batch. | def add_image(self, batch_id, image_id, image_properties=None):
"""Adds image to given batch."""
if batch_id not in self._data:
raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id))
if image_properties is None:
image_properties = {}
if not isinstance(image_properties, dict):
... |
Reads list of dataset images from the datastore. | def _read_image_list(self, skip_image_ids=None):
"""Reads list of dataset images from the datastore."""
if skip_image_ids is None:
skip_image_ids = []
images = self._storage_client.list_blobs(
prefix=os.path.join('dataset', self._dataset_name) + '/')
zip_files = [i for i in images if i.end... |
Initializes dataset batches from the list of images in the datastore.
Args:
batch_size: batch size
allowed_epsilon: list of allowed epsilon or None to use default
skip_image_ids: list of image ids to skip
max_num_images: maximum number of images to read | def init_from_storage_write_to_datastore(self,
batch_size=100,
allowed_epsilon=None,
skip_image_ids=None,
max_num_images=None):
"""Initializes d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.