Find any valid target for "ref()" in the graph by its name and
        package name, or None for any package.
1125
def find_refable_by_name(self, name, package):
        
        return self._find_by_name(name, package, 'nodes', NodeType.refable())
1094525
def check_package_data(dist, attr, value):
    """"""
    if isinstance(value, dict):
        for k, v in value.items():
            if not isinstance(k, str):
                break
            try:
                iter(v)
            except TypeError:
                break
        else:
            return
    raise DistutilsSetupError(
        attr + " must be a dictionary mapping package names to lists of "
        "wildcard patterns"
    )
702177
def contains_project_name(name, link):
    
    def unclutter(string):
        # strip out all python references and remove all excessive characters
        string = string.lower().replace("_", "-").replace(".", "-")
        for replace in ["python-", "py-", "-py", "-python"]:
            string = string.replace(replace, "")
        return re.sub("[^0123456789 a-zA-Z]", "", string).strip()
    return unclutter(name) in unclutter(link)
805827
def _check_all_deps(self, pkg_name=None, pkg_file=None, formula_def=None):
        '''
        
        '''
        if pkg_file and not os.path.exists(pkg_file):
            raise SPMInvocationError('Package file {0} not found'.format(pkg_file))

        self.repo_metadata = self._get_repo_metadata()
        if not formula_def:
            for repo in self.repo_metadata:
                if not isinstance(self.repo_metadata[repo]['packages'], dict):
                    continue
                if pkg_name in self.repo_metadata[repo]['packages']:
                    formula_def = self.repo_metadata[repo]['packages'][pkg_name]['info']

        if not formula_def:
            raise SPMInvocationError('Unable to read formula for {0}'.format(pkg_name))

        # Check to see if the package is already installed
        pkg_info = self._pkgdb_fun('info', pkg_name, self.db_conn)
        pkgs_to_install = []
        if pkg_info is None or self.opts['force']:
            pkgs_to_install.append(pkg_name)
        elif pkg_info is not None and not self.opts['force']:
            raise SPMPackageError(
                'Package {0} already installed, not installing again'.format(formula_def['name'])
            )

        optional_install = []
        recommended_install = []
        if 'dependencies' in formula_def or 'optional' in formula_def or 'recommended' in formula_def:
            self.avail_pkgs = {}
            for repo in self.repo_metadata:
                if not isinstance(self.repo_metadata[repo]['packages'], dict):
                    continue
                for pkg in self.repo_metadata[repo]['packages']:
                    self.avail_pkgs[pkg] = repo

            needs, unavail, optional, recommended = self._resolve_deps(formula_def)

            if unavail:
                raise SPMPackageError(
                    'Cannot install {0}, the following dependencies are needed:\n\n{1}'.format(
                        formula_def['name'], '\n'.join(unavail))
                )

            if optional:
                optional_install.extend(optional)
                for dep_pkg in optional:
                    pkg_info = self._pkgdb_fun('info', formula_def['name'])
                    msg = dep_pkg
                    if isinstance(pkg_info, dict):
                        msg = '{0} [Installed]'.format(dep_pkg)
                    optional_install.append(msg)

            if recommended:
                recommended_install.extend(recommended)
                for dep_pkg in recommended:
                    pkg_info = self._pkgdb_fun('info', formula_def['name'])
                    msg = dep_pkg
                    if isinstance(pkg_info, dict):
                        msg = '{0} [Installed]'.format(dep_pkg)
                    recommended_install.append(msg)

            if needs:
                pkgs_to_install.extend(needs)
                for dep_pkg in needs:
                    pkg_info = self._pkgdb_fun('info', formula_def['name'])
                    msg = dep_pkg
                    if isinstance(pkg_info, dict):
                        msg = '{0} [Installed]'.format(dep_pkg)

        return pkgs_to_install, optional_install, recommended_install
