class UnsafeLoaderWarning(YAMLWarning):
    text = """
The default 'Loader' for 'load(stream)' without further arguments can be unsafe.
Use 'load(stream, Loader=strictyaml.ruamel.Loader)' explicitly if that is OK.
Alternatively include the following in your code:

  import warnings
  warnings.simplefilter('ignore', strictyaml.ruamel.error.UnsafeLoaderWarning)

In most other cases you should consider using 'safe_load(stream)'"""
    pass class YAMLError(Exception):
    pass class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, VersionedResolver):
    def __init__(self, stream, version=None, preserve_quotes=None):
        # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
        Reader.__init__(self, stream, loader=self)
        Scanner.__init__(self, loader=self)
        Parser.__init__(self, loader=self)
        Composer.__init__(self, loader=self)
        BaseConstructor.__init__(self, loader=self)
        VersionedResolver.__init__(self, version, loader=self) class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, VersionedResolver):
    def __init__(self, stream, version=None, preserve_quotes=None):
        # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
        Reader.__init__(self, stream, loader=self)
        Scanner.__init__(self, loader=self)
        Parser.__init__(self, loader=self)
        Composer.__init__(self, loader=self)
        SafeConstructor.__init__(self, loader=self)
        VersionedResolver.__init__(self, version, loader=self) class Loader(Reader, Scanner, Parser, Composer, Constructor, VersionedResolver):
    def __init__(self, stream, version=None, preserve_quotes=None):
        # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
        Reader.__init__(self, stream, loader=self)
        Scanner.__init__(self, loader=self)
        Parser.__init__(self, loader=self)
        Composer.__init__(self, loader=self)
        Constructor.__init__(self, loader=self)
        VersionedResolver.__init__(self, version, loader=self) class RoundTripLoader(
    Reader,
    RoundTripScanner,
    RoundTripParser,
    Composer,
    RoundTripConstructor,
    VersionedResolver,
):
    def __init__(self, stream, version=None, preserve_quotes=None):
        # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
        # self.reader = Reader.__init__(self, stream)
        Reader.__init__(self, stream, loader=self)
        RoundTripScanner.__init__(self, loader=self)
        RoundTripParser.__init__(self, loader=self)
        Composer.__init__(self, loader=self)
        RoundTripConstructor.__init__(
            self, preserve_quotes=preserve_quotes, loader=self
        )
        VersionedResolver.__init__(self, version, loader=self) class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver):
    def __init__(
        self,
        stream,
        default_style=None,
        default_flow_style=None,
        canonical=None,
        indent=None,
        width=None,
        allow_unicode=None,
        line_break=None,
        encoding=None,
        explicit_start=None,
        explicit_end=None,
        version=None,
        tags=None,
        block_seq_indent=None,
        top_level_colon_align=None,
        prefix_colon=None,
    ):
        # type: (Any, StreamType, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None   # NOQA
        Emitter.__init__(
            self,
            stream,
            canonical=canonical,
            indent=indent,
            width=width,
            allow_unicode=allow_unicode,
            line_break=line_break,
            block_seq_indent=block_seq_indent,
            dumper=self,
        )
        Serializer.__init__(
            self,
            encoding=encoding,
            explicit_start=explicit_start,
            explicit_end=explicit_end,
            version=version,
            tags=tags,
            dumper=self,
        )
        BaseRepresenter.__init__(
            self,
            default_style=default_style,
            default_flow_style=default_flow_style,
            dumper=self,
        )
        BaseResolver.__init__(self, loadumper=self) class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver):
    def __init__(
        self,
        stream,
        default_style=None,
        default_flow_style=None,
        canonical=None,
        indent=None,
        width=None,
        allow_unicode=None,
        line_break=None,
        encoding=None,
        explicit_start=None,
        explicit_end=None,
        version=None,
        tags=None,
        block_seq_indent=None,
        top_level_colon_align=None,
        prefix_colon=None,
    ):
        # type: (StreamType, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None  # NOQA
        Emitter.__init__(
            self,
            stream,
            canonical=canonical,
            indent=indent,
            width=width,
            allow_unicode=allow_unicode,
            line_break=line_break,
            block_seq_indent=block_seq_indent,
            dumper=self,
        )
        Serializer.__init__(
            self,
            encoding=encoding,
            explicit_start=explicit_start,
            explicit_end=explicit_end,
            version=version,
            tags=tags,
            dumper=self,
        )
        SafeRepresenter.__init__(
            self,
            default_style=default_style,
            default_flow_style=default_flow_style,
            dumper=self,
        )
        Resolver.__init__(self, loadumper=self) class Dumper(Emitter, Serializer, Representer, Resolver):
    def __init__(
        self,
        stream,
        default_style=None,
        default_flow_style=None,
        canonical=None,
        indent=None,
        width=None,
        allow_unicode=None,
        line_break=None,
        encoding=None,
        explicit_start=None,
        explicit_end=None,
        version=None,
        tags=None,
        block_seq_indent=None,
        top_level_colon_align=None,
        prefix_colon=None,
    ):
        # type: (StreamType, Any, Any, Optional[bool], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None   # NOQA
        Emitter.__init__(
            self,
            stream,
            canonical=canonical,
            indent=indent,
            width=width,
            allow_unicode=allow_unicode,
            line_break=line_break,
            block_seq_indent=block_seq_indent,
            dumper=self,
        )
        Serializer.__init__(
            self,
            encoding=encoding,
            explicit_start=explicit_start,
            explicit_end=explicit_end,
            version=version,
            tags=tags,
            dumper=self,
        )
        Representer.__init__(
            self,
            default_style=default_style,
            default_flow_style=default_flow_style,
            dumper=self,
        )
        Resolver.__init__(self, loadumper=self) class RoundTripDumper(Emitter, Serializer, RoundTripRepresenter, VersionedResolver):
    def __init__(
        self,
        stream,
        default_style=None,
        default_flow_style=None,
        canonical=None,
        indent=None,
        width=None,
        allow_unicode=None,
        line_break=None,
        encoding=None,
        explicit_start=None,
        explicit_end=None,
        version=None,
        tags=None,
        block_seq_indent=None,
        top_level_colon_align=None,
        prefix_colon=None,
    ):
        # type: (StreamType, Any, Optional[bool], Optional[int], Optional[int], Optional[int], Optional[bool], Any, Any, Optional[bool], Optional[bool], Any, Any, Any, Any, Any) -> None  # NOQA
        Emitter.__init__(
            self,
            stream,
            canonical=canonical,
            indent=indent,
            width=width,
            allow_unicode=allow_unicode,
            line_break=line_break,
            block_seq_indent=block_seq_indent,
            top_level_colon_align=top_level_colon_align,
            prefix_colon=prefix_colon,
            dumper=self,
        )
        Serializer.__init__(
            self,
            encoding=encoding,
            explicit_start=explicit_start,
            explicit_end=explicit_end,
            version=version,
            tags=tags,
            dumper=self,
        )
        RoundTripRepresenter.__init__(
            self,
            default_style=default_style,
            default_flow_style=default_flow_style,
            dumper=self,
        )
        VersionedResolver.__init__(self, loader=self) _DEFAULT_YAML_VERSION = (1, 2)
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
    MAXSIZE = sys.maxsize
UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2
DBG_TOKEN = 1
DBG_EVENT = 2
DBG_NODE = 4
    class ordereddict(OrderedDict):  # type: ignore
    class ObjectCounter(object):
class Nprint(object):
class MutableSliceableSequence(MutableSequence):  # type: ignore
            def insert(self, pos, key, value):
    def utf8(s):
    def to_str(s):
    def to_unicode(s):
    def utf8(s):
    def to_str(s):
    def to_unicode(s):
def with_metaclass(meta, *bases):
        def __init__(self):
        def __call__(self, k):
        def dump(self):
def dbg(val=None):
    def __init__(self, file_name=None):
    def __call__(self, *args, **kw):
    def set_max_print(self, i):
