Resolve a ``fragment`` within the referenced ``document``.

        :argument document: the referrant document
        :argument str fragment: a URI fragment to resolve within it
326522
def resolve_fragment(self, document, fragment):
        

        fragment = fragment.lstrip(u"/")
        parts = unquote(fragment).split(u"/") if fragment else []

        for part in parts:
            part = part.replace(u"~1", u"/").replace(u"~0", u"~")

            if isinstance(document, Sequence):
                # Array indexes should be turned into integers
                try:
                    part = int(part)
                except ValueError:
                    pass
            try:
                document = document[part]
            except (TypeError, LookupError):
                raise RefResolutionError(
                    "Unresolvable JSON pointer: %r" % fragment
                )

        return document
911919
def substitute_ref_with_url(self, txt):
        

        # Find sphinx cross-references
        mi = re.finditer(r':([^:]+):`([^`]+)`', txt)
        if mi:
            # Iterate over match objects in iterator returned by re.finditer
            for mo in mi:
                # Initialize link label and url for substitution
                lbl = None
                url = None
                # Get components of current match: full matching text, the
                # role label in the reference, and the name of the
                # referenced type
                mtxt = mo.group(0)
                role = mo.group(1)
                name = mo.group(2)

                # If role is 'ref', the name component is in the form
                # label <name>
                if role == 'ref':
                    ma = re.match(r'\s*([^\s<]+)\s*<([^>]+)+>', name)
                    if ma:
                        name = ma.group(2)
                        lbl = ma.group(1)

                # Try to look up the current cross-reference. Issue a
                # warning if the lookup fails, and do the substitution
                # if it succeeds.
                try:
                    url = self.get_docs_url(role, name)
                    if role != 'ref':
                        lbl = self.get_docs_label(role, name)
                except KeyError as ex:
                    if len(ex.args) == 1 or ex.args[1] != 'role':
                        print('Warning: %s' % ex.args[0])
                else:
                    # If the cross-reference lookup was successful, replace
                    # it with an appropriate link to the online docs
                    rtxt = '[%s](%s)' % (lbl, url)
                    txt = re.sub(mtxt, rtxt, txt, flags=re.M)

        return txt
1045184
def schema_resolve_refs(schema, ref_resolver=None, root=None):
    
    # FIXME more stable implementation that only attempts to resolve {"$ref"} objects where they are allowed.
    if isinstance(schema, dict):
        if len(schema) == 1 and "$ref" in schema and isinstance(schema["$ref"], six.string_types):
            reference = schema["$ref"]
            if reference.startswith("#"):
                # TODO should also resolve any paths within the reference, which would need to be deferred.
                return root
            return ref_resolver(reference)

        resolved = {}
        for k, v in schema.items():
            resolved[k] = schema_resolve_refs(v,
                                              ref_resolver=ref_resolver,
                                              root=root if root is not None else resolved)
        return resolved
    if isinstance(schema, (list, tuple)):
        return [schema_resolve_refs(v, ref_resolver=ref_resolver, root=root) for v in schema]
    return schema
1223768
def resolving(self, ref: str):
        
        new_uri = urlparse.urljoin(self.resolution_scope, ref)
        uri, fragment = urlparse.urldefrag(new_uri)

        if normalize(uri) in self.store:
            schema = self.store[normalize(uri)]
        elif not uri or uri == self.base_uri:
            schema = self.schema
        else:
            schema = resolve_remote(uri, self.handlers)
            if self.cache:
                self.store[normalize(uri)] = schema

        old_base_uri, old_schema = self.base_uri, self.schema
        self.base_uri, self.schema = uri, schema
        try:
            with self.in_scope(uri):
                yield resolve_path(schema, fragment)
        finally:
            self.base_uri, self.schema = old_base_uri, old_schema
206245
def resolve_doc(cls, manifest, target_doc_name, target_doc_package,
                    current_project, node_package):
        
        if target_doc_package is not None:
            return manifest.find_docs_by_name(target_doc_name,
                                              target_doc_package)

        candidate_targets = [current_project, node_package, None]
        target_doc = None
        for candidate in candidate_targets:
            target_doc = manifest.find_docs_by_name(target_doc_name, candidate)
            if target_doc is not None:
                break
        return target_doc
