Link all templates, and create the template graph too

        :return: None
163451
def linkify_templates(self):
        
        # First we create a list of all templates
        for i in itertools.chain(iter(list(self.items.values())),
                                 iter(list(self.templates.values()))):
            self.linkify_item_templates(i)
        for i in self:
            i.tags = self.get_all_tags(i)
684006
def template(tpl, template_adapter=SimpleTemplate, **kwargs):
    '''
    
    '''
    if tpl not in TEMPLATES or DEBUG:
        settings = kwargs.get('template_settings',{})
        lookup = kwargs.get('template_lookup', TEMPLATE_PATH)
        if isinstance(tpl, template_adapter):
            TEMPLATES[tpl] = tpl
            if settings: TEMPLATES[tpl].prepare(settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, settings=settings)
        else:
            TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, settings=settings)
    if not TEMPLATES[tpl]:
        abort(500, 'Template (%s) not found' % tpl)
    kwargs['abort'] = abort
    kwargs['request'] = request
    kwargs['response'] = response
    return TEMPLATES[tpl].render(**kwargs)
994216
def create_all(graph):
    
    head = get_current_head(graph)
    if head is None:
        Model.metadata.create_all(graph.postgres)
        stamp_head(graph)
1174053
def templated(template=None, *templates):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            template_ = template
            if template_ is None:
                template_ = request.endpoint.split('.', 1)[1].replace(
                    '.', '/') + '.html'
            context = func(*args, **kwargs)
            if context is None:
                context = {}
            elif not isinstance(context, dict):
                return context
            return custom_render_template(
                list(chain(to_list(template_), templates)), **context)

        return wrapper

    return decorator
1322193
def copy_template(template_name, copy_to, tag_library_name):
    """"""
    import django_extensions
    import shutil

    template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)

    # walk the template structure and copies it
    for d, subdirs, files in os.walk(template_dir):
        relative_dir = d[len(template_dir) + 1:]
        if relative_dir and not os.path.exists(os.path.join(copy_to, relative_dir)):
            os.mkdir(os.path.join(copy_to, relative_dir))
        for i, subdir in enumerate(subdirs):
            if subdir.startswith('.'):
                del subdirs[i]
        for f in files:
            if f.endswith('.pyc') or f.startswith('.DS_Store'):
                continue
            path_old = os.path.join(d, f)
            path_new = os.path.join(copy_to, relative_dir, f.replace('sample', tag_library_name))
            if os.path.exists(path_new):
                path_new = os.path.join(copy_to, relative_dir, f)
                if os.path.exists(path_new):
                    continue
            path_new = path_new.rstrip(".tmpl")
            fp_old = open(path_old, 'r')
            fp_new = open(path_new, 'w')
            fp_new.write(fp_old.read())
            fp_old.close()
            fp_new.close()
            try:
                shutil.copymode(path_old, path_new)
                _make_writeable(path_new)
            except OSError:
                sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
134104
def _build_graph(self):
        ''''''

        # Set palette colors if necessary
        if not self.colors:
            self.palette = self.env.get_template('palette.js')
            self.template_vars.update({'palette': self.palette.render()})
            self.colors = {x['name']: 'palette.color()' for x in self.json_data}

        template_vars = []
        for index, dataset in enumerate(self.json_data):
            group = 'datagroup' + str(index)
            template_vars.append({'name': str(dataset['name']),
                                  'color': self.colors[dataset['name']],
                                  'data': 'json[{0}].data'.format(index)})

        variables = {'dataset': template_vars, 'width': self.width,
                     'height': self.height, 'render': self.renderer,
                     'chart_id': self.chart_id}
        if not self.y_zero:
            variables.update({'min': "min: 'auto',"})

        graph = self.env.get_template('graph.js')
        self.template_vars.update({'graph': graph.render(variables)})
