Converts the filename of an encrypted file to cleartext

    :param fname:
    :return: filename of clear secret file if found, else None
498946
def enc_to_clear_filename(fname):
    
    if not fname.lower().endswith('.json'):
        raise CredkeepException('Invalid filetype')

    if not fname.lower().endswith('.enc.json'):
        raise CredkeepException('Not filename of encrypted file')

    clear_fname = fname.replace('.enc.json', '.json')
    print clear_fname

    return clear_fname if exists(clear_fname) else None
122065
def get_md5(self, filename):
        
        with open(filename, 'rb') as f:
            m = hashlib.md5(f.read())
        return m.hexdigest()
10130
def get_filename(self, checksum):
        
        filename = None
        for _filename, metadata in self._log.items():
            if metadata['checksum'] == checksum:
                filename = _filename
                break
        return filename
306596
def make_fcn(filename):
    
    # collect lines and parse first several lines for fit info
    with open(filename, 'r') as ifile:
        lines = ifile.readlines()
    name = filename.split('.')[0]
    _certified_values = re.compile('.*Certified Values\s*\(lines\s*([0-9]*)\s*to\s*([0-9]*)\)')
    _data = re.compile('.*Data\s*\(lines\s*([0-9]*)\s*to\s*([0-9]*)\)')
    _model = re.compile('^Model:')
    values = None
    data = None
    fcn = None
    for i,line in enumerate(lines):
        m = _certified_values.match(line)
        if m is not None:
            values = (int(m.group(1)), int(m.group(2)))
        m = _data.match(line)
        if m is not None:
            data = (int(m.group(1)), int(m.group(2)))
        m = _model.match(line)
        if m is not None:
            fcn = ""
            for j in range(i+3,values[0] - 1):
                s = lines[j].strip()
                if s == '':
                    break
                fcn += s
        if None not in [values, data, fcn]:
            break
    # get rid of + e
    fcn = fcn[:-4]
    # fix [] brackets
    s = fcn.split('[')
    if len(s) > 1:
        _bracket = re.compile('(.*)\](.*)')
        nfcn = s[0]
        for si in s[1:]:
            m = _bracket.match(si)
            if m is not None:
                si = m.group(1) + ')' + m.group(2)
                si = '(' + m.group(1) + ')' + m.group(2)
            nfcn += si
        fcn = nfcn
    # parameter names
    nparam = values[1] - values[0] + 1 - 5
    pnames = ','.join(['b' + str(i+1) for i in range(nparam)])
    p = []
    p0 = []
    prior = []
    for i in range(values[0] - 1, values[0] - 1 + nparam):
        s = lines[i].split()
        p.append(gv.gvar(s[-2] + ' +- ' + s[-1]))
        if USE_2ND_STARTING_VALUE:
            p0.append(float(s[3]))
        else:
            p0.append(float(s[2]))
        prior.append(gv.gvar('0 +- ' + str(200 * p[-1].mean)))
    p = np.array(p)
    p0 = np.array(p0)
    prior = list(gv.fmt(prior))
    nistp = answers.get(name, str(p))
    # error on y
    s = lines[values[1] - 3].split()
    yerr = '0 +- ' + s[-1]
    # collect x, y
    x = []
    y = []
    for i in range(data[0] - 1, data[1]):
        s = lines[i].split()
        if len(s) == 2:
            x.append(float(s[-1]))
            y.append(float(s[-2]))
        elif len(s) > 2:
            y.append(float(s[0]))
            x.append([float(si) for si in s[1:]])
    x = np.array(x)
    if len(x.shape) > 1:
        xnames = ','.join(['x' + str(i+1) for i in range(x.shape[1])])
        x = x.T
    else:
        xnames = 'x'
    y = np.array(y)
    if len(nistp.split('\n')) > 1:
        nistp = '\\n'.join(nistp.split('\n'))
    if name == 'nelson':
        fcn = fcn.replace('log(y)', 'y')
        yname = 'log(y)'
    else:
        yname = 'y'
    if name == 'mgh10' and not USE_2ND_STARTING_VALUE:
        p0 = gv.sdev(gv.gvar(prior)) / 100.
    template = \
