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 _scalar_field_to_json(field, row_value): """Maps a field and value to a JSON-safe value. Args: field ( \ :class:`~google.cloud.bigquery.schema.SchemaField`, ...
converter = _SCALAR_VALUE_TO_JSON_ROW.get(field.field_type) if converter is None: # STRING doesn't need converting return row_value return converter(row_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_to_json(field, row_value): """Convert a field into JSON-serializable values. Args: field ( \ :class:`~google.cloud.bigquery.schema.SchemaField`, \ ): ...
if row_value is None: return None if field.mode == "REPEATED": return _repeated_field_to_json(field, row_value) if field.field_type == "RECORD": return _record_field_to_json(field.fields, row_value) return _scalar_field_to_json(field, row_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 _snake_to_camel_case(value): """Convert snake case string to camel case."""
words = value.split("_") return words[0] + "".join(map(str.capitalize, words[1:]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_sub_prop(container, keys, default=None): """Get a nested value from a dictionary. This method works like ``dict.get(key)``, but for nested values. Argum...
sub_val = container for key in keys: if key not in sub_val: return default sub_val = sub_val[key] return sub_val
<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_sub_prop(container, keys, value): """Set a nested value in a dictionary. Arguments: container (dict): A dictionary which may contain other dictionaries...
sub_val = container for key in keys[:-1]: if key not in sub_val: sub_val[key] = {} sub_val = sub_val[key] sub_val[keys[-1]] = 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 _del_sub_prop(container, keys): """Remove a nested key fro a dictionary. Arguments: container (dict): A dictionary which may contain other dictionaries as v...
sub_val = container for key in keys[:-1]: if key not in sub_val: sub_val[key] = {} sub_val = sub_val[key] if keys[-1] in sub_val: del sub_val[keys[-1]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_resource_from_properties(obj, filter_fields): """Build a resource based on a ``_properties`` dictionary, filtered by ``filter_fields``, which follow t...
partial = {} for filter_field in filter_fields: api_field = obj._PROPERTY_TO_API_FIELD.get(filter_field) if api_field is None and filter_field not in obj._properties: raise ValueError("No property %s" % filter_field) elif api_field is not None: partial[api_field]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_database_id(database_id): """Make sure a "Reference" database ID is empty. :type database_id: unicode :param database_id: The ``database_id`` field fr...
if database_id != u"": msg = _DATABASE_ID_TEMPLATE.format(database_id) 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 _add_id_or_name(flat_path, element_pb, empty_allowed): """Add the ID or name from an element to a list. :type flat_path: list :param flat_path: List of accum...
id_ = element_pb.id name = element_pb.name # NOTE: Below 0 and the empty string are the "null" values for their # respective types, indicating that the value is unset. if id_ == 0: if name == u"": if not empty_allowed: raise ValueError(_EMPTY_ELEMENT) ...
<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_flat_path(path_pb): """Convert a legacy "Path" protobuf to a flat path. For example Element { type: "parent" id: 59 } Element { type: "child" name: "nae...
num_elts = len(path_pb.element) last_index = num_elts - 1 result = [] for index, element in enumerate(path_pb.element): result.append(element.type) _add_id_or_name(result, element, index == last_index) return tuple(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_legacy_path(dict_path): """Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_...
elements = [] for part in dict_path: element_kwargs = {"type": part["kind"]} if "id" in part: element_kwargs["id"] = part["id"] elif "name" in part: element_kwargs["name"] = part["name"] element = _app_engine_key_pb2.Path.Element(**element_kwargs) ...
<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_path(path_args): """Parses positional arguments into key path with kinds and IDs. :type path_args: tuple :param path_args: A tuple from positional arg...
if len(path_args) == 0: raise ValueError("Key path must not be empty.") kind_list = path_args[::2] id_or_name_list = path_args[1::2] # Dummy sentinel value to pad incomplete key to even length path. partial_ending = object() if len(path_args) % 2 == 1: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _combine_args(self): """Sets protected data by combining raw data set from the constructor. If a ``_parent`` is set, updates the ``_flat_path`` and sets the ...
child_path = self._parse_path(self._flat_path) if self._parent is not None: if self._parent.is_partial: raise ValueError("Parent key must be complete.") # We know that _parent.path() will return a copy. child_path = self._parent.path + child_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 _clone(self): """Duplicates the Key. Most attributes are simple types, so don't require copying. Other attributes like ``parent`` are long-lived and so we re...
cloned_self = self.__class__( *self.flat_path, project=self.project, namespace=self.namespace ) # If the current parent has already been set, we re-use # the same instance cloned_self._parent = self._parent return cloned_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 to_protobuf(self): """Return a protobuf corresponding to the key. :rtype: :class:`.entity_pb2.Key` :returns: The protobuf representing the key. """
key = _entity_pb2.Key() key.partition_id.project_id = self.project if self.namespace: key.partition_id.namespace_id = self.namespace for item in self.path: element = key.path.add() if "kind" in item: element.kind = item["kind"] ...
<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_legacy_urlsafe(self, location_prefix=None): """Convert to a base64 encode urlsafe string for App Engine. This is intended to work with the "legacy" repres...
if location_prefix is None: project_id = self.project else: project_id = location_prefix + self.project reference = _app_engine_key_pb2.Reference( app=project_id, path=_to_legacy_path(self._path), # Avoid the copy. name_space=self.na...
<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_parent(self): """Creates a parent key for the current path. Extracts all but the last element in the key path and creates a new key, while still matchi...
if self.is_partial: parent_args = self.flat_path[:-1] else: parent_args = self.flat_path[:-2] if parent_args: return self.__class__( *parent_args, project=self.project, namespace=self.namespace )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self): """The parent of the current key. :rtype: :class:`google.cloud.datastore.key.Key` or :class:`NoneType` :returns: A new ``Key`` instance, whose ...
if self._parent is None: self._parent = self._make_parent() return self._parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _main_thread_terminated(self): """Callback that attempts to send pending logs before termination."""
if not self.is_alive: return if not self._queue.empty(): print( "Program shutting down, attempting to send %d queued log " "entries to Stackdriver Logging..." % (self._queue.qsize(),), file=sys.stderr, ) if se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enqueue( self, record, message, resource=None, labels=None, trace=None, span_id=None ): """Queues a log entry to be written by the background thread. :type r...
self._queue.put_nowait( { "info": {"message": message, "python_logger": record.name}, "severity": record.levelname, "resource": resource, "labels": labels, "trace": trace, "span_id": span_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 eq_or_parent(self, other): """Check whether ``other`` is an ancestor. Returns: (bool) True IFF ``other`` is an ancestor or equal to ``self``, else False. """
return self.parts[: len(other.parts)] == other.parts[: len(self.parts)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lineage(self): """Return field paths for all parents. Returns: Set[:class:`FieldPath`] """
indexes = six.moves.range(1, len(self.parts)) return {FieldPath(*self.parts[:index]) for index in indexes}
<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( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Gets the latest state of a long-running operation. Clients ca...
request = operations_pb2.GetOperationRequest(name=name) return self._get_operation(request, retry=retry, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_operations( self, name, filter_, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT, ): """ Lists operations that match the specified filter...
# Create the request object. request = operations_pb2.ListOperationsRequest(name=name, filter=filter_) # Create the method used to fetch pages method = functools.partial(self._list_operations, retry=retry, timeout=timeout) iterator = page_iterator.GRPCIterator( cli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Starts asynchronous cancellation on a long-running operati...
# Create the request object. request = operations_pb2.CancelOperationRequest(name=name) self._cancel_operation(request, retry=retry, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_operation( self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT ): """Deletes a long-running operation. This method indicates th...
# Create the request object. request = operations_pb2.DeleteOperationRequest(name=name) self._delete_operation(request, retry=retry, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_name_from_full_name(full_name): """Extract the config name from a full resource name. "my-config" :type full_name: str :param full_name: The full reso...
projects, _, configs, result = full_name.split("/") if projects != "projects" or configs != "configs": raise ValueError( "Unexpected format of resource", full_name, 'Expected "projects/{proj}/configs/{cfg}"', ) 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 variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. 'projects/my-proj/configs/my-config/variables/var-name') "va...
projects, _, configs, _, variables, result = full_name.split("/", 5) if projects != "projects" or configs != "configs" or variables != "variables": raise ValueError( "Unexpected format of resource", full_name, 'Expected "projects/{proj}/configs/{cfg}/variables/..."',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(self): """Return the maximum value in this histogram. If there are no values in the histogram at all, return 600. Returns: int: The maximum value in the ...
if len(self._data) == 0: return 600 return next(iter(reversed(sorted(self._data.keys()))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(self): """Return the minimum value in this histogram. If there are no values in the histogram at all, return 10. Returns: int: The minimum value in the h...
if len(self._data) == 0: return 10 return next(iter(sorted(self._data.keys())))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, value): """Add the value to this histogram. Args: value (int): The value. Values outside of ``10 <= x <= 600`` will be raised to ``10`` or reduced...
# If the value is out of bounds, bring it in bounds. value = int(value) if value < 10: value = 10 if value > 600: value = 600 # Add the value to the histogram's data dictionary. self._data.setdefault(value, 0) self._data[value] += 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def percentile(self, percent): """Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. ...
# Sanity check: Any value over 100 should become 100. if percent >= 100: percent = 100 # Determine the actual target number. target = len(self) - len(self) * (percent / 100) # Iterate over the values in reverse, dropping the target by the # number of times ...
<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 from_string(cls, model_id, default_project=None): """Construct a model reference from model ID string. Args: model_id (str): A model ID in standard SQL form...
proj, dset, model = _helpers._parse_3_part_id( model_id, default_project=default_project, property_name="model_id" ) return cls.from_api_repr( {"projectId": proj, "datasetId": dset, "modelId": model} )
<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_tasks( self, parent, lease_duration, max_tasks=None, response_view=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api...
# Wrap the transport method to add retry and timeout logic. if "lease_tasks" not in self._inner_api_calls: self._inner_api_calls[ "lease_tasks" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.lease_tasks, 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 format_stackdriver_json(record, message): """Helper to format a LogRecord in in Stackdriver fluentd format. :rtype: str :returns: JSON str to be written to t...
subsecond, second = math.modf(record.created) payload = { "message": message, "timestamp": {"seconds": int(second), "nanos": int(subsecond * 1e9)}, "thread": record.thread, "severity": record.levelname, } return json.dumps(payload)
<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_trace_id_from_flask(): """Get trace_id from flask request headers. :rtype: str :returns: TraceID in HTTP request headers. """
if flask is None or not flask.request: return None header = flask.request.headers.get(_FLASK_TRACE_HEADER) if header is None: return None trace_id = header.split("/", 1)[0] return trace_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 get_trace_id_from_webapp2(): """Get trace_id from webapp2 request headers. :rtype: str :returns: TraceID in HTTP request headers. """
if webapp2 is None: return None try: # get_request() succeeds if we're in the middle of a webapp2 # request, or raises an assertion error otherwise: # "Request global variable is not set". req = webapp2.get_request() except AssertionError: return None h...
<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_trace_id_from_django(): """Get trace_id from django request headers. :rtype: str :returns: TraceID in HTTP request headers. """
request = _get_django_request() if request is None: return None header = request.META.get(_DJANGO_TRACE_HEADER) if header is None: return None trace_id = header.split("/", 1)[0] return trace_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 get_trace_id(): """Helper to get trace_id from web application request header. :rtype: str :returns: TraceID in HTTP request headers. """
checkers = ( get_trace_id_from_django, get_trace_id_from_flask, get_trace_id_from_webapp2, ) for checker in checkers: trace_id = checker() if trace_id is not None: return trace_id 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 group_path(cls, project, group): """Return a fully-qualified group string."""
return google.api_core.path_template.expand( "projects/{project}/groups/{group}", project=project, group=group )
<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_groups( self, name, children_of_group=None, ancestors_of_group=None, descendants_of_group=None, page_size=None, retry=google.api_core.gapic_v1.method.DEF...
if metadata is None: metadata = [] metadata = list(metadata) # Wrap the transport method to add retry and timeout logic. if "list_groups" not in self._inner_api_calls: self._inner_api_calls[ "list_groups" ] = google.api_core.gapic_v1.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 list_voices( self, language_code=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_voices" not in self._inner_api_calls: self._inner_api_calls[ "list_voices" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_voices, 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 ensure_signed_credentials(credentials): """Raise AttributeError if the credentials are unsigned. :type credentials: :class:`google.auth.credentials.Signing` ...
if not isinstance(credentials, google.auth.credentials.Signing): auth_uri = ( "https://google-cloud-python.readthedocs.io/en/latest/" "core/auth.html?highlight=authentication#setting-up-" "a-service-account" ) raise AttributeError( "you need 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 get_signed_query_params_v2(credentials, expiration, string_to_sign): """Gets query parameters for creating a signed URL. :type credentials: :class:`google.au...
ensure_signed_credentials(credentials) signature_bytes = credentials.sign_bytes(string_to_sign) signature = base64.b64encode(signature_bytes) service_account_name = credentials.signer_email return { "GoogleAccessId": service_account_name, "Expires": str(expiration), "Signatu...
<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_expiration_seconds_v2(expiration): """Convert 'expiration' to a number of seconds in the future. :type expiration: Union[Integer, datetime.datetime, date...
# If it's a timedelta, add it to `now` in UTC. if isinstance(expiration, datetime.timedelta): now = NOW().replace(tzinfo=_helpers.UTC) expiration = now + expiration # If it's a datetime, convert to a timestamp. if isinstance(expiration, datetime.datetime): micros = _helpers._mi...
<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_expiration_seconds_v4(expiration): """Convert 'expiration' to a number of seconds offset from the current time. :type expiration: Union[Integer, datetime...
if not isinstance(expiration, _EXPIRATION_TYPES): raise TypeError( "Expected an integer timestamp, datetime, or " "timedelta. Got %s" % type(expiration) ) now = NOW().replace(tzinfo=_helpers.UTC) if isinstance(expiration, six.integer_types): seconds = expir...
<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_canonical_headers(headers): """Canonicalize headers for signing. See: https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-ex...
if headers is None: headers = [] elif isinstance(headers, dict): headers = list(headers.items()) if not headers: return [], [] normalized = collections.defaultdict(list) for key, val in headers: key = key.lower().strip() val = MULTIPLE_SPACES.sub(" ", val.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canonicalize(method, resource, query_parameters, headers): """Canonicalize method, resource :type method: str :param method: The HTTP verb that will be used ...
headers, _ = get_canonical_headers(headers) if method == "RESUMABLE": method = "POST" headers.append("x-goog-resumable:start") if query_parameters is None: return _Canonical(method, resource, [], headers) normalized_qp = sorted( (key.lower(), value and value.strip() o...
<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_v2( credentials, resource, expiration, api_access_endpoint="", method="GET", content_md5=None, content_type=None, response_type=None, resp...
expiration_stamp = get_expiration_seconds_v2(expiration) canonical = canonicalize(method, resource, query_parameters, headers) # Generate the string to sign. elements_to_sign = [ canonical.method, content_md5 or "", content_type or "", str(expiration_stamp), ] ...
<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_v4( credentials, resource, expiration, api_access_endpoint=DEFAULT_ENDPOINT, method="GET", content_md5=None, content_type=None, response_t...
ensure_signed_credentials(credentials) expiration_seconds = get_expiration_seconds_v4(expiration) if _request_timestamp is None: now = NOW() request_timestamp = now.strftime("%Y%m%dT%H%M%SZ") datestamp = now.date().strftime("%Y%m%d") else: request_timestamp = _request_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 glossary_path(cls, project, location, glossary): """Return a fully-qualified glossary string."""
return google.api_core.path_template.expand( "projects/{project}/locations/{location}/glossaries/{glossary}", project=project, location=location, glossary=glossary, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_text( self, contents, target_language_code, mime_type=None, source_language_code=None, parent=None, model=None, glossary_config=None, retry=google.a...
# Wrap the transport method to add retry and timeout logic. if "translate_text" not in self._inner_api_calls: self._inner_api_calls[ "translate_text" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.translate_text, 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 detect_language( self, parent=None, model=None, content=None, mime_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1....
# Wrap the transport method to add retry and timeout logic. if "detect_language" not in self._inner_api_calls: self._inner_api_calls[ "detect_language" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.detect_language, ...
<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_supported_languages( self, parent=None, display_language_code=None, model=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gap...
# Wrap the transport method to add retry and timeout logic. if "get_supported_languages" not in self._inner_api_calls: self._inner_api_calls[ "get_supported_languages" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_supported_l...
<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_glossary( self, parent, glossary, 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_glossary" not in self._inner_api_calls: self._inner_api_calls[ "create_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_glossary, ...
<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_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a ...
# Wrap the transport method to add retry and timeout logic. if "delete_glossary" not in self._inner_api_calls: self._inner_api_calls[ "delete_glossary" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_glossary, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_header(time_series): """Return a copy of time_series with the points removed."""
return TimeSeries( metric=time_series.metric, resource=time_series.resource, metric_kind=time_series.metric_kind, value_type=time_series.value_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 _extract_labels(time_series): """Build the combined resource and metric labels, with resource_type."""
labels = {"resource_type": time_series.resource.type} labels.update(time_series.resource.labels) labels.update(time_series.metric.labels) return 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 _sorted_resource_labels(labels): """Sort label names, putting well-known resource labels first."""
head = [label for label in TOP_RESOURCE_LABELS if label in labels] tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS) return head + tail
<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_daemon_thread(*args, **kwargs): """Starts a thread and marks it as a daemon thread."""
thread = threading.Thread(*args, **kwargs) thread.daemon = True thread.start() return thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_invoke_callback(callback, *args, **kwargs): """Invoke a callback, swallowing and logging any exceptions."""
# pylint: disable=bare-except # We intentionally want to swallow all exceptions. try: return callback(*args, **kwargs) except Exception: _LOGGER.exception("Error while executing Future callback.")
<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_project(self, project_id, name=None, labels=None): """Create a project bound to the current client. Use :meth:`Project.reload() \ <google.cloud.resource_...
return Project(project_id=project_id, client=self, name=name, labels=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 fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :c...
project = self.new_project(project_id) project.reload() return project
<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_projects(self, filter_params=None, page_size=None): """List the projects visible to this client. Example:: List all projects with label ``'environment'`...
extra_params = {} if page_size is not None: extra_params["pageSize"] = page_size if filter_params is not None: extra_params["filter"] = [ "{}:{}".format(key, value) for key, value in six.iteritems(filter_params) ] 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 execute_streaming_sql( self, session, sql, transaction=None, params=None, param_types=None, resume_token=None, query_mode=None, partition_token=None, seqno=No...
# Wrap the transport method to add retry and timeout logic. if "execute_streaming_sql" not in self._inner_api_calls: self._inner_api_calls[ "execute_streaming_sql" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_streaming_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_batch_dml( self, session, transaction, statements, seqno, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAU...
# Wrap the transport method to add retry and timeout logic. if "execute_batch_dml" not in self._inner_api_calls: self._inner_api_calls[ "execute_batch_dml" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.execute_batch_dml, ...
<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, session, mutations, transaction_id=None, single_use_transaction=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gap...
# Wrap the transport method to add retry and timeout logic. if "commit" not in self._inner_api_calls: self._inner_api_calls[ "commit" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.commit, default_retry=self._metho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition_query( self, session, sql, transaction=None, params=None, param_types=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAULT, t...
# Wrap the transport method to add retry and timeout logic. if "partition_query" not in self._inner_api_calls: self._inner_api_calls[ "partition_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_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 partition_read( self, session, table, key_set, transaction=None, index=None, columns=None, partition_options=None, retry=google.api_core.gapic_v1.method.DEFAU...
# Wrap the transport method to add retry and timeout logic. if "partition_read" not in self._inner_api_calls: self._inner_api_calls[ "partition_read" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.partition_read, 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 make_datastore_api(client): """Create an instance of the GAPIC Datastore API. :type client: :class:`~google.cloud.datastore.client.Client` :param client: The...
parse_result = six.moves.urllib_parse.urlparse(client._base_url) host = parse_result.netloc if parse_result.scheme == "https": channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host) else: channel = insecure_channel(host) return datastore_client.DatastoreClient...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snippets(session): """Run the snippets test suite."""
# Sanity check: Only run snippets tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable.") # Install all test dependencies, then install local packages in place. session.install("mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _indent(lines, prefix=" "): """Indent some text. Note that this is present as ``textwrap.indent``, but not in Python 2. Args: lines (str): The newline delim...
indented = [] for line in lines.split("\n"): indented.append(prefix + line) return "\n".join(indented)
<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_time(self): """Return the time that the message was originally published. Returns: datetime: The date and time that the message was published. """
timestamp = self._message.publish_time delta = datetime.timedelta( seconds=timestamp.seconds, microseconds=timestamp.nanos // 1000 ) return datetime_helpers._UTC_EPOCH + delta
<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): """Acknowledge the given message. Acknowledging a message in Pub/Sub means that you are done with it, and it will not be delivered to this subscri...
time_to_ack = math.ceil(time.time() - self._received_timestamp) self._request_queue.put( requests.AckRequest( ack_id=self._ack_id, byte_size=self.size, time_to_ack=time_to_ack ) )
<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): """Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver...
self._request_queue.put( requests.DropRequest(ack_id=self._ack_id, byte_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 lease(self): """Inform the policy to lease this message continually. .. note:: This method is called by the constructor, and you should never need to call it...
self._request_queue.put( requests.LeaseRequest(ack_id=self._ack_id, byte_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 modify_ack_deadline(self, seconds): """Resets the deadline for acknowledgement. New deadline will be the given value of seconds from now. The default impleme...
self._request_queue.put( requests.ModAckRequest(ack_id=self._ack_id, seconds=seconds) )
<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): """Decline to acknowldge the given message. This will cause the message to be re-delivered to the subscription. """
self._request_queue.put( requests.NackRequest(ack_id=self._ack_id, byte_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 _run_query(client, query, job_config=None): """Runs a query while printing status updates Args: client (google.cloud.bigquery.client.Client): Client to bund...
start_time = time.time() query_job = client.query(query, job_config=job_config) print("Executing query with job ID: {}".format(query_job.job_id)) while True: print("\rQuery executing: {:0.2f}s".format(time.time() - start_time), end="") try: query_job.result(timeout=0.5) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cell_magic(line, query): """Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. Thi...
args = magic_arguments.parse_argstring(_cell_magic, line) params = [] if args.params is not None: try: params = _helpers.to_query_parameters( ast.literal_eval("".join(args.params)) ) except Exception: raise SyntaxError( "-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def database_root_path(cls, project, database): """Return a fully-qualified database_root string."""
return google.api_core.path_template.expand( "projects/{project}/databases/{database}", project=project, database=database, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document_root_path(cls, project, database): """Return a fully-qualified document_root string."""
return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents", project=project, database=database, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string."""
return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database, document_path=document_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 any_path_path(cls, project, database, document, any_path): """Return a fully-qualified any_path string."""
return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document}/{any_path=**}", project=project, database=database, document=document, any_path=any_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 get_document( self, name, mask=None, transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method....
# Wrap the transport method to add retry and timeout logic. if "get_document" not in self._inner_api_calls: self._inner_api_calls[ "get_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_document, default...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_documents( self, parent, collection_id, page_size=None, order_by=None, mask=None, transaction=None, read_time=None, show_missing=None, retry=google.api_c...
# Wrap the transport method to add retry and timeout logic. if "list_documents" not in self._inner_api_calls: self._inner_api_calls[ "list_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_documents, 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_document( self, document, update_mask, mask=None, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v...
# Wrap the transport method to add retry and timeout logic. if "update_document" not in self._inner_api_calls: self._inner_api_calls[ "update_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_document, ...
<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_get_documents( self, database, documents, mask=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAU...
# Wrap the transport method to add retry and timeout logic. if "batch_get_documents" not in self._inner_api_calls: self._inner_api_calls[ "batch_get_documents" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_get_documents, ...
<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_transaction( self, database, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=Non...
# Wrap the transport method to add retry and timeout logic. if "begin_transaction" not in self._inner_api_calls: self._inner_api_calls[ "begin_transaction" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.begin_transaction, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_query( self, parent, structured_query=None, transaction=None, new_transaction=None, read_time=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout...
# Wrap the transport method to add retry and timeout logic. if "run_query" not in self._inner_api_calls: self._inner_api_calls[ "run_query" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.run_query, default_retry=se...
<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( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Streams batches ...
# Wrap the transport method to add retry and timeout logic. if "write" not in self._inner_api_calls: self._inner_api_calls[ "write" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.write, default_retry=self._method_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 log_path(cls, project, log): """Return a fully-qualified log string."""
return google.api_core.path_template.expand( "projects/{project}/logs/{log}", project=project, log=log )
<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_log( self, log_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes all...
# Wrap the transport method to add retry and timeout logic. if "delete_log" not in self._inner_api_calls: self._inner_api_calls[ "delete_log" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_log, 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 _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal v...
positional = match.group("positional") name = match.group("name") if name is not None: try: return six.text_type(named_vars[name]) except KeyError: raise ValueError( "Named variable '{}' not specified and needed by template " "`{}` 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 expand(tmpl, *args, **kwargs): """Expand a path template with the given variables. ..code-block:: python users/me/messages/123 /v1/shelves/1/books/3 Args: tm...
replacer = functools.partial(_expand_variable_match, list(args), kwargs) return _VARIABLE_RE.sub(replacer, tmpl)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_variable_with_pattern(match): """Replace a variable match with a pattern that can be used to validate it. Args: match (re.Match): A regular express...
positional = match.group("positional") name = match.group("name") template = match.group("template") if name is not None: if not template: return _SINGLE_SEGMENT_PATTERN.format(name) elif template == "**": return _MULTI_SEGMENT_PATTERN.format(name) 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 validate(tmpl, path): """Validate a path against the path template. .. code-block:: python True False True False Args: tmpl (str): The path template. path (...
pattern = _generate_pattern_for_template(tmpl) + "$" return True if re.match(pattern, path) is not None else 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 name(self): """AppProfile name used in requests. .. note:: This property will not change if ``app_profile_id`` does not, but the return value is not cached. ...
return self.instance_admin_client.app_profile_path( self._instance._client.project, self._instance.instance_id, self.app_profile_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 from_pb(cls, app_profile_pb, instance): """Creates an instance app_profile from a protobuf. :type app_profile_pb: :class:`instance_pb2.app_profile_pb` :param...
match_app_profile_name = _APP_PROFILE_NAME_RE.match(app_profile_pb.name) if match_app_profile_name is None: raise ValueError( "AppProfile protobuf name was not in the " "expected format.", app_profile_pb.name, ) if match_app_profile_name.g...