Returns the name of the output mask file that
        should reside on disk for the given signature.
11797
def getFilename(self,signature):
        

        filename=constructFilename(signature)

        if(fileutil.checkFileExists(filename)):
            return filename
        else:
            print("\nmMask file for ", str(signature), " does not exist on disk", file=sys.stderr)
            return None
1075765
def getsignaturefromtext(text, objname):
    """"""
    if isinstance(text, dict):
        text = text.get('docstring', '')
    # Regexps
    oneline_re = objname + r'\([^\)].+?(?<=[\w\]\}\'"])\)(?!,)'
    multiline_re = objname + r'\([^\)]+(?<=[\w\]\}\'"])\)(?!,)'
    multiline_end_parenleft_re = r'(%s\([^\)]+(\),\n.+)+(?<=[\w\]\}\'"])\))'
    # Grabbing signatures
    if not text:
        text = ''
    sigs_1 = re.findall(oneline_re + '|' + multiline_re, text)
    sigs_2 = [g[0] for g in re.findall(multiline_end_parenleft_re % objname, text)]
    all_sigs = sigs_1 + sigs_2
    # The most relevant signature is usually the first one. There could be
    # others in doctests but those are not so important
    if all_sigs:
        return all_sigs[0]
    else:
        return ''
934402
def getFilename(name):
    """"""
    # first replace all illegal chars
    name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name)
    # then remove double dots and underscores
    while ".." in name:
        name = name.replace('..', '.')
    while "__" in name:
        name = name.replace('__', '_')
    # remove a leading dot or minus
    if name.startswith((".", "-")):
        name = name[1:]
    return name
356469
def signature(self):
        
        sig_elems = [self.seqid, self.source, self.type, \
                    self.start, self.end, self.strand, \
                    self.phase]
        if re.search("exon|CDS|UTR", self.type):
            parent = self.get_attr("Parent")
            if parent:
                (locus, iso) = atg_name(parent, retval="locus,iso", \
                        trimpad0=False)
                if locus:
                    sig_elems.append(locus)
        else:
            sig_elems.extend([self.accn])

        return ",".join(str(elem) for elem in sig_elems)
796960
def _checkpoint_out_filenames(self):
        
        out_filenames = []
        if self.Parameters['-n'].isOn():
            out_name = str(self.Parameters['-n'].Value)
            walk_root = self.WorkingDir
            if self.Parameters['-w'].isOn():
                walk_root = str(self.Parameters['-w'].Value)
            for tup in walk(walk_root):
                dpath, dnames, dfiles = tup
                if dpath == walk_root:
                    for gen_file in dfiles:
                        if out_name in gen_file and "checkpoint" in gen_file:
                            out_filenames.append(walk_root + gen_file)
                    break

        else:
            raise ValueError, "No output file specified."
        return out_filenames
1038979
def write(self):
        '''
        '''
        if not self.output_files.valid():
            raise ValueError(
                f'Cannot write signature with undetermined output {self.output_files}'
            )
        else:
            if 'TARGET' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
                env.log_to_file(
                    'TARGET',
                    f'write signature {self.sig_id} with output {self.output_files}'
                )
        ret = super(RuntimeInfo, self).write()
        if ret is False:
            env.logger.debug(f'Failed to write signature {self.sig_id}')
            return ret
        send_message_to_controller(['step_sig', self.sig_id, ret])
        send_message_to_controller([
            'workflow_sig', 'tracked_files', self.sig_id,
            repr({
                'input_files': [
                    str(f.resolve())
                    for f in self.input_files
                    if isinstance(f, file_target)
                ],
                'dependent_files': [
                    str(f.resolve())
                    for f in self.dependent_files
                    if isinstance(f, file_target)
                ],
                'output_files': [
                    str(f.resolve())
                    for f in self.output_files
                    if isinstance(f, file_target)
                ]
            })
        ])
        return True
1256735
def signature(name: str) -> Optional[Tuple]:
    
    return url_signature(name) if is_url(name) else file_signature(name) if is_file(name) else None