def check_namespace_char(ch):
def check_anchorname_char(ch):
def version_tnf(t1, t2=None):
    def __getitem__(self, index):
    def __setitem__(self, index, value):
    def __delitem__(self, index):
    def __getsingleitem__(self, index):
    def __setsingleitem__(self, index, value):
    def __delsingleitem__(self, index): class VersionedResolver(BaseResolver):
    """
    contrary to the "normal" resolver, the smart resolver delays loading
    the pattern matching rules. That way it can decide to load 1.1 rules
    or the (default) 1.2 rules, that no longer support octal without 0o, sexagesimals
    and Yes/No/On/Off booleans.
    """

    def __init__(self, version=None, loader=None, loadumper=None):
        # type: (Optional[VersionType], Any, Any) -> None
        if loader is None and loadumper is not None:
            loader = loadumper
        BaseResolver.__init__(self, loader)
        self._loader_version = self.get_loader_version(version)
        self._version_implicit_resolver = {}  # type: Dict[Any, Any]

    def add_version_implicit_resolver(self, version, tag, regexp, first):
        # type: (VersionType, Any, Any, Any) -> None
        if first is None:
            first = [None]
        impl_resolver = self._version_implicit_resolver.setdefault(version, {})
        for ch in first:
            impl_resolver.setdefault(ch, []).append((tag, regexp))

    def get_loader_version(self, version):
        # type: (Optional[VersionType]) -> Any
        if version is None or isinstance(version, tuple):
            return version
        if isinstance(version, list):
            return tuple(version)
        # assume string
        return tuple(map(int, version.split(u".")))

    @property
    def versioned_resolver(self):
        # type: () -> Any
        """
        select the resolver based on the version we are parsing
        """
        version = self.processing_version
        if version not in self._version_implicit_resolver:
            for x in implicit_resolvers:
                if version in x[0]:
                    self.add_version_implicit_resolver(version, x[1], x[2], x[3])
        return self._version_implicit_resolver[version]

    def resolve(self, kind, value, implicit):
        # type: (Any, Any, Any) -> Any
        if kind is ScalarNode and implicit[0]:
            if value == "":
                resolvers = self.versioned_resolver.get("", [])
            else:
                resolvers = self.versioned_resolver.get(value[0], [])
            resolvers += self.versioned_resolver.get(None, [])
            for tag, regexp in resolvers:
                if regexp.match(value):
                    return tag
            implicit = implicit[1]
        if bool(self.yaml_path_resolvers):
            exact_paths = self.resolver_exact_paths[-1]
            if kind in exact_paths:
                return exact_paths[kind]
            if None in exact_paths:
                return exact_paths[None]
        if kind is ScalarNode:
            return self.DEFAULT_SCALAR_TAG
        elif kind is SequenceNode:
            return self.DEFAULT_SEQUENCE_TAG
        elif kind is MappingNode:
            return self.DEFAULT_MAPPING_TAG

    @property
    def processing_version(self):
        # type: () -> Any
        try:
            version = self.loadumper._scanner.yaml_version
        except AttributeError:
            try:
                if hasattr(self.loadumper, "typ"):
                    version = self.loadumper.version
                else:
                    version = self.loadumper._serializer.use_version  # dumping
            except AttributeError:
                version = None
        if version is None:
            version = self._loader_version
            if version is None:
                version = _DEFAULT_YAML_VERSION
        return version class Resolver(BaseResolver):
    pass class BaseRepresenter(object):

    yaml_representers = {}  # type: Dict[Any, Any]
    yaml_multi_representers = {}  # type: Dict[Any, Any]

    def __init__(self, default_style=None, default_flow_style=None, dumper=None):
        # type: (Any, Any, Any, Any) -> None
        self.dumper = dumper
        if self.dumper is not None:
            self.dumper._representer = self
        self.default_style = default_style
        self.default_flow_style = default_flow_style
        self.represented_objects = {}  # type: Dict[Any, Any]
        self.object_keeper = []  # type: List[Any]
        self.alias_key = None  # type: Optional[int]
        self.sort_base_mapping_type_on_output = True

    @property
    def serializer(self):
        # type: () -> Any
        try:
            if hasattr(self.dumper, "typ"):
                return self.dumper.serializer
            return self.dumper._serializer
        except AttributeError:
            return self  # cyaml

    def represent(self, data):
        # type: (Any) -> None
        node = self.represent_data(data)
        self.serializer.serialize(node)
        self.represented_objects = {}
        self.object_keeper = []
        self.alias_key = None

    def represent_data(self, data):
        # type: (Any) -> Any
        if self.ignore_aliases(data):
            self.alias_key = None
        else:
            self.alias_key = id(data)
        if self.alias_key is not None:
            if self.alias_key in self.represented_objects:
                node = self.represented_objects[self.alias_key]
                # if node is None:
                #     raise RepresenterError(
                #          "recursive objects are not allowed: %r" % data)
                return node
            # self.represented_objects[alias_key] = None
            self.object_keeper.append(data)
        data_types = type(data).__mro__
        if PY2:
            # if type(data) is types.InstanceType:
            if isinstance(data, types.InstanceType):
                data_types = get_classobj_bases(data.__class__) + list(data_types)
        if data_types[0] in self.yaml_representers:
            node = self.yaml_representers[data_types[0]](self, data)
        else:
            for data_type in data_types:
                if data_type in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[data_type](self, data)
                    break
            else:
                if None in self.yaml_multi_representers:
                    node = self.yaml_multi_representers[None](self, data)
                elif None in self.yaml_representers:
                    node = self.yaml_representers[None](self, data)
                else:
                    node = ScalarNode(None, text_type(data))
        # if alias_key is not None:
        #     self.represented_objects[alias_key] = node
        return node

    def represent_key(self, data):
        # type: (Any) -> Any
        """
        David Fraser: Extract a method to represent keys in mappings, so that
        a subclass can choose not to quote them (for example)
        used in represent_mapping
        https://bitbucket.org/davidfraser/pyyaml/commits/d81df6eb95f20cac4a79eed95ae553b5c6f77b8c
        """
        return self.represent_data(data)

    @classmethod
    def add_representer(cls, data_type, representer):
        # type: (Any, Any) -> None
        if "yaml_representers" not in cls.__dict__:
            cls.yaml_representers = cls.yaml_representers.copy()
        cls.yaml_representers[data_type] = representer

    @classmethod
    def add_multi_representer(cls, data_type, representer):
        # type: (Any, Any) -> None
        if "yaml_multi_representers" not in cls.__dict__:
            cls.yaml_multi_representers = cls.yaml_multi_representers.copy()
        cls.yaml_multi_representers[data_type] = representer

    def represent_scalar(self, tag, value, style=None, anchor=None):
        # type: (Any, Any, Any, Any) -> Any
        if style is None:
            style = self.default_style
        comment = None
        if style and style[0] in "|>":
            comment = getattr(value, "comment", None)
            if comment:
                comment = [None, [comment]]
        node = ScalarNode(tag, value, style=style, comment=comment, anchor=anchor)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        return node

    def represent_sequence(self, tag, sequence, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        node = SequenceNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        for item in sequence:
            node_item = self.represent_data(item)
            if not (isinstance(node_item, ScalarNode) and not node_item.style):
                best_style = False
            value.append(node_item)
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def represent_omap(self, tag, omap, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        node = SequenceNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        for item_key in omap:
            item_val = omap[item_key]
            node_item = self.represent_data({item_key: item_val})
            # if not (isinstance(node_item, ScalarNode) \
            #    and not node_item.style):
            #     best_style = False
            value.append(node_item)
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def represent_mapping(self, tag, mapping, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        node = MappingNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        if hasattr(mapping, "items"):
            mapping = list(mapping.items())
            if self.sort_base_mapping_type_on_output:
                try:
                    mapping = sorted(mapping)
                except TypeError:
                    pass
        for item_key, item_value in mapping:
            node_key = self.represent_key(item_key)
            node_value = self.represent_data(item_value)
            if not (isinstance(node_key, ScalarNode) and not node_key.style):
                best_style = False
            if not (isinstance(node_value, ScalarNode) and not node_value.style):
                best_style = False
            value.append((node_key, node_value))
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def ignore_aliases(self, data):
        # type: (Any) -> bool
        return False class SafeRepresenter(BaseRepresenter):
    def ignore_aliases(self, data):
        # type: (Any) -> bool
        # https://docs.python.org/3/reference/expressions.html#parenthesized-forms :
        # "i.e. two occurrences of the empty tuple may or may not yield the same object"
        # so "data is ()" should not be used
        if data is None or (isinstance(data, tuple) and data == ()):
            return True
        if isinstance(data, (binary_type, text_type, bool, int, float)):
            return True
        return False

    def represent_none(self, data):
        # type: (Any) -> Any
        return self.represent_scalar(u"tag:yaml.org,2002:null", u"null")

    if PY3:

        def represent_str(self, data):
            # type: (Any) -> Any
            return self.represent_scalar(u"tag:yaml.org,2002:str", data)

        def represent_binary(self, data):
            # type: (Any) -> Any
            if hasattr(base64, "encodebytes"):
                data = base64.encodebytes(data).decode("ascii")
            else:
                data = base64.encodestring(data).decode("ascii")
            return self.represent_scalar(u"tag:yaml.org,2002:binary", data, style="|")

    else:

        def represent_str(self, data):
            # type: (Any) -> Any
            tag = None
            style = None
            try:
                data = unicode(data, "ascii")
                tag = u"tag:yaml.org,2002:str"
            except UnicodeDecodeError:
                try:
                    data = unicode(data, "utf-8")
                    tag = u"tag:yaml.org,2002:str"
                except UnicodeDecodeError:
                    data = data.encode("base64")
                    tag = u"tag:yaml.org,2002:binary"
                    style = "|"
            return self.represent_scalar(tag, data, style=style)

        def represent_unicode(self, data):
            # type: (Any) -> Any
            return self.represent_scalar(u"tag:yaml.org,2002:str", data)

    def represent_bool(self, data, anchor=None):
        # type: (Any, Optional[Any]) -> Any
        try:
            value = self.dumper.boolean_representation[bool(data)]
        except AttributeError:
            if data:
                value = u"true"
            else:
                value = u"false"
        return self.represent_scalar(u"tag:yaml.org,2002:bool", value, anchor=anchor)

    def represent_int(self, data):
        # type: (Any) -> Any
        return self.represent_scalar(u"tag:yaml.org,2002:int", text_type(data))

    if PY2:

        def represent_long(self, data):
            # type: (Any) -> Any
            return self.represent_scalar(u"tag:yaml.org,2002:int", text_type(data))

    inf_value = 1e300
    while repr(inf_value) != repr(inf_value * inf_value):
        inf_value *= inf_value

    def represent_float(self, data):
        # type: (Any) -> Any
        if data != data or (data == 0.0 and data == 1.0):
            value = u".nan"
        elif data == self.inf_value:
            value = u".inf"
        elif data == -self.inf_value:
            value = u"-.inf"
        else:
            value = to_unicode(repr(data)).lower()
            if getattr(self.serializer, "use_version", None) == (1, 1):
                if u"." not in value and u"e" in value:
                    # Note that in some cases `repr(data)` represents a float number
                    # without the decimal parts.  For instance:
                    #   >>> repr(1e17)
                    #   '1e17'
                    # Unfortunately, this is not a valid float representation according
                    # to the definition of the `!!float` tag in YAML 1.1.  We fix
                    # this by adding '.0' before the 'e' symbol.
                    value = value.replace(u"e", u".0e", 1)
        return self.represent_scalar(u"tag:yaml.org,2002:float", value)

    def represent_list(self, data):
        # type: (Any) -> Any
        # pairs = (len(data) > 0 and isinstance(data, list))
        # if pairs:
        #     for item in data:
        #         if not isinstance(item, tuple) or len(item) != 2:
        #             pairs = False
        #             break
        # if not pairs:
        return self.represent_sequence(u"tag:yaml.org,2002:seq", data)

    # value = []
    # for item_key, item_value in data:
    #     value.append(self.represent_mapping(u'tag:yaml.org,2002:map',
    #         [(item_key, item_value)]))
    # return SequenceNode(u'tag:yaml.org,2002:pairs', value)

    def represent_dict(self, data):
        # type: (Any) -> Any
        return self.represent_mapping(u"tag:yaml.org,2002:map", data)

    def represent_ordereddict(self, data):
        # type: (Any) -> Any
        return self.represent_omap(u"tag:yaml.org,2002:omap", data)

    def represent_set(self, data):
        # type: (Any) -> Any
        value = {}  # type: Dict[Any, None]
        for key in data:
            value[key] = None
        return self.represent_mapping(u"tag:yaml.org,2002:set", value)

    def represent_date(self, data):
        # type: (Any) -> Any
        value = to_unicode(data.isoformat())
        return self.represent_scalar(u"tag:yaml.org,2002:timestamp", value)

    def represent_datetime(self, data):
        # type: (Any) -> Any
        value = to_unicode(data.isoformat(" "))
        return self.represent_scalar(u"tag:yaml.org,2002:timestamp", value)

    def represent_yaml_object(self, tag, data, cls, flow_style=None):
        # type: (Any, Any, Any, Any) -> Any
        if hasattr(data, "__getstate__"):
            state = data.__getstate__()
        else:
            state = data.__dict__.copy()
        return self.represent_mapping(tag, state, flow_style=flow_style)

    def represent_undefined(self, data):
        # type: (Any) -> None
        raise RepresenterError("cannot represent an object: %s" % (data,)) class Representer(SafeRepresenter):
    if PY2:

        def represent_str(self, data):
            # type: (Any) -> Any
            tag = None
            style = None
            try:
                data = unicode(data, "ascii")
                tag = u"tag:yaml.org,2002:str"
            except UnicodeDecodeError:
                try:
                    data = unicode(data, "utf-8")
                    tag = u"tag:yaml.org,2002:python/str"
                except UnicodeDecodeError:
                    data = data.encode("base64")
                    tag = u"tag:yaml.org,2002:binary"
                    style = "|"
            return self.represent_scalar(tag, data, style=style)

        def represent_unicode(self, data):
            # type: (Any) -> Any
            tag = None
            try:
                data.encode("ascii")
                tag = u"tag:yaml.org,2002:python/unicode"
            except UnicodeEncodeError:
                tag = u"tag:yaml.org,2002:str"
            return self.represent_scalar(tag, data)

        def represent_long(self, data):
            # type: (Any) -> Any
            tag = u"tag:yaml.org,2002:int"
            if int(data) is not data:
                tag = u"tag:yaml.org,2002:python/long"
            return self.represent_scalar(tag, to_unicode(data))

    def represent_complex(self, data):
        # type: (Any) -> Any
        if data.imag == 0.0:
            data = u"%r" % data.real
        elif data.real == 0.0:
            data = u"%rj" % data.imag
        elif data.imag > 0:
            data = u"%r+%rj" % (data.real, data.imag)
        else:
            data = u"%r%rj" % (data.real, data.imag)
        return self.represent_scalar(u"tag:yaml.org,2002:python/complex", data)

    def represent_tuple(self, data):
        # type: (Any) -> Any
        return self.represent_sequence(u"tag:yaml.org,2002:python/tuple", data)

    def represent_name(self, data):
        # type: (Any) -> Any
        try:
            name = u"%s.%s" % (data.__module__, data.__qualname__)
        except AttributeError:
            # probably PY2
            name = u"%s.%s" % (data.__module__, data.__name__)
        return self.represent_scalar(u"tag:yaml.org,2002:python/name:" + name, "")

    def represent_module(self, data):
        # type: (Any) -> Any
        return self.represent_scalar(
            u"tag:yaml.org,2002:python/module:" + data.__name__, ""
        )

    if PY2:

        def represent_instance(self, data):
            # type: (Any) -> Any
            # For instances of classic classes, we use __getinitargs__ and
            # __getstate__ to serialize the data.

            # If data.__getinitargs__ exists, the object must be reconstructed
            # by calling cls(**args), where args is a tuple returned by
            # __getinitargs__. Otherwise, the cls.__init__ method should never
            # be called and the class instance is created by instantiating a
            # trivial class and assigning to the instance's __class__ variable.

            # If data.__getstate__ exists, it returns the state of the object.
            # Otherwise, the state of the object is data.__dict__.

            # We produce either a !!python/object or !!python/object/new node.
            # If data.__getinitargs__ does not exist and state is a dictionary,
            # we produce a !!python/object node . Otherwise we produce a
            # !!python/object/new node.

            cls = data.__class__
            class_name = u"%s.%s" % (cls.__module__, cls.__name__)
            args = None
            state = None
            if hasattr(data, "__getinitargs__"):
                args = list(data.__getinitargs__())
            if hasattr(data, "__getstate__"):
                state = data.__getstate__()
            else:
                state = data.__dict__
            if args is None and isinstance(state, dict):
                return self.represent_mapping(
                    u"tag:yaml.org,2002:python/object:" + class_name, state
                )
            if isinstance(state, dict) and not state:
                return self.represent_sequence(
                    u"tag:yaml.org,2002:python/object/new:" + class_name, args
                )
            value = {}
            if bool(args):
                value["args"] = args
            value["state"] = state  # type: ignore
            return self.represent_mapping(
                u"tag:yaml.org,2002:python/object/new:" + class_name, value
            )

    def represent_object(self, data):
        # type: (Any) -> Any
        # We use __reduce__ API to save the data. data.__reduce__ returns
        # a tuple of length 2-5:
        #   (function, args, state, listitems, dictitems)

        # For reconstructing, we calls function(*args), then set its state,
        # listitems, and dictitems if they are not None.

        # A special case is when function.__name__ == '__newobj__'. In this
        # case we create the object with args[0].__new__(*args).

        # Another special case is when __reduce__ returns a string - we don't
        # support it.

        # We produce a !!python/object, !!python/object/new or
        # !!python/object/apply node.

        cls = type(data)
        if cls in copyreg.dispatch_table:
            reduce = copyreg.dispatch_table[cls](data)
        elif hasattr(data, "__reduce_ex__"):
            reduce = data.__reduce_ex__(2)
        elif hasattr(data, "__reduce__"):
            reduce = data.__reduce__()
        else:
            raise RepresenterError("cannot represent object: %r" % (data,))
        reduce = (list(reduce) + [None] * 5)[:5]
        function, args, state, listitems, dictitems = reduce
        args = list(args)
        if state is None:
            state = {}
        if listitems is not None:
            listitems = list(listitems)
        if dictitems is not None:
            dictitems = dict(dictitems)
        if function.__name__ == "__newobj__":
            function = args[0]
            args = args[1:]
            tag = u"tag:yaml.org,2002:python/object/new:"
            newobj = True
        else:
            tag = u"tag:yaml.org,2002:python/object/apply:"
            newobj = False
        try:
            function_name = u"%s.%s" % (function.__module__, function.__qualname__)
        except AttributeError:
            # probably PY2
            function_name = u"%s.%s" % (function.__module__, function.__name__)
        if (
            not args
            and not listitems
            and not dictitems
            and isinstance(state, dict)
            and newobj
        ):
            return self.represent_mapping(
                u"tag:yaml.org,2002:python/object:" + function_name, state
            )
        if not listitems and not dictitems and isinstance(state, dict) and not state:
            return self.represent_sequence(tag + function_name, args)
        value = {}
        if args:
            value["args"] = args
        if state or not isinstance(state, dict):
            value["state"] = state
        if listitems:
            value["listitems"] = listitems
        if dictitems:
            value["dictitems"] = dictitems
        return self.represent_mapping(tag + function_name, value) class RoundTripRepresenter(SafeRepresenter):
    # need to add type here and write out the .comment
    # in serializer and emitter

    def __init__(self, default_style=None, default_flow_style=None, dumper=None):
        # type: (Any, Any, Any) -> None
        if not hasattr(dumper, "typ") and default_flow_style is None:
            default_flow_style = False
        SafeRepresenter.__init__(
            self,
            default_style=default_style,
            default_flow_style=default_flow_style,
            dumper=dumper,
        )

    def ignore_aliases(self, data):
        # type: (Any) -> bool
        try:
            if data.anchor is not None and data.anchor.value is not None:
                return False
        except AttributeError:
            pass
        return SafeRepresenter.ignore_aliases(self, data)

    def represent_none(self, data):
        # type: (Any) -> Any
        if (
            len(self.represented_objects) == 0
            and not self.serializer.use_explicit_start
        ):
            # this will be open ended (although it is not yet)
            return self.represent_scalar(u"tag:yaml.org,2002:null", u"null")
        return self.represent_scalar(u"tag:yaml.org,2002:null", "")

    def represent_literal_scalarstring(self, data):
        # type: (Any) -> Any
        tag = None
        style = "|"
        anchor = data.yaml_anchor(any=True)
        if PY2 and not isinstance(data, unicode):
            data = unicode(data, "ascii")
        tag = u"tag:yaml.org,2002:str"
        return self.represent_scalar(tag, data, style=style, anchor=anchor)

    represent_preserved_scalarstring = represent_literal_scalarstring

    def represent_folded_scalarstring(self, data):
        # type: (Any) -> Any
        tag = None
        style = ">"
        anchor = data.yaml_anchor(any=True)
        for fold_pos in reversed(getattr(data, "fold_pos", [])):
            if (
                data[fold_pos] == " "
                and (fold_pos > 0 and not data[fold_pos - 1].isspace())
                and (fold_pos < len(data) and not data[fold_pos + 1].isspace())
            ):
                data = data[:fold_pos] + "\a" + data[fold_pos:]
        if PY2 and not isinstance(data, unicode):
            data = unicode(data, "ascii")
        tag = u"tag:yaml.org,2002:str"
        return self.represent_scalar(tag, data, style=style, anchor=anchor)

    def represent_single_quoted_scalarstring(self, data):
        # type: (Any) -> Any
        tag = None
        style = "'"
        anchor = data.yaml_anchor(any=True)
        if PY2 and not isinstance(data, unicode):
            data = unicode(data, "ascii")
        tag = u"tag:yaml.org,2002:str"
        return self.represent_scalar(tag, data, style=style, anchor=anchor)

    def represent_double_quoted_scalarstring(self, data):
        # type: (Any) -> Any
        tag = None
        style = '"'
        anchor = data.yaml_anchor(any=True)
        if PY2 and not isinstance(data, unicode):
            data = unicode(data, "ascii")
        tag = u"tag:yaml.org,2002:str"
        return self.represent_scalar(tag, data, style=style, anchor=anchor)

    def represent_plain_scalarstring(self, data):
        # type: (Any) -> Any
        tag = None
        style = ""
        anchor = data.yaml_anchor(any=True)
        if PY2 and not isinstance(data, unicode):
            data = unicode(data, "ascii")
        tag = u"tag:yaml.org,2002:str"
        return self.represent_scalar(tag, data, style=style, anchor=anchor)

    def insert_underscore(self, prefix, s, underscore, anchor=None):
        # type: (Any, Any, Any, Any) -> Any
        if underscore is None:
            return self.represent_scalar(
                u"tag:yaml.org,2002:int", prefix + s, anchor=anchor
            )
        if underscore[0]:
            sl = list(s)
            pos = len(s) - underscore[0]
            while pos > 0:
                sl.insert(pos, "_")
                pos -= underscore[0]
            s = "".join(sl)
        if underscore[1]:
            s = "_" + s
        if underscore[2]:
            s += "_"
        return self.represent_scalar(
            u"tag:yaml.org,2002:int", prefix + s, anchor=anchor
        )

    def represent_scalar_int(self, data):
        # type: (Any) -> Any
        if data._width is not None:
            s = "{:0{}d}".format(data, data._width)
        else:
            s = format(data, "d")
        anchor = data.yaml_anchor(any=True)
        return self.insert_underscore("", s, data._underscore, anchor=anchor)

    def represent_binary_int(self, data):
        # type: (Any) -> Any
        if data._width is not None:
            # cannot use '{:#0{}b}', that strips the zeros
            s = "{:0{}b}".format(data, data._width)
        else:
            s = format(data, "b")
        anchor = data.yaml_anchor(any=True)
        return self.insert_underscore("0b", s, data._underscore, anchor=anchor)

    def represent_octal_int(self, data):
        # type: (Any) -> Any
        if data._width is not None:
            # cannot use '{:#0{}o}', that strips the zeros
            s = "{:0{}o}".format(data, data._width)
        else:
            s = format(data, "o")
        anchor = data.yaml_anchor(any=True)
        return self.insert_underscore("0o", s, data._underscore, anchor=anchor)

    def represent_hex_int(self, data):
        # type: (Any) -> Any
        if data._width is not None:
            # cannot use '{:#0{}x}', that strips the zeros
            s = "{:0{}x}".format(data, data._width)
        else:
            s = format(data, "x")
        anchor = data.yaml_anchor(any=True)
        return self.insert_underscore("0x", s, data._underscore, anchor=anchor)

    def represent_hex_caps_int(self, data):
        # type: (Any) -> Any
        if data._width is not None:
            # cannot use '{:#0{}X}', that strips the zeros
            s = "{:0{}X}".format(data, data._width)
        else:
            s = format(data, "X")
        anchor = data.yaml_anchor(any=True)
        return self.insert_underscore("0x", s, data._underscore, anchor=anchor)

    def represent_scalar_float(self, data):
        # type: (Any) -> Any
        """ this is way more complicated """
        value = None
        anchor = data.yaml_anchor(any=True)
        if data != data or (data == 0.0 and data == 1.0):
            value = u".nan"
        elif data == self.inf_value:
            value = u".inf"
        elif data == -self.inf_value:
            value = u"-.inf"
        if value:
            return self.represent_scalar(
                u"tag:yaml.org,2002:float", value, anchor=anchor
            )
        if data._exp is None and data._prec > 0 and data._prec == data._width - 1:
            # no exponent, but trailing dot
            value = u"{}{:d}.".format(
                data._m_sign if data._m_sign else "", abs(int(data))
            )
        elif data._exp is None:
            # no exponent, "normal" dot
            prec = data._prec
            ms = data._m_sign if data._m_sign else ""
            # -1 for the dot
            value = u"{}{:0{}.{}f}".format(
                ms, abs(data), data._width - len(ms), data._width - prec - 1
            )
            if prec == 0 or (prec == 1 and ms != ""):
                value = value.replace(u"0.", u".")
            while len(value) < data._width:
                value += u"0"
        else:
            # exponent
            m, es = u"{:{}.{}e}".format(
                # data, data._width, data._width - data._prec + (1 if data._m_sign else 0)
                data,
                data._width,
                data._width + (1 if data._m_sign else 0),
            ).split("e")
            w = data._width if data._prec > 0 else (data._width + 1)
            if data < 0:
                w += 1
            m = m[:w]
            e = int(es)
            m1, m2 = m.split(".")  # always second?
            while len(m1) + len(m2) < data._width - (1 if data._prec >= 0 else 0):
                m2 += u"0"
            if data._m_sign and data > 0:
                m1 = "+" + m1
            esgn = u"+" if data._e_sign else ""
            if data._prec < 0:  # mantissa without dot
                if m2 != u"0":
                    e -= len(m2)
                else:
                    m2 = ""
                while (len(m1) + len(m2) - (1 if data._m_sign else 0)) < data._width:
                    m2 += u"0"
                    e -= 1
                value = (
                    m1 + m2 + data._exp + u"{:{}0{}d}".format(e, esgn, data._e_width)
                )
            elif data._prec == 0:  # mantissa with trailing dot
                e -= len(m2)
                value = (
                    m1
                    + m2
                    + u"."
                    + data._exp
                    + u"{:{}0{}d}".format(e, esgn, data._e_width)
                )
            else:
                if data._m_lead0 > 0:
                    m2 = u"0" * (data._m_lead0 - 1) + m1 + m2
                    m1 = u"0"
                    m2 = m2[: -data._m_lead0]  # these should be zeros
                    e += data._m_lead0
                while len(m1) < data._prec:
                    m1 += m2[0]
                    m2 = m2[1:]
                    e -= 1
                value = (
                    m1
                    + u"."
                    + m2
                    + data._exp
                    + u"{:{}0{}d}".format(e, esgn, data._e_width)
                )

        if value is None:
            value = to_unicode(repr(data)).lower()
        return self.represent_scalar(u"tag:yaml.org,2002:float", value, anchor=anchor)

    def represent_sequence(self, tag, sequence, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        # if the flow_style is None, the flow style tacked on to the object
        # explicitly will be taken. If that is None as well the default flow
        # style rules
        try:
            flow_style = sequence.fa.flow_style(flow_style)
        except AttributeError:
            flow_style = flow_style
        try:
            anchor = sequence.yaml_anchor()
        except AttributeError:
            anchor = None
        node = SequenceNode(tag, value, flow_style=flow_style, anchor=anchor)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        try:
            comment = getattr(sequence, comment_attrib)
            node.comment = comment.comment
            # reset any comment already printed information
            if node.comment and node.comment[1]:
                for ct in node.comment[1]:
                    ct.reset()
            item_comments = comment.items
            for v in item_comments.values():
                if v and v[1]:
                    for ct in v[1]:
                        ct.reset()
            item_comments = comment.items
            node.comment = comment.comment
            try:
                node.comment.append(comment.end)
            except AttributeError:
                pass
        except AttributeError:
            item_comments = {}
        for idx, item in enumerate(sequence):
            node_item = self.represent_data(item)
            self.merge_comments(node_item, item_comments.get(idx))
            if not (isinstance(node_item, ScalarNode) and not node_item.style):
                best_style = False
            value.append(node_item)
        if flow_style is None:
            if len(sequence) != 0 and self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def merge_comments(self, node, comments):
        # type: (Any, Any) -> Any
        if comments is None:
            assert hasattr(node, "comment")
            return node
        if getattr(node, "comment", None) is not None:
            for idx, val in enumerate(comments):
                if idx >= len(node.comment):
                    continue
                nc = node.comment[idx]
                if nc is not None:
                    assert val is None or val == nc
                    comments[idx] = nc
        node.comment = comments
        return node

    def represent_key(self, data):
        # type: (Any) -> Any
        if isinstance(data, CommentedKeySeq):
            self.alias_key = None
            return self.represent_sequence(
                u"tag:yaml.org,2002:seq", data, flow_style=True
            )
        if isinstance(data, CommentedKeyMap):
            self.alias_key = None
            return self.represent_mapping(
                u"tag:yaml.org,2002:map", data, flow_style=True
            )
        return SafeRepresenter.represent_key(self, data)

    def represent_mapping(self, tag, mapping, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        try:
            flow_style = mapping.fa.flow_style(flow_style)
        except AttributeError:
            flow_style = flow_style
        try:
            anchor = mapping.yaml_anchor()
        except AttributeError:
            anchor = None
        node = MappingNode(tag, value, flow_style=flow_style, anchor=anchor)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        # no sorting! !!
        try:
            comment = getattr(mapping, comment_attrib)
            node.comment = comment.comment
            if node.comment and node.comment[1]:
                for ct in node.comment[1]:
                    ct.reset()
            item_comments = comment.items
            for v in item_comments.values():
                if v and v[1]:
                    for ct in v[1]:
                        ct.reset()
            try:
                node.comment.append(comment.end)
            except AttributeError:
                pass
        except AttributeError:
            item_comments = {}
        merge_list = [m[1] for m in getattr(mapping, merge_attrib, [])]
        try:
            merge_pos = getattr(mapping, merge_attrib, [[0]])[0][0]
        except IndexError:
            merge_pos = 0
        item_count = 0
        if bool(merge_list):
            items = mapping.non_merged_items()
        else:
            items = mapping.items()
        for item_key, item_value in items:
            item_count += 1
            node_key = self.represent_key(item_key)
            node_value = self.represent_data(item_value)
            item_comment = item_comments.get(item_key)
            if item_comment:
                assert getattr(node_key, "comment", None) is None
                node_key.comment = item_comment[:2]
                nvc = getattr(node_value, "comment", None)
                if nvc is not None:  # end comment already there
                    nvc[0] = item_comment[2]
                    nvc[1] = item_comment[3]
                else:
                    node_value.comment = item_comment[2:]
            if not (isinstance(node_key, ScalarNode) and not node_key.style):
                best_style = False
            if not (isinstance(node_value, ScalarNode) and not node_value.style):
                best_style = False
            value.append((node_key, node_value))
        if flow_style is None:
            if (
                (item_count != 0) or bool(merge_list)
            ) and self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        if bool(merge_list):
            # because of the call to represent_data here, the anchors
            # are marked as being used and thereby created
            if len(merge_list) == 1:
                arg = self.represent_data(merge_list[0])
            else:
                arg = self.represent_data(merge_list)
                arg.flow_style = True
            value.insert(merge_pos, (ScalarNode(u"tag:yaml.org,2002:merge", "<<"), arg))
        return node

    def represent_omap(self, tag, omap, flow_style=None):
        # type: (Any, Any, Any) -> Any
        value = []  # type: List[Any]
        try:
            flow_style = omap.fa.flow_style(flow_style)
        except AttributeError:
            flow_style = flow_style
        try:
            anchor = omap.yaml_anchor()
        except AttributeError:
            anchor = None
        node = SequenceNode(tag, value, flow_style=flow_style, anchor=anchor)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        try:
            comment = getattr(omap, comment_attrib)
            node.comment = comment.comment
            if node.comment and node.comment[1]:
                for ct in node.comment[1]:
                    ct.reset()
            item_comments = comment.items
            for v in item_comments.values():
                if v and v[1]:
                    for ct in v[1]:
                        ct.reset()
            try:
                node.comment.append(comment.end)
            except AttributeError:
                pass
        except AttributeError:
            item_comments = {}
        for item_key in omap:
            item_val = omap[item_key]
            node_item = self.represent_data({item_key: item_val})
            # node_item.flow_style = False
            # node item has two scalars in value: node_key and node_value
            item_comment = item_comments.get(item_key)
            if item_comment:
                if item_comment[1]:
                    node_item.comment = [None, item_comment[1]]
                assert getattr(node_item.value[0][0], "comment", None) is None
                node_item.value[0][0].comment = [item_comment[0], None]
                nvc = getattr(node_item.value[0][1], "comment", None)
                if nvc is not None:  # end comment already there
                    nvc[0] = item_comment[2]
                    nvc[1] = item_comment[3]
                else:
                    node_item.value[0][1].comment = item_comment[2:]
            # if not (isinstance(node_item, ScalarNode) \
            #    and not node_item.style):
            #     best_style = False
            value.append(node_item)
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def represent_set(self, setting):
        # type: (Any) -> Any
        flow_style = False
        tag = u"tag:yaml.org,2002:set"
        # return self.represent_mapping(tag, value)
        value = []  # type: List[Any]
        flow_style = setting.fa.flow_style(flow_style)
        try:
            anchor = setting.yaml_anchor()
        except AttributeError:
            anchor = None
        node = MappingNode(tag, value, flow_style=flow_style, anchor=anchor)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        # no sorting! !!
        try:
            comment = getattr(setting, comment_attrib)
            node.comment = comment.comment
            if node.comment and node.comment[1]:
                for ct in node.comment[1]:
                    ct.reset()
            item_comments = comment.items
            for v in item_comments.values():
                if v and v[1]:
                    for ct in v[1]:
                        ct.reset()
            try:
                node.comment.append(comment.end)
            except AttributeError:
                pass
        except AttributeError:
            item_comments = {}
        for item_key in setting.odict:
            node_key = self.represent_key(item_key)
            node_value = self.represent_data(None)
            item_comment = item_comments.get(item_key)
            if item_comment:
                assert getattr(node_key, "comment", None) is None
                node_key.comment = item_comment[:2]
            node_key.style = node_value.style = "?"
            if not (isinstance(node_key, ScalarNode) and not node_key.style):
                best_style = False
            if not (isinstance(node_value, ScalarNode) and not node_value.style):
                best_style = False
            value.append((node_key, node_value))
        best_style = best_style
        return node

    def represent_dict(self, data):
        # type: (Any) -> Any
        """write out tag if saved on loading"""
        try:
            t = data.tag.value
        except AttributeError:
            t = None
        if t:
            if t.startswith("!!"):
                tag = "tag:yaml.org,2002:" + t[2:]
            else:
                tag = t
        else:
            tag = u"tag:yaml.org,2002:map"
        return self.represent_mapping(tag, data)

    def represent_list(self, data):
        # type: (Any) -> Any
        try:
            t = data.tag.value
        except AttributeError:
            t = None
        if t:
            if t.startswith("!!"):
                tag = "tag:yaml.org,2002:" + t[2:]
            else:
                tag = t
        else:
            tag = u"tag:yaml.org,2002:seq"
        return self.represent_sequence(tag, data)

    def represent_datetime(self, data):
        # type: (Any) -> Any
        inter = "T" if data._yaml["t"] else " "
        _yaml = data._yaml
        if _yaml["delta"]:
            data += _yaml["delta"]
            value = data.isoformat(inter)
        else:
            value = data.isoformat(inter)
        if _yaml["tz"]:
            value += _yaml["tz"]
        return self.represent_scalar(u"tag:yaml.org,2002:timestamp", to_unicode(value))

    def represent_tagged_scalar(self, data):
        # type: (Any) -> Any
        try:
            tag = data.tag.value
        except AttributeError:
            tag = None
        try:
            anchor = data.yaml_anchor()
        except AttributeError:
            anchor = None
        return self.represent_scalar(tag, data.value, style=data.style, anchor=anchor)

    def represent_scalar_bool(self, data):
        # type: (Any) -> Any
        try:
            anchor = data.yaml_anchor()
        except AttributeError:
            anchor = None
        return SafeRepresenter.represent_bool(self, data, anchor=anchor) class BaseConstructor(object):

    yaml_constructors = {}  # type: Dict[Any, Any]
    yaml_multi_constructors = {}  # type: Dict[Any, Any]

    def __init__(self, preserve_quotes=None, loader=None):
        # type: (Optional[bool], Any) -> None
        self.loader = loader
        if (
            self.loader is not None
            and getattr(self.loader, "_constructor", None) is None
        ):
            self.loader._constructor = self
        self.loader = loader
        self.yaml_base_dict_type = dict
        self.yaml_base_list_type = list
        self.constructed_objects = {}  # type: Dict[Any, Any]
        self.recursive_objects = {}  # type: Dict[Any, Any]
        self.state_generators = []  # type: List[Any]
        self.deep_construct = False
        self._preserve_quotes = preserve_quotes
        self.allow_duplicate_keys = version_tnf((0, 15, 1), (0, 16))

    @property
    def composer(self):
        # type: () -> Any
        if hasattr(self.loader, "typ"):
            return self.loader.composer
        try:
            return self.loader._composer
        except AttributeError:
            sys.stdout.write("slt {}\n".format(type(self)))
            sys.stdout.write("slc {}\n".format(self.loader._composer))
            sys.stdout.write("{}\n".format(dir(self)))
            raise

    @property
    def resolver(self):
        # type: () -> Any
        if hasattr(self.loader, "typ"):
            return self.loader.resolver
        return self.loader._resolver

    def check_data(self):
        # type: () -> Any
        # If there are more documents available?
        return self.composer.check_node()

    def get_data(self):
        # type: () -> Any
        # Construct and return the next document.
        if self.composer.check_node():
            return self.construct_document(self.composer.get_node())

    def get_single_data(self):
        # type: () -> Any
        # Ensure that the stream contains a single document and construct it.
        node = self.composer.get_single_node()
        if node is not None:
            return self.construct_document(node)
        return None

    def construct_document(self, node):
        # type: (Any) -> Any
        data = self.construct_object(node)
        while bool(self.state_generators):
            state_generators = self.state_generators
            self.state_generators = []
            for generator in state_generators:
                for _dummy in generator:
                    pass
        self.constructed_objects = {}
        self.recursive_objects = {}
        self.deep_construct = False
        return data

    def construct_object(self, node, deep=False):
        # type: (Any, bool) -> Any
        """deep is True when creating an object/mapping recursively,
        in that case want the underlying elements available during construction
        """
        if node in self.constructed_objects:
            return self.constructed_objects[node]
        if deep:
            old_deep = self.deep_construct
            self.deep_construct = True
        if node in self.recursive_objects:
            return self.recursive_objects[node]
            # raise ConstructorError(
            #     None, None, 'found unconstructable recursive node', node.start_mark
            # )
        self.recursive_objects[node] = None
        data = self.construct_non_recursive_object(node)

        self.constructed_objects[node] = data
        del self.recursive_objects[node]
        if deep:
            self.deep_construct = old_deep
        return data

    def construct_non_recursive_object(self, node, tag=None):
        # type: (Any, Optional[str]) -> Any
        constructor = None  # type: Any
        tag_suffix = None
        if tag is None:
            tag = node.tag
        if tag in self.yaml_constructors:
            constructor = self.yaml_constructors[tag]
        else:
            for tag_prefix in self.yaml_multi_constructors:
                if tag.startswith(tag_prefix):
                    tag_suffix = tag[len(tag_prefix) :]
                    constructor = self.yaml_multi_constructors[tag_prefix]
                    break
            else:
                if None in self.yaml_multi_constructors:
                    tag_suffix = tag
                    constructor = self.yaml_multi_constructors[None]
                elif None in self.yaml_constructors:
                    constructor = self.yaml_constructors[None]
                elif isinstance(node, ScalarNode):
                    constructor = self.__class__.construct_scalar
                elif isinstance(node, SequenceNode):
                    constructor = self.__class__.construct_sequence
                elif isinstance(node, MappingNode):
                    constructor = self.__class__.construct_mapping
        if tag_suffix is None:
            data = constructor(self, node)
        else:
            data = constructor(self, tag_suffix, node)
        if isinstance(data, types.GeneratorType):
            generator = data
            data = next(generator)
            if self.deep_construct:
                for _dummy in generator:
                    pass
            else:
                self.state_generators.append(generator)
        return data

    def construct_scalar(self, node):
        # type: (Any) -> Any
        if not isinstance(node, ScalarNode):
            raise ConstructorError(
                None,
                None,
                "expected a scalar node, but found %s" % node.id,
                node.start_mark,
            )
        return node.value

    def construct_sequence(self, node, deep=False):
        # type: (Any, bool) -> Any
        """deep is True when creating an object/mapping recursively,
        in that case want the underlying elements available during construction
        """
        if not isinstance(node, SequenceNode):
            raise ConstructorError(
                None,
                None,
                "expected a sequence node, but found %s" % node.id,
                node.start_mark,
            )
        return [self.construct_object(child, deep=deep) for child in node.value]

    def construct_mapping(self, node, deep=False):
        # type: (Any, bool) -> Any
        """deep is True when creating an object/mapping recursively,
        in that case want the underlying elements available during construction
        """
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None,
                None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark,
            )
        total_mapping = self.yaml_base_dict_type()
        if getattr(node, "merge", None) is not None:
            todo = [(node.merge, False), (node.value, False)]
        else:
            todo = [(node.value, True)]
        for values, check in todo:
            mapping = self.yaml_base_dict_type()  # type: Dict[Any, Any]
            for key_node, value_node in values:
                # keys can be list -> deep
                key = self.construct_object(key_node, deep=True)
                # lists are not hashable, but tuples are
                if not isinstance(key, Hashable):
                    if isinstance(key, list):
                        key = tuple(key)
                if PY2:
                    try:
                        hash(key)
                    except TypeError as exc:
                        raise ConstructorError(
                            "while constructing a mapping",
                            node.start_mark,
                            "found unacceptable key (%s)" % exc,
                            key_node.start_mark,
                        )
                else:
                    if not isinstance(key, Hashable):
                        raise ConstructorError(
                            "while constructing a mapping",
                            node.start_mark,
                            "found unhashable key",
                            key_node.start_mark,
                        )

                value = self.construct_object(value_node, deep=deep)
                if check:
                    if self.check_mapping_key(node, key_node, mapping, key, value):
                        mapping[key] = value
                else:
                    mapping[key] = value
            total_mapping.update(mapping)
        return total_mapping

    def check_mapping_key(self, node, key_node, mapping, key, value):
        # type: (Any, Any, Any, Any, Any) -> bool
        """return True if key is unique"""
        if key in mapping:
            if not self.allow_duplicate_keys:
                mk = mapping.get(key)
                if PY2:
                    if isinstance(key, unicode):
                        key = key.encode("utf-8")
                    if isinstance(value, unicode):
                        value = value.encode("utf-8")
                    if isinstance(mk, unicode):
                        mk = mk.encode("utf-8")
                args = [
                    "while constructing a mapping",
                    node.start_mark,
                    'found duplicate key "{}" with value "{}" '
                    '(original value: "{}")'.format(key, value, mk),
                    key_node.start_mark,
                    """
                    To suppress this check see:
                        http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                    """,
                    """\
                    Duplicate keys will become an error in future releases, and are errors
                    by default when using the new API.
                    """,
                ]
                if self.allow_duplicate_keys is None:
                    warnings.warn(DuplicateKeyFutureWarning(*args))
                else:
                    raise DuplicateKeyError(*args)
            return False
        return True

    def check_set_key(self, node, key_node, setting, key):
        # type: (Any, Any, Any, Any, Any) -> None
        if key in setting:
            if not self.allow_duplicate_keys:
                if PY2:
                    if isinstance(key, unicode):
                        key = key.encode("utf-8")
                args = [
                    "while constructing a set",
                    node.start_mark,
                    'found duplicate key "{}"'.format(key),
                    key_node.start_mark,
                    """
                    To suppress this check see:
                        http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                    """,
                    """\
                    Duplicate keys will become an error in future releases, and are errors
                    by default when using the new API.
                    """,
                ]
                if self.allow_duplicate_keys is None:
                    warnings.warn(DuplicateKeyFutureWarning(*args))
                else:
                    raise DuplicateKeyError(*args)

    def construct_pairs(self, node, deep=False):
        # type: (Any, bool) -> Any
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None,
                None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark,
            )
        pairs = []
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            value = self.construct_object(value_node, deep=deep)
            pairs.append((key, value))
        return pairs

    @classmethod
    def add_constructor(cls, tag, constructor):
        # type: (Any, Any) -> None
        if "yaml_constructors" not in cls.__dict__:
            cls.yaml_constructors = cls.yaml_constructors.copy()
        cls.yaml_constructors[tag] = constructor

    @classmethod
    def add_multi_constructor(cls, tag_prefix, multi_constructor):
        # type: (Any, Any) -> None
        if "yaml_multi_constructors" not in cls.__dict__:
            cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
        cls.yaml_multi_constructors[tag_prefix] = multi_constructor class SafeConstructor(BaseConstructor):
    def construct_scalar(self, node):
        # type: (Any) -> Any
        if isinstance(node, MappingNode):
            for key_node, value_node in node.value:
                if key_node.tag == u"tag:yaml.org,2002:value":
                    return self.construct_scalar(value_node)
        return BaseConstructor.construct_scalar(self, node)

    def flatten_mapping(self, node):
        # type: (Any) -> Any
        """
        This implements the merge key feature http://yaml.org/type/merge.html
        by inserting keys from the merge dict/list of dicts if not yet
        available in this node
        """
        merge = []  # type: List[Any]
        index = 0
        while index < len(node.value):
            key_node, value_node = node.value[index]
            if key_node.tag == u"tag:yaml.org,2002:merge":
                if merge:  # double << key
                    if self.allow_duplicate_keys:
                        del node.value[index]
                        index += 1
                        continue
                    args = [
                        "while constructing a mapping",
                        node.start_mark,
                        'found duplicate key "{}"'.format(key_node.value),
                        key_node.start_mark,
                        """
                        To suppress this check see:
                           http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                        """,
                        """\
                        Duplicate keys will become an error in future releases, and are errors
                        by default when using the new API.
                        """,
                    ]
                    if self.allow_duplicate_keys is None:
                        warnings.warn(DuplicateKeyFutureWarning(*args))
                    else:
                        raise DuplicateKeyError(*args)
                del node.value[index]
                if isinstance(value_node, MappingNode):
                    self.flatten_mapping(value_node)
                    merge.extend(value_node.value)
                elif isinstance(value_node, SequenceNode):
                    submerge = []
                    for subnode in value_node.value:
                        if not isinstance(subnode, MappingNode):
                            raise ConstructorError(
                                "while constructing a mapping",
                                node.start_mark,
                                "expected a mapping for merging, but found %s"
                                % subnode.id,
                                subnode.start_mark,
                            )
                        self.flatten_mapping(subnode)
                        submerge.append(subnode.value)
                    submerge.reverse()
                    for value in submerge:
                        merge.extend(value)
                else:
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "expected a mapping or list of mappings for merging, "
                        "but found %s" % value_node.id,
                        value_node.start_mark,
                    )
            elif key_node.tag == u"tag:yaml.org,2002:value":
                key_node.tag = u"tag:yaml.org,2002:str"
                index += 1
            else:
                index += 1
        if bool(merge):
            node.merge = (
                merge  # separate merge keys to be able to update without duplicate
            )
            node.value = merge + node.value

    def construct_mapping(self, node, deep=False):
        # type: (Any, bool) -> Any
        """deep is True when creating an object/mapping recursively,
        in that case want the underlying elements available during construction
        """
        if isinstance(node, MappingNode):
            self.flatten_mapping(node)
        return BaseConstructor.construct_mapping(self, node, deep=deep)

    def construct_yaml_null(self, node):
        # type: (Any) -> Any
        self.construct_scalar(node)
        return None

    # YAML 1.2 spec doesn't mention yes/no etc any more, 1.1 does
    bool_values = {
        u"yes": True,
        u"no": False,
        u"y": True,
        u"n": False,
        u"true": True,
        u"false": False,
        u"on": True,
        u"off": False,
    }

    def construct_yaml_bool(self, node):
        # type: (Any) -> bool
        value = self.construct_scalar(node)
        return self.bool_values[value.lower()]

    def construct_yaml_int(self, node):
        # type: (Any) -> int
        value_s = to_str(self.construct_scalar(node))
        value_s = value_s.replace("_", "")
        sign = +1
        if value_s[0] == "-":
            sign = -1
        if value_s[0] in "+-":
            value_s = value_s[1:]
        if value_s == "0":
            return 0
        elif value_s.startswith("0b"):
            return sign * int(value_s[2:], 2)
        elif value_s.startswith("0x"):
            return sign * int(value_s[2:], 16)
        elif value_s.startswith("0o"):
            return sign * int(value_s[2:], 8)
        elif self.resolver.processing_version == (1, 1) and value_s[0] == "0":
            return sign * int(value_s, 8)
        elif self.resolver.processing_version == (1, 1) and ":" in value_s:
            digits = [int(part) for part in value_s.split(":")]
            digits.reverse()
            base = 1
            value = 0
            for digit in digits:
                value += digit * base
                base *= 60
            return sign * value
        else:
            return sign * int(value_s)

    inf_value = 1e300
    while inf_value != inf_value * inf_value:
        inf_value *= inf_value
    nan_value = -inf_value / inf_value  # Trying to make a quiet NaN (like C99).

    def construct_yaml_float(self, node):
        # type: (Any) -> float
        value_so = to_str(self.construct_scalar(node))
        value_s = value_so.replace("_", "").lower()
        sign = +1
        if value_s[0] == "-":
            sign = -1
        if value_s[0] in "+-":
            value_s = value_s[1:]
        if value_s == ".inf":
            return sign * self.inf_value
        elif value_s == ".nan":
            return self.nan_value
        elif self.resolver.processing_version != (1, 2) and ":" in value_s:
            digits = [float(part) for part in value_s.split(":")]
            digits.reverse()
            base = 1
            value = 0.0
            for digit in digits:
                value += digit * base
                base *= 60
            return sign * value
        else:
            if self.resolver.processing_version != (1, 2) and "e" in value_s:
                # value_s is lower case independent of input
                mantissa, exponent = value_s.split("e")
                if "." not in mantissa:
                    warnings.warn(MantissaNoDotYAML1_1Warning(node, value_so))
            return sign * float(value_s)

    if PY3:

        def construct_yaml_binary(self, node):
            # type: (Any) -> Any
            try:
                value = self.construct_scalar(node).encode("ascii")
            except UnicodeEncodeError as exc:
                raise ConstructorError(
                    None,
                    None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark,
                )
            try:
                if hasattr(base64, "decodebytes"):
                    return base64.decodebytes(value)
                else:
                    return base64.decodestring(value)
            except binascii.Error as exc:
                raise ConstructorError(
                    None,
                    None,
                    "failed to decode base64 data: %s" % exc,
                    node.start_mark,
                )

    else:

        def construct_yaml_binary(self, node):
            # type: (Any) -> Any
            value = self.construct_scalar(node)
            try:
                return to_str(value).decode("base64")
            except (binascii.Error, UnicodeEncodeError) as exc:
                raise ConstructorError(
                    None,
                    None,
                    "failed to decode base64 data: %s" % exc,
                    node.start_mark,
                )

    timestamp_regexp = RegExp(
        u"""^(?P<year>[0-9][0-9][0-9][0-9])
          -(?P<month>[0-9][0-9]?)
          -(?P<day>[0-9][0-9]?)
          (?:((?P<t>[Tt])|[ \\t]+)   # explictly not retaining extra spaces
          (?P<hour>[0-9][0-9]?)
          :(?P<minute>[0-9][0-9])
          :(?P<second>[0-9][0-9])
          (?:\\.(?P<fraction>[0-9]*))?
          (?:[ \\t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
          (?::(?P<tz_minute>[0-9][0-9]))?))?)?$""",
        re.X,
    )

    def construct_yaml_timestamp(self, node, values=None):
        # type: (Any, Any) -> Any
        if values is None:
            try:
                match = self.timestamp_regexp.match(node.value)
            except TypeError:
                match = None
            if match is None:
                raise ConstructorError(
                    None,
                    None,
                    'failed to construct timestamp from "{}"'.format(node.value),
                    node.start_mark,
                )
            values = match.groupdict()
        year = int(values["year"])
        month = int(values["month"])
        day = int(values["day"])
        if not values["hour"]:
            return datetime.date(year, month, day)
        hour = int(values["hour"])
        minute = int(values["minute"])
        second = int(values["second"])
        fraction = 0
        if values["fraction"]:
            fraction_s = values["fraction"][:6]
            while len(fraction_s) < 6:
                fraction_s += "0"
            fraction = int(fraction_s)
            if len(values["fraction"]) > 6 and int(values["fraction"][6]) > 4:
                fraction += 1
        delta = None
        if values["tz_sign"]:
            tz_hour = int(values["tz_hour"])
            minutes = values["tz_minute"]
            tz_minute = int(minutes) if minutes else 0
            delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
            if values["tz_sign"] == "-":
                delta = -delta
        # should do something else instead (or hook this up to the preceding if statement
        # in reverse
        #  if delta is None:
        #      return datetime.datetime(year, month, day, hour, minute, second, fraction)
        #  return datetime.datetime(year, month, day, hour, minute, second, fraction,
        #                           datetime.timezone.utc)
        # the above is not good enough though, should provide tzinfo. In Python3 that is easily
        # doable drop that kind of support for Python2 as it has not native tzinfo
        data = datetime.datetime(year, month, day, hour, minute, second, fraction)
        if delta:
            data -= delta
        return data

    def construct_yaml_omap(self, node):
        # type: (Any) -> Any
        # Note: we do now check for duplicate keys
        omap = ordereddict()
        yield omap
        if not isinstance(node, SequenceNode):
            raise ConstructorError(
                "while constructing an ordered map",
                node.start_mark,
                "expected a sequence, but found %s" % node.id,
                node.start_mark,
            )
        for subnode in node.value:
            if not isinstance(subnode, MappingNode):
                raise ConstructorError(
                    "while constructing an ordered map",
                    node.start_mark,
                    "expected a mapping of length 1, but found %s" % subnode.id,
                    subnode.start_mark,
                )
            if len(subnode.value) != 1:
                raise ConstructorError(
                    "while constructing an ordered map",
                    node.start_mark,
                    "expected a single mapping item, but found %d items"
                    % len(subnode.value),
                    subnode.start_mark,
                )
            key_node, value_node = subnode.value[0]
            key = self.construct_object(key_node)
            assert key not in omap
            value = self.construct_object(value_node)
            omap[key] = value

    def construct_yaml_pairs(self, node):
        # type: (Any) -> Any
        # Note: the same code as `construct_yaml_omap`.
        pairs = []  # type: List[Any]
        yield pairs
        if not isinstance(node, SequenceNode):
            raise ConstructorError(
                "while constructing pairs",
                node.start_mark,
                "expected a sequence, but found %s" % node.id,
                node.start_mark,
            )
        for subnode in node.value:
            if not isinstance(subnode, MappingNode):
                raise ConstructorError(
                    "while constructing pairs",
                    node.start_mark,
                    "expected a mapping of length 1, but found %s" % subnode.id,
                    subnode.start_mark,
                )
            if len(subnode.value) != 1:
                raise ConstructorError(
                    "while constructing pairs",
                    node.start_mark,
                    "expected a single mapping item, but found %d items"
                    % len(subnode.value),
                    subnode.start_mark,
                )
            key_node, value_node = subnode.value[0]
            key = self.construct_object(key_node)
            value = self.construct_object(value_node)
            pairs.append((key, value))

    def construct_yaml_set(self, node):
        # type: (Any) -> Any
        data = set()  # type: Set[Any]
        yield data
        value = self.construct_mapping(node)
        data.update(value)

    def construct_yaml_str(self, node):
        # type: (Any) -> Any
        value = self.construct_scalar(node)
        if PY3:
            return value
        try:
            return value.encode("ascii")
        except UnicodeEncodeError:
            return value

    def construct_yaml_seq(self, node):
        # type: (Any) -> Any
        data = self.yaml_base_list_type()  # type: List[Any]
        yield data
        data.extend(self.construct_sequence(node))

    def construct_yaml_map(self, node):
        # type: (Any) -> Any
        data = self.yaml_base_dict_type()  # type: Dict[Any, Any]
        yield data
        value = self.construct_mapping(node)
        data.update(value)

    def construct_yaml_object(self, node, cls):
        # type: (Any, Any) -> Any
        data = cls.__new__(cls)
        yield data
        if hasattr(data, "__setstate__"):
            state = self.construct_mapping(node, deep=True)
            data.__setstate__(state)
        else:
            state = self.construct_mapping(node)
            data.__dict__.update(state)

    def construct_undefined(self, node):
        # type: (Any) -> None
        raise ConstructorError(
            None,
            None,
            "could not determine a constructor for the tag %r" % utf8(node.tag),
            node.start_mark,
        ) class Constructor(SafeConstructor):
    def construct_python_str(self, node):
        # type: (Any) -> Any
        return utf8(self.construct_scalar(node))

    def construct_python_unicode(self, node):
        # type: (Any) -> Any
        return self.construct_scalar(node)

    if PY3:

        def construct_python_bytes(self, node):
            # type: (Any) -> Any
            try:
                value = self.construct_scalar(node).encode("ascii")
            except UnicodeEncodeError as exc:
                raise ConstructorError(
                    None,
                    None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark,
                )
            try:
                if hasattr(base64, "decodebytes"):
                    return base64.decodebytes(value)
                else:
                    return base64.decodestring(value)
            except binascii.Error as exc:
                raise ConstructorError(
                    None,
                    None,
                    "failed to decode base64 data: %s" % exc,
                    node.start_mark,
                )

    def construct_python_long(self, node):
        # type: (Any) -> int
        val = self.construct_yaml_int(node)
        if PY3:
            return val
        return int(val)

    def construct_python_complex(self, node):
        # type: (Any) -> Any
        return complex(self.construct_scalar(node))

    def construct_python_tuple(self, node):
        # type: (Any) -> Any
        return tuple(self.construct_sequence(node))

    def find_python_module(self, name, mark):
        # type: (Any, Any) -> Any
        if not name:
            raise ConstructorError(
                "while constructing a Python module",
                mark,
                "expected non-empty name appended to the tag",
                mark,
            )
        try:
            __import__(name)
        except ImportError as exc:
            raise ConstructorError(
                "while constructing a Python module",
                mark,
                "cannot find module %r (%s)" % (utf8(name), exc),
                mark,
            )
        return sys.modules[name]

    def find_python_name(self, name, mark):
        # type: (Any, Any) -> Any
        if not name:
            raise ConstructorError(
                "while constructing a Python object",
                mark,
                "expected non-empty name appended to the tag",
                mark,
            )
        if u"." in name:
            lname = name.split(".")
            lmodule_name = lname
            lobject_name = []  # type: List[Any]
            while len(lmodule_name) > 1:
                lobject_name.insert(0, lmodule_name.pop())
                module_name = ".".join(lmodule_name)
                try:
                    __import__(module_name)
                    # object_name = '.'.join(object_name)
                    break
                except ImportError:
                    continue
        else:
            module_name = builtins_module
            lobject_name = [name]
        try:
            __import__(module_name)
        except ImportError as exc:
            raise ConstructorError(
                "while constructing a Python object",
                mark,
                "cannot find module %r (%s)" % (utf8(module_name), exc),
                mark,
            )
        module = sys.modules[module_name]
        object_name = ".".join(lobject_name)
        obj = module
        while lobject_name:
            if not hasattr(obj, lobject_name[0]):

                raise ConstructorError(
                    "while constructing a Python object",
                    mark,
                    "cannot find %r in the module %r"
                    % (utf8(object_name), module.__name__),
                    mark,
                )
            obj = getattr(obj, lobject_name.pop(0))
        return obj

    def construct_python_name(self, suffix, node):
        # type: (Any, Any) -> Any
        value = self.construct_scalar(node)
        if value:
            raise ConstructorError(
                "while constructing a Python name",
                node.start_mark,
                "expected the empty value, but found %r" % utf8(value),
                node.start_mark,
            )
        return self.find_python_name(suffix, node.start_mark)

    def construct_python_module(self, suffix, node):
        # type: (Any, Any) -> Any
        value = self.construct_scalar(node)
        if value:
            raise ConstructorError(
                "while constructing a Python module",
                node.start_mark,
                "expected the empty value, but found %r" % utf8(value),
                node.start_mark,
            )
        return self.find_python_module(suffix, node.start_mark)

    def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False):
        # type: (Any, Any, Any, Any, bool) -> Any
        if not args:
            args = []
        if not kwds:
            kwds = {}
        cls = self.find_python_name(suffix, node.start_mark)
        if PY3:
            if newobj and isinstance(cls, type):
                return cls.__new__(cls, *args, **kwds)
            else:
                return cls(*args, **kwds)
        else:
            if newobj and isinstance(cls, type(classobj)) and not args and not kwds:
                instance = classobj()
                instance.__class__ = cls
                return instance
            elif newobj and isinstance(cls, type):
                return cls.__new__(cls, *args, **kwds)
            else:
                return cls(*args, **kwds)

    def set_python_instance_state(self, instance, state):
        # type: (Any, Any) -> None
        if hasattr(instance, "__setstate__"):
            instance.__setstate__(state)
        else:
            slotstate = {}  # type: Dict[Any, Any]
            if isinstance(state, tuple) and len(state) == 2:
                state, slotstate = state
            if hasattr(instance, "__dict__"):
                instance.__dict__.update(state)
            elif state:
                slotstate.update(state)
            for key, value in slotstate.items():
                setattr(instance, key, value)

    def construct_python_object(self, suffix, node):
        # type: (Any, Any) -> Any
        # Format:
        #   !!python/object:module.name { ... state ... }
        instance = self.make_python_instance(suffix, node, newobj=True)
        self.recursive_objects[node] = instance
        yield instance
        deep = hasattr(instance, "__setstate__")
        state = self.construct_mapping(node, deep=deep)
        self.set_python_instance_state(instance, state)

    def construct_python_object_apply(self, suffix, node, newobj=False):
        # type: (Any, Any, bool) -> Any
        # Format:
        #   !!python/object/apply       # (or !!python/object/new)
        #   args: [ ... arguments ... ]
        #   kwds: { ... keywords ... }
        #   state: ... state ...
        #   listitems: [ ... listitems ... ]
        #   dictitems: { ... dictitems ... }
        # or short format:
        #   !!python/object/apply [ ... arguments ... ]
        # The difference between !!python/object/apply and !!python/object/new
        # is how an object is created, check make_python_instance for details.
        if isinstance(node, SequenceNode):
            args = self.construct_sequence(node, deep=True)
            kwds = {}  # type: Dict[Any, Any]
            state = {}  # type: Dict[Any, Any]
            listitems = []  # type: List[Any]
            dictitems = {}  # type: Dict[Any, Any]
        else:
            value = self.construct_mapping(node, deep=True)
            args = value.get("args", [])
            kwds = value.get("kwds", {})
            state = value.get("state", {})
            listitems = value.get("listitems", [])
            dictitems = value.get("dictitems", {})
        instance = self.make_python_instance(suffix, node, args, kwds, newobj)
        if bool(state):
            self.set_python_instance_state(instance, state)
        if bool(listitems):
            instance.extend(listitems)
        if bool(dictitems):
            for key in dictitems:
                instance[key] = dictitems[key]
        return instance

    def construct_python_object_new(self, suffix, node):
        # type: (Any, Any) -> Any
        return self.construct_python_object_apply(suffix, node, newobj=True) class RoundTripConstructor(SafeConstructor):
    """need to store the comments on the node itself,
    as well as on the items
    """

    def construct_scalar(self, node):
        # type: (Any) -> Any
        if not isinstance(node, ScalarNode):
            raise ConstructorError(
                None,
                None,
                "expected a scalar node, but found %s" % node.id,
                node.start_mark,
            )

        if node.style == "|" and isinstance(node.value, text_type):
            lss = LiteralScalarString(node.value, anchor=node.anchor)
            if node.comment and node.comment[1]:
                lss.comment = node.comment[1][0]  # type: ignore
            return lss
        if node.style == ">" and isinstance(node.value, text_type):
            fold_positions = []  # type: List[int]
            idx = -1
            while True:
                idx = node.value.find("\a", idx + 1)
                if idx < 0:
                    break
                fold_positions.append(idx - len(fold_positions))
            fss = FoldedScalarString(node.value.replace("\a", ""), anchor=node.anchor)
            if node.comment and node.comment[1]:
                fss.comment = node.comment[1][0]  # type: ignore
            if fold_positions:
                fss.fold_pos = fold_positions  # type: ignore
            return fss
        elif bool(self._preserve_quotes) and isinstance(node.value, text_type):
            if node.style == "'":
                return SingleQuotedScalarString(node.value, anchor=node.anchor)
            if node.style == '"':
                return DoubleQuotedScalarString(node.value, anchor=node.anchor)
        if node.anchor:
            return PlainScalarString(node.value, anchor=node.anchor)
        return node.value

    def construct_yaml_int(self, node):
        # type: (Any) -> Any
        width = None  # type: Any
        value_su = to_str(self.construct_scalar(node))
        try:
            sx = value_su.rstrip("_")
            underscore = [len(sx) - sx.rindex("_") - 1, False, False]  # type: Any
        except ValueError:
            underscore = None
        except IndexError:
            underscore = None
        value_s = value_su.replace("_", "")
        sign = +1
        if value_s[0] == "-":
            sign = -1
        if value_s[0] in "+-":
            value_s = value_s[1:]
        if value_s == "0":
            return 0
        elif value_s.startswith("0b"):
            if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
                width = len(value_s[2:])
            if underscore is not None:
                underscore[1] = value_su[2] == "_"
                underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
            return BinaryInt(
                sign * int(value_s[2:], 2),
                width=width,
                underscore=underscore,
                anchor=node.anchor,
            )
        elif value_s.startswith("0x"):
            # default to lower-case if no a-fA-F in string
            if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
                width = len(value_s[2:])
            hex_fun = HexInt  # type: Any
            for ch in value_s[2:]:
                if ch in "ABCDEF":  # first non-digit is capital
                    hex_fun = HexCapsInt
                    break
                if ch in "abcdef":
                    break
            if underscore is not None:
                underscore[1] = value_su[2] == "_"
                underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
            return hex_fun(
                sign * int(value_s[2:], 16),
                width=width,
                underscore=underscore,
                anchor=node.anchor,
            )
        elif value_s.startswith("0o"):
            if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
                width = len(value_s[2:])
            if underscore is not None:
                underscore[1] = value_su[2] == "_"
                underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
            return OctalInt(
                sign * int(value_s[2:], 8),
                width=width,
                underscore=underscore,
                anchor=node.anchor,
            )
        elif self.resolver.processing_version != (1, 2) and value_s[0] == "0":
            return sign * int(value_s, 8)
        elif self.resolver.processing_version != (1, 2) and ":" in value_s:
            digits = [int(part) for part in value_s.split(":")]
            digits.reverse()
            base = 1
            value = 0
            for digit in digits:
                value += digit * base
                base *= 60
            return sign * value
        elif self.resolver.processing_version > (1, 1) and value_s[0] == "0":
            # not an octal, an integer with leading zero(s)
            if underscore is not None:
                # cannot have a leading underscore
                underscore[2] = len(value_su) > 1 and value_su[-1] == "_"
            return ScalarInt(
                sign * int(value_s), width=len(value_s), underscore=underscore
            )
        elif underscore:
            # cannot have a leading underscore
            underscore[2] = len(value_su) > 1 and value_su[-1] == "_"
            return ScalarInt(
                sign * int(value_s),
                width=None,
                underscore=underscore,
                anchor=node.anchor,
            )
        elif node.anchor:
            return ScalarInt(sign * int(value_s), width=None, anchor=node.anchor)
        else:
            return sign * int(value_s)

    def construct_yaml_float(self, node):
        # type: (Any) -> Any
        def leading_zeros(v):
            # type: (Any) -> int
            lead0 = 0
            idx = 0
            while idx < len(v) and v[idx] in "0.":
                if v[idx] == "0":
                    lead0 += 1
                idx += 1
            return lead0

        # underscore = None
        m_sign = False  # type: Any
        value_so = to_str(self.construct_scalar(node))
        value_s = value_so.replace("_", "").lower()
        sign = +1
        if value_s[0] == "-":
            sign = -1
        if value_s[0] in "+-":
            m_sign = value_s[0]
            value_s = value_s[1:]
        if value_s == ".inf":
            return sign * self.inf_value
        if value_s == ".nan":
            return self.nan_value
        if self.resolver.processing_version != (1, 2) and ":" in value_s:
            digits = [float(part) for part in value_s.split(":")]
            digits.reverse()
            base = 1
            value = 0.0
            for digit in digits:
                value += digit * base
                base *= 60
            return sign * value
        if "e" in value_s:
            try:
                mantissa, exponent = value_so.split("e")
                exp = "e"
            except ValueError:
                mantissa, exponent = value_so.split("E")
                exp = "E"
            if self.resolver.processing_version != (1, 2):
                # value_s is lower case independent of input
                if "." not in mantissa:
                    warnings.warn(MantissaNoDotYAML1_1Warning(node, value_so))
            lead0 = leading_zeros(mantissa)
            width = len(mantissa)
            prec = mantissa.find(".")
            if m_sign:
                width -= 1
            e_width = len(exponent)
            e_sign = exponent[0] in "+-"
            # nprint('sf', width, prec, m_sign, exp, e_width, e_sign)
            return ScalarFloat(
                sign * float(value_s),
                width=width,
                prec=prec,
                m_sign=m_sign,
                m_lead0=lead0,
                exp=exp,
                e_width=e_width,
                e_sign=e_sign,
                anchor=node.anchor,
            )
        width = len(value_so)
        prec = value_so.index(
            "."
        )  # you can use index, this would not be float without dot
        lead0 = leading_zeros(value_so)
        return ScalarFloat(
            sign * float(value_s),
            width=width,
            prec=prec,
            m_sign=m_sign,
            m_lead0=lead0,
            anchor=node.anchor,
        )

    def construct_yaml_str(self, node):
        # type: (Any) -> Any
        value = self.construct_scalar(node)
        if isinstance(value, ScalarString):
            return value
        if PY3:
            return value
        try:
            return value.encode("ascii")
        except AttributeError:
            # in case you replace the node dynamically e.g. with a dict
            return value
        except UnicodeEncodeError:
            return value

    def construct_rt_sequence(self, node, seqtyp, deep=False):
        # type: (Any, Any, bool) -> Any
        if not isinstance(node, SequenceNode):
            raise ConstructorError(
                None,
                None,
                "expected a sequence node, but found %s" % node.id,
                node.start_mark,
            )
        ret_val = []
        if node.comment:
            seqtyp._yaml_add_comment(node.comment[:2])
            if len(node.comment) > 2:
                seqtyp.yaml_end_comment_extend(node.comment[2], clear=True)
        if node.anchor:
            from strictyaml.ruamel.serializer import templated_id

            if not templated_id(node.anchor):
                seqtyp.yaml_set_anchor(node.anchor)
        for idx, child in enumerate(node.value):
            if child.comment:
                seqtyp._yaml_add_comment(child.comment, key=idx)
                child.comment = None  # if moved to sequence remove from child
            ret_val.append(self.construct_object(child, deep=deep))
            seqtyp._yaml_set_idx_line_col(
                idx, [child.start_mark.line, child.start_mark.column]
            )
        return ret_val

    def flatten_mapping(self, node):
        # type: (Any) -> Any
        """
        This implements the merge key feature http://yaml.org/type/merge.html
        by inserting keys from the merge dict/list of dicts if not yet
        available in this node
        """

        def constructed(value_node):
            # type: (Any) -> Any
            # If the contents of a merge are defined within the
            # merge marker, then they won't have been constructed
            # yet. But if they were already constructed, we need to use
            # the existing object.
            if value_node in self.constructed_objects:
                value = self.constructed_objects[value_node]
            else:
                value = self.construct_object(value_node, deep=False)
            return value

        # merge = []
        merge_map_list = []  # type: List[Any]
        index = 0
        while index < len(node.value):
            key_node, value_node = node.value[index]
            if key_node.tag == u"tag:yaml.org,2002:merge":
                if merge_map_list:  # double << key
                    if self.allow_duplicate_keys:
                        del node.value[index]
                        index += 1
                        continue
                    args = [
                        "while constructing a mapping",
                        node.start_mark,
                        'found duplicate key "{}"'.format(key_node.value),
                        key_node.start_mark,
                        """
                        To suppress this check see:
                           http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                        """,
                        """\
                        Duplicate keys will become an error in future releases, and are errors
                        by default when using the new API.
                        """,
                    ]
                    if self.allow_duplicate_keys is None:
                        warnings.warn(DuplicateKeyFutureWarning(*args))
                    else:
                        raise DuplicateKeyError(*args)
                del node.value[index]
                if isinstance(value_node, MappingNode):
                    merge_map_list.append((index, constructed(value_node)))
                    # self.flatten_mapping(value_node)
                    # merge.extend(value_node.value)
                elif isinstance(value_node, SequenceNode):
                    # submerge = []
                    for subnode in value_node.value:
                        if not isinstance(subnode, MappingNode):
                            raise ConstructorError(
                                "while constructing a mapping",
                                node.start_mark,
                                "expected a mapping for merging, but found %s"
                                % subnode.id,
                                subnode.start_mark,
                            )
                        merge_map_list.append((index, constructed(subnode)))
                    #     self.flatten_mapping(subnode)
                    #     submerge.append(subnode.value)
                    # submerge.reverse()
                    # for value in submerge:
                    #     merge.extend(value)
                else:
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "expected a mapping or list of mappings for merging, "
                        "but found %s" % value_node.id,
                        value_node.start_mark,
                    )
            elif key_node.tag == u"tag:yaml.org,2002:value":
                key_node.tag = u"tag:yaml.org,2002:str"
                index += 1
            else:
                index += 1
        return merge_map_list
        # if merge:
        #     node.value = merge + node.value

    def _sentinel(self):
        # type: () -> None
        pass

    def construct_mapping(self, node, maptyp, deep=False):  # type: ignore
        # type: (Any, Any, bool) -> Any
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None,
                None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark,
            )
        merge_map = self.flatten_mapping(node)
        # mapping = {}
        if node.comment:
            maptyp._yaml_add_comment(node.comment[:2])
            if len(node.comment) > 2:
                maptyp.yaml_end_comment_extend(node.comment[2], clear=True)
        if node.anchor:
            from strictyaml.ruamel.serializer import templated_id

            if not templated_id(node.anchor):
                maptyp.yaml_set_anchor(node.anchor)
        last_key, last_value = None, self._sentinel
        for key_node, value_node in node.value:
            # keys can be list -> deep
            key = self.construct_object(key_node, deep=True)
            # lists are not hashable, but tuples are
            if not isinstance(key, Hashable):
                if isinstance(key, MutableSequence):
                    key_s = CommentedKeySeq(key)
                    if key_node.flow_style is True:
                        key_s.fa.set_flow_style()
                    elif key_node.flow_style is False:
                        key_s.fa.set_block_style()
                    key = key_s
                elif isinstance(key, MutableMapping):
                    key_m = CommentedKeyMap(key)
                    if key_node.flow_style is True:
                        key_m.fa.set_flow_style()
                    elif key_node.flow_style is False:
                        key_m.fa.set_block_style()
                    key = key_m
            if PY2:
                try:
                    hash(key)
                except TypeError as exc:
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "found unacceptable key (%s)" % exc,
                        key_node.start_mark,
                    )
            else:
                if not isinstance(key, Hashable):
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "found unhashable key",
                        key_node.start_mark,
                    )
            value = self.construct_object(value_node, deep=deep)
            if self.check_mapping_key(node, key_node, maptyp, key, value):
                if (
                    key_node.comment
                    and len(key_node.comment) > 4
                    and key_node.comment[4]
                ):
                    if last_value is None:
                        key_node.comment[0] = key_node.comment.pop(4)
                        maptyp._yaml_add_comment(key_node.comment, value=last_key)
                    else:
                        key_node.comment[2] = key_node.comment.pop(4)
                        maptyp._yaml_add_comment(key_node.comment, key=key)
                    key_node.comment = None
                if key_node.comment:
                    maptyp._yaml_add_comment(key_node.comment, key=key)
                if value_node.comment:
                    maptyp._yaml_add_comment(value_node.comment, value=key)
                maptyp._yaml_set_kv_line_col(
                    key,
                    [
                        key_node.start_mark.line,
                        key_node.start_mark.column,
                        value_node.start_mark.line,
                        value_node.start_mark.column,
                    ],
                )
                maptyp[key] = value
                last_key, last_value = key, value  # could use indexing
        # do this last, or <<: before a key will prevent insertion in instances
        # of collections.OrderedDict (as they have no __contains__
        if merge_map:
            maptyp.add_yaml_merge(merge_map)

    def construct_setting(self, node, typ, deep=False):
        # type: (Any, Any, bool) -> Any
        if not isinstance(node, MappingNode):
            raise ConstructorError(
                None,
                None,
                "expected a mapping node, but found %s" % node.id,
                node.start_mark,
            )
        if node.comment:
            typ._yaml_add_comment(node.comment[:2])
            if len(node.comment) > 2:
                typ.yaml_end_comment_extend(node.comment[2], clear=True)
        if node.anchor:
            from strictyaml.ruamel.serializer import templated_id

            if not templated_id(node.anchor):
                typ.yaml_set_anchor(node.anchor)
        for key_node, value_node in node.value:
            # keys can be list -> deep
            key = self.construct_object(key_node, deep=True)
            # lists are not hashable, but tuples are
            if not isinstance(key, Hashable):
                if isinstance(key, list):
                    key = tuple(key)
            if PY2:
                try:
                    hash(key)
                except TypeError as exc:
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "found unacceptable key (%s)" % exc,
                        key_node.start_mark,
                    )
            else:
                if not isinstance(key, Hashable):
                    raise ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        "found unhashable key",
                        key_node.start_mark,
                    )
            # construct but should be null
            value = self.construct_object(value_node, deep=deep)  # NOQA
            self.check_set_key(node, key_node, typ, key)
            if key_node.comment:
                typ._yaml_add_comment(key_node.comment, key=key)
            if value_node.comment:
                typ._yaml_add_comment(value_node.comment, value=key)
            typ.add(key)

    def construct_yaml_seq(self, node):
        # type: (Any) -> Any
        data = CommentedSeq()
        data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
        if node.comment:
            data._yaml_add_comment(node.comment)
        yield data
        data.extend(self.construct_rt_sequence(node, data))
        self.set_collection_style(data, node)

    def construct_yaml_map(self, node):
        # type: (Any) -> Any
        data = CommentedMap()
        data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
        yield data
        self.construct_mapping(node, data, deep=True)
        self.set_collection_style(data, node)

    def set_collection_style(self, data, node):
        # type: (Any, Any) -> None
        if len(data) == 0:
            return
        if node.flow_style is True:
            data.fa.set_flow_style()
        elif node.flow_style is False:
            data.fa.set_block_style()

    def construct_yaml_object(self, node, cls):
        # type: (Any, Any) -> Any
        data = cls.__new__(cls)
        yield data
        if hasattr(data, "__setstate__"):
            state = SafeConstructor.construct_mapping(self, node, deep=True)
            data.__setstate__(state)
        else:
            state = SafeConstructor.construct_mapping(self, node)
            data.__dict__.update(state)

    def construct_yaml_omap(self, node):
        # type: (Any) -> Any
        # Note: we do now check for duplicate keys
        omap = CommentedOrderedMap()
        omap._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
        if node.flow_style is True:
            omap.fa.set_flow_style()
        elif node.flow_style is False:
            omap.fa.set_block_style()
        yield omap
        if node.comment:
            omap._yaml_add_comment(node.comment[:2])
            if len(node.comment) > 2:
                omap.yaml_end_comment_extend(node.comment[2], clear=True)
        if not isinstance(node, SequenceNode):
            raise ConstructorError(
                "while constructing an ordered map",
                node.start_mark,
                "expected a sequence, but found %s" % node.id,
                node.start_mark,
            )
        for subnode in node.value:
            if not isinstance(subnode, MappingNode):
                raise ConstructorError(
                    "while constructing an ordered map",
                    node.start_mark,
                    "expected a mapping of length 1, but found %s" % subnode.id,
                    subnode.start_mark,
                )
            if len(subnode.value) != 1:
                raise ConstructorError(
                    "while constructing an ordered map",
                    node.start_mark,
                    "expected a single mapping item, but found %d items"
                    % len(subnode.value),
                    subnode.start_mark,
                )
            key_node, value_node = subnode.value[0]
            key = self.construct_object(key_node)
            assert key not in omap
            value = self.construct_object(value_node)
            if key_node.comment:
                omap._yaml_add_comment(key_node.comment, key=key)
            if subnode.comment:
                omap._yaml_add_comment(subnode.comment, key=key)
            if value_node.comment:
                omap._yaml_add_comment(value_node.comment, value=key)
            omap[key] = value

    def construct_yaml_set(self, node):
        # type: (Any) -> Any
        data = CommentedSet()
        data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
        yield data
        self.construct_setting(node, data)

    def construct_undefined(self, node):
        # type: (Any) -> Any
        try:
            if isinstance(node, MappingNode):
                data = CommentedMap()
                data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
                if node.flow_style is True:
                    data.fa.set_flow_style()
                elif node.flow_style is False:
                    data.fa.set_block_style()
                data.yaml_set_tag(node.tag)
                yield data
                if node.anchor:
                    data.yaml_set_anchor(node.anchor)
                self.construct_mapping(node, data)
                return
            elif isinstance(node, ScalarNode):
                data2 = TaggedScalar()
                data2.value = self.construct_scalar(node)
                data2.style = node.style
                data2.yaml_set_tag(node.tag)
                yield data2
                if node.anchor:
                    data2.yaml_set_anchor(node.anchor, always_dump=True)
                return
            elif isinstance(node, SequenceNode):
                data3 = CommentedSeq()
                data3._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
                if node.flow_style is True:
                    data3.fa.set_flow_style()
                elif node.flow_style is False:
                    data3.fa.set_block_style()
                data3.yaml_set_tag(node.tag)
                yield data3
                if node.anchor:
                    data3.yaml_set_anchor(node.anchor)
                data3.extend(self.construct_sequence(node))
                return
        except:  # NOQA
            pass
        raise ConstructorError(
            None,
            None,
            "could not determine a constructor for the tag %r" % utf8(node.tag),
            node.start_mark,
        )

    def construct_yaml_timestamp(self, node, values=None):
        # type: (Any, Any) -> Any
        try:
            match = self.timestamp_regexp.match(node.value)
        except TypeError:
            match = None
        if match is None:
            raise ConstructorError(
                None,
                None,
                'failed to construct timestamp from "{}"'.format(node.value),
                node.start_mark,
            )
        values = match.groupdict()
        if not values["hour"]:
            return SafeConstructor.construct_yaml_timestamp(self, node, values)
        for part in ["t", "tz_sign", "tz_hour", "tz_minute"]:
            if values[part]:
                break
        else:
            return SafeConstructor.construct_yaml_timestamp(self, node, values)
        year = int(values["year"])
        month = int(values["month"])
        day = int(values["day"])
        hour = int(values["hour"])
        minute = int(values["minute"])
        second = int(values["second"])
        fraction = 0
        if values["fraction"]:
            fraction_s = values["fraction"][:6]
            while len(fraction_s) < 6:
                fraction_s += "0"
            fraction = int(fraction_s)
            if len(values["fraction"]) > 6 and int(values["fraction"][6]) > 4:
                fraction += 1
        delta = None
        if values["tz_sign"]:
            tz_hour = int(values["tz_hour"])
            minutes = values["tz_minute"]
            tz_minute = int(minutes) if minutes else 0
            delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
            if values["tz_sign"] == "-":
                delta = -delta
        # shold check for NOne and solve issue 366 should be tzinfo=delta)
        if delta:
            dt = datetime.datetime(year, month, day, hour, minute)
            dt -= delta
            data = TimeStamp(
                dt.year, dt.month, dt.day, dt.hour, dt.minute, second, fraction
            )
            data._yaml["delta"] = delta
            tz = values["tz_sign"] + values["tz_hour"]
            if values["tz_minute"]:
                tz += ":" + values["tz_minute"]
            data._yaml["tz"] = tz
        else:
            data = TimeStamp(year, month, day, hour, minute, second, fraction)
            if values["tz"]:  # no delta
                data._yaml["tz"] = values["tz"]

        if values["t"]:
            data._yaml["t"] = True
        return data

    def construct_yaml_bool(self, node):
        # type: (Any) -> Any
        b = SafeConstructor.construct_yaml_bool(self, node)
        if node.anchor:
            return ScalarBoolean(b, anchor=node.anchor)
        return b class Loader(Reader, Scanner, Parser, Composer, Constructor, VersionedResolver):
    def __init__(self, stream, version=None, preserve_quotes=None):
        # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
        Reader.__init__(self, stream, loader=self)
        Scanner.__init__(self, loader=self)
        Parser.__init__(self, loader=self)
        Composer.__init__(self, loader=self)
        Constructor.__init__(self, loader=self)
        VersionedResolver.__init__(self, version, loader=self)