225441
def main_url
      main_page = @options.main_page
      ref = nil
      if main_page
        ref = AllReferences[main_page]
        if ref
          ref = ref.path
        else
          $stderr.puts "Could not find main page #{main_page}"
        end
      end

      unless ref
        for file in @files
          if file.document_self
            ref = file.path 
            break
          end
        end
      end

      unless ref
        $stderr.puts "Couldn't find anything to document"
        $stderr.puts "Perhaps you've used :stopdoc: in all classes"
        exit(1)
      end

      ref
    end
105132
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
        
        fragment = self.fragment
        if fragment is not None:
            return uridecode(fragment, encoding, errors)
        else:
            return default
477416
def resolve_ref(cls, domain, env, fromdocname, builder, typ, target, node,
                    contnode):
        
        # indexes appear to be automatically generated at doc DOMAIN-NAME
        todocname = "bb-%s" % target

        node = nodes.reference('', '', internal=True)
        node['refuri'] = builder.get_relative_uri(fromdocname, todocname)
        node['reftitle'] = cls.localname
        node.append(nodes.emphasis(cls.localname, cls.localname))
        return node
361095
def _definition(self):
        """"""
        footerReference = self._sectPr.get_footerReference(self._hdrftr_index)
        return self._document_part.footer_part(footerReference.rId)
444318
function getItemsFragment() {
  var fragment = document.createDocumentFragment();
  for ( var i = 0; i < 7; i++ ) {
    var item = getImageItem();
    fragment.appendChild( item );
  }
  return fragment;
}
354869
public void resolveReferences() {
        // Resolve annotations to their definitions
        Map<String, AnnotationDefinition> defs = getDefinitionMap();
        final List<Annotation> annos = new ArrayList<Annotation>();

        // Get all the annotation used by the document's statement groups
        for (final StatementGroup sg : statementGroups) {
            annos.addAll(sg.getAllAnnotations());
        }

        // Resolve the references
        for (final Annotation a : annos) {
            AnnotationDefinition ad = a.getDefinition();
            // Skip annotations without definitions
            if (ad == null) {
                continue;
            }

            final String id = ad.getId();
            AnnotationDefinition documentDefinition = defs.get(id);

            // BEL document annotations must reference valid definitions...
            assert documentDefinition != null;
            // ... so sanity check that for now.

            // Resolve the reference to the instance
            a.setDefinition(documentDefinition);
        }

        // Resolve parameters to their namespaces
        Map<String, Namespace> nspcs = getNamespaceMap();
        final List<Parameter> params = new ArrayList<Parameter>();

        // Get all the parameters within the document
        for (final StatementGroup sg : statementGroups) {
            params.addAll(sg.getAllParameters());
        }

        // Get the default namespace if present
        final Namespace defaultNS = nspcs.get(DEFAULT_NAMESPACE_PREFIX);

        // Resolve the references
        for (final Parameter av : params) {
            Namespace ns = av.getNamespace();

            // Skip parameters without namespaces
            if (ns == null) {
                if (defaultNS != null) {
                    av.setNamespace(defaultNS);
                }
                continue;
            }

            final String prefix = ns.getPrefix();
            Namespace documentNamespace = nspcs.get(prefix);

            // BEL document parameters must reference valid namespaces...
            assert documentNamespace != null;
            // ... so sanity check that for now.

            // Resolve the reference to the instance
            av.setNamespace(documentNamespace);
        }
    }
1131828
def find_fragments(base_directory, sections, fragment_directory, definitions):
    
    content = OrderedDict()
    fragment_filenames = []

    for key, val in sections.items():

        if fragment_directory is not None:
            section_dir = os.path.join(base_directory, val, fragment_directory)
        else:
            section_dir = os.path.join(base_directory, val)

        files = os.listdir(section_dir)

        file_content = {}

        for basename in files:
            parts = basename.split(u".")

            counter = 0
            if len(parts) == 1:
                continue
            else:
                ticket, category = parts[:2]

            # If there is a number after the category then use it as a counter,
            # otherwise ignore it.
            # This means 1.feature.1 and 1.feature do not conflict but
            # 1.feature.rst and 1.feature do.
            if len(parts) > 2:
                try:
                    counter = int(parts[2])
                except ValueError:
                    pass

            if category not in definitions:
                continue

            full_filename = os.path.join(section_dir, basename)
            fragment_filenames.append(full_filename)
            with open(full_filename, "rb") as f:
                data = f.read().decode("utf8", "replace")

            if (ticket, category, counter) in file_content:
                raise ValueError(
                    "multiple files for {}.{} in {}".format(
                        ticket, category, section_dir
                    )
                )
            file_content[ticket, category, counter] = data

        content[key] = file_content

    return content, fragment_filenames