387787
def infer_reference_name(reference_name_or_path):
    
    # identify all cases where reference name or path matches candidate aliases
    reference_file_name = os.path.basename(reference_name_or_path)
    matches = {'file_name': list(), 'full_path': list()}
    for assembly_name in reference_alias_dict.keys():
        candidate_list = [assembly_name] + reference_alias_dict[assembly_name]
        for candidate in candidate_list:
            if candidate.lower() in reference_file_name.lower():
                matches['file_name'].append(assembly_name)
            elif candidate.lower() in reference_name_or_path.lower():
                matches['full_path'].append(assembly_name)
    # remove duplicate matches (happens due to overlapping aliases)
    matches['file_name'] = list(set(matches['file_name']))
    matches['full_path'] = list(set(matches['full_path']))
    # given set of existing matches, choose one to return
    # (first select based on file_name, then full path. If multiples, use most recent)
    if len(matches['file_name']) == 1:
        match = matches['file_name'][0]
    elif len(matches['file_name']) > 1:
        # separate logic for >1 vs 1 to give informative warning
        match = _most_recent_assembly(matches['file_name'])
        warn(
            ('More than one reference ({}) matches path in header ({}); '
             'the most recent one ({}) was used.').format(
                ','.join(matches['file_name']), reference_file_name, match))
    elif len(matches['full_path']) >= 1:
        # combine full-path logic since warning is the same
        match = _most_recent_assembly(matches['full_path'])
        warn((
            'Reference could not be matched against filename ({}); '
            'using best match against full path ({}).').format(
                reference_name_or_path, match))
    else:
        raise ValueError(
            "Failed to infer genome assembly name for %s" % reference_name_or_path)
    return match
189022
def prune_graph(graph_str, package_name):
    
    # find nodes of interest
    g = read_dot(graph_str)
    nodes = set()

    for node, attrs in g.node_attr.iteritems():
        attr = [x for x in attrs if x[0] == "label"]
        if attr:
            label = attr[0][1]
            try:
                req_str = _request_from_label(label)
                request = PackageRequest(req_str)
            except PackageRequestError:
                continue

            if request.name == package_name:
                nodes.add(node)

    if not nodes:
        raise ValueError("The package %r does not appear in the graph."
                         % package_name)

    # find nodes upstream from these nodes
    g_rev = g.reverse()
    accessible_nodes = set()
    access = accessibility(g_rev)
    for node in nodes:
        nodes_ = access.get(node, [])
        accessible_nodes |= set(nodes_)

    # remove inaccessible nodes
    inaccessible_nodes = set(g.nodes()) - accessible_nodes
    for node in inaccessible_nodes:
        g.del_node(node)

    return write_dot(g)
1240959
def find_package_versions(ref, leaf, location)
      return {} unless ref =~ Lyp::PACKAGE_RE
      ref_package = $1
      version_clause = $2

      matches = find_matching_packages(ref)

      # Raise if no match found and we're at top of the tree
      if matches.empty? && (leaf == tree) && !opts[:ignore_missing]
        msg = "Missing package dependency #{ref} in %sYou can install any missing packages by running:\n\n  lyp resolve #{@user_file}"
        error(msg, location)
      end

      matches.each do |p, package_leaf|
        if package_leaf.path
          queue_file_for_processing(package_leaf.path, package_leaf)
        end
      end

      # Setup up dependency leaf
      leaf.add_dependency(ref_package, DependencySpec.new(ref, matches, location))
    end
1347918
def find(self, package, **kwargs):
        
        if not exists(package):
            return None
        name, path = None, None
        enforce_init = kwargs.pop('enforce_init', True)
        if isdir(package):
            if isfile(join(package, '__init__.py')) or not enforce_init:
                name, path = basename(package), package
        elif isfile(package) and package.endswith('.py'):
            name, path = splitext(basename(package))[0], package
        if name and path:
            return PackageSpec(name, path)
        return None
1055290
def _bse_cli_get_refs(args):
    ''''''
    return api.get_references(
        basis_name=args.basis, elements=args.elements, version=args.version, fmt=args.reffmt, data_dir=args.data_dir)
1303829
def _process_refs(x, labels):
    """"""

    # Scan the element list x for Cite elements with known labels
    for i, v in enumerate(x):
        if v['t'] == 'Cite' and len(v['c']) == 2 and \
          _get_label(v['t'], v['c']) in labels:

            # A new reference was found; create some empty attributes for it
            attrs = ['', [], []]

            # Extract the modifiers.  'attrs' is updated in place.  Element
            # deletion could change the index of the Cite being processed.
            if i > 0:
                i = _extract_modifier(x, i, attrs)

            # Attach the attributes
            v['c'].insert(0, attrs)

            # Remove surrounding brackets
            if i > 0 and i < len(x)-1:
                _remove_brackets(x, i)

            # The element list may be changed
            return None  # Forces processing to repeat via _repeat decorator

    return True
