Decorator to easily create a jinja extension which acts as a fragment.
421525
def jinja_fragment_extension(tag, endtag=None, name=None, tag_only=False, allow_args=True, callblock_args=None):
    
    if endtag is None:
        endtag = "end" + tag

    def decorator(f):
        def parse(self, parser):
            lineno = parser.stream.next().lineno
            args = []
            kwargs = []
            if allow_args:
                args, kwargs = parse_block_signature(parser)

            call = self.call_method("support_method", args, kwargs, lineno=lineno)
            if tag_only:
                return nodes.Output([call], lineno=lineno)

            call_args = []
            if callblock_args is not None:
                for arg in callblock_args:
                    call_args.append(nodes.Name(arg, 'param', lineno=lineno))

            body = parser.parse_statements(['name:' + endtag], drop_needle=True)
            return nodes.CallBlock(call, call_args, [], body, lineno=lineno)

        def support_method(self, *args, **kwargs):
            return f(*args, **kwargs)

        attrs = {"tags": set([tag]), "parse": parse, "support_method": support_method}
        return type(name or f.__name__, (Extension,), attrs)

    return decorator
493299
def initialize_renderer(extensions=None):
    
    if extensions is None:
        extensions = []

    if isinstance(extensions, str):
        extensions = [extension.strip() for extension in extensions.split(',')]

    for extension in getattr(settings, 'MARKYMARK_EXTENSIONS', DEFAULT_MARKYMARK_EXTENSIONS):
        extensions.append(extension)

    return markdown.Markdown(extensions=extensions)
926026
def _process_extends(self, node, **kwargs):
        

        # find all the blocks in this template
        for b in self.ast.find_all(nodes.Block):

            # if not already in `child_blocks` then this is the first time a
            # block with this name has been encountered.
            if b.name not in self.child_blocks:
                self.child_blocks[b.name] = b
            else:

                # otherwise we have seen this block before, so we need to find the last
                # super_block and add the block from this template to the end.
                block = self.child_blocks.get(b.name)
                while hasattr(block, 'super_block'):
                    block = block.super_block
                block.super_block = b

        # load the parent template
        parent_template = JinjaToJS(template_root=self.template_root,
                                    template_name=node.template.value,
                                    js_module_format=self.js_module_format,
                                    runtime_path=self.runtime_path,
                                    include_prefix=self.include_prefix,
                                    include_ext=self.include_ext,
                                    child_blocks=self.child_blocks,
                                    dependencies=self.dependencies)

        # add the parent templates output to the current output
        self.output.write(parent_template.output.getvalue())

        # Raise an exception so we stop parsing this template
        raise ExtendsException
357255
def load_template(self, template: str) -> Template:
        """"""
        env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
        jinja2_ext = ".jinja2"
        if not template.endswith(jinja2_ext):
            self._log.error("Template file name must end with %s" % jinja2_ext)
            raise ValueError
        if not template[:-len(jinja2_ext)].endswith(".md"):
            self._log.error("Template file should be a Markdown file.")
            raise ValueError
        if not os.path.isabs(template):
            template = os.path.join(os.path.dirname(__file__), template)
        with open(template, encoding="utf-8") as fin:
            template_obj = Template(fin.read(), **env)
        template_obj.filename = template
        self._log.info("Loaded %s", template)
        return template_obj
539588
def get_fragment(self, **kwargs):
        
        gen, namespaces, plan = self.get_fragment_generator(**kwargs)
        graph = ConjunctiveGraph()
        [graph.bind(prefix, u) for (prefix, u) in namespaces]
        [graph.add((s, p, o)) for (_, s, p, o) in gen]

        return graph
347891
def get_rendered_toctree(builder, docname, prune=False, collapse=True):
    
    fulltoc = build_full_toctree(builder,
                                 docname,
                                 prune=prune,
                                 collapse=collapse,
                                 )
    rendered_toc = builder.render_partial(fulltoc)['fragment']
    return rendered_toc
1264644
def prepend_items(self, items, **kwargs):
        
        rv = self.prepend_multi(items, **kwargs)
        for k, v in items.dict.items():
            if k.success:
                k.value = v['fragment'] + k.value

        return rv
608030
def _get_template(self, template_name, template_file):
        
        template = os.path.join(self.location, 'templates',
                                template_name, template_file)
        return jinja2.Template(open(template).read())
777286
function (elems, context) {
            var oldFragment = $.buildFragment,
                ret;

            elems = [elems];
            // Set context per 1.8 logic
            context = context || document;
            context = !context.nodeType && context[0] || context;
            context = context.ownerDocument || context;

            ret = oldFragment.call(jQuery, elems, context);

            return ret.cacheable ? $.clone(ret.fragment) : ret.fragment || ret;
        }