736482
def _get_passage(self, urn):
        
        urn = URN(urn)
        subreference = None
        if len(urn) < 4:
            raise InvalidURN
        if urn.reference is not None:
            subreference = str(urn.reference)
        node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)

        r = render_template(
            "cts/GetPassage.xml",
            filters="urn={}".format(urn),
            request_urn=str(urn),
            full_urn=node.urn,
            passage=Markup(node.export(Mimetypes.XML.TEI))
        )
        return r, 200, {"content-type": "application/xml"}
1004411
function(fragment, reg, value) {
            if (typeof fragment == 'string') {
                if (fragment.match(reg)) {
                    fragment = fragment.replace(reg, value);
                }
                return fragment;
            }
            else if (typeof fragment == "function") {
                return fragment;
            }
            // watch out for infinite loops.  We make all changes to the array after iteration.

            var keysToRename = {};
            for (var key in fragment) {
                // recurse
                if (typeof fragment[key] == 'object') {
                    Splunk.util.replaceTokens(fragment[key], reg, value);
                }
                // we have hit a string value.
                else if (typeof fragment[key] == 'string' && fragment[key].match(reg)) {
                    fragment[key] = fragment[key].replace(reg, value);
                }
                // now that the value is changed we check the key itself
                if (key.match(reg)) {
                    // mark this to be changed after we're out of the iterator
                    keysToRename[key] = key.replace(reg, value);
                }
            }
            for (oldKey in keysToRename) {
                var newKey = keysToRename[oldKey];
                fragment[newKey] = fragment[oldKey];
                delete(fragment[oldKey]);
            }
            return fragment;
        }
11863
def p_document_shorthand_with_fragments(self, p):
        
        p[0] = Document(definitions=[Query(selections=p[1])] + p[2])
974304
function _get(refelm, selector)
    {

        function find(elm, selectorFragment)
        {
            var c, results = selectorFragment.id
			?
				((c = ((elm && elm.ownerDocument) || _document).getElementById(selectorFragment.id)) && _isDescendant(c, elm)) ? [c] : []
			:
				toArray(elm.getElementsByTagName(selectorFragment.tag ? selectorFragment.uTag : "*"));
            c = results.length;

            if (c > 0 && (selectorFragment.id || selectorFragment.classes))
            {
                while (c--)
                {
                    if (!_match(results[c], selectorFragment)) results.splice(c, 1)
                }
            }
            return results
        }


        function toArray(nodes)
        {
            try
            {
                return Array.prototype.slice.call(nodes)
            }
            catch (e)
            {
                var arr = [];
                for (var i = 0; i < nodes.length; i++) arr.push(nodes[i]);
                return arr
            }
        }


        function contains(o)
        {
            for (var c = results.length; c--; )
            {
                if (results[c] === o) return _true;
            }
            return _false
        }

        var results = [],
			elements = [refelm],
			selectorFragments = _sel(selector),
			c, lc,
			d, ld,
			e, le,
			fragment,
			elm, elms;

        if (selectorFragments.length == 0) selectorFragments = [{}];

        for (c = 0, lc = selectorFragments.length; c < lc; c++)
        {
            fragment = selectorFragments[c];
            for (d = 0, ld = elements.length; d < ld; d++)
            {
                elm = elements[d];
                switch (fragment.rel)
                {
                    case ">":
                        var children = elm.childNodes;
                        for (e = 0, le = children.length; e < le; e++)
                        {
                            if (_match(children[e], fragment))
                            {
                                results.push(children[e])
                            }
                        }
                        break;

                    case "~":
                        while (elm = elm.nextSibling)
                        {
 							
							if (_match(elm, fragment))
                            {
                                if (contains(elm))
                                {
                                    break;
                                }
                                results.push(elm);
                            }
                        }
                        break;

                    case "+":
                        while ((elm = elm.nextSibling) && elm.nodeType != 1) { };
                        if (elm && _match(elm, fragment))
                        {
                            results.push(elm)
                        }
						
                        break;

                    default:
                        elms = find(elm, fragment);
                        if (c > 0)
                        {
                            for (e = 0, le = elms.length; e < le; e++)
                            {
                                if (!contains(elms[e])) results.push(elms[e])
                            }
                        }
                        else { results = results.concat(elms) }
                        break;
                }
            }

            if (results.length === 0) return [];
            elements = results.splice(0, results.length)

        }
        return elements
    }
1342889
def document(self):
        
        if self.is_document:
            return self
        return self.adapter.wrap_document(self.adapter.impl_document)