Return blocks of code as list of dicts

    Arguments:
        fname (str): Relative name of caveats file
438186
def parse(fname):
    

    blocks = list()
    with io.open(fname, "r", encoding="utf-8") as f:
        in_block = False
        current_block = None
        current_header = ""

        for line in f:

            # Doctests are within a quadruple hashtag header.
            if line.startswith("#### "):
                current_header = line.rstrip()

            # The actuat test is within a fenced block.
            if line.startswith("```"):
                in_block = False

            if in_block:
                current_block.append(line)

            if line.startswith("```python"):
                in_block = True
                current_block = list()
                current_block.append(current_header)
                blocks.append(current_block)

    tests = list()
    for block in blocks:
        header = (
            block[0].strip("# ")  # Remove Markdown
                    .rstrip()     # Remove newline
                    .lower()      # PEP08
        )

        # Remove unsupported characters
        header = re.sub(r"\W", "_", header)

        # Adding "untested" anywhere in the first line of
        # the doctest excludes it from the test.
        if "untested" in block[1].lower():
            continue

        data = re.sub(" ", "", block[1])  # Remove spaces
        data = (
            data.strip("#")
                .rstrip()     # Remove newline
                .split(",")
        )

        binding, doctest_version = (data + [None])[:2]

        # Run tests on both Python 2 and 3, unless explicitly stated
        if doctest_version is not None:
            if doctest_version not in ("Python2", "Python3"):
                raise SyntaxError(
                    "Invalid Python version:\n%s\n"
                    "Python version must follow binding, e.g.\n"
                    "# PyQt5, Python3" % doctest_version)

            active_version = "Python%i" % sys.version_info[0]
            if doctest_version != active_version:
                continue

        tests.append({
            "header": header,
            "binding": binding,
            "body": block[2:]
        })

    return tests
509149
def tbfuncs(frames):
  ''
  return ['%s:%s:%s'%(os.path.split(f.f_code.co_filename)[-1],f.f_code.co_name,f.f_lineno) for f in frames]
1204015
def get_lines(fname):
    """"""
    for line in fileinput.input(fname):
        yield fileinput.filelineno(), line.strip()
946395
def _get_module_name_from_fname(fname):
    """"""
    fname = fname.replace(".pyc", ".py")
    for mobj in sys.modules.values():
        if (
            hasattr(mobj, "__file__")
            and mobj.__file__
            and (mobj.__file__.replace(".pyc", ".py") == fname)
        ):
            module_name = mobj.__name__
            return module_name
    raise RuntimeError("Module could not be found")
1277473
def find_prototypes(code):
    

    prots = []
    lines = code.split('\n')
    for line in lines:
        m = re.match("\s*" + re_func_prot, line)
        if m is not None:
            rtype, name, args = m.groups()[:3]
            if args == 'void' or args.strip() == '':
                args = []
            else:
                args = [tuple(arg.strip().split(' '))
                        for arg in args.split(',')]
            prots.append((name, args, rtype))

    return prots
267269
def reader(fname):
    ''''''
    f = pyfastaq.utils.open_file_read(fname)

    for line in f:
        if line.startswith('[') or (not '\t' in line):
            continue

        yield alignment.Alignment(line)

    pyfastaq.utils.close(f)
932725
def prepare_filename_decorator(fn):
    
    @wraps(fn)
    def inner(self, normalized_url, request):
        ext = settings.ROUGHPAGES_TEMPLATE_FILE_EXT
        if not normalized_url:
            normalized_url = settings.ROUGHPAGES_INDEX_FILENAME
        filenames = fn(self, normalized_url, request)
        filenames = [x + ext for x in filenames if x]
        return filenames
    return inner
891346
def to_python(fname, *args):
    
    [node] = read(fname)
    return node_to_obj(node, fname, *args)
5429
def p_include_fname(p):
    
    if ENABLED:
        p[0] = include_file(p[2], p.lineno(2), local_first=False)
    else:
        p[0] = []
        p.lexer.next_token = '_ENDFILE_'
319712
def read_dict(file_name, clear_none=False, encoding='utf-8'):
    
    with open(file_name, 'rb') as f:
        data = f.read()

    if encoding is not None:
        data = data.decode(encoding)

    line_list = data.splitlines()
    data = []
    i = 0
    for line in line_list:
        i += 1
        try:
            line = force_text(line).strip()
            data.append(line)
        except:
            print('read error line %s' % i)
    if clear_none:
        data = [t for t in data if t != '']
    data = deque(data)
    return data
286632
def dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET):
        
        code = self.block(f"{name} = {{}}")
        for p in params:
            code.add(
                self.block(f"if {p.name} is not {not_specified_literal}:").of(
                    f"{name}[{p.name!r}] = {p.name}"
                ),
            )
        return code
1278881
def get_conf_files(filename):
    
    if not os.path.isfile(filename):
        raise ValueError("'%s' is not a file" % filename)
    conf_d_path = "%s.d" % filename
    if not os.path.exists(conf_d_path):
        return [filename]
    return [filename] + get_conf_d_files(conf_d_path)
663670
def parse_requirements(filename):
    
    with open(filename, 'r') as f:
        lineiter = list(line.strip() for line in f)
    return [line for line in lineiter if line and not line.startswith("#")]
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
58459
def _read_file(fname):
    
    with open(fname) as input_file:
        re_grammar = [x.strip('\n') for x in input_file.readlines()]
    return re_grammar
701617
def dict_conf(filename):
  

  f, ext = os.path.splitext(filename)
  ext = ext.lower()

  if ext == "conf" or ext == "ini":
    # python config via config parser

    config = ConfigParser()
    config.optionxform=str
    config.read(filename)
    rv = {}
    for section in config.sections():
      rv[section] = {}
      for key,value in config.items(section):
        rv[section][key] = value.strip('"').strip("'").decode("string_escape")
    return rv
  else:
    # other type of config, use munge
    if munge_config:
      src = munge_config.parse_url(filename)
      return src.cls().load(open(filename)).get("vodka")
    else:
      raise Exception("'%s' type of config encountered, install munge" % ext)
884923
def getArguments(names, local_dict=None, global_dict=None):
    """"""
    call_frame = sys._getframe(2)

    clear_local_dict = False
    if local_dict is None:
        local_dict = call_frame.f_locals
        clear_local_dict = True
    try:
        frame_globals = call_frame.f_globals
        if global_dict is None:
            global_dict = frame_globals

        # If `call_frame` is the top frame of the interpreter we can't clear its 
        # `local_dict`, because it is actually the `global_dict`.
        clear_local_dict = clear_local_dict and not frame_globals is local_dict

        arguments = []
        for name in names:
            try:
                a = local_dict[name]
            except KeyError:
                a = global_dict[name]
            arguments.append(numpy.asarray(a))
    finally:
        # If we generated local_dict via an explicit reference to f_locals,
        # clear the dict to prevent creating extra ref counts in the caller's scope
        # See https://github.com/pydata/numexpr/issues/310
        if clear_local_dict:
            local_dict.clear()

    return arguments