648873
def retrieve_template(self):
        
        links = self.retrieve_instance_links()
        self.log.debug('Links is \n%s', pformat(links))
        self.pipeline_config['instance_links'].update(links)
        jsondata = get_template(
            template_file='infrastructure/app_data.json.j2',
            appinfo=self.appinfo,
            pipeline_config=self.pipeline_config,
            formats=self.generated,
            run_as_user=DEFAULT_RUN_AS_USER)
        self.log.debug('jsondata is %s', pformat(jsondata))
        return jsondata
424303
def render_chart_to_file(self, template_name: str, chart: Any, path: str):
        
        tpl = self.env.get_template(template_name)
        html = tpl.render(chart=self.generate_js_link(chart))
        write_utf8_html_file(path, self._reg_replace(html))
1357273
def _register_template(cls, template_bytes):
    ''''''

    # This implementation won't work if there are nested templates, but
    # we can't do that anyways due to PyGObject limitations so it's ok

    if not hasattr(cls, 'set_template'):
        raise TypeError("Requires PyGObject 3.13.2 or greater")

    cls.set_template(template_bytes)

    bound_methods = set()
    bound_widgets = set()

    # Walk the class, find marked callbacks and child attributes
    for name in dir(cls):
        o = getattr(cls, name, None)

        if inspect.ismethod(o):
            if hasattr(o, '_gtk_callback'):
                bound_methods.add(name)
                # Don't need to call this, as connect_func always gets called
                #cls.bind_template_callback_full(name, o)
        elif isinstance(o, _Child):
            cls.bind_template_child_full(name, True, 0)
            bound_widgets.add(name)

    # Have to setup a special connect function to connect at template init
    # because the methods are not bound yet
    cls.set_connect_func(_connect_func, cls)

    cls.__gtemplate_methods__ = bound_methods
    cls.__gtemplate_widgets__ = bound_widgets

    base_init_template = cls.init_template
    cls.init_template = lambda s: _init_template(s, cls, base_init_template)
748922
def templates(self):
        """"""
        template = lib.EnvGetNextDeftemplate(self._env, ffi.NULL)

        while template != ffi.NULL:
            yield Template(self._env, template)

            template = lib.EnvGetNextDeftemplate(self._env, template)
177811
def find_templates():
    
    templates = []
    templates_directory = (inspect.getsourcefile(lambda: 0).rstrip('__init__.py') +
                           'templates')
    template_files = os.listdir(templates_directory)
    for template_file in template_files:
        if template_file.startswith('.') or not template_file.endswith('.py'):
            continue
        # Hack for dev development and disutils
        try:
            template_module = importlib.import_module('templates.{}'.format(
               template_file.rstrip('.py')
            ))
        except ImportError:
            template_module = importlib.import_module('ross.templates.{}'.format(
               template_file.rstrip('.py')
            ))
        # Iterate throw items in template.
        # If there are variable ends with 'templates',
        # extend templates list with it.
        for (name, content) in template_module.__dict__.items():
            if name.endswith('templates'):
                for (regex_text, data_func) in content:
                    templates.append((re.compile(regex_text, re.IGNORECASE), data_func))
    return templates
216140
def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout):
    
    known_sg, open_sg = _analyze_sg(template['Resources'])
    (graph, edges) = _extract_graph(template.get('Description', ''),
                                    template['Resources'], known_sg, open_sg)
    graph['edges'].extend(edges)
    _handle_terminals(template, graph, 'Parameters', 'source', parameters)
    _handle_terminals(template, graph, 'Outputs', 'sink', outputs)
    graph['subgraphs'].append(_handle_pseudo_params(graph['edges']))

    _render(graph, out=out)
53616
def list_templates(self) -> List[str]:
        
        result = set()
        for loader in self._loaders():
            for template in loader.list_templates():
                result.add(str(template))
        return list(result)
