text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transaction_id(transaction, read_operation=True):
"""Get the transaction ID from a ``Transaction`` object. Args: transaction (Optional[~.firestore_v1beta... |
if transaction is None:
return None
else:
if not transaction.in_progress:
raise ValueError(INACTIVE_TXN)
if read_operation and len(transaction._write_pbs) > 0:
raise ReadAfterWriteError(READ_AFTER_WRITE_ERROR)
return transaction.id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uptime_check_config_path(cls, project, uptime_check_config):
"""Return a fully-qualified uptime_check_config string.""" |
return google.api_core.path_template.expand(
"projects/{project}/uptimeCheckConfigs/{uptime_check_config}",
project=project,
uptime_check_config=uptime_check_config,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_uptime_check_config( self, parent, uptime_check_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT,... |
if metadata is None:
metadata = []
metadata = list(metadata)
# Wrap the transport method to add retry and timeout logic.
if "create_uptime_check_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_uptime_check_config"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def owners(self):
"""Legacy access to owner role. DEPRECATED: use ``policy["roles/owners"]`` instead.""" |
result = set()
for role in self._OWNER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def owners(self, value):
"""Update owners. DEPRECATED: use ``policy["roles/owners"] = value`` instead.""" |
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning
)
self[OWNER_ROLE] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def editors(self):
"""Legacy access to editor role. DEPRECATED: use ``policy["roles/editors"]`` instead.""" |
result = set()
for role in self._EDITOR_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def editors(self, value):
"""Update editors. DEPRECATED: use ``policy["roles/editors"] = value`` instead.""" |
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
DeprecationWarning,
)
self[EDITOR_ROLE] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def viewers(self):
"""Legacy access to viewer role. DEPRECATED: use ``policy["roles/viewers"]`` instead """ |
result = set()
for role in self._VIEWER_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def viewers(self, value):
"""Update viewers. DEPRECATED: use ``policy["roles/viewers"] = value`` instead. """ |
warnings.warn(
_ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE),
DeprecationWarning,
)
self[VIEWER_ROLE] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reference_info(references):
"""Get information about document references. Helper for :meth:`~.firestore_v1beta1.client.Client.get_all`. Args: references. Re... |
document_paths = []
reference_map = {}
for reference in references:
doc_path = reference._document_path
document_paths.append(doc_path)
reference_map[doc_path] = reference
return document_paths, reference_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_reference(document_path, reference_map):
"""Get a document reference from a dictionary. This just wraps a simple dictionary look-up with a helpful error... |
try:
return reference_map[document_path]
except KeyError:
msg = _BAD_DOC_TEMPLATE.format(document_path)
raise ValueError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_batch_get(get_doc_response, reference_map, client):
"""Parse a `BatchGetDocumentsResponse` protobuf. Args: get_doc_response (~google.cloud.proto.fires... |
result_type = get_doc_response.WhichOneof("result")
if result_type == "found":
reference = _get_reference(get_doc_response.found.name, reference_map)
data = _helpers.decode_dict(get_doc_response.found.fields, client)
snapshot = DocumentSnapshot(
reference,
data,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _firestore_api(self):
"""Lazy-loading getter GAPIC Firestore API. Returns: ~.gapic.firestore.v1beta1.firestore_client.FirestoreClient: The GAPIC client with ... |
if self._firestore_api_internal is None:
self._firestore_api_internal = firestore_client.FirestoreClient(
credentials=self._credentials
)
return self._firestore_api_internal |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _database_string(self):
"""The database string corresponding to this client's project. This value is lazy-loaded and cached. Will be of the form ``projects/{... |
if self._database_string_internal is None:
# NOTE: database_root_path() is a classmethod, so we don't use
# self._firestore_api (it isn't necessary).
db_str = firestore_client.FirestoreClient.database_root_path(
self.project, self._database
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rpc_metadata(self):
"""The RPC metadata for this client's associated database. Returns: Sequence[Tuple(str, str)]: RPC metadata with resource prefix for the... |
if self._rpc_metadata_internal is None:
self._rpc_metadata_internal = _helpers.metadata_with_prefix(
self._database_string
)
return self._rpc_metadata_internal |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collection(self, *collection_path):
"""Get a reference to a collection. For a top-level collection: .. code-block:: python For a sub-collection: .. code-bloc... |
if len(collection_path) == 1:
path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = collection_path
return CollectionReference(*path, client=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document(self, *document_path):
"""Get a reference to a document in a collection. For a top-level document: .. code-block:: python For a document in a sub-co... |
if len(document_path) == 1:
path = document_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = document_path
return DocumentReference(*path, client=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_option(**kwargs):
"""Create a write option for write operations. Write operations include :meth:`~.DocumentReference.set`, :meth:`~.DocumentReference.u... |
if len(kwargs) != 1:
raise TypeError(_BAD_OPTION_ERR)
name, value = kwargs.popitem()
if name == "last_update_time":
return _helpers.LastUpdateOption(value)
elif name == "exists":
return _helpers.ExistsOption(value)
else:
extra = "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all(self, references, field_paths=None, transaction=None):
"""Retrieve a batch of documents. .. note:: Documents returned by this method are not guarante... |
document_paths, reference_map = _reference_info(references)
mask = _get_doc_mask(field_paths)
response_iterator = self._firestore_api.batch_get_documents(
self._database_string,
document_paths,
mask,
transaction=_helpers.get_transaction_id(transac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collections(self):
"""List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of... |
iterator = self._firestore_api.list_collection_ids(
self._database_string, metadata=self._rpc_metadata
)
iterator.client = self
iterator.item_to_value = _item_to_collection_ref
return iterator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin(self):
"""Begin a transaction on the database. :rtype: bytes :returns: the ID for the newly-begun transaction. :raises ValueError: if the transaction i... |
if self._transaction_id is not None:
raise ValueError("Transaction already begun")
if self.committed is not None:
raise ValueError("Transaction already committed")
if self._rolled_back:
raise ValueError("Transaction is already rolled back")
databas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(self):
"""Roll back a transaction on the database.""" |
self._check_state()
database = self._session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
api.rollback(self._session.name, self._transaction_id, metadata=metadata)
self._rolled_back = True
del self._session._transaction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_update(self, dml, params=None, param_types=None, query_mode=None):
"""Perform an ``ExecuteSql`` API request with DML. :type dml: str :param dml: SQL ... |
params_pb = self._make_params_pb(params, param_types)
database = self._session._database
metadata = _metadata_with_prefix(database.name)
transaction = self._make_txn_selector()
api = database.spanner_api
response = api.execute_sql(
self._session.name,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_update(self, statements):
"""Perform a batch of DML statements via an ``ExecuteBatchDml`` request. :type statements: Sequence[Union[ str, Tuple[str, Di... |
parsed = []
for statement in statements:
if isinstance(statement, str):
parsed.append({"sql": statement})
else:
dml, params, param_types = statement
params_pb = self._make_params_pb(params, param_types)
parsed.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def organization_deidentify_template_path(cls, organization, deidentify_template):
"""Return a fully-qualified organization_deidentify_template string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/deidentifyTemplates/{deidentify_template}",
organization=organization,
deidentify_template=deidentify_template,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_deidentify_template_path(cls, project, deidentify_template):
"""Return a fully-qualified project_deidentify_template string.""" |
return google.api_core.path_template.expand(
"projects/{project}/deidentifyTemplates/{deidentify_template}",
project=project,
deidentify_template=deidentify_template,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def organization_inspect_template_path(cls, organization, inspect_template):
"""Return a fully-qualified organization_inspect_template string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/inspectTemplates/{inspect_template}",
organization=organization,
inspect_template=inspect_template,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_inspect_template_path(cls, project, inspect_template):
"""Return a fully-qualified project_inspect_template string.""" |
return google.api_core.path_template.expand(
"projects/{project}/inspectTemplates/{inspect_template}",
project=project,
inspect_template=inspect_template,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_job_trigger_path(cls, project, job_trigger):
"""Return a fully-qualified project_job_trigger string.""" |
return google.api_core.path_template.expand(
"projects/{project}/jobTriggers/{job_trigger}",
project=project,
job_trigger=job_trigger,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dlp_job_path(cls, project, dlp_job):
"""Return a fully-qualified dlp_job string.""" |
return google.api_core.path_template.expand(
"projects/{project}/dlpJobs/{dlp_job}", project=project, dlp_job=dlp_job
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def organization_stored_info_type_path(cls, organization, stored_info_type):
"""Return a fully-qualified organization_stored_info_type string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/storedInfoTypes/{stored_info_type}",
organization=organization,
stored_info_type=stored_info_type,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_stored_info_type_path(cls, project, stored_info_type):
"""Return a fully-qualified project_stored_info_type string.""" |
return google.api_core.path_template.expand(
"projects/{project}/storedInfoTypes/{stored_info_type}",
project=project,
stored_info_type=stored_info_type,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace_api(self):
""" Helper for trace-related API calls. See https://cloud.google.com/trace/docs/reference/v2/rpc/google.devtools. cloudtrace.v2 """ |
if self._trace_api is None:
self._trace_api = make_trace_api(self)
return self._trace_api |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_error_event(self, error_report):
"""Report error payload. :type error_report: dict :param: error_report: dict payload of the error report formatted ac... |
logger = self.logging_client.logger("errors")
logger.log_struct(error_report) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_routing_header(params):
"""Returns a routing header string for the given request parameters. Args: params (Mapping[str, Any]):
A dictionary containing th... |
if sys.version_info[0] < 3:
# Python 2 does not have the "safe" parameter for urlencode.
return urlencode(params).replace("%2F", "/")
return urlencode(
params,
# Per Google API policy (go/api-url-encoding), / is not encoded.
safe="/",
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StructField(name, field_type):
# pylint: disable=invalid-name """Construct a field description protobuf. :type name: str :param name: the name of the field :... |
return type_pb2.StructType.Field(name=name, type=field_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Struct(fields):
# pylint: disable=invalid-name """Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.F... |
return type_pb2.Type(
code=type_pb2.STRUCT, struct_type=type_pb2.StructType(fields=fields)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def streaming_recognize( self, config, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ):
"""Perform bi... |
return super(SpeechHelpers, self).streaming_recognize(
self._streaming_request_iterable(config, requests),
retry=retry,
timeout=timeout,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _streaming_request_iterable(self, config, requests):
"""A generator that yields the config followed by the requests. Args: config (~.speech_v1.types.Streamin... |
yield self.types.StreamingRecognizeRequest(streaming_config=config)
for request in requests:
yield request |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_data_source_path(cls, project, data_source):
"""Return a fully-qualified project_data_source string.""" |
return google.api_core.path_template.expand(
"projects/{project}/dataSources/{data_source}",
project=project,
data_source=data_source,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_transfer_config_path(cls, project, transfer_config):
"""Return a fully-qualified project_transfer_config string.""" |
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}",
project=project,
transfer_config=transfer_config,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_run_path(cls, project, transfer_config, run):
"""Return a fully-qualified project_run string.""" |
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}/runs/{run}",
project=project,
transfer_config=transfer_config,
run=run,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_transfer_config( self, parent, transfer_config, authorization_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v... |
# Wrap the transport method to add retry and timeout logic.
if "create_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"create_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_transfer_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_transfer_config( self, transfer_config, update_mask, authorization_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.ga... |
# Wrap the transport method to add retry and timeout logic.
if "update_transfer_config" not in self._inner_api_calls:
self._inner_api_calls[
"update_transfer_config"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_transfer_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_threat_list_diff( self, threat_type, constraints, version_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.... |
# Wrap the transport method to add retry and timeout logic.
if "compute_threat_list_diff" not in self._inner_api_calls:
self._inner_api_calls[
"compute_threat_list_diff"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.compute_threa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_uris( self, uri, threat_types, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" T... |
# Wrap the transport method to add retry and timeout logic.
if "search_uris" not in self._inner_api_calls:
self._inner_api_calls[
"search_uris"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_uris,
default_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_hashes( self, hash_prefix=None, threat_types=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, meta... |
# Wrap the transport method to add retry and timeout logic.
if "search_hashes" not in self._inner_api_calls:
self._inner_api_calls[
"search_hashes"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_hashes,
defa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asset_path(cls, organization, asset):
"""Return a fully-qualified asset string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}",
organization=organization,
asset=asset,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asset_security_marks_path(cls, organization, asset):
"""Return a fully-qualified asset_security_marks string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/assets/{asset}/securityMarks",
organization=organization,
asset=asset,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source_path(cls, organization, source):
"""Return a fully-qualified source string.""" |
return google.api_core.path_template.expand(
"organizations/{organization}/sources/{source}",
organization=organization,
source=source,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_source( self, parent, source, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Cr... |
# Wrap the transport method to add retry and timeout logic.
if "create_source" not in self._inner_api_calls:
self._inner_api_calls[
"create_source"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_source,
defa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_finding( self, parent, finding_id, finding, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=No... |
# Wrap the transport method to add retry and timeout logic.
if "create_finding" not in self._inner_api_calls:
self._inner_api_calls[
"create_finding"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_finding,
d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_asset_discovery( self, parent, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Runs... |
# Wrap the transport method to add retry and timeout logic.
if "run_asset_discovery" not in self._inner_api_calls:
self._inner_api_calls[
"run_asset_discovery"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.run_asset_discovery,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_security_marks( self, security_marks, update_mask=None, start_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v... |
# Wrap the transport method to add retry and timeout logic.
if "update_security_marks" not in self._inner_api_calls:
self._inner_api_calls[
"update_security_marks"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_security_mar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_row_range_from_keys( self, start_key=None, end_key=None, start_inclusive=True, end_inclusive=False ):
"""Add row range to row_ranges list from the row ke... |
row_range = RowRange(start_key, end_key, start_inclusive, end_inclusive)
self.row_ranges.append(row_range) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_message_request(self, message):
"""Add row keys and row range to given request message :type message: class:`data_messages_v2_pb2.ReadRowsRequest` :p... |
for each in self.row_keys:
message.rows.row_keys.append(_to_bytes(each))
for each in self.row_ranges:
r_kwrags = each.get_range_kwargs()
message.rows.row_ranges.add(**r_kwrags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_range_kwargs(self):
""" Convert row range object to dict which can be passed to google.bigtable.v2.RowRange add method. """ |
range_kwargs = {}
if self.start_key is not None:
start_key_key = "start_key_open"
if self.start_inclusive:
start_key_key = "start_key_closed"
range_kwargs[start_key_key] = _to_bytes(self.start_key)
if self.end_key is not None:
end... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_error_report( self, message, report_location=None, http_context=None, user=None ):
"""Builds the Error Reporting object to report. This builds the obj... |
payload = {
"serviceContext": {"service": self.service},
"message": "{0}".format(message),
}
if self.version:
payload["serviceContext"]["version"] = self.version
if report_location or http_context or user:
payload["context"] = {}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_error_report( self, message, report_location=None, http_context=None, user=None ):
"""Makes the call to the Error Reporting API. This is the lower-leve... |
error_report = self._build_error_report(
message, report_location, http_context, user
)
self.report_errors_api.report_error_event(error_report) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report(self, message, http_context=None, user=None):
""" Reports a message to Stackdriver Error Reporting https://cloud.google.com/error-reporting/docs/forma... |
stack = traceback.extract_stack()
last_call = stack[-2]
file_path = last_call[0]
line_number = last_call[1]
function_name = last_call[2]
report_location = {
"filePath": file_path,
"lineNumber": line_number,
"functionName": function_nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error Reporting. :type http_context: :c... |
self._send_error_report(
traceback.format_exc(), http_context=http_context, user=user
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current(self):
"""Return the topmost transaction. .. note:: If the topmost element on the stack is not a transaction, returns None. :rtype: :class:`google.cl... |
top = super(Transaction, self).current()
if isinstance(top, Transaction):
return top |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin(self):
"""Begins a transaction. This method is called automatically when entering a with statement, however it can be called explicitly if you don't wa... |
super(Transaction, self).begin()
try:
response_pb = self._client._datastore_api.begin_transaction(self.project)
self._id = response_pb.transaction
except: # noqa: E722 do not use bare except, specify exception instead
self._status = self._ABORTED
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(self):
"""Rolls back the current transaction. This method has necessary side-effects: - Sets the current transaction's ID to None. """ |
try:
# No need to use the response it contains nothing.
self._client._datastore_api.rollback(self.project, self._id)
finally:
super(Transaction, self).rollback()
# Clear our own ID in case this gets accidentally reused.
self._id = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, entity):
"""Adds an entity to be committed. Ensures the transaction is not marked readonly. Please see documentation at :meth:`~google.cloud.datast... |
if self._options.HasField("read_only"):
raise RuntimeError("Transaction is read only")
else:
super(Transaction, self).put(entity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_findings( self, parent, filter_=None, order_by=None, read_time=None, field_mask=None, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, time... |
# Wrap the transport method to add retry and timeout logic.
if "list_findings" not in self._inner_api_calls:
self._inner_api_calls[
"list_findings"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_findings,
defa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dict_mapping_to_pb(mapping, proto_type):
""" Convert a dict to protobuf. Args: mapping (dict):
A dict that needs to be converted to protobuf. proto_type (s... |
converted_pb = getattr(trace_pb2, proto_type)()
ParseDict(mapping, converted_pb)
return converted_pb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _span_attrs_to_pb(span_attr, proto_type):
""" Convert a span attribute dict to protobuf, including Links, Attributes, TimeEvents. Args: span_attr (dict):
A ... |
attr_pb = getattr(trace_pb2.Span, proto_type)()
ParseDict(span_attr, attr_pb)
return attr_pb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_pb(cls, cluster_pb, instance):
"""Creates an cluster instance from a protobuf. For example: .. literalinclude:: snippets.py :start-after: [START bigtabl... |
match_cluster_name = _CLUSTER_NAME_RE.match(cluster_pb.name)
if match_cluster_name is None:
raise ValueError(
"Cluster protobuf name was not in the " "expected format.",
cluster_pb.name,
)
if match_cluster_name.group("instance") != instanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""Cluster name used in requests. .. note:: This property will not change if ``_instance`` and ``cluster_id`` do not, but the return value is not... |
return self._instance._client.instance_admin_client.cluster_path(
self._instance._client.project, self._instance.instance_id, self.cluster_id
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self):
"""Reload the metadata for this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_cluster] :end-before... |
cluster_pb = self._instance._client.instance_admin_client.get_cluster(self.name)
# NOTE: _update_from_pb does not check that the project and
# cluster ID on the response match the request.
self._update_from_pb(cluster_pb) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
"""Check whether the cluster already exists. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_check_cluster_exists] :... |
client = self._instance._client
try:
client.instance_admin_client.get_cluster(name=self.name)
return True
# NOTE: There could be other exceptions that are returned to the user.
except NotFound:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Create this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-before: [END bigtable_c... |
client = self._instance._client
cluster_pb = self._to_pb()
return client.instance_admin_client.create_cluster(
self._instance.name, self.cluster_id, cluster_pb
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_update_cluster] :end-before: [END bigtable_u... |
client = self._instance._client
# We are passing `None` for second argument location.
# Location is set only at the time of creation of a cluster
# and can not be changed after cluster has been created.
return client.instance_admin_client.update_cluster(
self.name, s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete this cluster. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_delete_cluster] :end-before: [END bigtable_d... |
client = self._instance._client
client.instance_admin_client.delete_cluster(self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_pb(self):
""" Create cluster proto buff message for API calls """ |
client = self._instance._client
location = client.instance_admin_client.location_path(
client.project, self.location_id
)
cluster_pb = instance_pb2.Cluster(
location=location,
serve_nodes=self.serve_nodes,
default_storage_type=self.default... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_pb(cls, cell_pb):
"""Create a new cell from a Cell protobuf. :type cell_pb: :class:`._generated.data_pb2.Cell` :param cell_pb: The protobuf to convert. ... |
if cell_pb.labels:
return cls(cell_pb.value, cell_pb.timestamp_micros, labels=cell_pb.labels)
else:
return cls(cell_pb.value, cell_pb.timestamp_micros) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
"""Convert the cells to a dictionary. This is intended to be used with HappyBase, so the column family and column qualiers are combined (with ... |
result = {}
for column_family_id, columns in six.iteritems(self._cells):
for column_qual, cells in six.iteritems(columns):
key = _to_bytes(column_family_id) + b":" + _to_bytes(column_qual)
result[key] = cells
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cell_value(self, column_family_id, column, index=0):
"""Get a single cell value stored on this instance. For example: .. literalinclude:: snippets_table.py :... |
cells = self.find_cells(column_family_id, column)
try:
cell = cells[index]
except (TypeError, IndexError):
num_cells = len(cells)
msg = _MISSING_INDEX.format(index, column, column_family_id, num_cells)
raise IndexError(msg)
return cell.v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more. .. warning:: This method will be removed in future releases. Pl... |
for row in self:
self.rows[row.row_key] = row |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_updated_request(self):
""" Updates the given message request as per last scanned key """ |
r_kwargs = {
"table_name": self.message.table_name,
"filter": self.message.filter,
}
if self.message.rows_limit != 0:
r_kwargs["rows_limit"] = max(
1, self.message.rows_limit - self.rows_read_so_far
)
# if neither RowSet.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_traces( self, project_id, traces, 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 "patch_traces" not in self._inner_api_calls:
self._inner_api_calls[
"patch_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.patch_traces,
default... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_traces( self, project_id, view=None, page_size=None, start_time=None, end_time=None, filter_=None, order_by=None, retry=google.api_core.gapic_v1.method.D... |
# Wrap the transport method to add retry and timeout logic.
if "list_traces" not in self._inner_api_calls:
self._inner_api_calls[
"list_traces"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_traces,
default_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Gets the deta... |
# Wrap the transport method to add retry and timeout logic.
if "get_instance" not in self._inner_api_calls:
self._inner_api_calls[
"get_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_instance,
default... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_instance( self, update_mask, instance, 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 "update_instance" not in self._inner_api_calls:
self._inner_api_calls[
"update_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_instance,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Deletes a ... |
# Wrap the transport method to add retry and timeout logic.
if "delete_instance" not in self._inner_api_calls:
self._inner_api_calls[
"delete_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.delete_instance,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def region_path(cls, project, region):
"""Return a fully-qualified region string.""" |
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}", project=project, region=region
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def workflow_template_path(cls, project, region, workflow_template):
"""Return a fully-qualified workflow_template string.""" |
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}/workflowTemplates/{workflow_template}",
project=project,
region=region,
workflow_template=workflow_template,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_workflow_template( self, parent, template, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=Non... |
# Wrap the transport method to add retry and timeout logic.
if "create_workflow_template" not in self._inner_api_calls:
self._inner_api_calls[
"create_workflow_template"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_workfl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_workflow_template( self, name, version=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None... |
# Wrap the transport method to add retry and timeout logic.
if "get_workflow_template" not in self._inner_api_calls:
self._inner_api_calls[
"get_workflow_template"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_workflow_templa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_schema_resource(info):
"""Parse a resource fragment into a schema field. Args: info: (Mapping[str->dict]):
should contain a "fields" key to be parsed... |
if "fields" not in info:
return ()
schema = []
for r_field in info["fields"]:
name = r_field["name"]
field_type = r_field["type"]
mode = r_field.get("mode", "NULLABLE")
description = r_field.get("description")
sub_fields = _parse_schema_resource(r_field)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_api_repr(cls, api_repr):
"""Return a ``SchemaField`` object deserialized from a dictionary. Args: api_repr (Mapping[str, str]):
The serialized represen... |
# Handle optional properties with default values
mode = api_repr.get("mode", "NULLABLE")
description = api_repr.get("description")
fields = api_repr.get("fields", ())
return cls(
field_type=api_repr["type"].upper(),
fields=[cls.from_api_repr(f) for f in f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_api_repr(self):
"""Return a dictionary representing this schema field. Returns: dict: A dictionary representing the SchemaField in a serialized form. """ |
# Put together the basic representation. See http://bit.ly/2hOAT5u.
answer = {
"mode": self.mode.upper(),
"name": self.name,
"type": self.field_type.upper(),
"description": self.description,
}
# If this is a RECORD type, then sub-fields a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_options():
"""Parses options.""" |
parser = argparse.ArgumentParser()
parser.add_argument('command', help='The YCSB command.')
parser.add_argument('benchmark', help='The YCSB benchmark.')
parser.add_argument('-P', '--workload', action='store', dest='workload',
default='', help='The path to a YCSB workload file.')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_keys(database, parameters):
"""Loads keys from database.""" |
keys = []
with database.snapshot() as snapshot:
results = snapshot.execute_sql(
'SELECT u.id FROM %s u' % parameters['table'])
for row in results:
keys.append(row[0])
return keys |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(database, table, key):
"""Does a single read operation.""" |
with database.snapshot() as snapshot:
result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id="%s"' %
(table, key))
for row in result:
key = row[0]
for i in range(NUM_FIELD):
field = row[i + 1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(database, table, key):
"""Does a single update operation.""" |
field = random.randrange(10)
value = ''.join(random.choice(string.printable) for i in range(100))
with database.batch() as batch:
batch.update(table=table, columns=('id', 'field%d' % field),
values=[(key, value)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_operation(database, keys, table, operation, latencies_ms):
"""Does a single operation and records latency.""" |
key = random.choice(keys)
start = timeit.default_timer()
if operation == 'read':
read(database, table, key)
elif operation == 'update':
update(database, table, key)
else:
raise ValueError('Unknown operation: %s' % operation)
end = timeit.default_timer()
latencies_ms... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_metrics(latencies_ms, duration_ms, num_bucket):
"""Aggregates metrics.""" |
overall_op_count = 0
op_counts = {operation : len(latency) for operation,
latency in latencies_ms.iteritems()}
overall_op_count = sum([op_count for op_count in op_counts.itervalues()])
print('[OVERALL], RunTime(ms), %f' % duration_ms)
print('[OVERALL], Throughput(ops/sec), %f' % (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_workload(database, keys, parameters):
"""Runs workload against the database.""" |
total_weight = 0.0
weights = []
operations = []
latencies_ms = {}
for operation in OPERATIONS:
weight = float(parameters[operation])
if weight <= 0.0:
continue
total_weight += weight
op_code = operation.split('proportion')[0]
operations.append(op_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.