Parse a named Verilog file
  
  Args:
    fname (str): File to parse.
  Returns:
    List of parsed objects.
170746
def parse_verilog_file(fname):
  '''
  '''
  with open(fname, 'rt') as fh:
    text = fh.read()
  return parse_verilog(text)
989512
def load(cls, fname):
        
        with open(fname) as f:
            return Config(**json.load(f))
1353808
def _parse_file(self):
        """"""

        # We need to set the CPU type to pull in the right register definitions
        # only preprocess the file (-E) and get rid of gcc extensions that aren't
        # supported in ISO C.
        args = utilities.build_includes(self.arch.includes())

        # args.append('-mcpu=%s' % self.arch.property('chip'))
        args.append('-E')
        args.append('-D__attribute__(x)=')
        args.append('-D__extension__=')
        self.ast = parse_file(self.filepath, use_cpp=True, cpp_path='arm-none-eabi-gcc', cpp_args=args)
896155
def parse(self, fo):
        
        motifs = []

        pwm = []
        info = {}
        for line in fo.readlines():
            if line.startswith("#"):
                vals =  line.strip()[1:].split(" = ")
                if len(vals) > 1:
                    info[vals[0]] = vals[1]
            elif len(line) > 1:
                pwm.append([float(x) for x in line.strip().split("\t")])
            else:
                motifs.append(Motif())
                motifs[-1].consensus = info["Consensus"]
                motifs[-1].width = info["W"]
                motifs[-1].id = info["ID"]
                motifs[-1].pwm = pwm[:]
                pwm = []
            
        return motifs
668776
def regex_findall(regex, fname):
    ''''''
    try:
        with fileobj(fname) as f:
            return re.findall(regex, f.read(), re.MULTILINE)
    except AttributeError:
        return []
27988
def read(fname):
    
    fpath = os.path.join(os.path.dirname(__file__), fname)
    with codecs.open(fpath, 'r', 'utf8') as fhandle:
        return fhandle.read().strip()
186555
def from_file(fn, **options):
        
        if hasattr(fn, 'read'):
            return TableFu(fn, **options)
        with open(fn) as f:
            return TableFu(f, **options)
1222669
def read_kwfile(fname):
    """"""
    d={}
    f=open(fname)
    for line in f:
        try:
            kvpair=re.findall("(.*):: (.*)=(.*)$",line)[0]
            d['name']=os.path.basename(kvpair[0])
            key,val=kvpair[1:]
            d[key.lower()]=val
        except (ValueError,IndexError):
            break
        
    f.close()
    return d
1048861
def read_objfile(fname):
    """"""
    verts = defaultdict(list)
    obj_props = []
    with open(fname) as f:
        lines = f.read().splitlines()

    for line in lines:
        if line:
            split_line = line.strip().split(' ', 1)
            if len(split_line) < 2:
                continue

            prefix, value = split_line[0], split_line[1]
            if prefix == 'o':
                obj_props.append({})
                obj = obj_props[-1]
                obj['f'] = []
                obj[prefix] = value
            # For files without an 'o' statement
            elif prefix == 'v' and len(obj_props) < 1:
                obj_props.append({})
                obj = obj_props[-1]
                obj['f'] = []
                obj['o'] = fname
            if obj_props:
                if prefix[0] == 'v':
                    verts[prefix].append([float(val) for val in value.split(' ')])
                elif prefix == 'f':
                    obj[prefix].append(parse_mixed_delim_str(value))
                else:
                    obj[prefix] = value


    # Reindex vertices to be in face index order, then remove face indices.
    verts = {key: np.array(value) for key, value in iteritems(verts)}
    for obj in obj_props:
        obj['f'] = tuple(np.array(verts) if verts[0] else tuple() for verts in zip(*obj['f']))
        for idx, vertname in enumerate(['v' ,'vt', 'vn']):
            if vertname in verts:
                obj[vertname] = verts[vertname][obj['f'][idx].flatten() - 1, :]
            else:
                obj[vertname] = tuple()
        del obj['f']

    geoms = {obj['o']:obj for obj in obj_props}

    return geoms
1101801
def parse_fn(fn):
    
    try:
        parts = os.path.splitext(os.path.split(fn)[-1])[0].replace('o', '.')\
            .split('_')[:2]
        coords = [float(crds)
                  for crds in re.split('[NSEW]', parts[0] + parts[1])[1:]]
    except:
        coords = [np.nan] * 4
    return coords
829455
def _fset(self, name):
        
        def fset(inst, value):
            # the setter uses the wrapped function as well
            # to allow for value checks
            value = self.fparse(inst, value)
            setattr(inst, name, value)
        return fset