"""
def {name}():
    print(20 * '=', '{name}')
    x = np.{x}
    y = np.{y}
    y = {yname} + gv.gvar(len(y) * ['{yerr}'])
    def fcn(x, b):
        {xnames} = x
        {pnames} = b
        {fcn}
        return y
    prior = gv.gvar({prior})
    p0 = np.{p0}
    fit = lsqfit.nonlinear_fit(
        prior=prior, data=(x,y), fcn=fcn, p0=p0, tol=1e-10,
        )
    print(fit)
    assert str(fit.p) == '{nistp}'
"""
    return template.format(
        name=name,
        x=repr(x),
        y=repr(y),
        p0=repr(p0),
        yerr=yerr,
        fcn=fcn,
        prior=repr(prior),
        nistp=nistp,
        pnames=pnames,
        xnames=xnames,
        yname=yname,
        )
554833
def reduce_filename(f):
    
    '''

    f = os.path.basename(f).split('.')
    return keep_only_digits(f[-3])
55725
def remove_files(filename):
        # type: (AnyStr) -> None
        
        pattern = os.path.splitext(filename)[0] + '.*'
        for f in glob.iglob(pattern):
            os.remove(f)
125050
def _decrypt_and_extract(self, fname):
        '''
        
        '''
        with open(fname, "r") as fp_in:
            encrypted_data = fp_in.read()

            decrypted_data = self._hilink_decrypt(encrypted_data)

            with open(binwalk.core.common.unique_file_name(fname[:-4], "dec"), "w") as fp_out:
                fp_out.write(decrypted_data)
3331
def make_filenames(self, **kwargs):
        
        out_dict = dict(ft1file=self.ft1file(**kwargs),
                        ltcube=self.ltcube(**kwargs),
                        ccube=self.ccube(**kwargs),
                        bexpcube=self.bexpcube(**kwargs),
                        srcmaps=self.srcmaps(**kwargs),
                        mcube=self.mcube(**kwargs))
        return out_dict
899056
def make_safe_filename_from_url(self, url):
        ''''''
        r = re.compile("([^a-zA-Z0-9_.-])")
        filename = r.sub(lambda m : "%" + str(hex(ord(str(m.group(1))))).upper(), url)
        return filename
864871
def file_current(self, fname, md5):
        
        return os.path.isfile(fname) and util.md5_file(fname) == md5
93174
def get_key_filename(vm_):
    '''
    
    '''
    key_filename = config.get_cloud_config_value(
        'ssh_private_key', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None:
        key_filename = os.path.expanduser(key_filename)
        if not os.path.isfile(key_filename):
            raise SaltCloudConfigError(
                'The defined ssh_private_key \'{0}\' does not exist'.format(
                    key_filename
                )
            )

        return key_filename
894653
def getfullfilename(file_path):
        ''' 
        '''
        warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning)
        if file_path:
            return os.path.basename(file_path)
        else:
            return ''
505092
def _encode_filename_to_filesystem(f):
    ''''''
    log.debug('_encode_filename_to_filesystem(%s)', repr(f))
    if isinstance(f, str):
        return f
    try:
        return f.encode(sys.getfilesystemencoding())
    except UnicodeEncodeError:
        raise
415103
def safe_filename(url)
      url  = url.sub(/\?.*\Z/, '')
      ext  = File.extname(url)
      name = URI.unescape(File.basename(url)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-')
      File.basename(name, ext).gsub('.', '-') + ext
    end
417992
def safe_filename(self, otype, oid):
        """"""
        permitted = set(['_', '-', '(', ')'])
        oid = ''.join([c for c in oid if c.isalnum() or c in permitted])
        while oid.find('--') != -1:
            oid = oid.replace('--', '-')
        ext = 'json'
        ts = datetime.now().strftime("%Y%m%dT%H%M%S")
        fname = ''
        is_new = False
        while not is_new:
            oid_len = 255 - len('%s--%s.%s' % (otype, ts, ext))
            fname = '%s-%s-%s.%s' % (otype, oid[:oid_len], ts, ext)
            is_new = True
            if os.path.exists(fname):
                is_new = False
                ts += '-bck'
        return fname
911279
def example_filename(fn):
    
    fn = os.path.join(data_dir(), fn)
    if not os.path.exists(fn):
        raise ValueError("%s does not exist" % fn)
    return fn
1147290
def file_to_str(fname):
    
    data = None
    # rU = read with Universal line terminator
    with open(fname, 'rU') as fd:
        data = fd.read()
    return data