1214614
def validate_linked_references(
    link_deps: Tuple[Tuple[int, bytes], ...], bytecode: bytes
) -> None:
    
    offsets, values = zip(*link_deps)
    for idx, offset in enumerate(offsets):
        value = values[idx]
        # https://github.com/python/mypy/issues/4975
        offset_value = int(offset)
        dep_length = len(value)
        end_of_bytes = offset_value + dep_length
        # Ignore b/c whitespace around ':' conflict b/w black & flake8
        actual_bytes = bytecode[offset_value:end_of_bytes]  # noqa: E203
        if actual_bytes != values[idx]:
            raise ValidationError(
                "Error validating linked reference. "
                f"Offset: {offset} "
                f"Value: {values[idx]} "
                f"Bytecode: {bytecode} ."
            )
1013973
private Object find(String name) {
		if (name == null)
			throw new NullPointerException("Dependency name cannot be null");
		if (_references == null)
			throw new NullPointerException("References shall be set");

		return _dependencies.get(name);
	}
341756
def _get_ref_info_helper(cls, repo, ref_path):
        """"""
        tokens = None
        repodir = _git_dir(repo, ref_path)
        try:
            with open(osp.join(repodir, ref_path), 'rt') as fp:
                value = fp.read().rstrip()
            # Don't only split on spaces, but on whitespace, which allows to parse lines like
            # 60b64ef992065e2600bfef6187a97f92398a9144                branch 'master' of git-server:/path/to/repo
            tokens = value.split()
            assert(len(tokens) != 0)
        except (OSError, IOError):
            # Probably we are just packed, find our entry in the packed refs file
            # NOTE: We are not a symbolic ref if we are in a packed file, as these
            # are excluded explicitly
            for sha, path in cls._iter_packed_refs(repo):
                if path != ref_path:
                    continue
                # sha will be used
                tokens = sha, path
                break
            # END for each packed ref
        # END handle packed refs
        if tokens is None:
            raise ValueError("Reference at %r does not exist" % ref_path)

        # is it a reference ?
        if tokens[0] == 'ref:':
            return (None, tokens[1])

        # its a commit
        if repo.re_hexsha_only.match(tokens[0]):
            return (tokens[0], None)

        raise ValueError("Failed to parse reference information from %r" % ref_path)
1090486
def check_missing_references(client):
    """"""
    from renku.models.refs import LinkReference

    missing = [
        ref for ref in LinkReference.iter_items(client)
        if not ref.reference.exists()
    ]

    if not missing:
        return True

    click.secho(
        WARNING + 'There are missing references.'
        '\n  (use "git rm <name>" to clean them)\n\n\t' + '\n\t  '.join(
            click.style(str(ref.path), fg='yellow') + ' -> ' +
            click.style(str(ref.reference), fg='red') for ref in missing
        ) + '\n'
    )
    return False
1247330
def process_link(self, env, refnode, has_explicit_title, title, target):
        
        refnode['chpl:module'] = env.temp_data.get('chpl:module')
        refnode['chpl:class'] = env.temp_data.get('chpl:class')
        if not has_explicit_title:
            # Only has a meaning for the target.
            title = title.lstrip('.')

            # Only has a meaning for the title.
            target = target.lstrip('~')

            if title[0:1] == '~':
                title = title[1:]
                dot = title.rfind('.')
                if dot != -1:
                    title = title[dot+1:]

        # IF the first character is a dot, search more specific names
        # first. Else, search builtins first.
        if target[0:1] == '.':
            target = target[1:]
            refnode['refspecific'] = True

        return title, target
106056
def eval_forward_ref(typ: _ForwardRef):
    
    for frame in stack():
        m = getmodule(frame[0])
        m_name = m.__name__ if m is not None else '<unknown>'
        if m_name.startswith('parsyfiles.tests') or not m_name.startswith('parsyfiles'):
            try:
                # print("File {}:{}".format(frame.filename, frame.lineno))
                return typ._eval_type(frame[0].f_globals, frame[0].f_locals)
            except NameError:
                pass

    raise InvalidForwardRefError(typ)
706032
def select_dag_nodes(reftrack):
    
    refobj = reftrack.get_refobj()
    if not refobj:
        return
    parentns = common.get_namespace(refobj)
    ns = cmds.getAttr("%s.namespace" % refobj)
    fullns = ":".join((parentns.rstrip(":"), ns.lstrip(":")))
    c = cmds.namespaceInfo(fullns, listOnlyDependencyNodes=True, dagPath=True, recurse=True)
    dag = cmds.ls(c, dag=True, ap=True)
    cmds.select(dag, replace=True)