1176558
def validate(self, signature):
        ''''''
        if not signature:
            return 'Empty signature'
        sig_files = self.input_files._targets + self.output_files._targets + \
            self.dependent_files._targets
        for x in sig_files:
            if not x.target_exists('any'):
                return f'Missing target {x}'
        #

        files_checked = {x.target_name(): False for x in sig_files}
        res = {'input': [], 'output': [], 'depends': [], 'vars': {}}
        cur_type = 'input'
        # old signature
        if 'init_context' in signature:
            for key, value in signature['init_context'].items():
                if key not in env.sos_dict:
                    return f'Variable {key} not in running environment'
                try:
                    if env.sos_dict[key] != value:
                        return f'Context variable {key} value mismatch: {short_repr(value)} saved, {short_repr(env.sos_dict[key])} current'
                except Exception as e:
                    env.logger.debug(
                        f"Variable {key} of type {type(value).__name__} cannot be compared: {e}"
                    )
        elif 'init_context_sig' in signature:
            for key, value in signature['init_context_sig'].items():
                if key not in env.sos_dict:
                    return f'Variable {key} not in running environment'
                try:
                    if objectMD5(env.sos_dict[key]) != value:
                        return f'ID of context variable {key} ({objectMD5(env.sos_dict[key])}) mismatch: {short_repr(env.sos_dict[key])} does not match id {value}'
                except Exception as e:
                    env.logger.debug(f"Variable {key} cannot be compared: {e}")

        res['vars'].update(signature['end_context'])
        #
        for cur_type in ['input', 'output', 'depends']:
            for f, m in signature[cur_type].items():
                try:
                    if '(' in f and ')' in f:
                        # this part is hard, because this can be a customized target.
                        target_type = f.split('(')[0]
                        target_class = None
                        if target_type in globals():
                            target_class = eval(target_type)
                        else:
                            # check registry
                            for entrypoint in pkg_resources.iter_entry_points(
                                    group='sos_targets'):
                                if entrypoint.name.strip() == target_type:
                                    target_class = entrypoint.load()
                                    break
                        if target_class is None:
                            raise ValueError(
                                f'Failed to identify target class {target_type}'
                            )
                        # parameter of class?
                        freal = eval(f, {target_type: target_class})
                    else:
                        freal = file_target(f)
                    if not freal.validate(m):
                        return f'Target {f} does not exist or does not match saved signature {m}'
                    res[cur_type].append(freal.target_name(
                    ) if isinstance(freal, file_target) else freal)
                    files_checked[freal.target_name()] = True
                except Exception as e:
                    env.logger.debug(f'Wrong md5 in signature: {e}')
        #
        if not all(files_checked.values()):
            return f'No MD5 signature for {", ".join(x for x,y in files_checked.items() if not y)}'
        if 'input_obj' in signature:
            # for new style signature, the entire objects are kept
            res['input'] = signature['input_obj']
            res['depends'] = signature['depends_obj']
            res['output'] = signature['output_obj']
        return res
463148
def _GetSignatureScanner(cls, specification_store):
    
    signature_scanner = pysigscan.scanner()
    signature_scanner.set_scan_buffer_size(cls._SCAN_BUFFER_SIZE)

    for format_specification in specification_store.specifications:
      for signature in format_specification.signatures:
        pattern_offset = signature.offset

        if pattern_offset is None:
          signature_flags = pysigscan.signature_flags.NO_OFFSET
        elif pattern_offset < 0:
          pattern_offset *= -1
          signature_flags = pysigscan.signature_flags.RELATIVE_FROM_END
        else:
          signature_flags = pysigscan.signature_flags.RELATIVE_FROM_START

        signature_scanner.add_signature(
            signature.identifier, pattern_offset, signature.pattern,
            signature_flags)

    return signature_scanner
983601
def signature(self):
        """"""
        #We can't really do anything sensible without the name of the function
        #whose signature we are completing.
        iexec, execmod = self.context.parser.tree_find(self.context.el_name, 
                                              self.context.module, "executables")
        if iexec is None:
            #Look in the interfaces next using a tree find as well
            iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module,
                                                  "interfaces")
        if iexec is None:
            return []

        return self._signature_index(iexec)
717506
def generate_filename(self, mark, **kwargs):
        """"""

        kwargs = kwargs.copy()

        kwargs['opacity'] = int(kwargs['opacity'] * 100)
        kwargs['st_mtime'] = kwargs['fstat'].st_mtime
        kwargs['st_size'] = kwargs['fstat'].st_size

        params = [
            '%(original_basename)s',
            'wm',
            'w%(watermark)i',
            'o%(opacity)i',
            'gs%(greyscale)i',
            'r%(rotation)i',
            'fm%(st_mtime)i',
            'fz%(st_size)i',
            'p%(position)s',
        ]

        scale = kwargs.get('scale', None)
        if scale and scale != mark.size:
            params.append('_s%i' % (float(kwargs['scale'][0]) / mark.size[0] * 100))

        if kwargs.get('tile', None):
            params.append('_tiled')

        # make thumbnail filename
        filename = '%s%s' % ('_'.join(params), kwargs['ext'])

        return filename % kwargs
