code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.append_volume(runtime, volume.resolved, volume.target, writable=True) else: if host_outdir_tgt: # shortcut, just copy to the output directory # which is already going to be mounted if not os.path.exists(o...
def add_writable_file_volume(self, runtime, # type: List[Text] volume, # type: MapperEnt host_outdir_tgt, # type: Optional[Text] tmpdir_prefix # type: Text ...
Append a writable file mapping to the runtime option list.
2.973884
2.772563
1.072612
# Synthetic directory that needs creating first if not host_outdir_tgt: tmp_dir, tmp_prefix = os.path.split(tmpdir_prefix) new_dir = os.path.join( tempfile.mkdtemp(prefix=tmp_prefix, dir=tmp_dir), os.path.basename(volume.tar...
def add_writable_directory_volume(self, runtime, # type: List[Text] volume, # type: MapperEnt host_outdir_tgt, # type: Optional[Text] tmpdir_prefix ...
Append a writable directory mapping to the runtime option list.
2.15505
2.24123
0.961548
load = load_tool.load_tool(cwl, self.loading_context) if isinstance(load, int): raise Exception("Error loading tool") return Callable(load, self)
def make(self, cwl)
Instantiate a CWL object from a CWl document.
9.447151
8.99241
1.050569
optional = False if 'null' in inptype: inptype.remove('null') optional = True if len(inptype) == 1: example, comment = generate_example_input(inptype[0], default) if optional: if comment: comment = u"{} (optional...
def generate_example_input(inptype, # type: Any default # type: Optional[Any] ): # type: (...) -> Tuple[Any, Text] example = None comment = u"" defaults = {u'null': 'null', u'Any': 'null', u'boolean': False, ...
Converts a single input schema into an example.
2.106876
2.063619
1.020961
if isinstance(entry, string_types): if '#' in entry: _, input_type_name = entry.split('#') else: input_type_name = entry if input_type_name in schema_defs: entry = input_types[index] = schema_defs[input_type_name] if isi...
def realize_input_schema(input_types, # type: MutableSequence[Dict[Text, Any]] schema_defs # type: Dict[Text, Any] ): # type: (...) -> MutableSequence[Dict[Text, Any]] for index, entry in enumerate(input_types)
Replace references to named typed with the actual types.
1.839013
1.763735
1.042681
# type: (Process) -> Dict[Text, Any] template = yaml.comments.CommentedMap() for inp in realize_input_schema(tool.tool["inputs"], tool.schemaDefs): name = shortname(inp["id"]) value, comment = generate_example_input( inp['type'], inp.get('default', None)) template.in...
def generate_input_template(tool)
Generate an example input object for the given CWL process.
7.278247
6.29298
1.156566
uri = obj.get("location", obj.get("path")) if ":" in uri.split("/")[0] and not uri.startswith("file://"): pass else: if uri.startswith("file://"): uri = uri_file_path(uri) obj["location"] = os.path.relpath(uri, base)
def make_relative(base, obj)
Relativize the location URI of a File or Directory object.
4.116307
3.696947
1.113434
base = basedir if basedir else os.path.dirname(uri_file_path(str(uri))) elif relative_deps == "cwd": base = os.getcwd() visit_class(deps, ("File", "Directory"), functools.partial( make_relative, base)) stdout.write(json_dumps(deps, indent=4))
def printdeps(obj, # type: Mapping[Text, Any] document_loader, # type: Loader stdout, # type: Union[TextIO, StreamWriter] relative_deps, # type: bool uri, # type: Text basedir=None, # type: Text ...
Print a JSON representation of the dependencies of the CWL document.
6.402553
5.893164
1.086437
return document_loader.fetch(document_loader.fetcher.urljoin(base, uri)) sfs = scandeps( basedir if basedir else uri, obj, {"$import", "run"}, {"$include", "$schemas", "location"}, loadref, nestdirs=nestdirs) if sfs is not None: deps["secondaryFiles"] = sfs return deps
def find_deps(obj, # type: Mapping[Text, Any] document_loader, # type: Loader uri, # type: Text basedir=None, # type: Text nestdirs=True # type: bool ): # type: (...) -> Dict[Text, Any] deps = {"class": "Fi...
Find the dependencies of the CWL document.
6.033099
6.139338
0.982695
return json_dumps(packed, indent=4) return json_dumps(packed["$graph"][0], indent=4)
def print_pack(document_loader, # type: Loader processobj, # type: CommentedMap uri, # type: Text metadata # type: Dict[Text, Any] ): # type (...) -> Text packed = pack(document_loader, processobj, uri, metadata) if le...
Return a CWL serialization of the CWL document in JSON.
3.555724
3.23725
1.098378
default_container = get_container_from_software_requirements( use_biocontainers, builder) return default_container
def find_default_container(builder, # type: HasReqsHints default_container=None, # type: Text use_biocontainers=None, # type: bool ): # type: (...) -> Optional[Text] if not default_container and use_biocontaine...
Default finder for default containers.
10.447235
6.332307
1.649831
# type: (...) -> None signal.signal(signal.SIGTERM, _signal_handler) try: sys.exit(main(*args, **kwargs)) finally: _terminate_processes()
def run(*args, **kwargs)
Run cwltool.
4.073208
3.92281
1.038339
raise Exception("Secret store only accepts strings") if value not in self.secrets: placeholder = "(secret-%s)" % Text(uuid.uuid4()) self.secrets[placeholder] = value return placeholder return value
def add(self, value): # type: (Text) -> Text if not isinstance(value, string_types)
Add the given value to the store. Returns a placeholder value to use until the real value is needed.
9.827287
7.405854
1.326962
# type: (List[Text], MutableMapping[Text, Any]) -> None for j in job: if j in secrets: job[j] = self.add(job[j])
def store(self, secrets, job)
Sanitize the job object of any of the given secrets.
5.693315
4.804946
1.184886
for k in self.secrets: if k in value: return True elif isinstance(value, MutableMapping): for this_value in value.values(): if self.has_secret(this_value): return True elif isinstance(value, MutableSequence):...
def has_secret(self, value): # type: (Any) -> bool if isinstance(value, string_types)
Test if the provided document has any of our secrets.
2.275934
2.020026
1.126685
for key, this_value in self.secrets.items(): value = value.replace(key, this_value) elif isinstance(value, MutableMapping): return {k: self.retrieve(v) for k, v in value.items()} elif isinstance(value, MutableSequence): return [self.retrieve(v) for k, ...
def retrieve(self, value): # type: (Any) -> Any if isinstance(value, string_types)
Replace placeholders with their corresponding secrets.
2.865964
2.212635
1.295272
# type: () -> Tuple[Text,Text] username = getuser() try: if onWindows(): get_user_name = ctypes.windll.secur32.GetUserNameExW # type: ignore size = ctypes.pointer(ctypes.c_ulong(0)) get_user_name(3, None, size) name_buffer = ctypes.create_unicod...
def _whoami()
Return the current operating system account as (username, fullname).
3.082693
2.793751
1.103424
# type: (Text) -> bool # Strip - nums = numeric_string.replace("-", "") total = 0 # skip last (check)digit for num in nums[:-1]: digit = int(num) total = (total+digit)*2 remainder = total % 11 result = (12-remainder) % 11 if result == 10: checkdigit = "X"...
def _check_mod_11_2(numeric_string)
Validate numeric_string for its MOD-11-2 checksum. Any "-" in the numeric_string are ignored. The last digit of numeric_string is assumed to be the checksum, 0-9 or X. See ISO/IEC 7064:2003 and https://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier
4.28021
4.45548
0.960662
raise ValueError(u'ORCID cannot be unspecified') # Liberal in what we consume, e.g. ORCID.org/0000-0002-1825-009x orcid = orcid.lower() match = re.match( # Note: concatinated r"" r"" below so we can add comments to pattern # Optional hostname, with or without protocol r"(htt...
def _valid_orcid(orcid): # type: (Optional[Text]) -> Text if orcid is None or not orcid
Ensure orcid is a valid ORCID identifier. The string must be equivalent to one of these forms: 0000-0002-1825-0097 orcid.org/0000-0002-1825-0097 http://orcid.org/0000-0002-1825-0097 https://orcid.org/0000-0002-1825-0097 If the ORCID number or prefix is invalid, a ValueError is raised. Th...
5.22257
5.058656
1.032403
temp_location = os.path.join(os.path.dirname(dst_file.name), str(uuid.uuid4())) try: os.rename(dst_file.name, temp_location) os.link(src_file.name, dst_file.name) dst_file = None os.unlink(temp_location) except ...
def checksum_copy(src_file, # type: IO dst_file=None, # type: Optional[IO] hasher=Hasher, # type: Callable[[], Any] buffersize=1024*1024 # type: int ): # type: (...) -> str # TODO: Use hashlib.new(Hasher_str) instead...
Compute checksums while copying a file.
2.081784
2.076236
1.002673
# type: (Any, Any) -> Any if not hasattr(job, "tool"): # direct command line tool execution return job_order_object customised_job = {} # new job object for RO for each, i in enumerate(job.tool["inputs"]): with SourceLine(job.tool["inputs"], each, WorkflowException, ...
def copy_job_order(job, job_order_object)
Create copy of job object for provenance.
5.46123
5.191853
1.051885
# record provenance of independent commandline tool executions self.prospective_prov(job) customised_job = copy_job_order(job, job_order_object) self.used_artefacts(customised_job, self.workflow_run_uri) research_obj.create_job(customised_job, job) eli...
def evaluate(self, process, # type: Process job, # type: Any job_order_object, # type: Dict[Text, Text] research_obj # type: ResearchObject ): # type: (...) -> None if not hasattr(process...
Evaluate the nature of job
4.956556
4.875307
1.016665
# type: (Text, datetime.datetime, Optional[str]) -> str if process_run_id is None: process_run_id = uuid.uuid4().urn prov_label = "Run of workflow/packed.cwl#main/" + process_name self.document.activity( process_run_id, None, None, {provM.PROV...
def start_process(self, process_name, when, process_run_id=None)
Record the start of each Process.
4.348245
4.33716
1.002556
# type: (Union[Text, str]) -> Tuple[ProvEntity,Text] byte_s = BytesIO(str(value).encode(ENCODING)) data_file = self.research_object.add_data_file(byte_s, content_type=TEXT_PLAIN) checksum = posixpath.basename(data_file) # FIXME: Don't naively assume add_data_file uses ha...
def declare_string(self, value)
Save as string in UTF-8.
7.314722
7.363397
0.99339
base += "/" + name for key, value in job_order.items(): prov_role = self.wf_ns["%s/%s" % (base, key)] entity = self.declare_artefact(value) self.document.used( process_run_id, entity, datetime.datetime.now(), None, {"prov:role": pro...
def used_artefacts(self, job_order, # type: Dict process_run_id, # type: str name=None # type: str ): # type: (...) -> None # FIXME: Use workflow name in packed.cwl, "main" is wrong ...
Add used() for each data artefact.
7.318515
6.001051
1.219539
entity = self.declare_artefact(value) if name is not None: name = urllib.parse.quote(str(name), safe=":/,#") # FIXME: Probably not "main" in nested workflows role = self.wf_ns["main/%s/%s" % (name, output)] else: role = ...
def generate_output_prov(self, final_output, # type: Dict[Text, Any] process_run_id, # type: Optional[str] name # type: Optional[Text] ): # type: (...) -> None # Timestam...
Call wasGeneratedBy() for each output,copy the files into the RO.
5.904745
5.462313
1.080997
# type: (Any) -> None if not hasattr(job, "steps"): # direct command line tool execution self.document.entity( "wf:main", {provM.PROV_TYPE: WFDESC["Process"], "prov:type": PROV["Plan"], "prov:label":...
def prospective_prov(self, job)
Create prospective prov recording as wfdesc prov:Plan.
3.875356
3.536282
1.095884
# type: (str, List[Identifier]) -> None # NOTE: The below will only work if the corresponding metadata/provenance arcp URI # is a pre-registered namespace in the PROV Document attribs = [(PROV["has_provenance"], prov_id) for prov_id in prov_ids] self.document.activity(ac...
def activity_has_provenance(self, activity, prov_ids)
Add http://www.w3.org/TR/prov-aq/ relations to nested PROV files.
9.738184
9.482772
1.026934
# type: (Optional[Text]) -> List[Identifier] # NOTE: Relative posix path if name is None: # master workflow, fixed filenames filename = "primary.cwlprov" else: # ASCII-friendly filename, avoiding % as we don't want %2520 in manifest.json ...
def finalize_prov_profile(self, name)
Transfer the provenance related files to the RO.
3.173836
3.170161
1.001159
# TODO: \n or \r\n ? bag_it_file.write(u"BagIt-Version: 0.97\n") bag_it_file.write(u"Tag-File-Character-Encoding: %s\n" % ENCODING)
def _initialize_bagit(self): # type: () -> None self.self_check() bagit = os.path.join(self.folder, "bagit.txt") # encoding: always UTF-8 (although ASCII would suffice here) # newline: ensure LF also on Windows with open(bagit, "w", encoding=ENCODING, newline='\n') as b...
Write fixed bagit header.
2.586115
2.307371
1.120806
self.full_name = fullname document.add_namespace(UUID) document.add_namespace(ORCID) document.add_namespace(FOAF) account = document.agent( ACCOUNT_UUID, {provM.PROV_TYPE: FOAF["OnlineAccount"], "prov:label": username, ...
def user_provenance(self, document): # type: (ProvDocument) -> None self.self_check() (username, fullname) = _whoami() if not self.full_name
Add the user provenance.
7.217757
6.901415
1.045837
# type: (Text, Optional[str]) -> IO self.self_check() # For some reason below throws BlockingIOError #fp = BufferedWriter(WritableBagFile(self, path)) bag_file = cast(IO, WritableBagFile(self, path)) if encoding is not None: # encoding: match Tag-File...
def write_bag_file(self, path, encoding=ENCODING)
Write the bag file into our research object.
9.750151
9.822235
0.992661
# type: (Text, datetime.datetime) -> None self.self_check() checksums = {} # Read file to calculate its checksum if os.path.isdir(path): return # FIXME: do the right thing for directories with open(path, "rb") as tag_file: # FI...
def add_tagfile(self, path, timestamp=None)
Add tag files to our research object.
4.725503
4.677817
1.010194
# type: (str, List[str], str) -> str self.self_check() curr = self.base_uri + METADATA + "/" content = [c.replace(curr, "").replace(self.base_uri, "../") for c in content] uri = uuid.uuid4().urn ann = { "uri": uri, "abou...
def add_annotation(self, about, content, motivated_by="oa:describing")
Cheap URI relativize for current directory and /.
4.299294
4.129321
1.041163
# type: (MutableMapping[Text, Any]) -> None self.self_check() for key, value in prov_dep.items(): if key == "location" and value.split("/")[-1]: filename = value.split("/")[-1] path = os.path.join(self.folder, SNAPSHOT, filename) ...
def generate_snapshot(self, prov_dep)
Copy all of the CWL files to the snapshot/ directory.
4.072756
3.715724
1.096087
# YAML is always UTF8, but json.dumps gives us str in py2 write_pack.write(packed.encode(ENCODING)) _logger.debug(u"[provenance] Added packed workflow: %s", rel_path)
def packed_workflow(self, packed): # type: (Text) -> None self.self_check() rel_path = posixpath.join(_posix_path(WORKFLOW), "packed.cwl") # Write as binary with self.write_bag_file(rel_path, encoding=None) as write_pack
Pack CWL description to generate re-runnable CWL object in RO.
11.485443
13.286945
0.864416
def has_data_file(self, sha1hash): # type: (str) -> bool folder = os.path.join(self.folder, DATA, sha1hash[0:2]) hash_path = os.path.join(folder, sha1hash) return os.path.isfile(hash_path)
Confirms the presence of the given file in the RO.
null
null
null
# type: (IO, Optional[datetime.datetime], Optional[str]) -> Text self.self_check() tmp_dir, tmp_prefix = os.path.split(self.temp_prefix) with tempfile.NamedTemporaryFile( prefix=tmp_prefix, dir=tmp_dir, delete=False) as tmp: checksum = checksum_copy(f...
def add_data_file(self, from_fp, timestamp=None, content_type=None)
Copy inputs to data/ folder.
4.539057
4.535145
1.000863
# type: (Text, Dict[str,str]) -> None self.self_check() if posixpath.isabs(rel_path): raise ValueError("rel_path must be relative: %s" % rel_path) if posixpath.commonprefix(["data/", rel_path]) == "data/": # payload file, go to manifest manif...
def add_to_manifest(self, rel_path, checksums)
Add files to the research object manifest.
5.800461
5.762374
1.00661
return dict(o) if is_output: rel_path = posixpath.join(_posix_path(WORKFLOW), "primary-output.json") else: rel_path = posixpath.join(_posix_path(WORKFLOW), "primary-job.json") j = json_dumps(copied, indent=4, ensure_ascii=False, default=jdefault) with ...
def create_job(self, builder_job, # type: Dict[Text, Any] wf_job=None, # type: Callable[[Dict[Text, Text], Callable[[Any, Any], Any], RuntimeContext], Generator[Any, None, None]] is_output=False ): # type: (...) -> Dict #TODO cust...
Generate the new job object with RO specific relative paths.
3.609265
3.550532
1.016542
# type: (Dict[Any, Any]) -> None # Base case - we found a File we need to update _logger.debug(u"[provenance] Relativising: %s", structure) if isinstance(structure, MutableMapping): if structure.get("class") == "File": relative_path = None ...
def _relativise_files(self, structure)
Save any file objects into the RO and update the local paths.
5.240483
5.105295
1.02648
# type: (Optional[str]) -> None if save_to is None: if not self.closed: _logger.debug(u"[provenance] Deleting temporary %s", self.folder) shutil.rmtree(self.folder, ignore_errors=True) else: save_to = os.path.abspath(save_to) ...
def close(self, save_to=None)
Close the Research Object, optionally saving to specified folder. Closing will remove any temporary files used by this research object. After calling this method, this ResearchObject instance can no longer be used, except for no-op calls to .close(). The 'saveTo' folder should not exis...
3.196455
3.203749
0.997723
return u"" return rdf.decode('utf-8')
def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8') if not rdf
Serialize the CWL document into a string, ready for printing.
11.778735
11.011937
1.069633
# type: (...) -> bool found = False candidates = [] if "dockerImageId" not in dockerRequirement and "dockerPull" in dockerRequirement: match = re.search(pattern=r'([a-z]*://)', string=dockerRequirement["dockerPull"]) candidate = _normalize_image_id(dock...
def get_image(dockerRequirement, # type: Dict[Text, Text] pull_image, # type: bool force_pull=False # type: bool )
Acquire the software container image in the specified dockerRequirement using Singularity and returns the success as a bool. Updates the provided dockerRequirement with the specific dockerImageId to the full path of the local image, if found. Likewise the dockerRequirement['dockerPull'] ...
2.567498
2.513749
1.021382
# type: (...) -> Optional[Text] if not bool(spawn.find_executable('singularity')): raise WorkflowException('singularity executable is not available') if not self.get_image(r, pull_image, force_pull): raise WorkflowException(u"Container image {} not " ...
def get_from_requirements(self, r, # type: Dict[Text, Text] pull_image, # type: bool force_pull=False, # type: bool tmp_outdir_prefix=None # type: Text ...
Returns the filename of the Singularity image (e.g. hello-world-latest.img).
4.911213
4.932778
0.995628
runtime.append(u"--userns") runtime.append(u"--bind") runtime.append(u"{}:{}:rw".format( docker_windows_path_adjust(os.path.realpath(self.outdir)), self.builder.outdir)) runtime.append(u"--bind") tmpdir = "/tmp" # nosec runtime.append(u"{}:{}:...
def create_runtime(self, env, # type: MutableMapping[Text, Text] runtime_context # type: RuntimeContext ): # type: (...) -> Tuple[List, Optional[Text]] any_path_okay = self.builder.get_requirement("DockerRequirement")[1] \...
Returns the Singularity runtime list of commands and options.
2.839666
2.730239
1.040079
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return result.strip() except (OSError, subprocess.CalledProcessError, TypeError, AttributeError): # OSError is raised if command doesn't exist # CalledProcessError is raised if command returns nonzero # Attribute...
def check_output_and_strip(cmd): # type: (List[Text]) -> Optional[Text] try
Passes a command list to subprocess.check_output, returning None if an expected exception is raised :param cmd: The command to execute :return: Stripped string output of the command, or None if error
4.441829
4.557132
0.974698
return (None, None) uid = cmd_output_to_int(['docker-machine', 'ssh', machine_name, "id -u"]) gid = cmd_output_to_int(['docker-machine', 'ssh', machine_name, "id -g"]) return (uid, gid)
def docker_machine_id(): # type: () -> Tuple[Optional[int], Optional[int]] machine_name = docker_machine_name() if not machine_name
Asks docker-machine for active machine and gets the UID of the docker user inside the vm :return: tuple (UID, GID), or (None, None) if error (e.g. docker-machine not present or stopped)
3.074366
2.992671
1.027298
loadingContext = LoadingContext() loadingContext.loader = default_loader() else: loadingContext = loadingContext.copy() if loadingContext.loader is None: loadingContext.loader = default_loader(loadingContext.fetcher_constructor) if isinstance(argsworkflow, string_typ...
def fetch_document(argsworkflow, # type: Union[Text, Dict[Text, Any]] loadingContext=None # type: Optional[LoadingContext] ): # type: (...) -> Tuple[LoadingContext, CommentedMap, Text] if loadingContext is None
Retrieve a CWL document.
4.308359
3.667494
1.174742
raise ValueError("loadingContext must have a loader") resolveduri, metadata = loadingContext.loader.resolve_ref(uri) processobj = None if isinstance(resolveduri, MutableSequence): for obj in resolveduri: if obj['id'].endswith('#main'): processobj = obj ...
def make_tool(uri, # type: Union[Text, CommentedMap, CommentedSeq] loadingContext # type: LoadingContext ): # type: (...) -> Process if loadingContext.loader is None
Make a Python CWL object.
4.578979
4.253862
1.076429
# type: (Builder, Text, Dict[Text, Any]) -> Union[Dict[Text, Any], None] split = urllib.parse.urlsplit(outdir) if not split.scheme: outdir = file_uri(str(outdir)) # builder.outdir is the inner (container/compute node) output directory # outdir is the outer (host/storage system) outpu...
def revmap_file(builder, outdir, f)
Remap a file from internal path to external path. For Docker, this maps from the path inside tho container to the path outside the container. Recognizes files in the pathmapper or remaps internal output directories to the external directory.
4.125576
4.11211
1.003275
# type: (Builder, Dict[Text, Any]) -> Dict[Text, Any] if not builder.pathmapper: raise ValueError("Do not call check_adjust using a builder that doesn't have a pathmapper.") file_o["path"] = docker_windows_path_adjust( builder.pathmapper.mapper(file_o["location"])[1]) dn, bn = ...
def check_adjust(builder, file_o)
Map files to assigned path inside a container. We need to also explicitly walk over input, as implicit reassignment doesn't reach everything in builder.bindings
3.320813
3.398672
0.977091
sjob = copy.copy(joborder) sjob[scatter_key] = joborder[scatter_key][index] if len(scatter_keys) == 1: if runtimeContext.postScatterEval is not None: sjob = runtimeContext.postScatterEval(sjob) steps.append(process.job( sjob, functools.par...
def _flat_crossproduct_scatter(process, # type: WorkflowJobStep joborder, # type: MutableMapping[Text, Any] scatter_keys, # type: MutableSequence[Text] callback, # type: ReceiveScatterOutput ...
Inner loop.
2.885459
2.810412
1.026703
# type: (Text, Text, Optional[Graph], Set[Text]) -> bool if URIRef(fmt) == URIRef(cls): return True if ontology is None: return False if fmt in visited: return False visited.add(fmt) uriRefFmt = URIRef(fmt) for s, p, o in ontology.triples((uriRefFmt, RDFS.s...
def formatSubclassOf(fmt, cls, ontology, visited)
Determine if `fmt` is a subclass of `cls`.
2.223917
2.104188
1.0569
if not afile: continue if "format" not in afile: raise validate.ValidationException( u"File has no 'format' defined: {}".format( json_dumps(afile, indent=4))) for inpf in aslist(input_formats): if afile["format"] == inpf or ...
def check_format(actual_file, # type: Union[Dict[Text, Any], List, Text] input_formats, # type: Union[List[Text], Text] ontology # type: Optional[Graph] ): # type: (...) -> None for afile in aslist(actual_file)
Confirms that the format present is valid for the allowed formats.
3.975965
3.696781
1.075521
if "requirements" in t: for r in t["requirements"]: if r["class"] in rewrite: r["class"] = rewrite[r["class"]] if "hints" in t: for r in t["hints"]: if r["class"] in rewrite: r["class"] = rewrite[r["class"]] ...
def v1_0to1_1_0dev1(doc, loader, baseuri): # pylint: disable=unused-argument # type: (Any, Loader, Text) -> Tuple[Any, Text] doc = copy.deepcopy(doc) rewrite = { "http://commonwl.org/cwltool#WorkReuse": "WorkReuse", "http://commonwl.org/cwltool#TimeLimit": "ToolTimeLimit", "h...
Public updater for v1.0 to v1.1.0-dev1.
2.862266
2.741783
1.043943
# type: (...) -> Tuple[Union[CommentedSeq, CommentedMap], Text] cdoc = None # type: Optional[CommentedMap] if isinstance(doc, CommentedSeq): if not isinstance(metadata, CommentedMap): raise Exception("Expected metadata to be CommentedMap") lc = metadata.lc metadata...
def checkversion(doc, # type: Union[CommentedSeq, CommentedMap] metadata, # type: CommentedMap enable_dev # type: bool )
Checks the validity of the version of the give CWL document. Returns the document and the validated version string.
3.204713
3.150372
1.017249
# type: (str) -> bool # parse nodejs version into int Tuple: 'v4.2.6\n' -> [4, 2, 6] current_version_str = subprocess.check_output( [working_alias, "-v"]).decode('utf-8') current_version = [int(v) for v in current_version_str.strip().strip('v').split('.')] minimum_node_version = [int(...
def check_js_threshold_version(working_alias)
Checks if the nodeJS engine version on the system with the allowed minimum version. https://github.com/nodejs/node/blob/master/CHANGELOG.md#nodejs-changelog
3.625526
4.127
0.878489
if not entry.staged: continue if not os.path.exists(os.path.dirname(entry.target)): os.makedirs(os.path.dirname(entry.target)) if entry.type in ("File", "Directory") and os.path.exists(entry.resolved): if symlink: # Use symlink func if allowed ...
def stage_files(pathmapper, # type: PathMapper stage_func=None, # type: Callable[..., Any] ignore_writable=False, # type: bool symlink=True, # type: bool secret_store=None # type: SecretStore ): # type: (...
Link or copy files to their targets. Create them as needed.
2.235059
2.194058
1.018687
# type: (Union[List[Dict[Text, Any]], Dict[Text, Any]], Text) -> Any if isinstance(field_type, MutableSequence): for field in field_type: avroize_type(field, name_prefix) elif isinstance(field_type, MutableMapping): if field_type["type"] in ("enum", "record"): if...
def avroize_type(field_type, name_prefix="")
adds missing information to a type so that CWL types are valid in schema_salad.
1.974519
1.901908
1.038178
if "var/spool/cwl" in obj and obj_key != "dockerOutputDirectory": _logger.warning( SourceLine(item=item, key=obj_key, raise_type=Text).makeError( _VAR_SPOOL_ERROR.format(obj))) r = True elif isinstance(obj, MutableMapping): for key, value i...
def var_spool_cwl_detector(obj, # type: Union[MutableMapping, List, Text] item=None, # type: Optional[Any] obj_key=None, # type: Optional[Any] ): # type: (...)->bool r = False if isinstance(obj, stri...
Detects any textual reference to /var/spool/cwl.
3.837018
3.335389
1.150396
# type: () -> Text ''' version of CWLtool used to execute the workflow. ''' pkg = pkg_resources.require("cwltool") if pkg: return u"%s %s" % (sys.argv[0], pkg[0].version) return u"%s %s" % (sys.argv[0], "unknown version")
def versionstring()
version of CWLtool used to execute the workflow.
3.848652
3.196059
1.204187
# type: (Text) -> Text r if onWindows(): split = path.split(':') if len(split) == 2: if platform.win32_ver()[0] in ('7', '8'): # type: ignore split[0] = split[0].lower() # Docker toolbox uses lowecase windows Drive letters else: split...
def docker_windows_path_adjust(path)
r""" Changes only windows paths so that the can be appropriately passed to the docker run command as as docker treats them as unix paths. Example: 'C:\Users\foo to /C/Users/foo (Docker for Windows) or /c/Users/foo (Docker toolbox).
4.482332
4.555577
0.983922
# type: (Text) -> (Text) r if path is not None and onWindows(): if path[0] == '/': path = path[1:] else: raise ValueError("not a docker path") splitpath = path.split('/') splitpath[0] = splitpath[0]+':' return '\\'.join(splitpath) return pa...
def docker_windows_reverse_path_adjust(path)
r""" Change docker path (only on windows os) appropriately back to Window path/ Example: /C/Users/foo to C:\Users\foo
4.48825
5.094244
0.881043
# type: (Text) -> (Text) r if fileuri is not None and onWindows(): if urllib.parse.urlsplit(fileuri).scheme == "file": filesplit = fileuri.split("/") if filesplit[3][-1] != ':': filesplit[3] = filesplit[3]+':' return '/'.join(filesplit) ...
def docker_windows_reverse_fileuri_adjust(fileuri)
r""" On docker in windows fileuri do not contain : in path To convert this file uri to windows compatible add : after drive letter, so file:///E/var becomes file:///E:/var
4.344378
5.174297
0.839607
if i == j: continue # in case 1st list is smaller # should come first in sorting if i is None: return -1 # if 1st list is longer, # it should come later in sort elif j is None: return 1 # if either of the list contains ...
def cmp_like_py2(dict1, dict2): # type: (Dict[Text, Any], Dict[Text, Any]) -> int # extract lists from both dicts first, second = dict1["position"], dict2["position"] # iterate through both list till max of their size for i, j in zip_longest(first, second)
Comparision function to be used in sorting as python3 doesn't allow sorting of different types like str() and int(). This function re-creates sorting nature in py2 of heterogeneous list of `int` and `str`
4.269977
4.496028
0.949722
# type: (...) -> Union[Text, MutableSequence[Any], MutableMapping[Text, Any]] # if input is dict, recursively call for each value if isinstance(inp, MutableMapping): for k in inp: inp[k] = bytes2str_in_dicts(inp[k]) return inp # if list, iterate through list and fn cal...
def bytes2str_in_dicts(inp # type: Union[MutableMapping[Text, Any], MutableSequence[Any], Any] )
Convert any present byte string to unicode string, inplace. input is a dict of nested dicts and lists
3.134932
3.32799
0.94199
# type: (Any, Iterable, Union[Callable[..., Any], partial[Any]]) -> None if isinstance(rec, MutableMapping): if "class" in rec and rec.get("class") in cls: op(rec) for d in rec: visit_class(rec[d], cls, op) if isinstance(rec, MutableSequence): for d in r...
def visit_class(rec, cls, op)
Apply a function to with "class" in cls.
3.600389
3.654803
0.985112
# type: (Any, Iterable, Union[Callable[..., Any], partial[Any]]) -> None if isinstance(rec, MutableMapping): if field in rec: rec[field] = op(rec[field]) for d in rec: visit_field(rec[d], field, op) if isinstance(rec, MutableSequence): for d in rec: ...
def visit_field(rec, field, op)
Apply a function to mapping with 'field'.
3.108854
3.058803
1.016363
random_outdir.outdir = '/' + ''.join([random.choice(string.ascii_letters) for _ in range(6)]) # type: ignore # nosec return random_outdir.outdir
def random_outdir(): # type: () -> Text # compute this once and store it as a function attribute - each subsequent call will return the same value if not hasattr(random_outdir, 'outdir')
Return the random directory name chosen to use for tool / workflow output
3.825633
3.441645
1.111571
''' Write a numeric result in various forms ''' out('hex: 0x{0:08x}'.format(num)) out('dec: {0:d}'.format(num)) out('oct: 0o{0:011o}'.format(num)) out('bin: 0b{0:032b}'.format(num))
def print_num(num)
Write a numeric result in various forms
3.70055
3.107255
1.190939
''' Runs the program and handles command line options ''' parser = get_parser() # Parse arguments and run the function global args args = parser.parse_args(argv) args.func()
def main(argv=None)
Runs the program and handles command line options
6.649134
5.455354
1.218827
if getattr(self, fieldname): # do not overwrite existing data return value = bytestring if transfunc is None else transfunc(bytestring) if DEBUG: stderr('Setting field "%s" to "%s"' % (fieldname, value)) if fieldname == 'genre' and value.isdigit() and in...
def _set_field(self, fieldname, bytestring, transfunc=None)
convienience function to set fields of the tinytag by name. the payload (bytestring) can be changed using the transfunc
3.63879
3.655301
0.995483
if value_type == 0: # Unicode string return self.__decode_string(value) elif value_type == 1: # BYTE array return value elif 1 < value_type < 6: # DWORD / QWORD / WORD return _bytes_to_int_le(value)
def __decode_ext_desc(self, value_type, value)
decode ASF_EXTENDED_CONTENT_DESCRIPTION_OBJECT values
4.773566
4.339852
1.099937
return super(Card, self).fetch(card_id, data, **kwargs)
def fetch(self, card_id, data={}, **kwargs)
Fetch Card for given Id Args: card_id : Id for which card object has to be retrieved Returns: Card dict for given card Id
3.783141
7.08352
0.534076
return super(VirtualAccount, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Virtual Account entities Returns: Dictionary of Virtual Account data
9.277731
7.078048
1.310775
return super(VirtualAccount, self).fetch( virtual_account_id, data, **kwargs)
def fetch(self, virtual_account_id, data={}, **kwargs)
Fetch Virtual Account for given Id Args: virtual_account_id : Id for which Virtual Account object has to be retrieved Returns: Virtual Account dict for given Virtual Account Id
3.675697
5.865595
0.626654
url = self.base_url return self.post_url(url, data, **kwargs)
def create(self, data={}, **kwargs)
Create Virtual Account from given dict Args: Param for Creating Virtual Account Returns: Virtual Account dict
5.067487
8.674877
0.584157
url = "{}/{}".format(self.base_url, virtual_account_id) data['status'] = 'closed' return self.patch_url(url, data, **kwargs)
def close(self, virtual_account_id, data={}, **kwargs)
Close Virtual Account from given Id Args: virtual_account_id : Id for which Virtual Account objects has to be Closed
3.299013
4.01466
0.821741
url = "{}/{}/payments".format(self.base_url, virtual_account_id) return self.get_url(url, data, **kwargs)
def payments(self, virtual_account_id, data={}, **kwargs)
Fetch Payment for Virtual Account Id Args: virtual_account_id : Id for which Virtual Account objects has to be retrieved Returns: Payment dict for given Virtual Account Id
2.932149
3.794897
0.772656
return super(Subscription, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Subscription entities Returns: Dictionary of Subscription data
7.566944
7.476111
1.01215
return super(Subscription, self).fetch(subscription_id, data, **kwargs)
def fetch(self, subscription_id, data={}, **kwargs)
Fetch Subscription for given Id Args: subscription_id : Id for which subscription object is retrieved Returns: Subscription dict for given subscription Id
3.63751
6.65626
0.54648
url = "{}/{}/cancel".format(self.base_url, subscription_id) return self.post_url(url, data, **kwargs)
def cancel(self, subscription_id, data={}, **kwargs)
Cancel subscription given by subscription_id Args: subscription_id : Id for which subscription has to be cancelled Returns: Subscription Dict for given subscription id
3.172784
4.322258
0.734057
return super(Order, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Order entities Returns: Dictionary of Order data
6.943742
7.85114
0.884425
return super(Order, self).fetch(order_id, data, **kwargs)
def fetch(self, order_id, data={}, **kwargs)
Fetch Order for given Id Args: order_id : Id for which order object has to be retrieved Returns: Order dict for given order Id
3.568805
7.224421
0.493992
return super(Customer, self).fetch(customer_id, data, **kwargs)
def fetch(self, customer_id, data={}, **kwargs)
Fetch Customer for given Id Args: customer_id : Id for which customer object has to be retrieved Returns: Order dict for given customer Id
3.513194
6.588949
0.533195
url = '{}/{}'.format(self.base_url, customer_id) return self.put_url(url, data, **kwargs)
def edit(self, customer_id, data={}, **kwargs)
Edit Customer information from given dict Returns: Customer Dict which was edited
3.434455
5.361854
0.640535
return super(Addon, self).fetch(addon_id, data, **kwargs)
def fetch(self, addon_id, data={}, **kwargs)
Fetch addon for given Id Args: addon_id : Id for which addon object has to be retrieved Returns: addon dict for given subscription Id
3.371734
7.271015
0.463723
return super(Addon, self).delete(addon_id, data, **kwargs)
def delete(self, addon_id, data={}, **kwargs)
Delete addon for given id Args: addon_id : Id for which addon object has to be deleted
3.23023
6.589307
0.490223
return super(Refund, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch All Refund Returns: Refund dict
9.180164
8.324315
1.102813
return super(Refund, self).fetch(refund_id, data, **kwargs)
def fetch(self, refund_id, data={}, **kwargs)
Refund object for given paymnet Id Args: refund_id : Refund Id for which refund has to be retrieved Returns: Refund dict for given refund Id
3.456102
6.80172
0.508122
return super(Payment, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all Payment entities Returns: Dictionary of Payment data
7.493647
7.619921
0.983428
return super(Payment, self).fetch(payment_id, data, **kwargs)
def fetch(self, payment_id, data={}, **kwargs)
Fetch Payment for given Id Args: payment_id : Id for which payment object has to be retrieved Returns: Payment dict for given payment Id
3.618662
6.810153
0.531363
url = "{}/{}/capture".format(self.base_url, payment_id) data['amount'] = amount return self.post_url(url, data, **kwargs)
def capture(self, payment_id, amount, data={}, **kwargs)
Capture Payment for given Id Args: payment_id : Id for which payment object has to be retrieved Amount : Amount for which the payment has to be retrieved Returns: Payment dict after getting captured
2.987216
4.559299
0.655192
url = "{}/{}/transfers".format(self.base_url, payment_id) return self.post_url(url, data, **kwargs)
def transfer(self, payment_id, data={}, **kwargs)
Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered
3.081543
5.137264
0.599841
url = "{}/{}/transfers".format(self.base_url, payment_id) return self.get_url(url, data, **kwargs)
def transfers(self, payment_id, data={}, **kwargs)
Fetches all transfer for given Payment Id Args: payment_id : Id for which payment object has to be refunded Amount : Amount for which the payment has to be refunded Returns: Payment dict after getting refunded
2.981315
4.988217
0.597671
return super(Plan, self).fetch(plan_id, data, **kwargs)
def fetch(self, plan_id, data={}, **kwargs)
Fetch Plan for given Id Args: plan_id : Id for which Plan object has to be retrieved Returns: Plan dict for given subscription Id
3.632527
7.1589
0.507414
return super(Plan, self).all(data, **kwargs)
def all(self, data={}, **kwargs)
Fetch all plan entities Returns: Dictionary of plan data
8.12765
8.584905
0.946737
url = "{}/{}/tokens/{}".format(self.base_url, customer_id, token_id) return self.get_url(url, data, **kwargs)
def fetch(self, customer_id, token_id, data={}, **kwargs)
Fetch Token for given Id and given customer Id Args: customer_id : Customer Id for which tokens have to be fetched token_id : Id for which TOken object has to be fetched Returns: Token dict for given token Id
2.755684
4.005899
0.687907
url = "{}/{}/tokens".format(self.base_url, customer_id) return self.get_url(url, data, **kwargs)
def all(self, customer_id, data={}, **kwargs)
Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id
4.036983
4.194809
0.962376