923365
def getlines(fname):
    

    with open(fname, 'rU') as f:
        for line in f:
            if line.strip() and not line.startswith('#'):
                yield line.split('#', 1)[0].strip()
1238278
def parsefile(self, filename):
        
        with open(filename, 'rb') as fd:
            return self.parse(fd.read())
726773
def parse_selfsm(self, f):
		
		#create a dictionary to populate from this sample's file
		parsed_data = dict()
		# set a empty variable which denotes if the headers have been read
		headers = None
		# for each line in the file
		for l in f['f'].splitlines():
			# split the line on tab
			s = l.split("\t")
			# if we haven't already read the header line
			if headers is None:
				# assign this list to headers variable
				headers = s
			# for all rows after the first
			else:
				# clean the sample name (first column) and assign to s_name
				s_name = self.clean_s_name(s[0], f['root'])
				# create a dictionary entry with the first column as a key (sample name) and empty dictionary as a value
				parsed_data[s_name] = {}
				# for each item in list of items in the row
				for i, v in enumerate(s):
					# if it's not the first element (if it's not the name)
					if i != 0:
						# see if CHIP is in the column header and the value is not NA
						if "CHIP" in [headers[i]] and v != "NA":
							# set hide_chip_columns = False so they are not hidden
							self.hide_chip_columns=False
						# try and convert the value into a float
						try:
							# and add to the dictionary the key as the corrsponding item from the header and the value from the list
							parsed_data[s_name][headers[i]] = float(v)
						#if can't convert to float...
						except ValueError:
							# add to the dictionary the key as the corrsponding item from the header and the value from the list
							parsed_data[s_name][headers[i]] = v

		# else return the dictionary
		return parsed_data
773492
def parse_arg(f, kwd, offset=0):
    
    vnames = describe(f)
    return tuple([kwd[k] for k in vnames[offset:]])
198666
def process(fn, bound_names):
    
    if isinstance(fn, _AutoContext):
        fn = fn.fn

    # noinspection PyArgumentList,PyArgumentList
    if isinstance(fn, _FnCodeStr):

        if bound_names:
            assign_code_str = '{syms} = map(state.ctx.get, {names})'.format(
                syms=', '.join(bound_names) + ',', names=repr(bound_names))
        else:
             assign_code_str = ''

        code = "def {0}({1}):\n{2}".format(
            fn.fn_name, ", ".join(fn.fn_args),
            textwrap.indent(assign_code_str + '\n' + fn.code, "    "))

        module_ast = ast.parse(code, fn.filename)

        bound_name_line_inc = int(bool(bound_names)) + 1

        module_ast: ast.Module = ast.increment_lineno(
            module_ast, fn.lineno - bound_name_line_inc)

        fn_ast = module_ast.body[0]

        if isinstance(fn_ast.body[-1], ast.Expr):
            # auto addition of tail expr return
            # in rbnf you don't need to write return if the last statement in the end is an expression.
            it: ast.Expr = fn_ast.body[-1]

            fn_ast.body[-1] = ast.Return(
                lineno=it.lineno, col_offset=it.col_offset, value=it.value)

        filename = fn.filename
        name = fn.fn_name

        code_object = compile(module_ast, filename, "exec")

        local = {}
        # TODO: using types.MethodType here to create the function object leads to various problems.
        # Actually I don't really known why util now.
        exec(code_object, fn.namespace, local)
        ret = local[name]

    else:
        if not bound_names:
            return fn, get_ast(fn)

        code = fn.__code__
        assigns = ast.parse("ctx = state.ctx\n" + "\n".join(
            "{0} = ctx.get({0!r})".format(name) for name in bound_names))

        module_ast = get_ast(fn)
        fn_ast: ast.FunctionDef = module_ast.body[0]
        fn_ast.body = assigns.body + fn_ast.body
        module_ast = ast.Module([fn_ast])

        filename = code.co_filename
        name = code.co_name
        __defaults__ = fn.__defaults__
        __closure__ = fn.__closure__
        __globals__ = fn.__globals__

        code_object = compile(module_ast, filename, "exec")

        code_object = next(
            each for each in code_object.co_consts
            if isinstance(each, types.CodeType) and each.co_name == name)

        # noinspection PyArgumentList,PyUnboundLocalVariable
        ret = types.FunctionType(code_object, __globals__, name, __defaults__,
                                 __closure__)
    return ret, module_ast
37018
def parse():
    
    from fortpy.code import CodeParser
    c = CodeParser()
    
    if args["verbose"]:
        c.verbose = True

    f90files = {}
    c.scan_path(args["source"], f90files)
    for fname, fpath in f90files.items():
        if fname not in c._modulefiles:
            c._modulefiles[fname] = []
        c._parse_from_file(fpath, fname, args["recursive"], args["recursive"], False)

    return c