1160195
def find_templates(self):
        
        paths = set()
        for loader in self.get_loaders():
            try:
                module = import_module(loader.__module__)
                get_template_sources = getattr(
                    module, 'get_template_sources', loader.get_template_sources)
                template_sources = get_template_sources('')
                paths.update([t.name if isinstance(t, Origin) else t for t in template_sources])
            except (ImportError, AttributeError):
                pass
        if not paths:
            raise CommandError(
                "No template paths found. None of the configured template loaders provided template paths")
        templates = set()
        for path in paths:
            for root, _, files in os.walk(str(path)):
                templates.update(os.path.join(root, name)
                                 for name in files if not name.startswith('.') and
                                 any(name.endswith(ext) for ext in self.template_exts))
        if not templates:
            raise CommandError(
                "No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.")
        return templates
888487
def _buildTemplates(self):
        

        # Ontology - MAIN PAGE
        contents = self._renderTemplate(
            "markdown/markdown_ontoinfo.md", extraContext=None)
        FILE_NAME = "index.md"
        main_url = self._save2File(contents, FILE_NAME, self.output_path)

        browser_output_path = self.output_path

        if self.ontospy_graph.all_classes:

            # BROWSER PAGES - CLASSES ======
            for entity in self.ontospy_graph.all_classes:
                extra_context = {
                    "main_entity": entity,
                    "main_entity_type": "class",
                    "ontograph": self.ontospy_graph
                }
                contents = self._renderTemplate(
                    "markdown/markdown_classinfo.md",
                    extraContext=extra_context)
                FILE_NAME = entity.slug + ".md"
                self._save2File(contents, FILE_NAME, browser_output_path)

        if self.ontospy_graph.all_properties:

            # BROWSER PAGES - PROPERTIES ======
            for entity in self.ontospy_graph.all_properties:
                extra_context = {
                    "main_entity": entity,
                    "main_entity_type": "property",
                    "ontograph": self.ontospy_graph
                }
                contents = self._renderTemplate(
                    "markdown/markdown_propinfo.md",
                    extraContext=extra_context)
                FILE_NAME = entity.slug + ".md"
                self._save2File(contents, FILE_NAME, browser_output_path)

        if self.ontospy_graph.all_skos_concepts:

            # BROWSER PAGES - CONCEPTS ======
            for entity in self.ontospy_graph.all_skos_concepts:
                extra_context = {
                    "main_entity": entity,
                    "main_entity_type": "concept",
                    "ontograph": self.ontospy_graph
                }
                contents = self._renderTemplate(
                    "markdown/markdown_conceptinfo.md",
                    extraContext=extra_context)
                FILE_NAME = entity.slug + ".ms"
                self._save2File(contents, FILE_NAME, browser_output_path)

        return main_url
488513
def process_templates(input_dir, target_dir, context):
    
    if not target_dir.endswith('/'):
        target_dir = "{}/".format(target_dir)
    if not os.path.exists(target_dir):
        LOGGER.info('Creating: {}'.format(target_dir))
        os.makedirs(target_dir)
    replicate_directory_tree(input_dir, target_dir)
    templates = find_templates(input_dir)
    for templ in templates:
        output_file = templ.replace(input_dir, target_dir)
        output_file = output_file[:-len('.mustache')]
        render_template(templ,  output_file, context)
752389
def get_template_sources(template_name, template_dirs=None):
        
        if not connection.tenant or isinstance(connection.tenant, FakeTenant):
            return
        if not template_dirs:
            try:
                template_dirs = settings.MULTITENANT_TEMPLATE_DIRS
            except AttributeError:
                raise ImproperlyConfigured('To use %s.%s you must define the MULTITENANT_TEMPLATE_DIRS' %
                                           (__name__, FilesystemLoader.__name__))
        for template_dir in template_dirs:
            try:
                if '%s' in template_dir:
                    yield safe_join(template_dir % connection.tenant.domain_url, template_name)
                else:
                    yield safe_join(template_dir, connection.tenant.domain_url, template_name)
            except UnicodeDecodeError:
                # The template dir name was a bytestring that wasn't valid UTF-8.
                raise
            except ValueError:
                # The joined path was located outside of this particular
                # template_dir (it might be inside another one, so this isn't
                # fatal).
                pass