304762
def getLockFilename(self):
        
        if self.baseFilename.endswith(".log"):
            lock_file = self.baseFilename[:-4]
        else:
            lock_file = self.baseFilename
        lock_file += ".lock"
        lock_path, lock_name = os.path.split(lock_file)
        # hide the file on Unix and generally from file completion
        lock_name = ".__" + lock_name
        return os.path.join(lock_path, lock_name)
433994
private String getFileName(int type, String tokenFilename) {
        StringBuilder sb = new StringBuilder();
        String filename = tokenFilename.substring(0, tokenFilename.indexOf(EXT_SEPERATOR));
        String ext = tokenFilename.substring(tokenFilename.indexOf(EXT_SEPERATOR));
        sb.append(filename);
        switch (type) {
            case 1:
                sb.append(IMAGE_WATERMARK_SUFFIX);
                break;
            case 2:
                sb.append(IMAGE_THUMB_SUFFIX);
                break;
        }
        sb.append(ext);
        return sb.toString();
    }
226603
def loadmask(self, filename: str) -> np.ndarray:
        """"""
        mask = scipy.io.loadmat(self.find_file(filename, what='mask'))
        maskkey = [k for k in mask.keys() if not (k.startswith('_') or k.endswith('_'))][0]
        return mask[maskkey].astype(np.bool)
295142
function getMaskTemplate(mask) {
                if (opts.numericInput) {
                    mask = mask.split('').reverse().join('');
                }
                var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
                if (repeat == "*") greedy = false;
                //if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
                if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
                var singleMask = $.map(mask.split(""), function (element, index) {
                    var outElem = [];
                    if (element == opts.escapeChar) {
                        escaped = true;
                    }
                    else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
                        var maskdef = opts.definitions[element];
                        if (maskdef && !escaped) {
                            for (var i = 0; i < maskdef.cardinality; i++) {
                                outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length));
                            }
                        } else {
                            outElem.push(element);
                            escaped = false;
                        }
                        outCount += outElem.length;
                        return outElem;
                    }
                });

                //allocate repetitions
                var repeatedMask = singleMask.slice();
                for (var i = 1; i < repeat && greedy; i++) {
                    repeatedMask = repeatedMask.concat(singleMask.slice());
                }

                return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
            }
362417
def signature(self):
        """"""
        if self.usage is not None:
            return self.usage


        params = self.clean_params
        if not params:
            return ''

        result = []
        for name, param in params.items():
            greedy = isinstance(param.annotation, converters._Greedy)

            if param.default is not param.empty:
                # We don't want None or '' to trigger the [name=value] case and instead it should
                # do [name] since [name=None] or [name=] are not exactly useful for the user.
                should_print = param.default if isinstance(param.default, str) else param.default is not None
                if should_print:
                    result.append('[%s=%s]' % (name, param.default) if not greedy else
                                  '[%s=%s]...' % (name, param.default))
                    continue
                else:
                    result.append('[%s]' % name)

            elif param.kind == param.VAR_POSITIONAL:
                result.append('[%s...]' % name)
            elif greedy:
                result.append('[%s]...' % name)
            elif self._is_typing_optional(param.annotation):
                result.append('[%s]' % name)
            else:
                result.append('<%s>' % name)

        return ' '.join(result)
369321
def _make_signature(self):
        
        # Create KEYWORD_ONLY arguments with the names of the minimizers.
        name = lambda x: x.__class__.__name__
        count = Counter(
            [name(minimizer) for minimizer in self.minimizers]
        ) # Count the number of each minimizer, they don't have to be unique

        # Note that these are inspect_sig.Parameter's, not symfit parameters!
        parameters = []
        for minimizer in reversed(self.minimizers):
            if count[name(minimizer)] == 1:
                # No ambiguity, so use the name directly.
                param_name = name(minimizer)
            else:
                # Ambiguity, so append the number of remaining minimizers
                param_name = '{}_{}'.format(name(minimizer), count[name(minimizer)])
            count[name(minimizer)] -= 1

            parameters.append(
                inspect_sig.Parameter(
                    param_name,
                    kind=inspect_sig.Parameter.KEYWORD_ONLY,
                    default={}
                )
            )
        return inspect_sig.Signature(parameters=reversed(parameters))