_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q257200 | _Pipelines.build_pipeline_args | validation | def build_pipeline_args(cls, project, script, job_params, task_params,
reserved_labels, preemptible, logging_uri, scopes,
keep_alive):
"""Builds pipeline args for execution.
Args:
project: string name of project.
script: Body of the script to exec... | python | {
"resource": ""
} |
q257201 | _Operations._datetime_to_utc_int | validation | def _datetime_to_utc_int(date):
"""Convert the integer UTC time value into a local datetime."""
if date is None:
return None
# Convert localized datetime to a UTC integer
epoch = dsub_util.replace_timezone(datetime.utcfromtimestamp(0), pytz.utc)
return (date - epoch).total_seconds() | python | {
"resource": ""
} |
q257202 | GoogleJobProvider._build_pipeline_request | validation | def _build_pipeline_request(self, task_view):
"""Returns a Pipeline objects for the job."""
job_metadata = task_view.job_metadata
job_params = task_view.job_params
job_resources = task_view.job_resources
task_metadata = task_view.task_descriptors[0].task_metadata
task_params = task_view.task_des... | python | {
"resource": ""
} |
q257203 | GoogleJobProvider.delete_jobs | validation | def delete_jobs(self,
user_ids,
job_ids,
task_ids,
labels,
create_time_min=None,
create_time_max=None):
"""Kills the operations associated with the specified job or job.task.
Args:
user_ids: List o... | python | {
"resource": ""
} |
q257204 | GoogleOperation._operation_status_message | validation | def _operation_status_message(self):
"""Returns the most relevant status string and last updated date string.
This string is meant for display only.
Returns:
A printable status string and date string.
"""
metadata = self._op['metadata']
if not self._op['done']:
if 'events' in metad... | python | {
"resource": ""
} |
q257205 | GoogleOperation._get_operation_input_field_values | validation | def _get_operation_input_field_values(self, metadata, file_input):
"""Returns a dictionary of envs or file inputs for an operation.
Args:
metadata: operation metadata field
file_input: True to return a dict of file inputs, False to return envs.
Returns:
A dictionary of input field name v... | python | {
"resource": ""
} |
q257206 | _format_task_name | validation | def _format_task_name(job_id, task_id, task_attempt):
"""Create a task name from a job-id, task-id, and task-attempt.
Task names are used internally by dsub as well as by the docker task runner.
The name is formatted as "<job-id>.<task-id>[.task-attempt]". Task names
follow formatting conventions allowing them... | python | {
"resource": ""
} |
q257207 | _convert_suffix_to_docker_chars | validation | def _convert_suffix_to_docker_chars(suffix):
"""Rewrite string so that all characters are valid in a docker name suffix."""
# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]
accepted_characters = string.ascii_letters + string.digits + '_.-'
def label_char_transform(char):
if char in accepted_c... | python | {
"resource": ""
} |
q257208 | _task_sort_function | validation | def _task_sort_function(task):
"""Return a tuple for sorting 'most recent first'."""
return (task.get_field('create-time'), int(task.get_field('task-id', 0)),
int(task.get_field('task-attempt', 0))) | python | {
"resource": ""
} |
q257209 | LocalJobProvider._datetime_in_range | validation | def _datetime_in_range(self, dt, dt_min=None, dt_max=None):
"""Determine if the provided time is within the range, inclusive."""
# The pipelines API stores operation create-time with second granularity.
# We mimic this behavior in the local provider by truncating to seconds.
dt = dt.replace(microsecond=... | python | {
"resource": ""
} |
q257210 | LocalJobProvider._get_task_from_task_dir | validation | def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt):
"""Return a Task object with this task's info."""
# We need to be very careful about how we read and interpret the contents
# of the task directory. The directory could be changing because a new
# task is being created. The dire... | python | {
"resource": ""
} |
q257211 | LocalJobProvider._delocalize_logging_command | validation | def _delocalize_logging_command(self, logging_path, user_project):
"""Returns a command to delocalize logs.
Args:
logging_path: location of log files.
user_project: name of the project to be billed for the request.
Returns:
eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'
... | python | {
"resource": ""
} |
q257212 | LocalJobProvider._task_directory | validation | def _task_directory(self, job_id, task_id, task_attempt):
"""The local dir for staging files for that particular task."""
dir_name = 'task' if task_id is None else str(task_id)
if task_attempt:
dir_name = '%s.%s' % (dir_name, task_attempt)
return self._provider_root() + '/' + job_id + '/' + dir_na... | python | {
"resource": ""
} |
q257213 | LocalJobProvider._make_environment | validation | def _make_environment(self, inputs, outputs, mounts):
"""Return a dictionary of environment variables for the container."""
env = {}
env.update(providers_util.get_file_environment_variables(inputs))
env.update(providers_util.get_file_environment_variables(outputs))
env.update(providers_util.get_file... | python | {
"resource": ""
} |
q257214 | LocalJobProvider._localize_inputs_recursive_command | validation | def _localize_inputs_recursive_command(self, task_dir, inputs):
"""Returns a command that will stage recursive inputs."""
data_dir = os.path.join(task_dir, _DATA_SUBDIR)
provider_commands = [
providers_util.build_recursive_localize_command(data_dir, inputs,
... | python | {
"resource": ""
} |
q257215 | LocalJobProvider._get_input_target_path | validation | def _get_input_target_path(self, local_file_path):
"""Returns a directory or file path to be the target for "gsutil cp".
If the filename contains a wildcard, then the target path must
be a directory in order to ensure consistency whether the source pattern
contains one or multiple files.
Args:
... | python | {
"resource": ""
} |
q257216 | LocalJobProvider._localize_inputs_command | validation | def _localize_inputs_command(self, task_dir, inputs, user_project):
"""Returns a command that will stage inputs."""
commands = []
for i in inputs:
if i.recursive or not i.value:
continue
source_file_path = i.uri
local_file_path = task_dir + '/' + _DATA_SUBDIR + '/' + i.docker_path... | python | {
"resource": ""
} |
q257217 | LocalJobProvider._delocalize_outputs_commands | validation | def _delocalize_outputs_commands(self, task_dir, outputs, user_project):
"""Copy outputs from local disk to GCS."""
commands = []
for o in outputs:
if o.recursive or not o.value:
continue
# The destination path is o.uri.path, which is the target directory
# (rather than o.uri, whi... | python | {
"resource": ""
} |
q257218 | get_dsub_version | validation | def get_dsub_version():
"""Get the dsub version out of the _dsub_version.py source file.
Setup.py should not import dsub version from dsub directly since ambiguity in
import order could lead to an old version of dsub setting the version number.
Parsing the file directly is simpler than using import tools (whos... | python | {
"resource": ""
} |
q257219 | GoogleV2EventMap.get_filtered_normalized_events | validation | def get_filtered_normalized_events(self):
"""Filter the granular v2 events down to events of interest.
Filter through the large number of granular events returned by the
pipelines API, and extract only those that are interesting to a user. This
is implemented by filtering out events which are known to ... | python | {
"resource": ""
} |
q257220 | GoogleV2EventMap._map | validation | def _map(self, event):
"""Extract elements from an operation event and map to a named event."""
description = event.get('description', '')
start_time = google_base.parse_rfc3339_utc_string(
event.get('timestamp', ''))
for name, regex in _EVENT_REGEX_MAP.items():
match = regex.match(descri... | python | {
"resource": ""
} |
q257221 | GoogleV2JobProvider._get_logging_env | validation | def _get_logging_env(self, logging_uri, user_project):
"""Returns the environment for actions that copy logging files."""
if not logging_uri.endswith('.log'):
raise ValueError('Logging URI must end in ".log": {}'.format(logging_uri))
logging_prefix = logging_uri[:-len('.log')]
return {
'L... | python | {
"resource": ""
} |
q257222 | GoogleV2JobProvider._get_prepare_env | validation | def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):
"""Return a dict with variables for the 'prepare' action."""
# Add the _SCRIPT_REPR with the repr(script) contents
# Add the _META_YAML_REPR with the repr(meta) contents
# Add variables for directories that need to be created... | python | {
"resource": ""
} |
q257223 | GoogleV2JobProvider._get_localization_env | validation | def _get_localization_env(self, inputs, user_project):
"""Return a dict with variables for the 'localization' action."""
# Add variables for paths that need to be localized, for example:
# INPUT_COUNT: 1
# INPUT_0: MY_INPUT_FILE
# INPUT_RECURSIVE_0: 0
# INPUT_SRC_0: gs://mybucket/mypath/myfile
... | python | {
"resource": ""
} |
q257224 | GoogleV2JobProvider._get_delocalization_env | validation | def _get_delocalization_env(self, outputs, user_project):
"""Return a dict with variables for the 'delocalization' action."""
# Add variables for paths that need to be delocalized, for example:
# OUTPUT_COUNT: 1
# OUTPUT_0: MY_OUTPUT_FILE
# OUTPUT_RECURSIVE_0: 0
# OUTPUT_SRC_0: gs://mybucket/my... | python | {
"resource": ""
} |
q257225 | GoogleV2JobProvider._build_user_environment | validation | def _build_user_environment(self, envs, inputs, outputs, mounts):
"""Returns a dictionary of for the user container environment."""
envs = {env.name: env.value for env in envs}
envs.update(providers_util.get_file_environment_variables(inputs))
envs.update(providers_util.get_file_environment_variables(ou... | python | {
"resource": ""
} |
q257226 | GoogleV2JobProvider._get_mount_actions | validation | def _get_mount_actions(self, mounts, mnt_datadisk):
"""Returns a list of two actions per gcs bucket to mount."""
actions_to_add = []
for mount in mounts:
bucket = mount.value[len('gs://'):]
mount_path = mount.docker_path
actions_to_add.extend([
google_v2_pipelines.build_action(
... | python | {
"resource": ""
} |
q257227 | GoogleOperation._operation_status | validation | def _operation_status(self):
"""Returns the status of this operation.
Raises:
ValueError: if the operation status cannot be determined.
Returns:
A printable status string (RUNNING, SUCCESS, CANCELED or FAILURE).
"""
if not google_v2_operations.is_done(self._op):
return 'RUNNING'
... | python | {
"resource": ""
} |
q257228 | GoogleOperation._operation_status_message | validation | def _operation_status_message(self):
"""Returns the most relevant status string and failed action.
This string is meant for display only.
Returns:
A printable status string and name of failed action (if any).
"""
msg = None
action = None
if not google_v2_operations.is_done(self._op):... | python | {
"resource": ""
} |
q257229 | GoogleV2CustomMachine._validate_ram | validation | def _validate_ram(ram_in_mb):
"""Rounds ram up to the nearest multiple of _MEMORY_MULTIPLE."""
return int(GoogleV2CustomMachine._MEMORY_MULTIPLE * math.ceil(
ram_in_mb / GoogleV2CustomMachine._MEMORY_MULTIPLE)) | python | {
"resource": ""
} |
q257230 | GoogleV2CustomMachine.build_machine_type | validation | def build_machine_type(cls, min_cores, min_ram):
"""Returns a custom machine type string."""
min_cores = min_cores or job_model.DEFAULT_MIN_CORES
min_ram = min_ram or job_model.DEFAULT_MIN_RAM
# First, min_ram is given in GB. Convert to MB.
min_ram *= GoogleV2CustomMachine._MB_PER_GB
# Only ma... | python | {
"resource": ""
} |
q257231 | build_machine | validation | def build_machine(network=None,
machine_type=None,
preemptible=None,
service_account=None,
boot_disk_size_gb=None,
disks=None,
accelerators=None,
labels=None,
cpu_platform=None... | python | {
"resource": ""
} |
q257232 | build_action | validation | def build_action(name=None,
image_uri=None,
commands=None,
entrypoint=None,
environment=None,
pid_namespace=None,
flags=None,
port_mappings=None,
mounts=None,
labels=N... | python | {
"resource": ""
} |
q257233 | StubJobProvider.lookup_job_tasks | validation | def lookup_job_tasks(self,
statuses,
user_ids=None,
job_ids=None,
job_names=None,
task_ids=None,
task_attempts=None,
labels=None,
create... | python | {
"resource": ""
} |
q257234 | get_provider | validation | def get_provider(args, resources):
"""Returns a provider for job submission requests."""
provider = getattr(args, 'provider', 'google')
if provider == 'google':
return google.GoogleJobProvider(
getattr(args, 'verbose', False),
getattr(args, 'dry_run', False), args.project)
elif provider ==... | python | {
"resource": ""
} |
q257235 | parse_args | validation | def parse_args(parser, provider_required_args, argv):
"""Add provider required arguments epilog message, parse, and validate."""
# Add the provider required arguments epilog message
epilog = 'Provider-required arguments:\n'
for provider in provider_required_args:
epilog += ' %s: %s\n' % (provider, provide... | python | {
"resource": ""
} |
q257236 | get_dstat_provider_args | validation | def get_dstat_provider_args(provider, project):
"""A string with the arguments to point dstat to the same provider+project."""
provider_name = get_provider_name(provider)
args = []
if provider_name == 'google':
args.append('--project %s' % project)
elif provider_name == 'google-v2':
args.append('--pr... | python | {
"resource": ""
} |
q257237 | _format_task_uri | validation | def _format_task_uri(fmt, job_metadata, task_metadata):
"""Returns a URI with placeholders replaced by metadata values."""
values = {
'job-id': None,
'task-id': 'task',
'job-name': None,
'user-id': None,
'task-attempt': None
}
for key in values:
values[key] = task_metadata.get... | python | {
"resource": ""
} |
q257238 | format_logging_uri | validation | def format_logging_uri(uri, job_metadata, task_metadata):
"""Inserts task metadata into the logging URI.
The core behavior is inspired by the Google Pipelines API:
(1) If a the uri ends in ".log", then that is the logging path.
(2) Otherwise, the uri is treated as "directory" for logs and a filename
... | python | {
"resource": ""
} |
q257239 | _google_v2_parse_arguments | validation | def _google_v2_parse_arguments(args):
"""Validated google-v2 arguments."""
if (args.zones and args.regions) or (not args.zones and not args.regions):
raise ValueError('Exactly one of --regions and --zones must be specified')
if args.machine_type and (args.min_cores or args.min_ram):
raise ValueError(
... | python | {
"resource": ""
} |
q257240 | _get_job_resources | validation | def _get_job_resources(args):
"""Extract job-global resources requirements from input args.
Args:
args: parsed command-line arguments
Returns:
Resources object containing the requested resources for the job
"""
logging = param_util.build_logging_param(
args.logging) if args.logging else None
... | python | {
"resource": ""
} |
q257241 | _get_job_metadata | validation | def _get_job_metadata(provider, user_id, job_name, script, task_ids,
user_project, unique_job_id):
"""Allow provider to extract job-specific metadata from command-line args.
Args:
provider: job service provider
user_id: user submitting the job
job_name: name for the job
script... | python | {
"resource": ""
} |
q257242 | _resolve_task_logging | validation | def _resolve_task_logging(job_metadata, job_resources, task_descriptors):
"""Resolve the logging path from job and task properties.
Args:
job_metadata: Job metadata, such as job-id, job-name, and user-id.
job_resources: Resources specified such as ram, cpu, and logging path.
task_descriptors: Task meta... | python | {
"resource": ""
} |
q257243 | _wait_after | validation | def _wait_after(provider, job_ids, poll_interval, stop_on_failure):
"""Print status info as we wait for those jobs.
Blocks until either all of the listed jobs succeed,
or one of them fails.
Args:
provider: job service provider
job_ids: a set of job IDs (string) to wait for
poll_interval: integer s... | python | {
"resource": ""
} |
q257244 | _wait_and_retry | validation | def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor):
"""Wait for job and retry any tasks that fail.
Stops retrying an individual task when: it succeeds, is canceled, or has been
retried "retries" times.
This function exits when there are no tasks running and there are no tasks
elig... | python | {
"resource": ""
} |
q257245 | _dominant_task_for_jobs | validation | def _dominant_task_for_jobs(tasks):
"""A list with, for each job, its dominant task.
The dominant task is the one that exemplifies its job's
status. It is either:
- the first (FAILURE or CANCELED) task, or if none
- the first RUNNING task, or if none
- the first SUCCESS task.
Args:
tasks: a list of ... | python | {
"resource": ""
} |
q257246 | _group_tasks_by_jobid | validation | def _group_tasks_by_jobid(tasks):
"""A defaultdict with, for each job, a list of its tasks."""
ret = collections.defaultdict(list)
for t in tasks:
ret[t.get_field('job-id')].append(t)
return ret | python | {
"resource": ""
} |
q257247 | _wait_for_any_job | validation | def _wait_for_any_job(provider, job_ids, poll_interval):
"""Waits until any of the listed jobs is not running.
In particular, if any of the jobs sees one of its tasks fail,
we count the whole job as failing (but do not terminate the remaining
tasks ourselves).
Args:
provider: job service provider
jo... | python | {
"resource": ""
} |
q257248 | _validate_job_and_task_arguments | validation | def _validate_job_and_task_arguments(job_params, task_descriptors):
"""Validates that job and task argument names do not overlap."""
if not task_descriptors:
return
task_params = task_descriptors[0].task_params
# The use case for specifying a label or env/input/output parameter on
# the command-line an... | python | {
"resource": ""
} |
q257249 | _name_for_command | validation | def _name_for_command(command):
r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the caller should just
specify a "--name... | python | {
"resource": ""
} |
q257250 | _local_uri_rewriter | validation | def _local_uri_rewriter(raw_uri):
"""Rewrite local file URIs as required by the rewrite_uris method.
Local file paths, unlike GCS paths, may have their raw URI simplified by
os.path.normpath which collapses extraneous indirect characters.
>>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')
('/tmp/B_PA... | python | {
"resource": ""
} |
q257251 | _get_filtered_mounts | validation | def _get_filtered_mounts(mounts, mount_param_type):
"""Helper function to return an appropriate set of mount parameters."""
return set([mount for mount in mounts if isinstance(mount, mount_param_type)]) | python | {
"resource": ""
} |
q257252 | build_logging_param | validation | def build_logging_param(logging_uri, util_class=OutputFileParamUtil):
"""Convenience function simplifies construction of the logging uri."""
if not logging_uri:
return job_model.LoggingParam(None, None)
recursive = not logging_uri.endswith('.log')
oututil = util_class('')
_, uri, provider = oututil.parse_... | python | {
"resource": ""
} |
q257253 | split_pair | validation | def split_pair(pair_string, separator, nullable_idx=1):
"""Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
... | python | {
"resource": ""
} |
q257254 | parse_tasks_file_header | validation | def parse_tasks_file_header(header, input_file_param_util,
output_file_param_util):
"""Parse the header from the tasks file into env, input, output definitions.
Elements are formatted similar to their equivalent command-line arguments,
but with associated values coming from the data r... | python | {
"resource": ""
} |
q257255 | tasks_file_to_task_descriptors | validation | def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,
output_file_param_util):
"""Parses task parameters from a TSV.
Args:
tasks: Dict containing the path to a TSV file and task numbers to run
variables, input, and output parameters as column headings.... | python | {
"resource": ""
} |
q257256 | parse_pair_args | validation | def parse_pair_args(labels, argclass):
"""Parse flags of key=value pairs and return a list of argclass.
For pair variables, we need to:
* split the input into name=value pairs (value optional)
* Create the EnvParam object
Args:
labels: list of 'key' or 'key=value' strings.
argclass: Container ... | python | {
"resource": ""
} |
q257257 | args_to_job_params | validation | def args_to_job_params(envs, labels, inputs, inputs_recursive, outputs,
outputs_recursive, mounts, input_file_param_util,
output_file_param_util, mount_param_util):
"""Parse env, input, and output parameters into a job parameters and data.
Passing arguments on the comm... | python | {
"resource": ""
} |
q257258 | validate_submit_args_or_fail | validation | def validate_submit_args_or_fail(job_descriptor, provider_name, input_providers,
output_providers, logging_providers):
"""Validate that arguments passed to submit_job have valid file providers.
This utility function takes resources and task data args from `submit_job`
in the base... | python | {
"resource": ""
} |
q257259 | _interval_to_seconds | validation | def _interval_to_seconds(interval, valid_units='smhdw'):
"""Convert the timeout duration to seconds.
The value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
interval: A "<integer><unit>" string.
valid_units: A list of suppor... | python | {
"resource": ""
} |
q257260 | FileParamUtil.get_variable_name | validation | def get_variable_name(self, name):
"""Produce a default variable name if none is specified."""
if not name:
name = '%s%s' % (self._auto_prefix, self._auto_index)
self._auto_index += 1
return name | python | {
"resource": ""
} |
q257261 | FileParamUtil.rewrite_uris | validation | def rewrite_uris(self, raw_uri, file_provider):
"""Accept a raw uri and return rewritten versions.
This function returns a normalized URI and a docker path. The normalized
URI may have minor alterations meant to disambiguate and prepare for use
by shell utilities that may require a specific format.
... | python | {
"resource": ""
} |
q257262 | FileParamUtil.parse_file_provider | validation | def parse_file_provider(uri):
"""Find the file provider for a URI."""
providers = {'gs': job_model.P_GCS, 'file': job_model.P_LOCAL}
# URI scheme detector uses a range up to 30 since none of the IANA
# registered schemes are longer than this.
provider_found = re.match(r'^([A-Za-z][A-Za-z0-9+.-]{0,29... | python | {
"resource": ""
} |
q257263 | FileParamUtil._validate_paths_or_fail | validation | def _validate_paths_or_fail(uri, recursive):
"""Do basic validation of the uri, return the path and filename."""
path, filename = os.path.split(uri)
# dsub could support character ranges ([0-9]) with some more work, but for
# now we assume that basic asterisk wildcards are sufficient. Reject any URI
... | python | {
"resource": ""
} |
q257264 | FileParamUtil.parse_uri | validation | def parse_uri(self, raw_uri, recursive):
"""Return a valid docker_path, uri, and file provider from a flag value."""
# Assume recursive URIs are directory paths.
if recursive:
raw_uri = directory_fmt(raw_uri)
# Get the file provider, validate the raw URI, and rewrite the path
# component of th... | python | {
"resource": ""
} |
q257265 | MountParamUtil._parse_image_uri | validation | def _parse_image_uri(self, raw_uri):
"""Return a valid docker_path from a Google Persistent Disk url."""
# The string replace is so we don't have colons and double slashes in the
# mount path. The idea is the resulting mount path would look like:
# /mnt/data/mount/http/www.googleapis.com/compute/v1/proj... | python | {
"resource": ""
} |
q257266 | MountParamUtil._parse_local_mount_uri | validation | def _parse_local_mount_uri(self, raw_uri):
"""Return a valid docker_path for a local file path."""
raw_uri = directory_fmt(raw_uri)
_, docker_path = _local_uri_rewriter(raw_uri)
local_path = docker_path[len('file'):]
docker_uri = os.path.join(self._relative_path, docker_path)
return local_path, ... | python | {
"resource": ""
} |
q257267 | MountParamUtil._parse_gcs_uri | validation | def _parse_gcs_uri(self, raw_uri):
"""Return a valid docker_path for a GCS bucket."""
# Assume URI is a directory path.
raw_uri = directory_fmt(raw_uri)
_, docker_path = _gcs_uri_rewriter(raw_uri)
docker_uri = os.path.join(self._relative_path, docker_path)
return docker_uri | python | {
"resource": ""
} |
q257268 | MountParamUtil.make_param | validation | def make_param(self, name, raw_uri, disk_size):
"""Return a MountParam given a GCS bucket, disk image or local path."""
if raw_uri.startswith('https://www.googleapis.com/compute'):
# Full Image URI should look something like:
# https://www.googleapis.com/compute/v1/projects/<project>/global/images/
... | python | {
"resource": ""
} |
q257269 | validate_param_name | validation | def validate_param_name(name, param_type):
"""Validate that the name follows posix conventions for env variables."""
# http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_235
#
# 3.235 Name
# In the shell command language, a word consisting solely of underscores,
# digits, and alp... | python | {
"resource": ""
} |
q257270 | validate_bucket_name | validation | def validate_bucket_name(bucket):
"""Validate that the name is a valid GCS bucket."""
if not bucket.startswith('gs://'):
raise ValueError(
'Invalid bucket path "%s". Must start with "gs://".' % bucket)
bucket_name = bucket[len('gs://'):]
if not re.search(r'^\w[\w_\.-]{1,61}\w$', bucket_name):
ra... | python | {
"resource": ""
} |
q257271 | convert_to_label_chars | validation | def convert_to_label_chars(s):
"""Turn the specified name and value into a valid Google label."""
# We want the results to be user-friendly, not just functional.
# So we can't base-64 encode it.
# * If upper-case: lower-case it
# * If the char is not a standard letter or digit. make it a dash
# March ... | python | {
"resource": ""
} |
q257272 | ensure_task_params_are_complete | validation | def ensure_task_params_are_complete(task_descriptors):
"""For each task, ensure that each task param entry is not None."""
for task_desc in task_descriptors:
for param in [
'labels', 'envs', 'inputs', 'outputs', 'input-recursives',
'output-recursives'
]:
if not task_desc.task_params.ge... | python | {
"resource": ""
} |
q257273 | _remove_empty_items | validation | def _remove_empty_items(d, required):
"""Return a new dict with any empty items removed.
Note that this is not a deep check. If d contains a dictionary which
itself contains empty items, those are never checked.
This method exists to make to_serializable() functions cleaner.
We could revisit this some day, ... | python | {
"resource": ""
} |
q257274 | task_view_generator | validation | def task_view_generator(job_descriptor):
"""Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more t... | python | {
"resource": ""
} |
q257275 | numeric_task_id | validation | def numeric_task_id(task_id):
"""Converts a task-id to the numeric task-id.
Args:
task_id: task-id in either task-n or n format
Returns:
n
"""
# This function exists to support the legacy "task-id" format in the "google"
# provider. Google labels originally could not be numeric. When the google
... | python | {
"resource": ""
} |
q257276 | LabelParam._validate_label | validation | def _validate_label(cls, name, value):
"""Raise ValueError if the label is invalid."""
# Rules for labels are described in:
# https://cloud.google.com/compute/docs/labeling-resources#restrictions
# * Keys and values cannot be longer than 63 characters each.
# * Keys and values can only contain low... | python | {
"resource": ""
} |
q257277 | JobDescriptor._from_yaml_v0 | validation | def _from_yaml_v0(cls, job):
"""Populate a JobDescriptor from the local provider's original meta.yaml.
The local job provider had the first incarnation of a YAML file for each
task. That idea was extended here in the JobDescriptor and the local
provider adopted the JobDescriptor.to_yaml() call to write... | python | {
"resource": ""
} |
q257278 | JobDescriptor.from_yaml | validation | def from_yaml(cls, yaml_string):
"""Populate and return a JobDescriptor from a YAML string."""
try:
job = yaml.full_load(yaml_string)
except AttributeError:
# For installations that cannot update their PyYAML version
job = yaml.load(yaml_string)
# If the YAML does not contain a top-le... | python | {
"resource": ""
} |
q257279 | JobDescriptor.find_task_descriptor | validation | def find_task_descriptor(self, task_id):
"""Returns the task_descriptor corresponding to task_id."""
# It is not guaranteed that the index will be task_id - 1 when --tasks is
# used with a min/max range.
for task_descriptor in self.task_descriptors:
if task_descriptor.task_metadata.get('task-id')... | python | {
"resource": ""
} |
q257280 | get_file_environment_variables | validation | def get_file_environment_variables(file_params):
"""Return a dictionary of environment variables for the user container."""
env = {}
for param in file_params:
# We have no cases where the environment variable provided to user
# scripts have a trailing slash, so be sure to always strip it.
# The case t... | python | {
"resource": ""
} |
q257281 | get_job_and_task_param | validation | def get_job_and_task_param(job_params, task_params, field):
"""Returns a dict combining the field for job and task params."""
return job_params.get(field, set()) | task_params.get(field, set()) | python | {
"resource": ""
} |
q257282 | _emit_search_criteria | validation | def _emit_search_criteria(user_ids, job_ids, task_ids, labels):
"""Print the filters used to delete tasks. Use raw flags as arguments."""
print('Delete running jobs:')
print(' user:')
print(' %s\n' % user_ids)
print(' job-id:')
print(' %s\n' % job_ids)
if task_ids:
print(' task-id:')
prin... | python | {
"resource": ""
} |
q257283 | ddel_tasks | validation | def ddel_tasks(provider,
user_ids=None,
job_ids=None,
task_ids=None,
labels=None,
create_time_min=None,
create_time_max=None):
"""Kill jobs or job tasks.
This function separates ddel logic from flag parsing and user output. U... | python | {
"resource": ""
} |
q257284 | get_action_by_id | validation | def get_action_by_id(op, action_id):
"""Return the operation's array of actions."""
actions = get_actions(op)
if actions and 1 <= action_id < len(actions):
return actions[action_id - 1] | python | {
"resource": ""
} |
q257285 | _get_action_by_name | validation | def _get_action_by_name(op, name):
"""Return the value for the specified action."""
actions = get_actions(op)
for action in actions:
if action.get('name') == name:
return action | python | {
"resource": ""
} |
q257286 | get_action_environment | validation | def get_action_environment(op, name):
"""Return the environment for the operation."""
action = _get_action_by_name(op, name)
if action:
return action.get('environment') | python | {
"resource": ""
} |
q257287 | get_action_image | validation | def get_action_image(op, name):
"""Return the image for the operation."""
action = _get_action_by_name(op, name)
if action:
return action.get('imageUri') | python | {
"resource": ""
} |
q257288 | get_event_of_type | validation | def get_event_of_type(op, event_type):
"""Return all events of a particular type."""
events = get_events(op)
if not events:
return None
return [e for e in events if e.get('details', {}).get('@type') == event_type] | python | {
"resource": ""
} |
q257289 | get_last_update | validation | def get_last_update(op):
"""Return the most recent timestamp in the operation."""
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if last_event:
last_update = last_event['timestamp']
if not last_update:
last_update = get_create_time(op)
return last_updat... | python | {
"resource": ""
} |
q257290 | _prepare_summary_table | validation | def _prepare_summary_table(rows):
"""Create a new table that is a summary of the input rows.
All with the same (job-name or job-id, status) go together.
Args:
rows: the input rows, a list of dictionaries.
Returns:
A new row set of summary information.
"""
if not rows:
return []
# We either ... | python | {
"resource": ""
} |
q257291 | lookup_job_tasks | validation | def lookup_job_tasks(provider,
statuses,
user_ids=None,
job_ids=None,
job_names=None,
task_ids=None,
task_attempts=None,
labels=None,
create_time_min=No... | python | {
"resource": ""
} |
q257292 | OutputFormatter.prepare_output | validation | def prepare_output(self, row):
"""Convert types of task fields."""
date_fields = ['last-update', 'create-time', 'start-time', 'end-time']
int_fields = ['task-attempt']
for col in date_fields:
if col in row:
row[col] = self.default_format_date(row[col])
for col in int_fields:
if... | python | {
"resource": ""
} |
q257293 | TextOutput.trim_display_field | validation | def trim_display_field(self, value, max_length):
"""Return a value for display; if longer than max length, use ellipsis."""
if not value:
return ''
if len(value) > max_length:
return value[:max_length - 3] + '...'
return value | python | {
"resource": ""
} |
q257294 | TextOutput.format_pairs | validation | def format_pairs(self, values):
"""Returns a string of comma-delimited key=value pairs."""
return ', '.join(
'%s=%s' % (key, value) for key, value in sorted(values.items())) | python | {
"resource": ""
} |
q257295 | YamlOutput.string_presenter | validation | def string_presenter(self, dumper, data):
"""Presenter to force yaml.dump to use multi-line string style."""
if '\n' in data:
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
else:
return dumper.represent_scalar('tag:yaml.org,2002:str', data) | python | {
"resource": ""
} |
q257296 | get_zones | validation | def get_zones(input_list):
"""Returns a list of zones based on any wildcard input.
This function is intended to provide an easy method for producing a list
of desired zones for a pipeline to run in.
The Pipelines API default zone list is "any zone". The problem with
"any zone" is that it can lead to incurri... | python | {
"resource": ""
} |
q257297 | parse_rfc3339_utc_string | validation | def parse_rfc3339_utc_string(rfc3339_utc_string):
"""Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime.
"""
# The timestamp from the Google Operations are all in RFC3339 format, but
# they are sometime... | python | {
"resource": ""
} |
q257298 | get_operation_full_job_id | validation | def get_operation_full_job_id(op):
"""Returns the job-id or job-id.task-id for the operation."""
job_id = op.get_field('job-id')
task_id = op.get_field('task-id')
if task_id:
return '%s.%s' % (job_id, task_id)
else:
return job_id | python | {
"resource": ""
} |
q257299 | _cancel_batch | validation | def _cancel_batch(batch_fn, cancel_fn, ops):
"""Cancel a batch of operations.
Args:
batch_fn: API-specific batch function.
cancel_fn: API-specific cancel function.
ops: A list of operations to cancel.
Returns:
A list of operations canceled and a list of error messages.
"""
# We define an in... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.