import sys
import os
import warnings
import glob
import strictyaml.ruamel
from importlib import import_module
from strictyaml.ruamel.error import UnsafeLoaderWarning, YAMLError  # NOQA
from strictyaml.ruamel.tokens import *  # NOQA
from strictyaml.ruamel.events import *  # NOQA
from strictyaml.ruamel.nodes import *  # NOQA
from strictyaml.ruamel.loader import (
    BaseLoader,
    SafeLoader,
    Loader,
    RoundTripLoader,
)  # NOQA
from strictyaml.ruamel.dumper import (
    BaseDumper,
    SafeDumper,
    Dumper,
    RoundTripDumper,
)  # NOQA
from strictyaml.ruamel.compat import StringIO, BytesIO, with_metaclass, PY3, nprint
from strictyaml.ruamel.resolver import VersionedResolver, Resolver  # NOQA
from strictyaml.ruamel.representer import (
    BaseRepresenter,
    SafeRepresenter,
    Representer,
    RoundTripRepresenter,
)
from strictyaml.ruamel.constructor import (
    BaseConstructor,
    SafeConstructor,
    Constructor,
    RoundTripConstructor,
)
from strictyaml.ruamel.loader import Loader as UnsafeLoader
    from typing import List, Set, Dict, Union, Any, Callable, Optional, Text  # NOQA
    from strictyaml.ruamel.compat import StreamType, StreamTextType, VersionType  # NOQA
        from pathlib import Path
    from _ruamel_yaml import CParser, CEmitter  # type: ignore
            from strictyaml.ruamel.comments import CommentedMap
            from strictyaml.ruamel.comments import CommentedSeq
