_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12000 | _image_to_data | train | def _image_to_data(img):
"""
Does the work of encoding an image into Base64
"""
# If the image is already encoded in Base64, we have nothing to do here
if "src" not in img.attrs or img["src"].startswith("data:"):
return
elif re.match("https?://", img["src"]):
img_data = _load_url... | python | {
"resource": ""
} |
q12001 | _bake_css | train | def _bake_css(link):
"""
Takes a link element and turns it into an inline style link if applicable
"""
if "href" in link.attrs and (re.search("\.css$", link["href"])) or ("rel" in link.attrs and link["rel"] is "stylesheet") or ("type" in link.attrs and link["type"] is "text/css"):
if re.match("h... | python | {
"resource": ""
} |
q12002 | _bake_script | train | def _bake_script(script):
"""
Takes a script element and bakes it in only if it contains a remote resource
"""
if "src" in script.attrs:
if re.match("https?://", script["src"]):
script_data = _load_url(script["src"]).read()
else:
script_data = _load_file(script["s... | python | {
"resource": ""
} |
q12003 | _load_file | train | def _load_file(path):
"""
Loads a file from the local filesystem
"""
if not os.path.exists(path):
parser.error("{} was not found!".format(path))
if USING_PYTHON2:
mode = "r"
else:
mode = "rb"
try:
f = open(path, mode)
return f
except IOError as ex:... | python | {
"resource": ""
} |
q12004 | _load_url | train | def _load_url(url):
"""
Loads a URL resource from a remote server
"""
try:
response = requests.get(url)
return BytesIO(response.content)
except IOError as ex:
parser.error("{url} could not be loaded remotely! ({ex})".format(url=url, ex=ex)) | python | {
"resource": ""
} |
q12005 | _get_bs4_string | train | def _get_bs4_string(soup):
"""
Outputs a BeautifulSoup object as a string that should hopefully be minimally modified
"""
if len(soup.find_all("script")) == 0:
soup_str = soup.prettify(formatter=None).strip()
else:
soup_str = str(soup.html)
soup_str = re.sub("&", "&", sou... | python | {
"resource": ""
} |
q12006 | bake | train | def bake(src):
"""
Runs the encoder on the given source file
"""
src = os.path.realpath(src)
path = os.path.dirname(src)
filename = os.path.basename(src)
html = _load_file(src).read()
if imghdr.what("", html):
html = "<html><body><img src='{}'/></body></html>".format(cgi.escape(f... | python | {
"resource": ""
} |
q12007 | upload_html | train | def upload_html(destination, html, name=None):
"""
Uploads the HTML to a file on the server
"""
[project, path, n] = parse_destination(destination)
try:
dxfile = dxpy.upload_string(html, media_type="text/html", project=project, folder=path, hidden=True, name=name or None)
return dxfi... | python | {
"resource": ""
} |
q12008 | create_record | train | def create_record(destination, file_ids, width=None, height=None):
"""
Creates a master record for the HTML report; this doesn't contain contain the actual HTML, but reports
are required to be records rather than files and we can link more than one HTML file to a report
"""
[project, path, name] = p... | python | {
"resource": ""
} |
q12009 | save | train | def save(filename, html):
"""
Creates a baked HTML file on the local system
"""
try:
out_file = open(filename, "w")
out_file.write(html)
out_file.close()
except IOError as ex:
parser.error("Could not write baked HTML to local file {name}. ({ex})".format(name=filename,... | python | {
"resource": ""
} |
q12010 | get_size_str | train | def get_size_str(size):
"""
Formats a byte size as a string.
The returned string is no more than 9 characters long.
"""
if size == 0:
magnitude = 0
level = 0
else:
magnitude = math.floor(math.log(size, 10))
level = int(min(math.floor(magnitude // 3), 4))
retu... | python | {
"resource": ""
} |
q12011 | get_ls_l_desc | train | def get_ls_l_desc(desc, include_folder=False, include_project=False):
"""
desc must have at least all the fields given by get_ls_l_desc_fields.
"""
# If you make this method consume an additional field, you must add it to
# get_ls_l_desc_fields above.
if 'state' in desc:
state_len = len(... | python | {
"resource": ""
} |
q12012 | _recursive_cleanup | train | def _recursive_cleanup(foo):
"""
Aggressively cleans up things that look empty.
"""
if isinstance(foo, dict):
for (key, val) in list(foo.items()):
if isinstance(val, dict):
_recursive_cleanup(val)
if val == "" or val == [] or val == {}:
del... | python | {
"resource": ""
} |
q12013 | dump_executable | train | def dump_executable(executable, destination_directory, omit_resources=False, describe_output={}):
"""
Reconstitutes an app, applet, or a workflow into a directory that would
create a functionally identical executable if "dx build" were run on it.
destination_directory will be the root source directory f... | python | {
"resource": ""
} |
q12014 | _gen_helper_dict | train | def _gen_helper_dict(filtered_inputs):
'''
Create a dict of values for the downloaded files. This is similar to the variables created
when running a bash app.
'''
file_key_descs, _ignore = file_load_utils.analyze_bash_vars(
file_load_utils.get_input_json_file(), None)
flattened_dict = ... | python | {
"resource": ""
} |
q12015 | _get_num_parallel_threads | train | def _get_num_parallel_threads(max_threads, num_cores, mem_available_mb):
'''
Ensure at least ~1.2 GB memory per thread, see PTFM-18767
'''
return min(max_threads, num_cores, max(int(mem_available_mb/1200), 1)) | python | {
"resource": ""
} |
q12016 | main | train | def main(**kwargs):
"""
Draw a couple of simple graphs and optionally generate an HTML file to upload them
"""
draw_lines()
draw_histogram()
draw_bar_chart()
destination = "-r /report"
if use_html:
generate_html()
command = "dx-build-report-html {h} {d}".format(h=html_fil... | python | {
"resource": ""
} |
q12017 | draw_lines | train | def draw_lines():
"""
Draws a line between a set of random values
"""
r = numpy.random.randn(200)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(r)
ax.grid(True)
pyplot.savefig(lines_filename) | python | {
"resource": ""
} |
q12018 | generate_html | train | def generate_html():
"""
Generate an HTML file incorporating the images produced by this script
"""
html_file = open(html_filename, "w")
html_file.write("<html><body>")
html_file.write("<h1>Here are some graphs for you!</h1>")
for image in [lines_filename, bars_filename, histogram_filename]:... | python | {
"resource": ""
} |
q12019 | _safe_unicode | train | def _safe_unicode(o):
"""
Returns an equivalent unicode object, trying harder to avoid
dependencies on the Python default encoding.
"""
def clean(s):
return u''.join([c if c in ASCII_PRINTABLE else '?' for c in s])
if USING_PYTHON2:
try:
return unicode(o)
exce... | python | {
"resource": ""
} |
q12020 | _format_exception_message | train | def _format_exception_message(e):
"""
Formats the specified exception.
"""
# Prevent duplication of "AppError" in places that print "AppError"
# and then this formatted string
if isinstance(e, dxpy.AppError):
return _safe_unicode(e)
if USING_PYTHON2:
return unicode(e.__class_... | python | {
"resource": ""
} |
q12021 | run | train | def run(function_name=None, function_input=None):
"""Triggers the execution environment entry point processor.
Use this function in the program entry point code:
.. code-block:: python
import dxpy
@dxpy.entry_point('main')
def hello(i):
pass
dxpy.run()
This m... | python | {
"resource": ""
} |
q12022 | entry_point | train | def entry_point(entry_point_name):
"""Use this to decorate a DNAnexus execution environment entry point.
Example:
.. code-block:: python
@dxpy.entry_point('main')
def hello(i):
pass
"""
def wrap(f):
ENTRY_POINT_TABLE[entry_point_name] = f
@wraps(f)
... | python | {
"resource": ""
} |
q12023 | user_info | train | def user_info(authserver_host=None, authserver_port=None):
"""Returns the result of the user_info call against the specified auth
server.
.. deprecated:: 0.108.0
Use :func:`whoami` instead where possible.
"""
authserver = get_auth_server_name(authserver_host, authserver_port)
return DXH... | python | {
"resource": ""
} |
q12024 | get_job_input_filenames | train | def get_job_input_filenames(job_input_file):
"""Extract list of files, returns a set of directories to create, and
a set of files, with sources and destinations. The paths created are
relative to the input directory.
Note: we go through file names inside arrays, and create a
separate subdirectory f... | python | {
"resource": ""
} |
q12025 | analyze_bash_vars | train | def analyze_bash_vars(job_input_file, job_homedir):
'''
This function examines the input file, and calculates variables to
instantiate in the shell environment. It is called right before starting the
execution of an app in a worker.
For each input key, we want to have
$var
$var_filename
... | python | {
"resource": ""
} |
q12026 | wait_for_a_future | train | def wait_for_a_future(futures, print_traceback=False):
"""
Return the next future that completes. If a KeyboardInterrupt is
received, then the entire process is exited immediately. See
wait_for_all_futures for more notes.
"""
while True:
try:
future = next(concurrent.future... | python | {
"resource": ""
} |
q12027 | _dict_raise_on_duplicates | train | def _dict_raise_on_duplicates(ordered_pairs):
"""
Reject duplicate keys.
"""
d = {}
for k, v in ordered_pairs:
if k in d:
raise ValueError("duplicate key: %r" % (k,))
else:
d[k] = v
return d | python | {
"resource": ""
} |
q12028 | assert_consistent_reg_options | train | def assert_consistent_reg_options(exec_type, json_spec, executable_builder_exeception):
"""
Validates the "regionalOptions" field and verifies all the regions used
in "regionalOptions" have the same options.
"""
reg_options_spec = json_spec.get('regionalOptions')
json_fn = 'dxapp.json' if exec_t... | python | {
"resource": ""
} |
q12029 | _check_suggestions | train | def _check_suggestions(app_json, publish=False):
"""
Examines the specified dxapp.json file and warns about any
violations of suggestions guidelines.
:raises: AppBuilderException for data objects that could not be found
"""
for input_field in app_json.get('inputSpec', []):
for suggestio... | python | {
"resource": ""
} |
q12030 | _check_syntax | train | def _check_syntax(code, lang, temp_dir, enforce=True):
"""
Checks that the code whose text is in CODE parses as LANG.
Raises DXSyntaxError if there is a problem and "enforce" is True.
"""
# This function needs the language to be explicitly set, so we can
# generate an appropriate temp filename.... | python | {
"resource": ""
} |
q12031 | _check_file_syntax | train | def _check_file_syntax(filename, temp_dir, override_lang=None, enforce=True):
"""
Checks that the code in FILENAME parses, attempting to autodetect
the language if necessary.
Raises IOError if the file cannot be read.
Raises DXSyntaxError if there is a problem and "enforce" is True.
"""
de... | python | {
"resource": ""
} |
q12032 | _parse_app_spec | train | def _parse_app_spec(src_dir):
"""Returns the parsed contents of dxapp.json.
Raises either AppBuilderException or a parser error (exit codes 3 or
2 respectively) if this cannot be done.
"""
if not os.path.isdir(src_dir):
parser.error("%s is not a directory" % src_dir)
if not os.path.exis... | python | {
"resource": ""
} |
q12033 | DXApp.install | train | def install(self, **kwargs):
"""
Installs the app in the current user's account.
"""
if self._dxid is not None:
return dxpy.api.app_install(self._dxid, **kwargs)
else:
return dxpy.api.app_install('app-' + self._name, alias=self._alias, **kwargs) | python | {
"resource": ""
} |
q12034 | DXApp.uninstall | train | def uninstall(self, **kwargs):
"""
Uninstalls the app from the current user's account.
"""
if self._dxid is not None:
return dxpy.api.app_uninstall(self._dxid, **kwargs)
else:
return dxpy.api.app_uninstall('app-' + self._name, alias=self._alias, **kwargs) | python | {
"resource": ""
} |
q12035 | DXApp.delete | train | def delete(self, **kwargs):
"""
Removes this app object from the platform.
The current user must be a developer of the app.
"""
if self._dxid is not None:
return dxpy.api.app_delete(self._dxid, **kwargs)
else:
return dxpy.api.app_delete('app-' + s... | python | {
"resource": ""
} |
q12036 | _version_exists | train | def _version_exists(json_spec, name=None, version=None):
"""
Returns True if a global workflow with the given name and version
already exists in the platform and the user has developer rights
to the workflow. "name" and "version" can be passed if we already
made a "describe" API call on the global w... | python | {
"resource": ""
} |
q12037 | _get_validated_stages | train | def _get_validated_stages(stages):
"""
Validates stages of the workflow as a list of dictionaries.
"""
if not isinstance(stages, list):
raise WorkflowBuilderException("Stages must be specified as a list of dictionaries")
validated_stages = []
for index, stage in enumerate(stages):
... | python | {
"resource": ""
} |
q12038 | _validate_json_for_regular_workflow | train | def _validate_json_for_regular_workflow(json_spec, args):
"""
Validates fields used only for building a regular, project-based workflow.
"""
validated = {}
override_project_id, override_folder, override_workflow_name = \
dxpy.executable_builder.get_parsed_destination(args.destination)
va... | python | {
"resource": ""
} |
q12039 | _validate_json_for_global_workflow | train | def _validate_json_for_global_workflow(json_spec, args):
"""
Validates fields used for building a global workflow.
Since building a global workflow is done after all the underlying workflows
are built, which may be time-consuming, we validate as much as possible here.
"""
# TODO: verify the bill... | python | {
"resource": ""
} |
q12040 | _create_temporary_projects | train | def _create_temporary_projects(enabled_regions, args):
"""
Creates a temporary project needed to build an underlying workflow
for a global workflow. Returns a dictionary with region names as keys
and project IDs as values
The regions in which projects will be created can be:
i. regions specifie... | python | {
"resource": ""
} |
q12041 | _build_global_workflow | train | def _build_global_workflow(json_spec, args):
"""
Creates a workflow in a temporary project for each enabled region
and builds a global workflow on the platform based on these workflows.
"""
# First determine in which regions the global workflow needs to be available
enabled_regions = _get_valida... | python | {
"resource": ""
} |
q12042 | _build_or_update_workflow | train | def _build_or_update_workflow(json_spec, args):
"""
Creates or updates a workflow on the platform.
Returns the workflow ID, or None if the workflow cannot be created.
"""
try:
if args.mode == 'workflow':
json_spec = _get_validated_json(json_spec, args)
workflow_id = _... | python | {
"resource": ""
} |
q12043 | _readable_part_size | train | def _readable_part_size(num_bytes):
"Returns the file size in readable form."
B = num_bytes
KB = float(1024)
MB = float(KB * 1024)
GB = float(MB * 1024)
TB = float(GB * 1024)
if B < KB:
return '{0} {1}'.format(B, 'bytes' if B != 1 else 'byte')
elif KB <= B < MB:
return '... | python | {
"resource": ""
} |
q12044 | DXFile.flush | train | def flush(self, multithread=True, **kwargs):
'''
Flushes the internal write buffer.
'''
if self._write_buf.tell() > 0:
data = self._write_buf.getvalue()
self._write_buf = BytesIO()
if multithread:
self._async_upload_part_request(data, ... | python | {
"resource": ""
} |
q12045 | setup_ssh_tunnel | train | def setup_ssh_tunnel(job_id, local_port, remote_port):
"""
Setup an ssh tunnel to the given job-id. This will establish
the port over the given local_port to the given remote_port
and then exit, keeping the tunnel in place until the job is
terminated.
"""
cmd = ['dx', 'ssh', '--suppress-run... | python | {
"resource": ""
} |
q12046 | poll_for_server_running | train | def poll_for_server_running(job_id):
"""
Poll for the job to start running and post the SERVER_READY_TAG.
"""
sys.stdout.write('Waiting for server in {0} to initialize ...'.format(job_id))
sys.stdout.flush()
desc = dxpy.describe(job_id)
# Keep checking until the server has begun or it has fa... | python | {
"resource": ""
} |
q12047 | multi_platform_open | train | def multi_platform_open(cmd):
"""
Take the given command and use the OS to automatically open the appropriate
resource. For instance, if a URL is provided, this will have the OS automatically
open the URL in the default web browser.
"""
if platform == "linux" or platform == "linux2":
cm... | python | {
"resource": ""
} |
q12048 | get_notebook_app_versions | train | def get_notebook_app_versions():
"""
Get the valid version numbers of the notebook app.
"""
notebook_apps = dxpy.find_apps(name=NOTEBOOK_APP, all_versions=True)
versions = [str(dxpy.describe(app['id'])['version']) for app in notebook_apps]
return versions | python | {
"resource": ""
} |
q12049 | run_notebook | train | def run_notebook(args, ssh_config_check):
"""
Launch the notebook server.
"""
# Check that ssh is setup. Currently notebooks require ssh for tunelling.
ssh_config_check()
if args.only_check_config:
return
# If the user requested a specific version of the notebook server,
# get ... | python | {
"resource": ""
} |
q12050 | ModelDatastoreInputReader._validate_filters | train | def _validate_filters(cls, filters, model_class):
"""Validate user supplied filters.
Validate filters are on existing properties and filter values
have valid semantics.
Args:
filters: user supplied filters. Each filter should be a list or tuple of
format (<property_name_as_str>, <query_o... | python | {
"resource": ""
} |
q12051 | _normalize_entity | train | def _normalize_entity(value):
"""Return an entity from an entity or model instance."""
if ndb is not None and isinstance(value, ndb.Model):
return None
if getattr(value, "_populate_internal_entity", None):
return value._populate_internal_entity()
return value | python | {
"resource": ""
} |
q12052 | _normalize_key | train | def _normalize_key(value):
"""Return a key from an entity, model instance, key, or key string."""
if ndb is not None and isinstance(value, (ndb.Model, ndb.Key)):
return None
if getattr(value, "key", None):
return value.key()
elif isinstance(value, basestring):
return datastore.Key(value)
else:
... | python | {
"resource": ""
} |
q12053 | _ItemList.append | train | def append(self, item):
"""Add new item to the list.
If needed, append will first flush existing items and clear existing items.
Args:
item: an item to add to the list.
"""
if self.should_flush():
self.flush()
self.items.append(item) | python | {
"resource": ""
} |
q12054 | _ItemList.flush | train | def flush(self):
"""Force a flush."""
if not self.items:
return
retry = 0
options = {"deadline": DATASTORE_DEADLINE}
while retry <= self.__timeout_retries:
try:
self.__flush_function(self.items, options)
self.clear()
break
except db.Timeout, e:
logg... | python | {
"resource": ""
} |
q12055 | _MutationPool.put | train | def put(self, entity):
"""Registers entity to put to datastore.
Args:
entity: an entity or model instance to put.
"""
actual_entity = _normalize_entity(entity)
if actual_entity is None:
return self.ndb_put(entity)
self.puts.append(actual_entity) | python | {
"resource": ""
} |
q12056 | _MutationPool.delete | train | def delete(self, entity):
"""Registers entity to delete from datastore.
Args:
entity: an entity, model instance, or key to delete.
"""
key = _normalize_key(entity)
if key is None:
return self.ndb_delete(entity)
self.deletes.append(key) | python | {
"resource": ""
} |
q12057 | _MutationPool._flush_puts | train | def _flush_puts(self, items, options):
"""Flush all puts to datastore."""
datastore.Put(items, config=self._create_config(options)) | python | {
"resource": ""
} |
q12058 | _MutationPool._flush_ndb_puts | train | def _flush_ndb_puts(self, items, options):
"""Flush all NDB puts to datastore."""
assert ndb is not None
ndb.put_multi(items, config=self._create_config(options)) | python | {
"resource": ""
} |
q12059 | _MutationPool._create_config | train | def _create_config(self, options):
"""Creates datastore Config.
Returns:
A datastore_rpc.Configuration instance.
"""
return datastore.CreateConfig(deadline=options["deadline"],
force_writes=self.force_writes) | python | {
"resource": ""
} |
q12060 | AbstractKeyRangeIterator.to_json | train | def to_json(self):
"""Serializes all states into json form.
Returns:
all states in json-compatible map.
"""
cursor = self._get_cursor()
cursor_object = False
if cursor and isinstance(cursor, datastore_query.Cursor):
cursor = cursor.to_websafe_string()
cursor_object = True
... | python | {
"resource": ""
} |
q12061 | AbstractKeyRangeIterator.from_json | train | def from_json(cls, json):
"""Reverse of to_json."""
obj = cls(key_range.KeyRange.from_json(json["key_range"]),
model.QuerySpec.from_json(json["query_spec"]))
cursor = json["cursor"]
# lint bug. Class method can access protected fields.
# pylint: disable=protected-access
if cursor a... | python | {
"resource": ""
} |
q12062 | find_mapreduce_yaml | train | def find_mapreduce_yaml(status_file=__file__):
"""Traverse directory trees to find mapreduce.yaml file.
Begins with the location of status.py and then moves on to check the working
directory.
Args:
status_file: location of status.py, overridable for testing purposes.
Returns:
the path of mapreduce.... | python | {
"resource": ""
} |
q12063 | _find_mapreduce_yaml | train | def _find_mapreduce_yaml(start, checked):
"""Traverse the directory tree identified by start until a directory already
in checked is encountered or the path of mapreduce.yaml is found.
Checked is present both to make loop termination easy to reason about and so
that the same directories do not get rechecked.
... | python | {
"resource": ""
} |
q12064 | parse_mapreduce_yaml | train | def parse_mapreduce_yaml(contents):
"""Parses mapreduce.yaml file contents.
Args:
contents: mapreduce.yaml file contents.
Returns:
MapReduceYaml object with all the data from original file.
Raises:
errors.BadYamlError: when contents is not a valid mapreduce.yaml file.
"""
try:
builder = y... | python | {
"resource": ""
} |
q12065 | get_mapreduce_yaml | train | def get_mapreduce_yaml(parse=parse_mapreduce_yaml):
"""Locates mapreduce.yaml, loads and parses its info.
Args:
parse: Used for testing.
Returns:
MapReduceYaml object.
Raises:
errors.BadYamlError: when contents is not a valid mapreduce.yaml file or the
file is missing.
"""
mr_yaml_path = ... | python | {
"resource": ""
} |
q12066 | MapReduceYaml.to_dict | train | def to_dict(mapreduce_yaml):
"""Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.
Re... | python | {
"resource": ""
} |
q12067 | _sort_records_map | train | def _sort_records_map(records):
"""Map function sorting records.
Converts records to KeyValue protos, sorts them by key and writes them
into new GCS file. Creates _OutputFile entity to record resulting
file name.
Args:
records: list of records which are serialized KeyValue protos.
"""
ctx = context.... | python | {
"resource": ""
} |
q12068 | _merge_map | train | def _merge_map(key, values, partial):
"""A map function used in merge phase.
Stores (key, values) into KeyValues proto and yields its serialization.
Args:
key: values key.
values: values themselves.
partial: True if more values for this key will follow. False otherwise.
Yields:
The proto.
"... | python | {
"resource": ""
} |
q12069 | _hashing_map | train | def _hashing_map(binary_record):
"""A map function used in hash phase.
Reads KeyValue from binary record.
Args:
binary_record: The binary record.
Yields:
The (key, value).
"""
proto = kv_pb.KeyValue()
proto.ParseFromString(binary_record)
yield (proto.key(), proto.value()) | python | {
"resource": ""
} |
q12070 | _MergingReader.split_input | train | def split_input(cls, mapper_spec):
"""Split input into multiple shards."""
filelists = mapper_spec.params[cls.FILES_PARAM]
max_values_count = mapper_spec.params.get(cls.MAX_VALUES_COUNT_PARAM, -1)
max_values_size = mapper_spec.params.get(cls.MAX_VALUES_SIZE_PARAM, -1)
return [cls([0] * len(files), m... | python | {
"resource": ""
} |
q12071 | _MergingReader.validate | train | def validate(cls, mapper_spec):
"""Validate reader parameters in mapper_spec."""
if mapper_spec.input_reader_class() != cls:
raise errors.BadReaderParamsError("Input reader class mismatch")
params = mapper_spec.params
if cls.FILES_PARAM not in params:
raise errors.BadReaderParamsError("Missi... | python | {
"resource": ""
} |
q12072 | _HashingGCSOutputWriter.validate | train | def validate(cls, mapper_spec):
"""Validates mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec to validate.
Raises:
BadWriterParamsError: when Output writer class mismatch.
"""
if mapper_spec.output_writer_class() != cls:
raise errors.BadWriterParamsError("O... | python | {
"resource": ""
} |
q12073 | _HashingGCSOutputWriter.to_json | train | def to_json(self):
"""Returns writer state to serialize in json.
Returns:
A json-izable version of the OutputWriter state.
"""
# Use the member variable (since we don't have access to the context) to
# flush each pool to minimize the size of each filehandle before we
# serialize it.
f... | python | {
"resource": ""
} |
q12074 | JobConfig._get_mapper_params | train | def _get_mapper_params(self):
"""Converts self to model.MapperSpec.params."""
reader_params = self.input_reader_cls.params_to_json(
self.input_reader_params)
# TODO(user): Do the same for writer params.
return {"input_reader": reader_params,
"output_writer": self.output_writer_params... | python | {
"resource": ""
} |
q12075 | JobConfig._get_mapper_spec | train | def _get_mapper_spec(self):
"""Converts self to model.MapperSpec."""
# pylint: disable=g-import-not-at-top
from mapreduce import model
return model.MapperSpec(
handler_spec=util._obj_to_path(self.mapper),
input_reader_spec=util._obj_to_path(self.input_reader_cls),
params=self._g... | python | {
"resource": ""
} |
q12076 | JobConfig._get_mr_params | train | def _get_mr_params(self):
"""Converts self to model.MapreduceSpec.params."""
return {"force_writes": self._force_writes,
"done_callback": self.done_callback_url,
"user_params": self.user_params,
"shard_max_attempts": self.shard_max_attempts,
"task_max_attempts": s... | python | {
"resource": ""
} |
q12077 | JobConfig._get_default_mr_params | train | def _get_default_mr_params(cls):
"""Gets default values for old API."""
cfg = cls(_lenient=True)
mr_params = cfg._get_mr_params()
mr_params["api_version"] = 0
return mr_params | python | {
"resource": ""
} |
q12078 | JobConfig._to_map_job_config | train | def _to_map_job_config(cls,
mr_spec,
# TODO(user): Remove this parameter after it can be
# read from mr_spec.
queue_name):
"""Converts model.MapreduceSpec back to JobConfig.
This method allows our internal metho... | python | {
"resource": ""
} |
q12079 | RecordsWriter.__write_record | train | def __write_record(self, record_type, data):
"""Write single physical record."""
length = len(data)
crc = crc32c.crc_update(crc32c.CRC_INIT, [record_type])
crc = crc32c.crc_update(crc, data)
crc = crc32c.crc_finalize(crc)
self.__writer.write(
struct.pack(_HEADER_FORMAT, _mask_crc(crc),... | python | {
"resource": ""
} |
q12080 | RecordsWriter.write | train | def write(self, data):
"""Write single record.
Args:
data: record data to write as string, byte array or byte sequence.
"""
block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE
if block_remaining < _HEADER_LENGTH:
# Header won't fit into remainder
self.__writer.write('\x... | python | {
"resource": ""
} |
q12081 | RecordsWriter._pad_block | train | def _pad_block(self):
"""Pad block with 0.
Pad current block with 0. Reader will simply treat these as corrupted
record and skip the block.
This method is idempotent.
"""
pad_length = _BLOCK_SIZE - self.__position % _BLOCK_SIZE
if pad_length and pad_length != _BLOCK_SIZE:
self.__writ... | python | {
"resource": ""
} |
q12082 | RecordsReader.__try_read_record | train | def __try_read_record(self):
"""Try reading a record.
Returns:
(data, record_type) tuple.
Raises:
EOFError: when end of file was reached.
InvalidRecordError: when valid record could not be read.
"""
block_remaining = _BLOCK_SIZE - self.__reader.tell() % _BLOCK_SIZE
if block_re... | python | {
"resource": ""
} |
q12083 | RecordsReader.__sync | train | def __sync(self):
"""Skip reader to the block boundary."""
pad_length = _BLOCK_SIZE - self.__reader.tell() % _BLOCK_SIZE
if pad_length and pad_length != _BLOCK_SIZE:
data = self.__reader.read(pad_length)
if len(data) != pad_length:
raise EOFError('Read %d bytes instead of %d' %
... | python | {
"resource": ""
} |
q12084 | RecordsReader.read | train | def read(self):
"""Reads record from current position in reader.
Returns:
original bytes stored in a single record.
"""
data = None
while True:
last_offset = self.tell()
try:
(chunk, record_type) = self.__try_read_record()
if record_type == _RECORD_TYPE_NONE:
... | python | {
"resource": ""
} |
q12085 | MapperPipeline.run | train | def run(self,
job_name,
handler_spec,
input_reader_spec,
output_writer_spec=None,
params=None,
shards=None,
base_path=None):
"""Start a mapreduce job.
Args:
job_name: mapreduce name. Only for display purpose.
handler_spec: fully ... | python | {
"resource": ""
} |
q12086 | MapperPipeline.callback | train | def callback(self):
"""Callback after this async pipeline finishes."""
if self.was_aborted:
return
mapreduce_id = self.outputs.job_id.value
mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id)
if mapreduce_state.result_status != model.MapreduceState.RESULT_SUCCESS:
self.re... | python | {
"resource": ""
} |
q12087 | start_map | train | def start_map(name,
handler_spec,
reader_spec,
mapper_parameters,
shard_count=None,
output_writer_spec=None,
mapreduce_parameters=None,
base_path=None,
queue_name=None,
eta=None,
c... | python | {
"resource": ""
} |
q12088 | Job.get_status | train | def get_status(self):
"""Get status enum.
Returns:
One of the status enum.
"""
self.__update_state()
if self._state.active:
return self.RUNNING
else:
return self._state.result_status | python | {
"resource": ""
} |
q12089 | Job.get_counter | train | def get_counter(self, counter_name, default=0):
"""Get the value of the named counter from this job.
When a job is running, counter values won't be very accurate.
Args:
counter_name: name of the counter in string.
default: default value if the counter doesn't exist.
Returns:
Value i... | python | {
"resource": ""
} |
q12090 | Job.get_outputs | train | def get_outputs(self):
"""Get outputs of this job.
Should only call if status is SUCCESS.
Yields:
Iterators, one for each shard. Each iterator is
from the argument of map_job.output_writer.commit_output.
"""
assert self.SUCCESS == self.get_status()
ss = model.ShardState.find_all_by... | python | {
"resource": ""
} |
q12091 | Job.submit | train | def submit(cls, job_config, in_xg_transaction=False):
"""Submit the job to run.
Args:
job_config: an instance of map_job.MapJobConfig.
in_xg_transaction: controls what transaction scope to use to start this MR
job. If True, there has to be an already opened cross-group transaction
s... | python | {
"resource": ""
} |
q12092 | Job.__update_state | train | def __update_state(self):
"""Fetches most up to date state from db."""
# Only if the job was not in a terminal state.
if self._state.active:
self._state = self.__get_state_by_id(self.job_config.job_id) | python | {
"resource": ""
} |
q12093 | Job.__get_state_by_id | train | def __get_state_by_id(cls, job_id):
"""Get job state by id.
Args:
job_id: job id.
Returns:
model.MapreduceState for the job.
Raises:
ValueError: if the job state is missing.
"""
state = model.MapreduceState.get_by_job_id(job_id)
if state is None:
raise ValueError("... | python | {
"resource": ""
} |
q12094 | Job.__create_and_save_state | train | def __create_and_save_state(cls, job_config, mapreduce_spec):
"""Save map job state to datastore.
Save state to datastore so that UI can see it immediately.
Args:
job_config: map_job.JobConfig.
mapreduce_spec: model.MapreduceSpec.
Returns:
model.MapreduceState for this job.
"""
... | python | {
"resource": ""
} |
q12095 | Job.__add_kickoff_task | train | def __add_kickoff_task(cls, job_config, mapreduce_spec):
"""Add kickoff task to taskqueue.
Args:
job_config: map_job.JobConfig.
mapreduce_spec: model.MapreduceSpec,
"""
params = {"mapreduce_id": job_config.job_id}
# Task is not named so that it can be added within a transaction.
kic... | python | {
"resource": ""
} |
q12096 | JsonMixin.to_json_str | train | def to_json_str(self):
"""Convert data to json string representation.
Returns:
json representation as string.
"""
_json = self.to_json()
try:
return json.dumps(_json, sort_keys=True, cls=JsonEncoder)
except:
logging.exception("Could not serialize JSON: %r", _json)
raise | python | {
"resource": ""
} |
q12097 | JsonMixin.from_json_str | train | def from_json_str(cls, json_str):
"""Convert json string representation into class instance.
Args:
json_str: json representation as string.
Returns:
New instance of the class with data loaded from json string.
"""
return cls.from_json(json.loads(json_str, cls=JsonDecoder)) | python | {
"resource": ""
} |
q12098 | JsonProperty.get_value_for_datastore | train | def get_value_for_datastore(self, model_instance):
"""Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value.
"""
value = super(JsonProperty, self).get_value_for_datastore(model_instance)
if not value:
return None
... | python | {
"resource": ""
} |
q12099 | JsonProperty.make_value_from_datastore | train | def make_value_from_datastore(self, value):
"""Convert value from datastore representation.
Args:
value: datastore value.
Returns:
value to store in the model.
"""
if value is None:
return None
_json = json.loads(value, cls=JsonDecoder)
if self.data_type == dict:
r... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.