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 make_sinks_api(client):
"""Create an instance of the Sinks API adapter. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client ... |
generated = ConfigServiceV2Client(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _SinksAPI(generated, 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 tenant_path(cls, project, tenant):
"""Return a fully-qualified tenant string.""" |
return google.api_core.path_template.expand(
"projects/{project}/tenants/{tenant}", project=project, tenant=tenant
) |
<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_tenant( self, parent, tenant, 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_tenant" not in self._inner_api_calls:
self._inner_api_calls[
"create_tenant"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_tenant,
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 get_tenant( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Retrieves speci... |
# Wrap the transport method to add retry and timeout logic.
if "get_tenant" not in self._inner_api_calls:
self._inner_api_calls[
"get_tenant"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_tenant,
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 update_tenant( self, tenant, update_mask=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 "update_tenant" not in self._inner_api_calls:
self._inner_api_calls[
"update_tenant"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_tenant,
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 _apply_decorators(func, decorators):
"""Apply a list of decorators to a given function. ``decorators`` may contain items that are ``None`` or ``False`` which... |
decorators = filter(_is_not_none_or_false, reversed(decorators))
for decorator in decorators:
func = decorator(func)
return func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _determine_timeout(default_timeout, specified_timeout, retry):
"""Determines how timeout should be applied to a wrapped method. Args: default_timeout (Option... |
if specified_timeout is DEFAULT:
specified_timeout = default_timeout
if specified_timeout is default_timeout:
# If timeout is the default and the default timeout is exponential and
# a non-default retry is specified, make sure the timeout's deadline
# matches the retry's. This ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_method( func, default_retry=None, default_timeout=None, client_info=client_info.DEFAULT_CLIENT_INFO, ):
"""Wrap an RPC method with common behavior. This... |
func = grpc_helpers.wrap_errors(func)
if client_info is not None:
user_agent_metadata = [client_info.to_grpc_metadata()]
else:
user_agent_metadata = None
return general_helpers.wraps(func)(
_GapicCallable(
func, default_retry, default_timeout, metadata=user_agent_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 _validate_name(name):
"""Pre-flight ``Bucket`` name validation. :type name: str or :data:`NoneType` :param name: Proposed bucket name. :rtype: str or :data:`... |
if name is None:
return
# The first and las characters must be alphanumeric.
if not all([name[0].isalnum(), name[-1].isalnum()]):
raise ValueError("Bucket names must start and end with a number or letter.")
return 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 _write_buffer_to_hash(buffer_object, hash_obj, digest_block_size=8192):
"""Read blocks from a buffer and update a hash with them. :type buffer_object: bytes ... |
block = buffer_object.read(digest_block_size)
while len(block) > 0:
hash_obj.update(block)
# Update the block for the next iteration.
block = buffer_object.read(digest_block_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 reload(self, client=None):
"""Reload properties from Cloud Storage. If :attr:`user_project` is set, bills the API request to that project. :type client: :cla... |
client = self._require_client(client)
query_params = self._query_params
# Pass only '?projection=noAcl' here because 'acl' and related
# are handled via custom endpoints.
query_params["projection"] = "noAcl"
api_response = client._connection.api_request(
meth... |
<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_property(self, name, value):
"""Update field of this object's properties. This method will only update the field provided and will not touch the other... |
self._changes.add(name)
self._properties[name] = 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 update(self, client=None):
"""Sends all properties in a PUT request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` ... |
client = self._require_client(client)
query_params = self._query_params
query_params["projection"] = "full"
api_response = client._connection.api_request(
method="PUT",
path=self.path,
data=self._properties,
query_params=query_params,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch_callback(self, items):
"""Map the callback request to the appropriate gRPC request. Args: action (str):
The method to be invoked. kwargs (Dict[str,... |
if not self._manager.is_active:
return
batched_commands = collections.defaultdict(list)
for item in items:
batched_commands[item.__class__].append(item)
_LOGGER.debug("Handling %d batched requests", len(items))
if batched_commands[requests.LeaseReques... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ack(self, items):
"""Acknowledge the given messages. Args: items(Sequence[AckRequest]):
The items to acknowledge. """ |
# If we got timing information, add it to the histogram.
for item in items:
time_to_ack = item.time_to_ack
if time_to_ack is not None:
self._manager.ack_histogram.add(time_to_ack)
ack_ids = [item.ack_id for item in items]
request = types.Streamin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop(self, items):
"""Remove the given messages from lease management. Args: items(Sequence[DropRequest]):
The items to drop. """ |
self._manager.leaser.remove(items)
self._manager.maybe_resume_consumer() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lease(self, items):
"""Add the given messages to lease management. Args: items(Sequence[LeaseRequest]):
The items to lease. """ |
self._manager.leaser.add(items)
self._manager.maybe_pause_consumer() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_ack_deadline(self, items):
"""Modify the ack deadline for the given messages. Args: items(Sequence[ModAckRequest]):
The items to modify. """ |
ack_ids = [item.ack_id for item in items]
seconds = [item.seconds for item in items]
request = types.StreamingPullRequest(
modify_deadline_ack_ids=ack_ids, modify_deadline_seconds=seconds
)
self._manager.send(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 nack(self, items):
"""Explicitly deny receipt of messages. Args: items(Sequence[NackRequest]):
The items to deny. """ |
self.modify_ack_deadline(
[requests.ModAckRequest(ack_id=item.ack_id, seconds=0) for item in items]
)
self.drop([requests.DropRequest(*item) for item in items]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit_job( self, project_id, region, job, request_id=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, me... |
# Wrap the transport method to add retry and timeout logic.
if "submit_job" not in self._inner_api_calls:
self._inner_api_calls[
"submit_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.submit_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 update_job( self, project_id, region, job_id, job, update_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT... |
# Wrap the transport method to add retry and timeout logic.
if "update_job" not in self._inner_api_calls:
self._inner_api_calls[
"update_job"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_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 instance_path(cls, project, instance):
"""Return a fully-qualified instance string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}",
project=project,
instance=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 app_profile_path(cls, project, instance, app_profile):
"""Return a fully-qualified app_profile string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/appProfiles/{app_profile}",
project=project,
instance=instance,
app_profile=app_profile,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cluster_path(cls, project, instance, cluster):
"""Return a fully-qualified cluster string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/clusters/{cluster}",
project=project,
instance=instance,
cluster=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 list_instances( self, parent, page_token=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 "list_instances" not in self._inner_api_calls:
self._inner_api_calls[
"list_instances"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.list_instances,
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 partial_update_instance( self, instance, update_mask, 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 "partial_update_instance" not in self._inner_api_calls:
self._inner_api_calls[
"partial_update_instance"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partial_update_... |
<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, parent, cluster_id, cluster, 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_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 update_cluster( self, name, serve_nodes, location=None, state=None, default_storage_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.a... |
# Wrap the transport method to add retry and timeout logic.
if "update_cluster" not in self._inner_api_calls:
self._inner_api_calls[
"update_cluster"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_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 create_app_profile( self, parent, app_profile_id, app_profile, ignore_warnings=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 "create_app_profile" not in self._inner_api_calls:
self._inner_api_calls[
"create_app_profile"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_app_profile,
... |
<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_app_profile( self, app_profile, update_mask, ignore_warnings=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.meth... |
# Wrap the transport method to add retry and timeout logic.
if "update_app_profile" not in self._inner_api_calls:
self._inner_api_calls[
"update_app_profile"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_app_profile,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotation_spec_set_path(cls, project, annotation_spec_set):
"""Return a fully-qualified annotation_spec_set string.""" |
return google.api_core.path_template.expand(
"projects/{project}/annotationSpecSets/{annotation_spec_set}",
project=project,
annotation_spec_set=annotation_spec_set,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataset_path(cls, project, dataset):
"""Return a fully-qualified dataset string.""" |
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}", project=project, dataset=dataset
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotated_dataset_path(cls, project, dataset, annotated_dataset):
"""Return a fully-qualified annotated_dataset string.""" |
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}",
project=project,
dataset=dataset,
annotated_dataset=annotated_dataset,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def example_path(cls, project, dataset, annotated_dataset, example):
"""Return a fully-qualified example string.""" |
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}",
project=project,
dataset=dataset,
annotated_dataset=annotated_dataset,
example=example,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_item_path(cls, project, dataset, data_item):
"""Return a fully-qualified data_item string.""" |
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}/dataItems/{data_item}",
project=project,
dataset=dataset,
data_item=data_item,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_path(cls, project, instruction):
"""Return a fully-qualified instruction string.""" |
return google.api_core.path_template.expand(
"projects/{project}/instructions/{instruction}",
project=project,
instruction=instruction,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_data( self, name, annotated_dataset, output_config, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.metho... |
# Wrap the transport method to add retry and timeout logic.
if "export_data" not in self._inner_api_calls:
self._inner_api_calls[
"export_data"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.export_data,
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 label_image( self, parent, basic_config, feature, image_classification_config=None, bounding_poly_config=None, polyline_config=None, segmentation_config=None,... |
# Wrap the transport method to add retry and timeout logic.
if "label_image" not in self._inner_api_calls:
self._inner_api_calls[
"label_image"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.label_image,
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 label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=No... |
# Wrap the transport method to add retry and timeout logic.
if "label_video" not in self._inner_api_calls:
self._inner_api_calls[
"label_video"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.label_video,
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 label_text( self, parent, basic_config, feature, text_classification_config=None, text_entity_extraction_config=None, retry=google.api_core.gapic_v1.method.DE... |
# Wrap the transport method to add retry and timeout logic.
if "label_text" not in self._inner_api_calls:
self._inner_api_calls[
"label_text"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.label_text,
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 create_instruction( self, parent, instruction, 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 "create_instruction" not in self._inner_api_calls:
self._inner_api_calls[
"create_instruction"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_instruction,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
"""Value of the variable, as bytes. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs... |
value = self._properties.get("value")
if value is not None:
value = base64.b64decode(value)
return 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 update_time(self):
"""Retrieve the timestamp at which the variable was updated. See https://cloud.google.com/deployment-manager/runtime-configurator/referenc... |
value = self._properties.get("updateTime")
if value is not None:
try:
value = datetime.datetime.strptime(
value, datetime_helpers._RFC3339_MICROS
)
except ValueError:
DatetimeNS = datetime_helpers.DatetimeWithNa... |
<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_pb(pb_type, any_pb):
"""Converts an ``Any`` protobuf to the specified message type. Args: pb_type (type):
the type of the message that any_pb store... |
msg = pb_type()
# Unwrap proto-plus wrapped messages.
if callable(getattr(pb_type, "pb", None)):
msg_pb = pb_type.pb(msg)
else:
msg_pb = msg
# Unpack the Any object and populate the protobuf message instance.
if not any_pb.Unpack(msg_pb):
raise TypeError(
"... |
<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_messages(module):
"""Discovers all protobuf Message classes in a given import module. Args: module (module):
A Python module; :func:`dir` will be run ag... |
answer = collections.OrderedDict()
for name in dir(module):
candidate = getattr(module, name)
if inspect.isclass(candidate) and issubclass(candidate, message.Message):
answer[name] = candidate
return answer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_subkeys(key, separator="."):
"""Resolve a potentially nested key. If the key contains the ``separator`` (e.g. ``.``) then the key will be split on t... |
parts = key.split(separator, 1)
if len(parts) > 1:
return parts
else:
return parts[0], 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 get(msg_or_dict, key, default=_SENTINEL):
"""Retrieve a key's value from a protobuf Message or dictionary. Args: mdg_or_dict (Union[~google.protobuf.message.... |
# We may need to get a nested key. Resolve this.
key, subkey = _resolve_subkeys(key)
# Attempt to get the value from the two types of objects we know about.
# If we get something else, complain.
if isinstance(msg_or_dict, message.Message):
answer = getattr(msg_or_dict, key, default)
el... |
<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_field_on_message(msg, key, value):
"""Set helper for protobuf Messages.""" |
# Attempt to set the value on the types of objects we know how to deal
# with.
if isinstance(value, (collections_abc.MutableSequence, tuple)):
# Clear the existing repeated protobuf message of any elements
# currently inside it.
while getattr(msg, key):
getattr(msg, key)... |
<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(msg_or_dict, key, value):
"""Set a key's value on a protobuf Message or dictionary. Args: msg_or_dict (Union[~google.protobuf.message.Message, Mapping]):... |
# Sanity check: Is our target object valid?
if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)):
raise TypeError(
"set() expected a dict or protobuf message, got {!r}.".format(
type(msg_or_dict)
)
)
# We may be setting 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 setdefault(msg_or_dict, key, value):
"""Set the key on a protobuf Message or dictionary to a given value if the current value is falsy. Because protobuf Mess... |
if not get(msg_or_dict, key, default=None):
set(msg_or_dict, 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 field_mask(original, modified):
"""Create a field mask by comparing two messages. Args: original (~google.protobuf.message.Message):
the original message. I... |
if original is None and modified is None:
return field_mask_pb2.FieldMask()
if original is None and modified is not None:
original = copy.deepcopy(modified)
original.Clear()
if modified is None and original is not None:
modified = copy.deepcopy(original)
modified.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 topic_path(cls, project, topic):
"""Return a fully-qualified topic string.""" |
return google.api_core.path_template.expand(
"projects/{project}/topics/{topic}", project=project, topic=topic
) |
<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_subscription( self, name, topic, push_config=None, ack_deadline_seconds=None, retain_acked_messages=None, message_retention_duration=None, labels=None,... |
# Wrap the transport method to add retry and timeout logic.
if "create_subscription" not in self._inner_api_calls:
self._inner_api_calls[
"create_subscription"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_subscription,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_query( self, name, query, page_size, language_codes=None, company_name=None, scope=None, type_=None, retry=google.api_core.gapic_v1.method.DEFAULT, t... |
# Wrap the transport method to add retry and timeout logic.
if "complete_query" not in self._inner_api_calls:
self._inner_api_calls[
"complete_query"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.complete_query,
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 _new_session(self):
"""Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new sessio... |
if self.labels:
return self._database.session(labels=self.labels)
return self._database.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 clear(self):
"""Delete all sessions in the pool.""" |
while True:
try:
session = self._sessions.get(block=False)
except queue.Empty:
break
else:
session.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ping(self):
"""Refresh maybe-expired sessions in the pool. This method is designed to be called from a background thread, or during the "idle" phase of an ev... |
while True:
try:
ping_after, session = self._sessions.get(block=False)
except queue.Empty: # all sessions in use
break
if ping_after > _NOW(): # oldest session is fresh
# Re-add to queue with existing expiration
... |
<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_pending_transactions(self):
"""Begin all transactions for sessions added to the pool.""" |
while not self._pending_sessions.empty():
session = self._pending_sessions.get()
session._transaction.begin()
super(TransactionPingingPool, self).put(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 setup_logging( handler, excluded_loggers=EXCLUDED_LOGGER_DEFAULTS, log_level=logging.INFO ):
"""Attach a logging handler to the Python root logger Excludes l... |
all_excluded_loggers = set(excluded_loggers + EXCLUDED_LOGGER_DEFAULTS)
logger = logging.getLogger()
logger.setLevel(log_level)
logger.addHandler(handler)
logger.addHandler(logging.StreamHandler())
for logger_name in all_excluded_loggers:
logger = logging.getLogger(logger_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 format(self, record):
"""Format the message into JSON expected by fluentd. :type record: :class:`~logging.LogRecord` :param record: the log record :rtype: st... |
message = super(ContainerEngineHandler, self).format(record)
return format_stackdriver_json(record, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze_sentiment( self, document, encoding_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadat... |
# Wrap the transport method to add retry and timeout logic.
if "analyze_sentiment" not in self._inner_api_calls:
self._inner_api_calls[
"analyze_sentiment"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.analyze_sentiment,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sleep(current_sleep, max_sleep=_MAX_SLEEP, multiplier=_MULTIPLIER):
"""Sleep and produce a new sleep time. .. _Exponential Backoff And Jitter: https://www.a... |
actual_sleep = random.uniform(0.0, current_sleep)
time.sleep(actual_sleep)
return min(multiplier * current_sleep, max_sleep) |
<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_write_pbs(self, write_pbs):
"""Add `Write`` protobufs to this transaction. Args: write_pbs (List[google.cloud.proto.firestore.v1beta1.\ write_pb2.Write]... |
if self._read_only:
raise ValueError(_WRITE_READ_ONLY)
super(Transaction, self)._add_write_pbs(write_pbs) |
<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, retry_id=None):
"""Begin the transaction. Args: retry_id (Optional[bytes]):
Transaction ID of a transaction to be retried. Raises: ValueError: ... |
if self.in_progress:
msg = _CANT_BEGIN.format(self._id)
raise ValueError(msg)
transaction_response = self._client._firestore_api.begin_transaction(
self._client._database_string,
options_=self._options_protobuf(retry_id),
metadata=self._clien... |
<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 the transaction. Raises: ValueError: If no transaction is in progress. """ |
if not self.in_progress:
raise ValueError(_CANT_ROLLBACK)
try:
# NOTE: The response is just ``google.protobuf.Empty``.
self._client._firestore_api.rollback(
self._client._database_string,
self._id,
metadata=self._clien... |
<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):
"""Transactionally commit the changes accumulated. Returns: List[google.cloud.proto.firestore.v1beta1.\ to the changes committed, returned in ... |
if not self.in_progress:
raise ValueError(_CANT_COMMIT)
commit_response = _commit_with_retry(self._client, self._write_pbs, self._id)
self._clean_up()
return list(commit_response.write_results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pre_commit(self, transaction, *args, **kwargs):
"""Begin transaction and call the wrapped callable. If the callable raises an exception, the transaction wil... |
# Force the ``transaction`` to be not "in progress".
transaction._clean_up()
transaction._begin(retry_id=self.retry_id)
# Update the stored transaction IDs.
self.current_id = transaction._id
if self.retry_id is None:
self.retry_id = self.current_id
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _maybe_commit(self, transaction):
"""Try to commit the transaction. If the transaction is read-write and the ``Commit`` fails with the ``ABORTED`` status cod... |
try:
transaction._commit()
return True
except exceptions.GoogleAPICallError as exc:
if transaction._read_only:
raise
if isinstance(exc, exceptions.Aborted):
# If a read-write transaction returns ABORTED, 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 profile_path(cls, project, tenant, profile):
"""Return a fully-qualified profile string.""" |
return google.api_core.path_template.expand(
"projects/{project}/tenants/{tenant}/profiles/{profile}",
project=project,
tenant=tenant,
profile=profile,
) |
<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_profile( self, parent, profile, 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 "create_profile" not in self._inner_api_calls:
self._inner_api_calls[
"create_profile"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_profile,
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_profile( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ):
""" Gets the speci... |
# Wrap the transport method to add retry and timeout logic.
if "get_profile" not in self._inner_api_calls:
self._inner_api_calls[
"get_profile"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.get_profile,
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 update_profile( self, profile, update_mask=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 "update_profile" not in self._inner_api_calls:
self._inner_api_calls[
"update_profile"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.update_profile,
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 search_profiles( self, parent, request_metadata, profile_query=None, page_size=None, offset=None, disable_spell_check=None, order_by=None, case_sensitive_sort... |
# Wrap the transport method to add retry and timeout logic.
if "search_profiles" not in self._inner_api_calls:
self._inner_api_calls[
"search_profiles"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.search_profiles,
... |
<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_service_account_json(cls, json_credentials_path, *args, **kwargs):
"""Factory to retrieve JSON credentials while creating client. :type json_credentials... |
if "credentials" in kwargs:
raise TypeError("credentials must not be in keyword arguments")
with io.open(json_credentials_path, "r", encoding="utf-8") as json_fi:
credentials_info = json.load(json_fi)
credentials = service_account.Credentials.from_service_account_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 _http(self):
"""Getter for object used for HTTP transport. :rtype: :class:`~requests.Session` :returns: An HTTP object. """ |
if self._http_internal is None:
self._http_internal = google.auth.transport.requests.AuthorizedSession(
self._credentials
)
return self._http_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 alert_policy_path(cls, project, alert_policy):
"""Return a fully-qualified alert_policy string.""" |
return google.api_core.path_template.expand(
"projects/{project}/alertPolicies/{alert_policy}",
project=project,
alert_policy=alert_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 alert_policy_condition_path(cls, project, alert_policy, condition):
"""Return a fully-qualified alert_policy_condition string.""" |
return google.api_core.path_template.expand(
"projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}",
project=project,
alert_policy=alert_policy,
condition=condition,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _error_result_to_exception(error_result):
"""Maps BigQuery error reasons to an exception. The reasons and their matching HTTP status codes are documented on ... |
reason = error_result.get("reason")
status_code = _ERROR_REASON_TO_EXCEPTION.get(
reason, http_client.INTERNAL_SERVER_ERROR
)
return exceptions.from_http_status(
status_code, error_result.get("message", ""), errors=[error_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 _from_api_repr(cls, resource):
"""Returns a job reference for an API resource representation.""" |
job_id = resource.get("jobId")
project = resource.get("projectId")
location = resource.get("location")
job_ref = cls(job_id, project, location)
return job_ref |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def created(self):
"""Datetime at which the job was created. :rtype: ``datetime.datetime``, or ``NoneType`` :returns: the creation time (None until set from the ... |
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("creationTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def started(self):
"""Datetime at which the job was started. :rtype: ``datetime.datetime``, or ``NoneType`` :returns: the start time (None until set from the ser... |
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("startTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ended(self):
"""Datetime at which the job finished. :rtype: ``datetime.datetime``, or ``NoneType`` :returns: the end time (None until set from the server). "... |
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("endTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _job_statistics(self):
"""Helper for job-type specific statistics-based properties.""" |
statistics = self._properties.get("statistics", {})
return statistics.get(self._JOB_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 _set_future_result(self):
"""Set the result or exception from the job if it is complete.""" |
# This must be done in a lock to prevent the polling thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fill_from_default(self, default_job_config):
"""Merge this job config with a default job config. The keys in this object take precedence over the keys in th... |
if self._job_type != default_job_config._job_type:
raise TypeError(
"attempted to merge two incompatible job types: "
+ repr(self._job_type)
+ ", "
+ repr(default_job_config._job_type)
)
new_job_config = self.__cla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destination_uri_file_counts(self):
"""Return file counts from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#... |
counts = self._job_statistics().get("destinationUriFileCounts")
if counts is not None:
return [int(count) for count in counts]
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 to_api_repr(self):
"""Build an API representation of the query job config. Returns: dict: A dictionary in the format used by the BigQuery API. """ |
resource = copy.deepcopy(self._properties)
# Query parameters have an addition property associated with them
# to indicate if the query is using named or positional parameters.
query_parameters = resource["query"].get("queryParameters")
if query_parameters:
if query... |
<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_plan(self):
"""Return query plan from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.q... |
plan_entries = self._job_statistics().get("queryPlan", ())
return [QueryPlanEntry.from_api_repr(entry) for entry in plan_entries] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_bytes_processed(self):
"""Return total bytes processed from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/j... |
result = self._job_statistics().get("totalBytesProcessed")
if result is not None:
result = int(result)
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 total_bytes_billed(self):
"""Return total bytes billed from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#st... |
result = self._job_statistics().get("totalBytesBilled")
if result is not None:
result = int(result)
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 num_dml_affected_rows(self):
"""Return the number of DML rows affected by the job. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statist... |
result = self._job_statistics().get("numDmlAffectedRows")
if result is not None:
result = int(result)
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 referenced_tables(self):
"""Return referenced tables from job statistics, if present. See: https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#stat... |
tables = []
datasets_by_project_name = {}
for table in self._job_statistics().get("referencedTables", ()):
t_project = table["projectId"]
ds_id = table["datasetId"]
t_dataset = datasets_by_project_name.get((t_project, ds_id))
if t_dataset is No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undeclared_query_parameters(self):
"""Return undeclared query parameters from job statistics, if present. See: https://cloud.google.com/bigquery/docs/referen... |
parameters = []
undeclared = self._job_statistics().get("undeclaredQueryParameters", ())
for parameter in undeclared:
p_type = parameter["parameterType"]
if "arrayType" in p_type:
klass = ArrayQueryParameter
elif "structTypes" in p_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 estimated_bytes_processed(self):
"""Return the estimated number of bytes processed by the query. See: https://cloud.google.com/bigquery/docs/reference/rest/v... |
result = self._job_statistics().get("estimatedBytesProcessed")
if result is not None:
result = int(result)
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 to_dataframe(self, bqstorage_client=None, dtypes=None, progress_bar_type=None):
"""Return a pandas DataFrame from a QueryJob Args: bqstorage_client ( \ googl... |
return self.result().to_dataframe(
bqstorage_client=bqstorage_client,
dtypes=dtypes,
progress_bar_type=progress_bar_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 from_api_repr(cls, resource, client):
"""Construct an UnknownJob from the JSON representation. Args: resource (dict):
JSON representation of a job. client (... |
job_ref_properties = resource.get("jobReference", {"projectId": client.project})
job_ref = _JobReference._from_api_repr(job_ref_properties)
job = cls(job_ref, client)
# Populate the job reference with the project, even if it has been
# redacted, because we know it should equal t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(self, value):
"""Update description of the zone. :type value: str :param value: (Optional) new description :raises: ValueError for invalid value ... |
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["description"] = 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 name_server_set(self, value):
"""Update named set of DNS name servers. :type value: str :param value: (Optional) new title :raises: ValueError for invalid va... |
if not isinstance(value, six.string_types) and value is not None:
raise ValueError("Pass a string, or None")
self._properties["nameServerSet"] = 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 resource_record_set(self, name, record_type, ttl, rrdatas):
"""Construct a resource record set bound to this zone. :type name: str :param name: Name of the r... |
return ResourceRecordSet(name, record_type, ttl, rrdatas, zone=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 _build_resource(self):
"""Generate a resource for ``create`` or ``update``.""" |
resource = {"name": self.name}
if self.dns_name is not None:
resource["dnsName"] = self.dns_name
if self.description is not None:
resource["description"] = self.description
if self.name_server_set is not None:
resource["nameServerSet"] = self.name_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.