# coding: utf-8

from __future__ import absolute_import, unicode_literals, print_function






if False:  # MYPY

    if PY3:
    else:
        Path = Any

try:
except:  # NOQA
    CParser = CEmitter = None

# import io

enforce = object()


# YAML is an acronym, i.e. spoken: rhymes with "camel". And thus a
# subset of abbreviations, which should be all caps according to PEP8


class YAML(object):
    def __init__(
        self,
        _kw=enforce,
        typ=None,
        pure=False,
        output=None,
        plug_ins=None,  # input=None,
    ):
        # type: (Any, Optional[Text], Any, Any, Any) -> None
        """
        _kw: not used, forces keyword arguments in 2.7 (in 3 you can do (*, safe_load=..)
        typ: 'rt'/None -> RoundTripLoader/RoundTripDumper,  (default)
             'safe'    -> SafeLoader/SafeDumper,
             'unsafe'  -> normal/unsafe Loader/Dumper
             'base'    -> baseloader
        pure: if True only use Python modules
        input/output: needed to work as context manager
        plug_ins: a list of plug-in files
        """
        if _kw is not enforce:
            raise TypeError(
                "{}.__init__() takes no positional argument but at least "
                "one was given ({!r})".format(self.__class__.__name__, _kw)
            )

        self.typ = ["rt"] if typ is None else (typ if isinstance(typ, list) else [typ])
        self.pure = pure

        # self._input = input
        self._output = output
        self._context_manager = None  # type: Any

        self.plug_ins = []  # type: List[Any]
        for pu in ([] if plug_ins is None else plug_ins) + self.official_plug_ins():
            file_name = pu.replace(os.sep, ".")
            self.plug_ins.append(import_module(file_name))

        self.Resolver = strictyaml.ruamel.resolver.VersionedResolver  # type: Any