<commit_before># -*- coding: utf-8 -*-
"""
Section survey element module.
"""
from pyxform.errors import PyXFormError
from pyxform.external_instance import ExternalInstance
from pyxform.question import SurveyElement
from pyxform.utils import node


class Section(SurveyElement):
    def validate(self):
        super(Section, self).validate()
        for element in self.children:
            element.validate()
        self._validate_uniqueness_of_element_names()

    # there's a stronger test of this when creating the xpath
    # dictionary for a survey.
    def _validate_uniqueness_of_element_names(self):
        element_slugs = []
        for element in self.children:
            if any(element.name.lower() == s.lower() for s in element_slugs):
                raise PyXFormError(
                    "There are more than one survey elements named '%s' "
                    "(case-insensitive) in the section named '%s'."
                    % (element.name.lower(), self.name)
                )
            element_slugs.append(element.name)

    def xml_instance(self, **kwargs):
        """
        Creates an xml representation of the section
        """
        append_template = kwargs.pop("append_template", False)

        attributes = {}
        attributes.update(kwargs)
        attributes.update(self.get("instance", {}))
        survey = self.get_root()
        # Resolve field references in attributes
        for key, value in attributes.items():
            attributes[key] = survey.insert_xpaths(value, self)
        result = node(self.name, **attributes)

        for child in self.children:
            repeating_template = None
            if child.get("flat"):
                for grandchild in child.xml_instance_array():
                    result.appendChild(grandchild)
            elif isinstance(child, ExternalInstance):
                continue
            else:
                if isinstance(child, RepeatingSection) and not append_template:
                    append_template = not append_template
                    repeating_template = child.generate_repeating_template()
                result.appendChild(child.xml_instance(append_template=append_template))
            if append_template and repeating_template:
                append_template = not append_template
                result.appendChild(repeating_template)
        return result
    
    def generate_repeating_template(self, **kwargs):
        attributes = {"jr:template": ""}
        result = node(self.name, **attributes)
        for child in self.children:
            if isinstance(child, RepeatingSection):
                result.appendChild(child.template_instance())
            else:   
                result.appendChild(child.xml_instance())
        return result

    def xml_instance_array(self):
        """
        This method is used for generating flat instances.
        """
        for child in self.children:
            if child.get("flat"):
                for grandchild in child.xml_instance_array():
                    yield grandchild
            else:
                yield child.xml_instance()

    def xml_control(self):
        """
        Ideally, we'll have groups up and rolling soon, but for now
        let's just yield controls from all the children of this section
        """
        for e in self.children:
            control = e.xml_control()
            if control is not None:<commit_msg>Using insert_before to put template before instance.<commit_after># -*- coding: utf-8 -*-
"""
Section survey element module.
"""
from pyxform.errors import PyXFormError
from pyxform.external_instance import ExternalInstance
from pyxform.question import SurveyElement
from pyxform.utils import node


class Section(SurveyElement):
    def validate(self):
        super(Section, self).validate()
        for element in self.children:
            element.validate()
        self._validate_uniqueness_of_element_names()

    # there's a stronger test of this when creating the xpath
    # dictionary for a survey.
    def _validate_uniqueness_of_element_names(self):
        element_slugs = []
        for element in self.children:
            if any(element.name.lower() == s.lower() for s in element_slugs):
                raise PyXFormError(
                    "There are more than one survey elements named '%s' "
                    "(case-insensitive) in the section named '%s'."
                    % (element.name.lower(), self.name)
                )
            element_slugs.append(element.name)

    def xml_instance(self, **kwargs):
        """
        Creates an xml representation of the section
        """
        append_template = kwargs.pop("append_template", False)

        attributes = {}
        attributes.update(kwargs)
        attributes.update(self.get("instance", {}))
        survey = self.get_root()
        # Resolve field references in attributes
        for key, value in attributes.items():
            attributes[key] = survey.insert_xpaths(value, self)
        result = node(self.name, **attributes)

        for child in self.children:
            repeating_template = None
            if child.get("flat"):
                for grandchild in child.xml_instance_array():
                    result.appendChild(grandchild)
            elif isinstance(child, ExternalInstance):
                continue
            else:
                if isinstance(child, RepeatingSection) and not append_template:
                    append_template = not append_template
                    repeating_template = child.generate_repeating_template()
                result.appendChild(child.xml_instance(append_template=append_template))
            if append_template and repeating_template:
                append_template = not append_template
                result.insertBefore(repeating_template, result._get_lastChild())
        return result
    
    def generate_repeating_template(self, **kwargs):
        attributes = {"jr:template": ""}
        result = node(self.name, **attributes)
        for child in self.children:
            if isinstance(child, RepeatingSection):
                result.appendChild(child.template_instance())
            else:   
                result.appendChild(child.xml_instance())
        return result

    def xml_instance_array(self):
        """
        This method is used for generating flat instances.
        """
        for child in self.children:
            if child.get("flat"):
                for grandchild in child.xml_instance_array():
                    yield grandchild
            else:
                yield child.xml_instance()

    def xml_control(self):
        """
        Ideally, we'll have groups up and rolling soon, but for now
        let's just yield controls from all the children of this section
        """
        for e in self.children:
            control = e.xml_control()
            if control is not None:
{'fraction_non_alphanumeric': 0.0826981159211851, 'fraction_numerical': 0.00028764562059542645, 'mean_word_length': 2.055360281195079, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 20}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2312629', 'n_tokens_mistral': 1729, 'n_tokens_neox': 1676, 'n_words': 480}