1134263
def create_class(self, data, options=None, **kwargs):
        
        obj_map = dict(
            (cls.type, cls)
            for cls in [
                PythonClass,
                PythonFunction,
                PythonModule,
                PythonMethod,
                PythonPackage,
                PythonAttribute,
                PythonData,
                PythonException,
            ]
        )
        try:
            cls = obj_map[data["type"]]
        except KeyError:
            LOGGER.warning("Unknown type: %s" % data["type"])
        else:
            obj = cls(
                data,
                class_content=self.app.config.autoapi_python_class_content,
                options=self.app.config.autoapi_options,
                jinja_env=self.jinja_env,
                url_root=self.url_root,
                **kwargs
            )

            lines = sphinx.util.docstrings.prepare_docstring(obj.docstring)
            if lines and "autodoc-process-docstring" in self.app.events.events:
                self.app.emit(
                    "autodoc-process-docstring",
                    cls.type,
                    obj.name,
                    None,  # object
                    None,  # options
                    lines,
                )
            obj.docstring = "\n".join(lines)

            for child_data in data.get("children", []):
                for child_obj in self.create_class(
                    child_data, options=options, **kwargs
                ):
                    obj.children.append(child_obj)
            yield obj
1058147
def _create_extended_jinja_tags(self, nodes):
        """"""

        jinja_a = None
        jinja_b = None
        ext_node = None
        ext_nodes = []

        for node in nodes:

            if isinstance(node, EmptyLine):
                continue


            if node.has_children():
                node.children = self._create_extended_jinja_tags(node.children)

            if not isinstance(node, JinjaTag):
                jinja_a = None
                continue

            if jinja_a is None or (
                node.tag_name in self._extended_tags and jinja_a.tag_name not in self._extended_tags[node.tag_name]):
                jinja_a = node
                continue


            if node.tag_name in self._extended_tags and \
                jinja_a.tag_name in self._extended_tags[node.tag_name]:

                if ext_node is None:
                    ext_node = ExtendedJinjaTag()
                    ext_node.add(jinja_a)
                    ext_nodes.append(ext_node)
                ext_node.add(node)

            else:
                ext_node = None
                jinja_a = node

        #replace the nodes with the new extended node
        for node in ext_nodes:
            nodes.insert(nodes.index(node.children[0]), node)

            index = nodes.index(node.children[0])
            del nodes[index:index+len(node.children)]

        return nodes
563185
def template(path, extend_path, out):
    
    files = []

    # add the "extender" template when it exists
    if len(extend_path) > 0:
        # determine the base readme path
        base_path = os.path.dirname(extend_path)
        new_base_path = os.path.join(base_path, "README.{0}.j2".format(out))

        if os.path.exists(new_base_path):
            path = new_base_path

        if os.path.exists(extend_path):
            files = [path, extend_path]
        else:
            ui.error(c.MESSAGES["template_extender_missing"])
            ui.error(extend_path)
            sys.exit(1)
    else:
        files = [path]

    try:
        # Use the subclassed relative environment class
        env = RelEnvironment(trim_blocks=True)

        # Add a unique dict filter, by key.
        # DEPRECATION WARNING: This is only used for backwards compatibility,
        #                      please use the unique filter instead.
        def unique_dict(items, key):
            return {v[key]: v for v in items}.values()

        env.filters["unique_dict"] = unique_dict

        def unique(a):

            # Don’t use the following commented out optimization which is used
            # in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome
            # as it resorts the role dependencies:
            # if isinstance(a,collections.Hashable):
            #     c = set(a)

            c = []
            for x in a:
                if x not in c:
                    c.append(x)
            return c

        env.filters["unique"] = unique

        # create a dictionary of templates
        templates = dict(
            (name, codecs.open(name, "rb", 'UTF-8').read())
            for name in files)
        env.loader = DictLoader(templates)

        # return the final result (the last template in the list)
        return env.get_template(files[len(files) - 1])
    except Exception as err:
        ui.error(c.MESSAGES["template_error"], err)
        sys.exit(1)
429911
def with_app(f):
    """"""
    @wraps(f)
    def decorator(*args, **kwargs):
        app = create_app()
        configure_extensions(app)
        configure_views(app)
        return f(app=app, *args, **kwargs)
    return decorator
934035
def _wrap_jinja_filter(self, function):
        """"""
        def wrapper(*args, **kwargs):
            """Filter wrapper."""
            try:
                return function(*args, **kwargs)
            except Exception:  # pylint: disable=broad-except
                return NestedUndefined()

        # Copy over Jinja filter decoration attributes.
        for attribute in dir(function):
            if attribute.endswith('filter'):
                setattr(wrapper, attribute, getattr(function, attribute))

        return wrapper
142472
function createDom(str) {
    var name = FRAGMENT_REG.test(str) && RegExp.$1;
    if (!(name in CONTAINERS)) {
      name = '*';
    }
    var container = CONTAINERS[name];
    str = str.replace(/(^\s*)|(\s*$)/g, '');
    container.innerHTML = '' + str;
    var dom = container.childNodes[0];
    container.removeChild(dom);
    return dom;
  }
600134
def create(cls):
        

        class NewPopupCreateView(PopupCreateView, cls.parent_class):
            model = cls.model
            form_class = cls.form_class
            popup_name = cls.get_class_verbose_name()
            template_name = cls.get_template_name_create()
            permission_required = cls.get_permission_required('create')

            def get_context_data(self, **kwargs):
                kwargs.update(cls.context_for_all)
                kwargs.update(cls.context_for_create)
                return super(NewPopupCreateView, self).get_context_data(**kwargs)

        return NewPopupCreateView
939844
def stream_template(template_name, **context):
    '''
    
    '''
    app.update_template_context(context)
    template = app.jinja_env.get_template(template_name)
    stream = template.generate(context)
    return Response(stream_with_context(stream))