Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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,
):
... | [
"\n Creates a new document.\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 ... |
Please provide a description of the function: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,
):
... | [
"\n Updates or inserts a document.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.FirestoreClient()\n >>>\n >>> # TODO: Initialize `document`:\n >>> document = {}\n >>>\n ... |
Please provide a description of the function: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,
):
# Wrap the transport method to add r... | [
"\n Deletes a 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 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.meth... | [
"\n Gets multiple documents.\n\n Documents returned by this method are not guaranteed to be returned in the\n same order that they were requested.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.Firesto... |
Please provide a description of the function: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,
):
# Wrap the transport method to add ret... | [
"\n Starts a new transaction.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.FirestoreClient()\n >>>\n >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')\n >>>\n ... |
Please provide a description of the function: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,
... | [
"\n Runs a query.\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 ... |
Please provide a description of the function:def write(
self,
requests,
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.
if "w... | [
"\n Streams batches of document updates and deletes, in order.\n\n EXPERIMENTAL: This method interface might change in the future.\n\n Example:\n >>> from google.cloud import firestore_v1beta1\n >>>\n >>> client = firestore_v1beta1.FirestoreClient()\n ... |
Please provide a description of the function:def log_path(cls, project, log):
return google.api_core.path_template.expand(
"projects/{project}/logs/{log}", project=project, log=log
) | [
"Return a fully-qualified log string."
] |
Please provide a description of the function:def delete_log(
self,
log_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 all the log entries in a log.\n The log reappears if it receives new entries.\n Log entries written shortly before the delete operation might not be\n deleted.\n\n Example:\n >>> from google.cloud import logging_v2\n >>>\n >>> client = ... |
Please provide a description of the function: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... | [
"\n Writes log entries to Logging. This API method is the\n only way to send log entries to Logging. This method\n is used, directly or indirectly, by the Logging agent\n (fluentd) and all logging libraries configured to use Logging.\n A single request may contain log entries for ... |
Please provide a description of the function: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,
... | [
"\n Lists log entries. Use this method to retrieve log entries from Logging.\n For ways to export log entries, see `Exporting\n Logs <https://cloud.google.com/logging/docs/export>`__.\n\n Example:\n >>> from google.cloud import logging_v2\n >>>\n >>> clie... |
Please provide a description of the function:def _expand_variable_match(positional_vars, named_vars, match):
positional = match.group("positional")
name = match.group("name")
if name is not None:
try:
return six.text_type(named_vars[name])
except KeyError:
raise ... | [
"Expand a matched variable with its value.\n\n Args:\n positional_vars (list): A list of positonal variables. This list will\n be modified.\n named_vars (dict): A dictionary of named variables.\n match (re.Match): A regular expression match.\n\n Returns:\n str: The expan... |
Please provide a description of the function:def expand(tmpl, *args, **kwargs):
replacer = functools.partial(_expand_variable_match, list(args), kwargs)
return _VARIABLE_RE.sub(replacer, tmpl) | [
"Expand a path template with the given variables.\n\n ..code-block:: python\n\n >>> expand('users/*/messages/*', 'me', '123')\n users/me/messages/123\n >>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3')\n /v1/shelves/1/books/3\n\n Args:\n tmpl (str): The pa... |
Please provide a description of the function:def _replace_variable_with_pattern(match):
positional = match.group("positional")
name = match.group("name")
template = match.group("template")
if name is not None:
if not template:
return _SINGLE_SEGMENT_PATTERN.format(name)
... | [
"Replace a variable match with a pattern that can be used to validate it.\n\n Args:\n match (re.Match): A regular expression match\n\n Returns:\n str: A regular expression pattern that can be used to validate the\n variable in an expanded path.\n\n Raises:\n ValueError: If a... |
Please provide a description of the function:def validate(tmpl, path):
pattern = _generate_pattern_for_template(tmpl) + "$"
return True if re.match(pattern, path) is not None else False | [
"Validate a path against the path template.\n\n .. code-block:: python\n\n >>> validate('users/*/messages/*', 'users/me/messages/123')\n True\n >>> validate('users/*/messages/*', 'users/me/drafts/123')\n False\n >>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3... |
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)
session.install('-e', '.')
# Run py.te... | [
"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 create_channel(cls, address="firestore.googleapis.com:443", credentials=None):
return google.api_core.grpc_helpers.create_channel(
address, credentials=credentials, scopes=cls._OAUTH_SCOPES
) | [
"Create and return a gRPC channel object.\n\n Args:\n address (str): The host for the channel to use.\n credentials (~.Credentials): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n ... |
Please provide a description of the function:def name(self):
return self.instance_admin_client.app_profile_path(
self._instance._client.project,
self._instance.instance_id,
self.app_profile_id,
) | [
"AppProfile name used in requests.\n\n .. note::\n\n This property will not change if ``app_profile_id`` does not, but\n the return value is not cached.\n\n The AppProfile name is of the form\n ``\"projects/../instances/../app_profile/{app_profile_id}\"``\n\n :rtype... |
Please provide a description of the function:def from_pb(cls, app_profile_pb, instance):
match_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name)
if match_app_profile_name is None:
raise ValueError(
"AppProfile protobuf name was not in the " "expected... | [
"Creates an instance app_profile from a protobuf.\n\n :type app_profile_pb: :class:`instance_pb2.app_profile_pb`\n :param app_profile_pb: An instance protobuf object.\n\n :type instance: :class:`google.cloud.bigtable.instance.Instance`\n :param instance: The instance that owns the cluste... |
Please provide a description of the function:def _update_from_pb(self, app_profile_pb):
self.routing_policy_type = None
self.allow_transactional_writes = None
self.cluster_id = None
self.description = app_profile_pb.description
routing_policy_type = None
if app... | [
"Refresh self from the server-provided protobuf.\n Helper for :meth:`from_pb` and :meth:`reload`.\n "
] |
Please provide a description of the function:def _to_pb(self):
if not self.routing_policy_type:
raise ValueError("AppProfile required routing policy.")
single_cluster_routing = None
multi_cluster_routing_use_any = None
if self.routing_policy_type == RoutingPolicyTy... | [
"Create an AppProfile proto buff message for API calls\n :rtype: :class:`.instance_pb2.AppProfile`\n :returns: The converted current object.\n\n :raises: :class:`ValueError <exceptions.ValueError>` if the AppProfile\n routing_policy_type is not set\n "
] |
Please provide a description of the function:def reload(self):
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_... | [
"Reload the metadata for this cluster"
] |
Please provide a description of the function:def exists(self):
try:
self.instance_admin_client.get_app_profile(self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False | [
"Check whether the AppProfile already exists.\n\n :rtype: bool\n :returns: True if the AppProfile exists, else False.\n "
] |
Please provide a description of the function:def create(self, ignore_warnings=None):
return self.from_pb(
self.instance_admin_client.create_app_profile(
parent=self._instance.name,
app_profile_id=self.app_profile_id,
app_profile=self._to_pb(),... | [
"Create this AppProfile.\n\n .. note::\n\n Uses the ``instance`` and ``app_profile_id`` on the current\n :class:`AppProfile` in addition to the ``routing_policy_type``,\n ``description``, ``cluster_id`` and ``allow_transactional_writes``.\n To change them before cr... |
Please provide a description of the function:def update(self, ignore_warnings=None):
update_mask_pb = field_mask_pb2.FieldMask()
if self.description is not None:
update_mask_pb.paths.append("description")
if self.routing_policy_type == RoutingPolicyType.ANY:
up... | [
"Update this app_profile.\n\n .. note::\n\n Update any or all of the following values:\n ``routing_policy_type``\n ``description``\n ``cluster_id``\n ``allow_transactional_writes``\n\n "
] |
Please provide a description of the function:def sink_path(cls, project, sink):
return google.api_core.path_template.expand(
"projects/{project}/sinks/{sink}", project=project, sink=sink
) | [
"Return a fully-qualified sink string."
] |
Please provide a description of the function:def exclusion_path(cls, project, exclusion):
return google.api_core.path_template.expand(
"projects/{project}/exclusions/{exclusion}",
project=project,
exclusion=exclusion,
) | [
"Return a fully-qualified exclusion string."
] |
Please provide a description of the function: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,
):
# Wrap the transpo... | [
"\n Creates a sink that exports specified log entries to a destination. The\n export of newly-ingested log entries begins immediately, unless the\n sink's ``writer_identity`` is not permitted to write to the destination.\n A sink can export log entries only from the resource owning the s... |
Please provide a description of the function: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,
):
... | [
"\n Updates a sink. This method replaces the following fields in the\n existing sink with values from the new sink: ``destination``, and\n ``filter``. The updated sink might also have a new ``writer_identity``;\n see the ``unique_writer_identity`` field.\n\n Example:\n ... |
Please provide a description of the function:def create_exclusion(
self,
parent,
exclusion,
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 ... | [
"\n Creates a new exclusion in a specified parent resource.\n Only log entries belonging to that resource can be excluded.\n You can have up to 10 exclusions in a resource.\n\n Example:\n >>> from google.cloud import logging_v2\n >>>\n >>> client = loggin... |
Please provide a description of the function:def _make_value_pb(value):
if value is None:
return Value(null_value="NULL_VALUE")
if isinstance(value, (list, tuple)):
return Value(list_value=_make_list_value_pb(value))
if isinstance(value, bool):
return Value(bool_value=value)
... | [
"Helper for :func:`_make_list_value_pbs`.\n\n :type value: scalar value\n :param value: value to convert\n\n :rtype: :class:`~google.protobuf.struct_pb2.Value`\n :returns: value protobufs\n :raises ValueError: if value is not of a known scalar type.\n "
] |
Please provide a description of the function:def _parse_value_pb(value_pb, field_type):
if value_pb.HasField("null_value"):
return None
if field_type.code == type_pb2.STRING:
result = value_pb.string_value
elif field_type.code == type_pb2.BYTES:
result = value_pb.string_value.en... | [
"Convert a Value protobuf to cell data.\n\n :type value_pb: :class:`~google.protobuf.struct_pb2.Value`\n :param value_pb: protobuf to convert\n\n :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type`\n :param field_type: type code for the value\n\n :rtype: varies on field_type\n ... |
Please provide a description of the function:def _parse_list_value_pbs(rows, row_type):
result = []
for row in rows:
row_data = []
for value_pb, field in zip(row.values, row_type.fields):
row_data.append(_parse_value_pb(value_pb, field.type))
result.append(row_data)
... | [
"Convert a list of ListValue protobufs into a list of list of cell data.\n\n :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue`\n :param rows: row data returned from a read/query\n\n :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType`\n :param row_type: row schema... |
Please provide a description of the function: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,
metada... | [
"\n Exports assets with time and resource types to a given Cloud Storage\n location. The output format is newline-delimited JSON. This API\n implements the ``google.longrunning.Operation`` API allowing you to keep\n track of the export.\n\n Example:\n >>> from google.cl... |
Please provide a description of the function: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,
):... | [
"\n Batch gets the update history of assets that overlap a time window. For\n RESOURCE content, this API outputs history with asset in both non-delete\n or deleted status. For IAM\\_POLICY content, this API outputs history\n when the asset and its attached IAM POLICY both exist. This can... |
Please provide a description of the function:def _avro_schema(read_session):
json_schema = json.loads(read_session.avro_schema.schema)
column_names = tuple((field["name"] for field in json_schema["fields"]))
return fastavro.parse_schema(json_schema), column_names | [
"Extract and parse Avro schema from a read session.\n\n Args:\n read_session ( \\\n ~google.cloud.bigquery_storage_v1beta1.types.ReadSession \\\n ):\n The read session associated with this read rows stream. This\n contains the schema, which is required to parse the ... |
Please provide a description of the function:def _avro_rows(block, avro_schema):
blockio = six.BytesIO(block.avro_rows.serialized_binary_rows)
while True:
# Loop in a while loop because schemaless_reader can only read
# a single record.
try:
# TODO: Parse DATETIME into d... | [
"Parse all rows in a stream block.\n\n Args:\n block ( \\\n ~google.cloud.bigquery_storage_v1beta1.types.ReadRowsResponse \\\n ):\n A block containing Avro bytes to parse into rows.\n avro_schema (fastavro.schema):\n A parsed Avro schema, used to deserialized... |
Please provide a description of the function:def _copy_stream_position(position):
if isinstance(position, types.StreamPosition):
output = types.StreamPosition()
output.CopyFrom(position)
return output
return types.StreamPosition(**position) | [
"Copy a StreamPosition.\n\n Args:\n position (Union[ \\\n dict, \\\n ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \\\n ]):\n StreamPostion (or dictionary in StreamPosition format) to copy.\n\n Returns:\n ~google.cloud.bigquery_storage_v1beta... |
Please provide a description of the function:def _reconnect(self):
self._wrapped = self._client.read_rows(
_copy_stream_position(self._position), **self._read_rows_kwargs
) | [
"Reconnect to the ReadRows stream using the most recent offset."
] |
Please provide a description of the function:def to_dataframe(self, read_session, dtypes=None):
if fastavro is None:
raise ImportError(_FASTAVRO_REQUIRED)
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
return self.rows(read_session).to_dataframe(dtypes=d... | [
"Create a :class:`pandas.DataFrame` of all rows in the stream.\n\n This method requires the pandas libary to create a data frame and the\n fastavro library to parse row blocks.\n\n .. warning::\n DATETIME columns are not supported. They are currently parsed as\n strings in... |
Please provide a description of the function:def pages(self):
# Each page is an iterator of rows. But also has num_items, remaining,
# and to_dataframe.
avro_schema, column_names = _avro_schema(self._read_session)
for block in self._reader:
self._status = block.statu... | [
"A generator of all pages in the stream.\n\n Returns:\n types.GeneratorType[google.cloud.bigquery_storage_v1beta1.ReadRowsPage]:\n A generator of pages.\n "
] |
Please provide a description of the function:def to_dataframe(self, dtypes=None):
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
frames = []
for page in self.pages:
frames.append(page.to_dataframe(dtypes=dtypes))
return pandas.concat(frames) | [
"Create a :class:`pandas.DataFrame` of all rows in the stream.\n\n This method requires the pandas libary to create a data frame and the\n fastavro library to parse row blocks.\n\n .. warning::\n DATETIME columns are not supported. They are currently parsed as\n strings in... |
Please provide a description of the function:def _parse_block(self):
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_count
... | [
"Parse metadata and rows from the block only once."
] |
Please provide a description of the function:def next(self):
self._parse_block()
if self._remaining > 0:
self._remaining -= 1
return six.next(self._iter_rows) | [
"Get the next row in the page."
] |
Please provide a description of the function:def to_dataframe(self, dtypes=None):
if pandas is None:
raise ImportError(_PANDAS_REQUIRED)
if dtypes is None:
dtypes = {}
columns = collections.defaultdict(list)
for row in self:
for column in ro... | [
"Create a :class:`pandas.DataFrame` of rows in the page.\n\n This method requires the pandas libary to create a data frame and the\n fastavro library to parse row blocks.\n\n .. warning::\n DATETIME columns are not supported. They are currently parsed as\n strings in the f... |
Please provide a description of the function:def instance_config_path(cls, project, instance_config):
return google.api_core.path_template.expand(
"projects/{project}/instanceConfigs/{instance_config}",
project=project,
instance_config=instance_config,
) | [
"Return a fully-qualified instance_config string."
] |
Please provide a description of the function: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,
):
# Wrap the transport metho... | [
"\n Creates an instance and begins preparing it to begin serving. The\n returned ``long-running operation`` can be used to track the progress of\n preparing the new instance. The instance name is assigned by the caller.\n If the named instance already exists, ``CreateInstance`` returns\n... |
Please provide a description of the function: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,
):
# Wrap the transport method to add retry an... | [
"\n Updates an instance, and begins allocating or releasing resources as\n requested. The returned ``long-running operation`` can be used to track\n the progress of updating the instance. If the named instance does not\n exist, returns ``NOT_FOUND``.\n\n Immediately upon completio... |
Please provide a description of the function:def finding_path(cls, project, scan_config, scan_run, finding):
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}",
project=project,
scan_conf... | [
"Return a fully-qualified finding string."
] |
Please provide a description of the function:def scan_config_path(cls, project, scan_config):
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}",
project=project,
scan_config=scan_config,
) | [
"Return a fully-qualified scan_config string."
] |
Please provide a description of the function:def scan_run_path(cls, project, scan_config, scan_run):
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}",
project=project,
scan_config=scan_config,
... | [
"Return a fully-qualified scan_run string."
] |
Please provide a description of the function:def instance_admin_api(self):
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."
] |
Please provide a description of the function:def database_admin_api(self):
if self._database_admin_api is None:
self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._database_admin_api | [
"Helper for session-related API calls."
] |
Please provide a description of the function:def copy(self):
return self.__class__(
project=self.project,
credentials=self._credentials,
user_agent=self.user_agent,
) | [
"Make a copy of this client.\n\n Copies the local data stored as simple types but does not copy the\n current state of any open connections with the Cloud Bigtable API.\n\n :rtype: :class:`.Client`\n :returns: A copy of the current client.\n "
] |
Please provide a description of the function:def list_instance_configs(self, page_size=None, page_token=None):
metadata = _metadata_with_prefix(self.project_name)
path = "projects/%s" % (self.project,)
page_iter = self.instance_admin_api.list_instance_configs(
path, page_siz... | [
"List available instance configurations for the client's project.\n\n .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\\\n google.spanner.admin.instance.v1#google.spanner.admin.\\\n instance.v1.InstanceAdmin.ListInstanceConfigs\n\n See `RPC d... |
Please provide a description of the function:def instance(
self,
instance_id,
configuration_name=None,
display_name=None,
node_count=DEFAULT_NODE_COUNT,
):
return Instance(instance_id, self, configuration_name, node_count, display_name) | [
"Factory to create a instance associated with this client.\n\n :type instance_id: str\n :param instance_id: The ID of the instance.\n\n :type configuration_name: string\n :param configuration_name:\n (Optional) Name of the instance configuration used to set up the\n i... |
Please provide a description of the function:def list_instances(self, filter_="", page_size=None, page_token=None):
metadata = _metadata_with_prefix(self.project_name)
path = "projects/%s" % (self.project,)
page_iter = self.instance_admin_api.list_instances(
path, page_size=... | [
"List instances for the client's project.\n\n See\n https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances\n\n :type filter_: string\n :param filter_: (Optional) Filter to select instances listed. See\... |
Please provide a description of the function:def _should_retry(exc):
if not hasattr(exc, "errors"):
return False
if len(exc.errors) == 0:
# Check for unstructured error returns, e.g. from GFE
return isinstance(exc, _UNSTRUCTURED_RETRYABLE_TYPES)
reason = exc.errors[0]["reason"... | [
"Predicate for determining when to retry.\n\n We retry if and only if the 'reason' is 'backendError'\n or 'rateLimitExceeded'.\n "
] |
Please provide a description of the function:def default(session, django_dep=('django',)):
# 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)... | [
"Default unit test session.\n "
] |
Please provide a description of the function:def unit(session):
# 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.interpret... | [
"Run the unit test suite."
] |
Please provide a description of the function:def system(session):
# 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... | [
"Run the system test suite."
] |
Please provide a description of the function:def entry_from_resource(resource, client, loggers):
if "textPayload" in resource:
return TextEntry.from_api_repr(resource, client, loggers)
if "jsonPayload" in resource:
return StructEntry.from_api_repr(resource, client, loggers)
if "protoP... | [
"Detect correct entry type from resource and instantiate.\n\n :type resource: dict\n :param resource: One entry resource from API response.\n\n :type client: :class:`~google.cloud.logging.client.Client`\n :param client: Client that owns the log entry.\n\n :type loggers: dict\n :param loggers:\n ... |
Please provide a description of the function:def retrieve_metadata_server(metadata_key):
url = METADATA_URL + metadata_key
try:
response = requests.get(url, headers=METADATA_HEADERS)
if response.status_code == requests.codes.ok:
return response.text
except requests.except... | [
"Retrieve the metadata key in the metadata server.\n\n See: https://cloud.google.com/compute/docs/storing-retrieving-metadata\n\n :type metadata_key: str\n :param metadata_key: Key of the metadata which will form the url. You can\n also supply query parameters after the metadata key... |
Please provide a description of the function:def model_loss(y, model, mean=True):
warnings.warn("This function is deprecated and will be removed on or after"
" 2019-04-05. Switch to cleverhans.train.train.")
op = model.op
if op.type == "Softmax":
logits, = op.inputs
else:
logits = mod... | [
"\n Define loss of TF graph\n :param y: correct labels\n :param model: output of the model\n :param mean: boolean indicating whether should return mean of loss\n or vector of losses for each input of the batch\n :return: return mean of loss if True, otherwise return vector with per\n sa... |
Please provide a description of the function:def initialize_uninitialized_global_variables(sess):
# List all global variables
global_vars = tf.global_variables()
# Find initialized status for all variables
is_var_init = [tf.is_variable_initialized(var) for var in global_vars]
is_initialized = sess.run(is_... | [
"\n Only initializes the variables of a TensorFlow session that were not\n already initialized.\n :param sess: the TensorFlow session\n :return:\n "
] |
Please provide a description of the function: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):
warnings.warn("This function is deprecated and will be removed on or after"
... | [
"\n Train a TF graph.\n This function is deprecated. Prefer cleverhans.train.train when possible.\n cleverhans.train.train supports multiple GPUs but this function is still\n needed to support legacy models that do not support calling fprop more\n than once.\n\n :param sess: TF session to use when training th... |
Please provide a description of the function:def model_eval(sess, x, y, predictions, X_test=None, Y_test=None,
feed=None, args=None):
global _model_eval_cache
args = _ArgsWrapper(args or {})
assert args.batch_size, "Batch size was not given in args dict"
if X_test is None or Y_test is None:
... | [
"\n Compute the accuracy of a TF model on some data\n :param sess: TF session to use\n :param x: input placeholder\n :param y: output placeholder (for labels)\n :param predictions: model output predictions\n :param X_test: numpy array with training inputs\n :param Y_test: numpy array with training outputs\n ... |
Please provide a description of the function:def batch_eval(*args, **kwargs):
# 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 or... | [
"\n Wrapper around deprecated function.\n "
] |
Please provide a description of the function:def model_argmax(sess, x, predictions, samples, feed=None):
feed_dict = {x: samples}
if feed is not None:
feed_dict.update(feed)
probabilities = sess.run(predictions, feed_dict)
if samples.shape[0] == 1:
return np.argmax(probabilities)
else:
return ... | [
"\n Helper function that computes the current class prediction\n :param sess: TF session\n :param x: the input placeholder\n :param predictions: the model's symbolic output\n :param samples: numpy array with input samples (dims must match x)\n :param feed: An optional dictionary that is appended to the feedin... |
Please provide a description of the function:def l2_batch_normalize(x, epsilon=1e-12, scope=None):
with tf.name_scope(scope, "l2_batch_normalize") as name_scope:
x_shape = tf.shape(x)
x = tf.contrib.layers.flatten(x)
x /= (epsilon + reduce_max(tf.abs(x), 1, keepdims=True))
square_sum = reduce_sum(t... | [
"\n Helper function to normalize a batch of vectors.\n :param x: the input placeholder\n :param epsilon: stabilizes division\n :return: the batch of l2 normalized vector\n "
] |
Please provide a description of the function:def kl_with_logits(p_logits, q_logits, scope=None,
loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES):
with tf.name_scope(scope, "kl_divergence") as name:
p = tf.nn.softmax(p_logits)
p_log = tf.nn.log_softmax(p_logits)
q_log = tf.nn.log_s... | [
"Helper function to compute kl-divergence KL(p || q)\n "
] |
Please provide a description of the function:def clip_eta(eta, ord, eps):
# Clipping perturbation eta to self.ord norm ball
if ord not in [np.inf, 1, 2]:
raise ValueError('ord must be np.inf, 1, or 2.')
reduc_ind = list(xrange(1, len(eta.get_shape())))
avoid_zero_div = 1e-12
if ord == np.inf:
eta ... | [
"\n Helper function to clip the perturbation to epsilon norm ball.\n :param eta: A tensor with the current perturbation.\n :param ord: Order of the norm (mimics Numpy).\n Possible values: np.inf, 1 or 2.\n :param eps: Epsilon, bound of the perturbation.\n "
] |
Please provide a description of the function:def infer_devices(devices=None):
if devices is None:
devices = get_available_gpus()
if len(devices) == 0:
warnings.warn("No GPUS, running on CPU")
# Set device to empy string, tf will figure out whether to use
# XLA or not, etc., automatically
... | [
"\n Returns the list of devices that multi-replica code should use.\n :param devices: list of string device names, e.g. [\"/GPU:0\"]\n If the user specifies this, `infer_devices` checks that it is\n valid, and then uses this user-specified list.\n If the user does not specify this, infer_devices us... |
Please provide a description of the function:def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU'] | [
"\n Returns a list of string names of all available GPUs\n "
] |
Please provide a description of the function:def clip_by_value(t, clip_value_min, clip_value_max, name=None):
def cast_clip(clip):
if t.dtype in (tf.float32, tf.float64):
if hasattr(clip, 'dtype'):
# Convert to tf dtype in case this is a numpy dtype
clip_dtype = tf.as_dtype(clip.dtyp... | [
"\n A wrapper for clip_by_value that casts the clipping range if needed.\n ",
"\n Cast clipping range argument if needed.\n "
] |
Please provide a description of the function:def mul(a, b):
def multiply(a, b):
return a * b
return op_with_scalar_cast(a, b, multiply) | [
"\n A wrapper around tf multiplication that does more automatic casting of\n the input.\n ",
"Multiplication"
] |
Please provide a description of the function:def div(a, b):
def divide(a, b):
return a / b
return op_with_scalar_cast(a, b, divide) | [
"\n A wrapper around tf division that does more automatic casting of\n the input.\n ",
"Division"
] |
Please provide a description of the function:def op_with_scalar_cast(a, b, f):
try:
return f(a, b)
except (TypeError, ValueError):
pass
def is_scalar(x):
if hasattr(x, "get_shape"):
shape = x.get_shape()
return shape.ndims == 0
if hasattr(x, "ndim"):
return x.ndim == 0
... | [
"\n Builds the graph to compute f(a, b).\n If only one of the two arguments is a scalar and the operation would\n cause a type error without casting, casts the scalar to match the\n tensor.\n :param a: a tf-compatible array or scalar\n :param b: a tf-compatible array or scalar\n ",
"Return True if `x` is a... |
Please provide a description of the function:def jacobian_graph(predictions, x, nb_classes):
# This function will return a list of TF gradients
list_derivatives = []
# Define the TF graph elements to compute our derivatives for each class
for class_ind in xrange(nb_classes):
derivatives, = tf.gradients... | [
"\n Create the Jacobian graph to be ran later in a TF session\n :param predictions: the model's symbolic output (linear output,\n pre-softmax)\n :param x: the input placeholder\n :param nb_classes: the number of classes the model has\n :return:\n "
] |
Please provide a description of the function:def jacobian_augmentation(sess,
x,
X_sub_prev,
Y_sub,
grads,
lmbda,
aug_batch_size=512,
feed=... | [
"\n Augment an adversary's substitute training set using the Jacobian\n of a substitute model to generate new synthetic inputs.\n See https://arxiv.org/abs/1602.02697 for more details.\n See cleverhans_tutorials/mnist_blackbox.py for example use case\n :param sess: TF session in which the substitute model is d... |
Please provide a description of the function:def evaluate_model(filepath,
train_start=0, train_end=60000, test_start=0,
test_end=10000, batch_size=128,
testing=False, num_threads=None):
# Set TF random seed to improve reproducibility
tf.set_random_seed(12... | [
"\n Run evaluation on a saved model\n :param filepath: path to model to evaluate\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set example\n :param bat... |
Please provide a description of the function:def set_input(self, X_batch=None):
inputs = self.inputs
outputs = self.outputs
# data for first gpu
fd = {}
if X_batch is not None:
self.next_vals[0] = OrderedDict()
for i, vname in enumerate(self.inputs[0]):
if vname in X_batch:... | [
"\n Preprocessing the inputs before calling session.run()\n\n :param X_batch: A dictionary of inputs to the first sub-graph\n :return: A tuple, `(fetches, fd)`, with `fetches` being a list of\n Tensors to be fetches and `fd` the feed dictionary.\n "
] |
Please provide a description of the function:def proc_fvals(self, fvals):
inputs = self.inputs
outputs = self.outputs
# Move data to the next sub-graph for the next step
cur = 0
for i in range(len(inputs)-1):
if not self.active_gpus[i]:
self.next_vals[i+1] = None
continue... | [
"\n Postprocess the outputs of the Session.run(). Move the outputs of\n sub-graphs to next ones and return the output of the last sub-graph.\n\n :param fvals: A list of fetched values returned by Session.run()\n :return: A dictionary of fetched values returned by the last sub-graph.\n "
] |
Please provide a description of the function:def _write_single_batch_images_internal(self, batch_id, client_batch):
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_entity = client.entity(... | [
"Helper method to write images from single batch into datastore."
] |
Please provide a description of the function:def write_to_datastore(self):
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 = cli... | [
"Writes all image batches to the datastore."
] |
Please provide a description of the function:def write_single_batch_images_to_datastore(self, batch_id):
client = self._datastore_client
with client.no_transact_batch() as client_batch:
self._write_single_batch_images_internal(batch_id, client_batch) | [
"Writes only images from one batch to the datastore."
] |
Please provide a description of the function:def init_from_datastore(self):
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]['images'] = {... | [
"Initializes batches by reading from the datastore."
] |
Please provide a description of the function:def add_batch(self, batch_id, batch_properties=None):
if batch_properties is None:
batch_properties = {}
if not isinstance(batch_properties, dict):
raise ValueError('batch_properties has to be dict, however it was: '
+ str(type... | [
"Adds batch with give ID and list of properties."
] |
Please provide a description of the function:def add_image(self, batch_id, image_id, image_properties=None):
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_proper... | [
"Adds image to given batch."
] |
Please provide a description of the function:def _read_image_list(self, skip_image_ids=None):
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.endswith('.z... | [
"Reads list of dataset images from the datastore."
] |
Please provide a description of the function:def init_from_storage_write_to_datastore(self,
batch_size=100,
allowed_epsilon=None,
skip_image_ids=None,
... | [
"Initializes dataset batches from the list of images in the datastore.\n\n Args:\n batch_size: batch size\n allowed_epsilon: list of allowed epsilon or None to use default\n skip_image_ids: list of image ids to skip\n max_num_images: maximum number of images to read\n "
] |
Please provide a description of the function:def init_from_dataset_and_submissions_write_to_datastore(
self, dataset_batches, attack_submission_ids):
batches_x_attacks = itertools.product(dataset_batches.data.keys(),
attack_submission_ids)
for idx, (dataset_b... | [
"Init list of adversarial batches from dataset batches and submissions.\n\n Args:\n dataset_batches: instances of DatasetBatches\n attack_submission_ids: iterable with IDs of all (targeted and nontargeted)\n attack submissions, could be obtains as\n CompetitionSubmissions.get_all_attack_i... |
Please provide a description of the function:def count_generated_adv_examples(self):
result = {}
for v in itervalues(self.data):
s_id = v['submission_id']
result[s_id] = result.get(s_id, 0) + len(v['images'])
return result | [
"Returns total number of all generated adversarial examples."
] |
Please provide a description of the function:def make_confidence_report_bundled(filepath, train_start=TRAIN_START,
train_end=TRAIN_END, test_start=TEST_START,
test_end=TEST_END, which_set=WHICH_SET,
recipe=RECIPE, r... | [
"\n Load a saved model, gather its predictions, and save a confidence report.\n :param filepath: path to model to evaluate\n :param train_start: index of first training set example to use\n :param train_end: index of last training set example to use\n :param test_start: index of first test set example to use\n... |
Please provide a description of the function:def print_stats(correctness, confidence, name):
accuracy = correctness.mean()
wrongness = 1 - correctness
denom1 = np.maximum(1, wrongness.sum())
ave_prob_on_mistake = (wrongness * confidence).sum() / denom1
assert ave_prob_on_mistake <= 1., ave_prob_on_mistake
... | [
"\n Prints out accuracy, coverage, etc. statistics\n :param correctness: ndarray\n One bool per example specifying whether it was correctly classified\n :param confidence: ndarray\n The probability associated with each prediction\n :param name: str\n The name of this type of data (e.g. \"clean\", \"Max... |
Please provide a description of the function:def make_confidence_report(filepath, train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START, test_end=TEST_END,
batch_size=BATCH_SIZE, which_set=WHICH_SET,
... | [
"\n Load a saved model, gather its predictions, and save a confidence report.\n\n\n This function works by running a single MaxConfidence attack on each example.\n This provides a reasonable estimate of the true failure rate quickly, so\n long as the model does not suffer from gradient masking.\n However, this... |
Please provide a description of the function:def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR,
filename=FILENAME, load_model=LOAD_MODEL,
... | [
"\n MNIST CleverHans tutorial\n :param train_start: index of first training set example\n :param train_end: index of last training set example\n :param test_start: index of first test set example\n :param test_end: index of last test set example\n :param nb_epochs: number of epochs to train model\n :param ba... |
Please provide a description of the function:def generate(self, x, **kwargs):
assert self.parse_params(**kwargs)
labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
adv_x = self.attack(x, labels)
return adv_x | [
"\n Generate symbolic graph for adversarial examples and return.\n\n :param x: The model's symbolic inputs.\n :param kwargs: Keyword arguments for the base attacker\n "
] |
Please provide a description of the function:def attack(self, x, true_y):
adv_x_cls = []
prob_cls = []
m = tf.shape(x)[0]
true_y_idx = tf.argmax(true_y, axis=1)
expanded_x = tf.concat([x] * self.nb_classes, axis=0)
target_ys = [tf.to_float(tf.one_hot(tf.ones(m, dtype=tf.int32) * cls,
... | [
"\n Runs the untargeted attack.\n :param x: The input\n :param true_y: The correct label for `x`. This attack aims to produce misclassification.\n "
] |
Please provide a description of the function:def attack_class(self, x, target_y):
adv = self.base_attacker.generate(x, y_target=target_y, **self.params)
return adv | [
"\n Run the attack on a specific target class.\n :param x: tf Tensor. The input example.\n :param target_y: tf Tensor. The attacker's desired target class.\n Returns:\n A targeted adversarial example, intended to be classified as the target class.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.