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 list_resource_record_sets(self, max_results=None, page_token=None, client=None): """List resource record sets for this zone. See https://cloud.google.com/dns...
client = self._require_client(client) path = "/projects/%s/managedZones/%s/rrsets" % (self.project, self.name) iterator = page_iterator.HTTPIterator( client=client, api_request=client._connection.api_request, path=path, item_to_value=_item_to_reso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_image(self, request, retry=None, timeout=None): """Run image detection and annotation for an image. Example: Args: request (:class:`~.vision_v1.type...
# If the image is a file handler, set the content. image = protobuf.get(request, "image") if hasattr(image, "read"): img_bytes = image.read() protobuf.set(request, "image", {}) protobuf.set(request, "image.content", img_bytes) image = protobuf.get...
<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_job( self, parent, job, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates ...
# Wrap the transport method to add retry and timeout logic. if "create_job" not in self._inner_api_calls: self._inner_api_calls[ "create_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_job, default_retry...
<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_job( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves the spec...
# Wrap the transport method to add retry and timeout logic. if "get_job" not in self._inner_api_calls: self._inner_api_calls[ "get_job" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_job, default_retry=self._me...
<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_delete_jobs( self, parent, filter_, 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 "batch_delete_jobs" not in self._inner_api_calls: self._inner_api_calls[ "batch_delete_jobs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_delete_jobs, ...
<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_jobs( self, parent, request_metadata, search_mode=None, job_query=None, enable_broadening=None, require_precise_result_size=None, histogram_queries=Non...
# Wrap the transport method to add retry and timeout logic. if "search_jobs" not in self._inner_api_calls: self._inner_api_calls[ "search_jobs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.search_jobs, 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 _compute_type_url(klass, prefix=_GOOGLE_APIS_PREFIX): """Compute a type URL for a klass. :type klass: type :param klass: class to be used as a factory for th...
name = klass.DESCRIPTOR.full_name return "%s/%s" % (prefix, 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 register_type(klass, type_url=None): """Register a klass as the factory for a given type URL. :type klass: :class:`type` :param klass: class to be used as a ...
if type_url is None: type_url = _compute_type_url(klass) if type_url in _TYPE_URL_MAP: if _TYPE_URL_MAP[type_url] is not klass: raise ValueError("Conflict: %s" % (_TYPE_URL_MAP[type_url],)) _TYPE_URL_MAP[type_url] = klass
<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_any(any_pb): """Convert an ``Any`` protobuf into the actual class. Uses the type URL to do the conversion. .. note:: This assumes that the type URL is ...
klass = _TYPE_URL_MAP[any_pb.type_url] return klass.FromString(any_pb.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 _get_operation_rpc(self): """Polls the status of the current operation. Uses gRPC request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operat...
request_pb = operations_pb2.GetOperationRequest(name=self.name) return self.client._operations_stub.GetOperation(request_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 _get_operation_http(self): """Checks the status of the current operation. Uses HTTP request to check. :rtype: :class:`~google.longrunning.operations_pb2.Oper...
path = "operations/%s" % (self.name,) api_response = self.client._connection.api_request(method="GET", path=path) return json_format.ParseDict(api_response, operations_pb2.Operation())
<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_state(self, operation_pb): """Update the state of the current object based on operation. :type operation_pb: :class:`~google.longrunning.operations_p...
if operation_pb.done: self._complete = True if operation_pb.HasField("metadata"): self.metadata = _from_any(operation_pb.metadata) result_type = operation_pb.WhichOneof("result") if result_type == "error": self.error = operation_pb.error eli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll(self): """Check if the operation has finished. :rtype: bool :returns: A boolean indicating if the current operation has completed. :raises ValueError: i...
if self.complete: raise ValueError("The operation has completed.") operation_pb = self._get_operation() self._update_state(operation_pb) return self.complete
<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_rmw_row_response(row_response): """Parses the response to a ``ReadModifyWriteRow`` request. :type row_response: :class:`.data_v2_pb2.Row` :param row_r...
result = {} for column_family in row_response.row.families: column_family_id, curr_family = _parse_family_pb(column_family) result[column_family_id] = curr_family 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 _parse_family_pb(family_pb): """Parses a Family protobuf into a dictionary. :type family_pb: :class:`._generated.data_pb2.Family` :param family_pb: A protobu...
result = {} for column in family_pb.columns: result[column.qualifier] = cells = [] for cell in column.cells: val_pair = (cell.value, _datetime_from_microseconds(cell.timestamp_micros)) cells.append(val_pair) return family_pb.name, 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 get_mutations_size(self): """ Gets the total mutations size for current row For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_...
mutation_size = 0 for mutation in self._get_mutations(): mutation_size += mutation.ByteSize() return mutation_size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_cell(self, column_family_id, column, value, timestamp=None): """Sets a value in this row. The cell is determined by the ``row_key`` of this :class:`Direc...
self._set_cell(column_family_id, column, value, timestamp=timestamp, state=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 delete_cell(self, column_family_id, column, time_range=None): """Deletes cell in this row. .. note:: This method adds a mutation to the accumulated mutations...
self._delete_cells( column_family_id, [column], time_range=time_range, state=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 delete_cells(self, column_family_id, columns, time_range=None): """Deletes cells in this row. .. note:: This method adds a mutation to the accumulated mutati...
self._delete_cells(column_family_id, columns, time_range=time_range, state=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 commit(self): """Makes a ``CheckAndMutateRow`` API request. If no mutations have been created in the row, no request is made. The mutations will be applied c...
true_mutations = self._get_mutations(state=True) false_mutations = self._get_mutations(state=False) num_true_mutations = len(true_mutations) num_false_mutations = len(false_mutations) if num_true_mutations == 0 and num_false_mutations == 0: return if num_true...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_cell_value(self, column_family_id, column, value): """Appends a value to an existing cell. .. note:: This method adds a read-modify rule protobuf to t...
column = _to_bytes(column) value = _to_bytes(value) rule_pb = data_v2_pb2.ReadModifyWriteRule( family_name=column_family_id, column_qualifier=column, append_value=value ) self._rule_pb_list.append(rule_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 increment_cell_value(self, column_family_id, column, int_value): """Increments a value in an existing cell. Assumes the value in the cell is stored as a 64 b...
column = _to_bytes(column) rule_pb = data_v2_pb2.ReadModifyWriteRule( family_name=column_family_id, column_qualifier=column, increment_amount=int_value, ) self._rule_pb_list.append(rule_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 commit(self): """Makes a ``ReadModifyWriteRow`` API request. This commits modifications made by :meth:`append_cell_value` and :meth:`increment_cell_value`. I...
num_mutations = len(self._rule_pb_list) if num_mutations == 0: return {} if num_mutations > MAX_MUTATIONS: raise ValueError( "%d total append mutations exceed the maximum " "allowable %d." % (num_mutations, MAX_MUTATIONS) ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _retry_from_retry_config(retry_params, retry_codes): """Creates a Retry object given a gapic retry configuration. Args: retry_params (dict): The retry param...
exception_classes = [ _exception_class_for_grpc_status_name(code) for code in retry_codes ] return retry.Retry( retry.if_exception_type(*exception_classes), initial=(retry_params["initial_retry_delay_millis"] / _MILLIS_PER_SECOND), maximum=(retry_params["max_retry_delay_mill...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _timeout_from_retry_config(retry_params): """Creates a ExponentialTimeout object given a gapic retry configuration. Args: retry_params (dict): The retry par...
return timeout.ExponentialTimeout( initial=(retry_params["initial_rpc_timeout_millis"] / _MILLIS_PER_SECOND), maximum=(retry_params["max_rpc_timeout_millis"] / _MILLIS_PER_SECOND), multiplier=retry_params["rpc_timeout_multiplier"], deadline=(retry_params["total_timeout_millis"] / _M...
<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_method_configs(interface_config): """Creates default retry and timeout objects for each method in a gapic interface config. Args: interface_config (Map...
# Grab all the retry codes retry_codes_map = { name: retry_codes for name, retry_codes in six.iteritems(interface_config.get("retry_codes", {})) } # Grab all of the retry params retry_params_map = { name: retry_params for name, retry_params in six.iteritems( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def done(self): """Return True the future is done, False otherwise. This still returns True in failure cases; checking :meth:`result` or :meth:`exception` is the...
return self._exception != self._SENTINEL or self._result != self._SENTINEL
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exception(self, timeout=None): """Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns...
# Wait until the future is done. if not self._completed.wait(timeout=timeout): raise exceptions.TimeoutError("Timed out waiting for result.") # If the batch completed successfully, this should return None. if self._result != self._SENTINEL: return 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 add_done_callback(self, fn): """Attach the provided callable to the future. The provided function is called, with this future as its only argument, when the ...
if self.done(): return fn(self) self._callbacks.append(fn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_result(self, result): """Set the result of the future to the provided result. Args: result (Any): The result """
# Sanity check: A future can only complete once. if self.done(): raise RuntimeError("set_result can only be called once.") # Set the result and trigger the future. self._result = result self._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 set_exception(self, exception): """Set the result of the future to the given exception. Args: exception (:exc:`Exception`): The exception raised. """
# Sanity check: A future can only complete once. if self.done(): raise RuntimeError("set_exception can only be called once.") # Set the exception and trigger the future. self._exception = exception self._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 _trigger(self): """Trigger all callbacks registered to this Future. This method is called internally by the batch once the batch completes. Args: message_id ...
self._completed.set() for callback in self._callbacks: callback(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 create_read_session( self, table_reference, parent, table_modifiers=None, requested_streams=None, read_options=None, format_=None, retry=google.api_core.gapic...
# Wrap the transport method to add retry and timeout logic. if "create_read_session" not in self._inner_api_calls: self._inner_api_calls[ "create_read_session" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_read_session, ...
<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_create_read_session_streams( self, session, requested_streams, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DE...
# Wrap the transport method to add retry and timeout logic. if "batch_create_read_session_streams" not in self._inner_api_calls: self._inner_api_calls[ "batch_create_read_session_streams" ] = google.api_core.gapic_v1.method.wrap_method( self.trans...
<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): """Build an API representation of this object. Returns: Dict[str, Any]: A dictionary in the format used by the BigQuery API. """
config = copy.deepcopy(self._properties) if self.options is not None: r = self.options.to_api_repr() if r != {}: config[self.options._RESOURCE_NAME] = r return 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 lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """
session.install('flake8', *LOCAL_DEPS) session.install('-e', '.') session.run( 'flake8', os.path.join('google', 'cloud', 'bigquery_storage_v1beta1')) session.run('flake8', 'tests')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _enum_from_op_string(op_string): """Convert a string representation of a binary operator to an enum. These enums come from the protobuf message definition ``...
try: return _COMPARISON_OPERATORS[op_string] except KeyError: choices = ", ".join(sorted(_COMPARISON_OPERATORS.keys())) msg = _BAD_OP_STRING.format(op_string, choices) 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 _enum_from_direction(direction): """Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one o...
if isinstance(direction, int): return direction if direction == Query.ASCENDING: return enums.StructuredQuery.Direction.ASCENDING elif direction == Query.DESCENDING: return enums.StructuredQuery.Direction.DESCENDING else: msg = _BAD_DIR_STRING.format(direction, Query.AS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_pb(field_or_unary): """Convert a specific protobuf filter to the generic filter type. Args: field_or_unary (Union[google.cloud.proto.firestore.v1beta...
if isinstance(field_or_unary, query_pb2.StructuredQuery.FieldFilter): return query_pb2.StructuredQuery.Filter(field_filter=field_or_unary) elif isinstance(field_or_unary, query_pb2.StructuredQuery.UnaryFilter): return query_pb2.StructuredQuery.Filter(unary_filter=field_or_unary) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cursor_pb(cursor_pair): """Convert a cursor pair to a protobuf. If ``cursor_pair`` is :data:`None`, just returns :data:`None`. Args: cursor_pair (Optional[T...
if cursor_pair is not None: data, before = cursor_pair value_pbs = [_helpers.encode_value(value) for value in data] return query_pb2.Cursor(values=value_pbs, before=before)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query_response_to_snapshot(response_pb, collection, expected_prefix): """Parse a query response protobuf to a document snapshot. Args: response_pb (google.c...
if not response_pb.HasField("document"): return None document_id = _helpers.get_doc_id(response_pb.document, expected_prefix) reference = collection.document(document_id) data = _helpers.decode_dict(response_pb.document.fields, collection._client) snapshot = document.DocumentSnapshot( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, field_paths): """Project documents matching query to a limited set of fields. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more ...
field_paths = list(field_paths) for field_path in field_paths: field_path_module.split_field_path(field_path) # raises new_projection = query_pb2.StructuredQuery.Projection( fields=[ query_pb2.StructuredQuery.FieldReference(field_path=field_path) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where(self, field_path, op_string, value): """Filter the query on a field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on *...
field_path_module.split_field_path(field_path) # raises if value is None: if op_string != _EQ_OP: raise ValueError(_BAD_OP_NAN_NULL) filter_pb = query_pb2.StructuredQuery.UnaryFilter( field=query_pb2.StructuredQuery.FieldReference(field_path=fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_by(self, field_path, direction=ASCENDING): """Modify the query to add an order clause on a specific field. See :meth:`~.firestore_v1beta1.client.Client...
field_path_module.split_field_path(field_path) # raises order_pb = self._make_order(field_path, direction) new_orders = self._orders + (order_pb,) return self.__class__( self._parent, projection=self._projection, field_filters=self._field_filters, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limit(self, count): """Limit a query to return a fixed number of results. If the current query already has a limit set, this will overwrite it. Args: count (...
return self.__class__( self._parent, projection=self._projection, field_filters=self._field_filters, orders=self._orders, limit=count, offset=self._offset, start_at=self._start_at, end_at=self._end_at, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def offset(self, num_to_skip): """Skip to an offset in a query. If the current query already has specified an offset, this will overwrite it. Args: num_to_skip (...
return self.__class__( self._parent, projection=self._projection, field_filters=self._field_filters, orders=self._orders, limit=self._limit, offset=num_to_skip, start_at=self._start_at, end_at=self._end_at, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cursor_helper(self, document_fields, before, start): """Set values to be used for a ``start_at`` or ``end_at`` cursor. The values will later be used in a qu...
if isinstance(document_fields, tuple): document_fields = list(document_fields) elif isinstance(document_fields, document.DocumentSnapshot): if document_fields.reference._path[:-1] != self._parent._path: raise ValueError( "Cannot use snapshot 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 start_at(self, document_fields): """Start query results at a particular document value. The result set will **include** the document specified by ``document_...
return self._cursor_helper(document_fields, before=True, start=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_after(self, document_fields): """Start query results after a particular document value. The result set will **exclude** the document specified by ``doc...
return self._cursor_helper(document_fields, before=False, start=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_before(self, document_fields): """End query results before a particular document value. The result set will **exclude** the document specified by ``docum...
return self._cursor_helper(document_fields, before=True, start=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 end_at(self, document_fields): """End query results at a particular document value. The result set will **include** the document specified by ``document_fiel...
return self._cursor_helper(document_fields, before=False, start=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 _filters_pb(self): """Convert all the filters into a single generic Filter protobuf. This may be a lone field filter or unary filter, may be a composite filt...
num_filters = len(self._field_filters) if num_filters == 0: return None elif num_filters == 1: return _filter_pb(self._field_filters[0]) else: composite_filter = query_pb2.StructuredQuery.CompositeFilter( op=enums.StructuredQuery.Compo...
<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_protobuf(self): """Convert the current query into the equivalent protobuf. Returns: google.cloud.firestore_v1beta1.types.StructuredQuery: The query proto...
projection = self._normalize_projection(self._projection) orders = self._normalize_orders() start_at = self._normalize_cursor(self._start_at, orders) end_at = self._normalize_cursor(self._end_at, orders) query_kwargs = { "select": projection, "from": [ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stream(self, transaction=None): """Read the documents in the collection that match this query. This sends a ``RunQuery`` RPC and then returns an iterator whi...
parent_path, expected_prefix = self._parent._parent_info() response_iterator = self._client._firestore_api.run_query( parent_path, self._to_protobuf(), transaction=_helpers.get_transaction_id(transaction), metadata=self._client._rpc_metadata, ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_snapshot(self, callback): """Monitor the documents in this collection that match this query. This starts a watch on this query using a background thread. ...
return Watch.for_query( self, callback, document.DocumentSnapshot, document.DocumentReference )
<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_model_reference(self, model_id): """Constructs a ModelReference. Args: model_id (str): the ID of the model. Returns: google.cloud.bigquery.model.ModelR...
return ModelReference.from_api_repr( {"projectId": self.project, "datasetId": self.dataset_id, "modelId": model_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 to_api_repr(self): """Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource ...
resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] = self.role return resource
<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_string(cls, dataset_id, default_project=None): """Construct a dataset reference from dataset ID string. Args: dataset_id (str): A dataset ID in standar...
output_dataset_id = dataset_id output_project_id = default_project parts = dataset_id.split(".") if len(parts) == 1 and not default_project: raise ValueError( "When default_project is not set, dataset_id must be a " "fully-qualified dataset I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _item_to_blob(iterator, item): """Convert a JSON blob to the native object. .. note:: This assumes that the ``bucket`` attribute has been added to the iterat...
name = item.get("name") blob = Blob(name, bucket=iterator.bucket) blob._set_properties(item) return blob
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_properties(self, value): """Set the properties for the current object. :type value: dict or :class:`google.cloud.storage.batch._FutureDict` :param value...
self._label_removals.clear() return super(Bucket, self)._set_properties(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 blob( self, blob_name, chunk_size=None, encryption_key=None, kms_key_name=None, generation=None, ): """Factory constructor for blob object. .. note:: This wi...
return Blob( name=blob_name, bucket=self, chunk_size=chunk_size, encryption_key=encryption_key, kms_key_name=kms_key_name, generation=generation, )
<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, client=None, project=None, location=None): """Creates current bucket. If the bucket already exists, will raise :class:`google.cloud.exceptions.C...
if self.user_project is not None: raise ValueError("Cannot create bucket with 'user_project' set.") client = self._require_client(client) if project is None: project = client.project if project is None: raise ValueError("Client project not set: pa...
<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_blob( self, blob_name, client=None, encryption_key=None, generation=None, **kwargs ): """Get a blob object by name. This will return None if the blob doe...
blob = Blob( bucket=self, name=blob_name, encryption_key=encryption_key, generation=generation, **kwargs ) try: # NOTE: This will not fail immediately in a batch. However, when # Batch.finish() is called, ...
<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_blobs( self, max_results=None, page_token=None, prefix=None, delimiter=None, versions=None, projection="noAcl", fields=None, client=None, ): """Return a...
extra_params = {"projection": projection} if prefix is not None: extra_params["prefix"] = prefix if delimiter is not None: extra_params["delimiter"] = delimiter if versions is not None: extra_params["versions"] = versions if fields is not ...
<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, force=False, client=None): """Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed,...
client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project if force: blobs = list( self.list_blobs( max_results=self._MAX_OBJECTS_FOR_ITERATION + ...
<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_blob(self, blob_name, client=None, generation=None): """Deletes a blob from the current bucket. If the blob isn't found (backend 404), raises a :class...
client = self._require_client(client) blob = Blob(blob_name, bucket=self, generation=generation) # We intentionally pass `_target_object=None` since a DELETE # request has no response value (whether in a standard request or # in a batch request). client._connection.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 delete_blobs(self, blobs, on_error=None, client=None): """Deletes a list of blobs from the current bucket. Uses :meth:`delete_blob` to delete each individual...
for blob in blobs: try: blob_name = blob if not isinstance(blob_name, six.string_types): blob_name = blob.name self.delete_blob(blob_name, client=client) except NotFound: if on_error is not 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 copy_blob( self, blob, destination_bucket, new_name=None, client=None, preserve_acl=True, source_generation=None, ): """Copy the given blob to the given buck...
client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project if source_generation is not None: query_params["sourceGeneration"] = source_generation if new_name is 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 rename_blob(self, blob, new_name, client=None): """Rename the given blob using copy and delete operations. If :attr:`user_project` is set, bills the API requ...
same_name = blob.name == new_name new_blob = self.copy_blob(blob, self, new_name, client=client) if not same_name: blob.delete(client=client) return new_blob
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_kms_key_name(self, value): """Set default KMS encryption key for objects in the bucket. :type value: str or None :param value: new KMS key name (None...
encryption_config = self._properties.get("encryption", {}) encryption_config["defaultKmsKeyName"] = value self._patch_property("encryption", encryption_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 labels(self): """Retrieve or set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels .. note:: The getter fo...
labels = self._properties.get("labels") if labels is None: return {} return copy.deepcopy(labels)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def labels(self, mapping): """Set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels :type mapping: :class:`dic...
# If any labels have been expressly removed, we need to track this # so that a future .patch() call can do the correct thing. existing = set([k for k in self.labels.keys()]) incoming = set([k for k in mapping.keys()]) self._label_removals = self._label_removals.union(existing.di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iam_configuration(self): """Retrieve IAM configuration for this bucket. :rtype: :class:`IAMConfiguration` :returns: an instance for managing the bucket's IAM...
info = self._properties.get("iamConfiguration", {}) return IAMConfiguration.from_api_repr(info, 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 lifecycle_rules(self): """Retrieve or set lifecycle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.g...
info = self._properties.get("lifecycle", {}) for rule in info.get("rule", ()): action_type = rule["action"]["type"] if action_type == "Delete": yield LifecycleRuleDelete.from_api_repr(rule) elif action_type == "SetStorageClass": yield ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lifecycle_rules(self, rules): """Set lifestyle rules configured for this bucket. See https://cloud.google.com/storage/docs/lifecycle and https://cloud.google...
rules = [dict(rule) for rule in rules] # Convert helpers if needed self._patch_property("lifecycle", {"rule": rules})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_logging(self, bucket_name, object_prefix=""): """Enable access logging for this bucket. See https://cloud.google.com/storage/docs/access-logs :type bu...
info = {"logBucket": bucket_name, "logObjectPrefix": object_prefix} self._patch_property("logging", info)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retention_policy_effective_time(self): """Retrieve the effective time of the bucket's retention policy. :rtype: datetime.datetime or ``NoneType`` :returns: p...
policy = self._properties.get("retentionPolicy") if policy is not None: timestamp = policy.get("effectiveTime") if timestamp is not None: return _rfc3339_to_datetime(timestamp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retention_period(self): """Retrieve or set the retention period for items in the bucket. :rtype: int or ``NoneType`` :returns: number of seconds to retain it...
policy = self._properties.get("retentionPolicy") if policy is not None: period = policy.get("retentionPeriod") if period is not None: return int(period)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retention_period(self, value): """Set the retention period for items in the bucket. :type value: int :param value: number of seconds to retain items after up...
policy = self._properties.setdefault("retentionPolicy", {}) if value is not None: policy["retentionPeriod"] = str(value) else: policy = None self._patch_property("retentionPolicy", policy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def storage_class(self, value): """Set the storage class for the bucket. See https://cloud.google.com/storage/docs/storage-classes :type value: str :param value:...
if value not in self._STORAGE_CLASSES: raise ValueError("Invalid storage class: %s" % (value,)) self._patch_property("storageClass", 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 configure_website(self, main_page_suffix=None, not_found_page=None): """Configure website-related properties. See https://cloud.google.com/storage/docs/hosti...
data = {"mainPageSuffix": main_page_suffix, "notFoundPage": not_found_page} self._patch_property("website", 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 get_iam_policy(self, client=None): """Retrieve the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy If :...
client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project info = client._connection.api_request( method="GET", path="%s/iam" % (self.path,), query_params=que...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_iam_policy(self, policy, client=None): """Update the IAM policy for the bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolic...
client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project resource = policy.to_api_repr() resource["resourceId"] = self.path info = client._connection.api_request( m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_private(self, recursive=False, future=False, client=None): """Update bucket's ACL, revoking read access for anonymous users. :type recursive: bool :para...
self.acl.all().revoke_read() self.acl.save(client=client) if future: doa = self.default_object_acl if not doa.loaded: doa.reload(client=client) doa.all().revoke_read() doa.save(client=client) if recursive: blo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_upload_policy(self, conditions, expiration=None, client=None): """Create a signed upload policy for uploading objects. This method generates and sig...
client = self._require_client(client) credentials = client._base_connection.credentials _signing.ensure_signed_credentials(credentials) if expiration is None: expiration = _NOW() + datetime.timedelta(hours=1) conditions = conditions + [{"bucket": 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 lock_retention_policy(self, client=None): """Lock the bucket's retention policy. :raises ValueError: if the bucket has no metageneration (i.e., new or never ...
if "metageneration" not in self._properties: raise ValueError("Bucket has no retention policy assigned: try 'reload'?") policy = self._properties.get("retentionPolicy") if policy is None: raise ValueError("Bucket has no retention policy assigned: try 'reload'?") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_signed_url( self, expiration=None, api_access_endpoint=_API_ACCESS_ENDPOINT, method="GET", headers=None, query_parameters=None, client=None, credenti...
if version is None: version = "v2" elif version not in ("v2", "v4"): raise ValueError("'version' must be either 'v2' or 'v4'") resource = "/{bucket_name}".format(bucket_name=self.name) if credentials is None: client = self._require_client(client) ...
<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_microseconds(value): """Convert a datetime to microseconds since the unix epoch. Args: value (datetime.datetime): The datetime to covert. Returns: int: M...
if not value.tzinfo: value = value.replace(tzinfo=pytz.utc) # Regardless of what timezone is on the value, convert it to UTC. value = value.astimezone(pytz.utc) # Convert the datetime to a microsecond timestamp. return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond
<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_rfc3339(value): """Convert a microsecond-precision timestamp to datetime. Args: value (str): The RFC3339 string to convert. Returns: datetime.datetime:...
return datetime.datetime.strptime(value, _RFC3339_MICROS).replace(tzinfo=pytz.utc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rfc3339(self): """Return an RFC 3339-compliant timestamp. Returns: (str): Timestamp string according to RFC 3339 spec. """
if self._nanosecond == 0: return to_rfc3339(self) nanos = str(self._nanosecond).rjust(9, '0').rstrip("0") return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timestamp_pb(self): """Return a timestamp message. Returns: (:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message """
inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC) delta = inst - _UTC_EPOCH seconds = int(delta.total_seconds()) nanos = self._nanosecond or self.microsecond * 1000 return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
<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_cluster( self, project_id, region, cluster, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEF...
# Wrap the transport method to add retry and timeout logic. if "create_cluster" not in self._inner_api_calls: self._inner_api_calls[ "create_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_cluster, 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 delete_cluster( self, project_id, region, cluster_name, cluster_uuid=None, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_...
# Wrap the transport method to add retry and timeout logic. if "delete_cluster" not in self._inner_api_calls: self._inner_api_calls[ "delete_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_cluster, 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 get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=...
# Wrap the transport method to add retry and timeout logic. if "get_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, 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 diagnose_cluster( self, project_id, region, cluster_name, 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 "diagnose_cluster" not in self._inner_api_calls: self._inner_api_calls[ "diagnose_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.diagnose_cluster, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor(self): """Commit this batch after sufficient time has elapsed. This simply sleeps for ``self._settings.max_latency`` seconds, and then calls commit u...
# NOTE: This blocks; it is up to the calling code to call it # in a separate thread. # Sleep for however long we should be waiting. time.sleep(self._settings.max_latency) _LOGGER.debug("Monitor is waking up") return self._commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, message): """Publish a single message. Add the given message to this object; this will cause it to be published once the batch either has enoug...
# Coerce the type, just in case. if not isinstance(message, types.PubsubMessage): message = types.PubsubMessage(**message) future = None with self._state_lock: if not self.will_accept(message): return future new_size = self._size + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path(self): """URL path for change set APIs. :rtype: str :returns: the path based on project, zone, and change set names. """
return "/projects/%s/managedZones/%s/changes/%s" % ( self.zone.project, self.zone.name, 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 name(self, value): """Update name of the change set. :type value: str :param value: New name for the changeset. """
if not isinstance(value, six.string_types): raise ValueError("Pass a string") self._properties["id"] = 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 add_record_set(self, record_set): """Append a record set to the 'additions' for the change set. :type record_set: :class:`google.cloud.dns.resource_record_se...
if not isinstance(record_set, ResourceRecordSet): raise ValueError("Pass a ResourceRecordSet") self._additions += (record_set,)