instance, (int, float, Decimal, AbstractDateTime, Duration, UntypedAtomic)

Prompt:
Please complete the code given below.
elementpath/helpers.py
NUMERIC_INF_OR_NAN = frozenset(('INF', '-INF', 'NaN'))
elementpath/helpers.py
BOOLEAN_VALUES = frozenset(('true', 'false', '1', '0'))
elementpath/datatypes/datetime.py
class AbstractDateTime(metaclass=AtomicTypeMeta):
    """
    A class for representing XSD date/time objects. It uses and internal datetime.datetime
    attribute and an integer attribute for processing BCE years or for years after 9999 CE.
    """
    xsd_version = '1.0'
    pattern = re.compile(r'^$')
    _utc_timezone = Timezone(datetime.timedelta(0))
    _year = None

    def __init__(self, year: int = 2000, month: int = 1, day: int = 1, hour: int = 0,
                 minute: int = 0, second: int = 0, microsecond: int = 0,
                 tzinfo: Optional[datetime.tzinfo] = None) -> None:

        if hour == 24 and minute == second == microsecond == 0:
            delta = datetime.timedelta(days=1)
            hour = 0
        else:
            delta = datetime.timedelta(0)

        if 1 <= year <= 9999:
            self._dt = datetime.datetime(year, month, day, hour, minute,
                                         second, microsecond, tzinfo)
        elif year == 0:
            raise ValueError('0 is an illegal value for year')
        elif not isinstance(year, int):
            raise TypeError("invalid type %r for year" % type(year))
        elif abs(year) > 2 ** 31:
            raise OverflowError("year overflow")
        else:
            self._year = year
            if isleap(year + bool(self.xsd_version != '1.0')):
                self._dt = datetime.datetime(4, month, day, hour, minute,
                                             second, microsecond, tzinfo)
            else:
                self._dt = datetime.datetime(6, month, day, hour, minute,
                                             second, microsecond, tzinfo)

        if delta:
            self._dt += delta

    def __repr__(self) -> str:
        fields = self.pattern.groupindex.keys()
        arg_string = ', '.join(
            str(getattr(self, k))
            for k in ['year', 'month', 'day', 'hour', 'minute'] if k in fields
        )
        if 'second' in fields:
            if self.microsecond:
                arg_string += ', %d.%06d' % (self.second, self.microsecond)
            else:
                arg_string += ', %d' % self.second

        if self.tzinfo is not None:
            arg_string += ', tzinfo=%r' % self.tzinfo
        return '%s(%s)' % (self.__class__.__name__, arg_string)

    @abstractmethod
    def __str__(self) -> str:
        raise NotImplementedError()

    @property
    def year(self) -> int:
        return self._year or self._dt.year

    @property
    def bce(self) -> bool:
        return self._year is not None and self._year < 0

    @property
    def iso_year(self) -> str:
        """The ISO string representation of the year field."""
        year = self.year
        if -9999 <= year < -1:
            return '{:05}'.format(year if self.xsd_version == '1.0' else year + 1)
        elif year == -1:
            return '-0001' if self.xsd_version == '1.0' else '0000'
        elif 0 <= year <= 9999:
            return '{:04}'.format(year)
        else:
            return str(year)

    @property
    def month(self) -> int:
        return self._dt.month

    @property
    def day(self) -> int:
        return self._dt.day

    @property
    def hour(self) -> int:
        return self._dt.hour

    @property
    def minute(self) -> int:
        return self._dt.minute

    @property
    def second(self) -> int:
        return self._dt.second

    @property
    def microsecond(self) -> int:
        return self._dt.microsecond

    @property
    def tzinfo(self) -> Optional[Timezone]:
        return cast(Timezone, self._dt.tzinfo)

    @tzinfo.setter
    def tzinfo(self, tz: Timezone) -> None:
        self._dt = self._dt.replace(tzinfo=tz)

    def tzname(self) -> Optional[str]:
        return self._dt.tzname()

    def astimezone(self, tz: Optional[datetime.tzinfo] = None) -> datetime.datetime:
        return self._dt.astimezone(tz)

    def isocalendar(self) -> Tuple[int, int, int]:
        return self._dt.isocalendar()

    @classmethod
    def fromstring(cls, datetime_string: str, tzinfo: Optional[Timezone] = None) \
            -> 'AbstractDateTime':
        """
        Creates an XSD date/time instance from a string formatted value.

        :param datetime_string: a string containing an XSD formatted date/time specification.
        :param tzinfo: optional implicit timezone information, must be a `Timezone` instance.
        :return: an AbstractDateTime concrete subclass instance.
        """
        if not isinstance(datetime_string, str):
            msg = '1st argument has an invalid type {!r}'
            raise TypeError(msg.format(type(datetime_string)))
        elif tzinfo and not isinstance(tzinfo, Timezone):
            msg = '2nd argument has an invalid type {!r}'
            raise TypeError(msg.format(type(tzinfo)))

        match = cls.pattern.match(datetime_string.strip())
        if match is None:
            msg = 'Invalid datetime string {!r} for {!r}'
            raise ValueError(msg.format(datetime_string, cls))

        match_dict = match.groupdict()
        kwargs: Dict[str, int] = {
            k: int(v) for k, v in match_dict.items() if k != 'tzinfo' and v is not None
        }

        if match_dict['tzinfo'] is not None:
            tzinfo = Timezone.fromstring(match_dict['tzinfo'])

        if 'microsecond' in kwargs:
            microseconds = match_dict['microsecond']
            if len(microseconds) != 6:
                microseconds += '0' * (6 - len(microseconds))
                kwargs['microsecond'] = int(microseconds[:6])

        if 'year' in kwargs:
            year_digits = match_dict['year'].lstrip('-')
            if year_digits.startswith('0') and len(year_digits) > 4:
                msg = "Invalid datetime string {!r} for {!r} (when year " \
                      "exceeds 4 digits leading zeroes are not allowed)"
                raise ValueError(msg.format(datetime_string, cls))

            if cls.xsd_version == '1.0':
                if kwargs['year'] == 0:
                    raise ValueError("year '0000' is an illegal value for XSD 1.0")
            elif kwargs['year'] <= 0:
                kwargs['year'] -= 1

        return cls(tzinfo=tzinfo, **kwargs)

    @classmethod
    def fromdatetime(cls, dt: Union[datetime.datetime, datetime.date, datetime.time],
                     year: Optional[int] = None) -> 'AbstractDateTime':
        """
        Creates an XSD date/time instance from a datetime.datetime/date/time instance.

        :param dt: the datetime, date or time instance that stores the XSD Date/Time value.
        :param year: if an year is provided the created instance refers to it and the \
        possibly present *dt.year* part is ignored.
        :return: an AbstractDateTime concrete subclass instance.
        """
        if not isinstance(dt, (datetime.datetime, datetime.date, datetime.time)):
            raise TypeError('1st argument has an invalid type %r' % type(dt))
        elif year is not None and not isinstance(year, int):
            raise TypeError('2nd argument has an invalid type %r' % type(year))

        kwargs = {k: getattr(dt, k) for k in cls.pattern.groupindex.keys() if hasattr(dt, k)}
        if year is not None:
            kwargs['year'] = year
        return cls(**kwargs)

    # Python can't compares offset-naive and offset-aware datetimes
    def _get_operands(self, other: object) -> Tuple[datetime.datetime, datetime.datetime]:
        if isinstance(other, (self.__class__, datetime.datetime)) or \
                isinstance(self, other.__class__):
            dt: datetime.datetime = getattr(other, '_dt', cast(datetime.datetime, other))

            if self._dt.tzinfo is dt.tzinfo:
                return self._dt, dt
            elif self.tzinfo is None:
                return self._dt.replace(tzinfo=self._utc_timezone), dt
            elif dt.tzinfo is None:
                return self._dt, dt.replace(tzinfo=self._utc_timezone)
            else:
                return self._dt, dt
        else:
            raise TypeError("wrong type %r for operand %r" % (type(other), other))

    def __hash__(self) -> int:
        return hash((self._dt, self._year))

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, (AbstractDateTime, datetime.datetime)):
            return False
        try:
            return operator.eq(*self._get_operands(other)) and self.year == other.year
        except TypeError:
            return False

    def __ne__(self, other: object) -> bool:
        if not isinstance(other, (AbstractDateTime, datetime.datetime)):
            return True
        try:
            return operator.ne(*self._get_operands(other)) or self.year != other.year
        except TypeError:
            return True
elementpath/datatypes/untyped.py
class UntypedAtomic(metaclass=AtomicTypeMeta):
    """
    Class for xs:untypedAtomic data. Provides special methods for comparing
    and converting to basic data types.

    :param value: the untyped value, usually a string.
    """
    name = 'untypedAtomic'
    value: str

    @classmethod
    def validate(cls, value: object) -> None:
        if not isinstance(value, cls):
            raise cls.invalid_type(value)

    def __init__(self, value: Union[str, bytes, bool, float, Decimal,
                                    'UntypedAtomic', AnyAtomicType]) -> None:
        if isinstance(value, str):
            self.value = value
        elif isinstance(value, bytes):
            self.value = value.decode('utf-8')
        elif isinstance(value, bool):
            self.value = 'true' if value else 'false'
        elif isinstance(value, float):
            self.value = str(value).rstrip('0').rstrip('.')
        elif isinstance(value, Decimal):
            self.value = str(value.normalize())
        elif isinstance(value, UntypedAtomic):
            self.value = value.value
        elif isinstance(value, AnyAtomicType):
            self.value = str(value)
        else:
            raise TypeError("{!r} is not an atomic value".format(value))

    def __repr__(self) -> str:
        return '%s(%r)' % (self.__class__.__name__, self.value)

    def _get_operands(self, other: Any, force_float: bool = True) -> Tuple[Any, Any]:
        """
        Returns a couple of operands, applying a cast to the instance value based on
        the type of the *other* argument.

        :param other: The other operand, that determines the cast for the untyped instance.
        :param force_float: Force a conversion to float if *other* is an UntypedAtomic instance.
        :return: A couple of values.
        """
        if isinstance(other, UntypedAtomic):
            if force_float:
                return float(self.value), float(other.value)
            return self.value, other.value
        elif isinstance(other, bool):
            # Cast to xs:boolean
            value = self.value.strip()
            if value not in BOOLEAN_VALUES:
                raise ValueError("{!r} cannot be cast to xs:boolean".format(self.value))
            return value in ('1', 'true'), other
        elif isinstance(other, int):
            return float(self.value), other
        elif other is None or isinstance(other, (str, list)):
            return self.value, other

        try:
            return type(other).fromstring(self.value), other
        except AttributeError:
            return type(other)(self.value), other

    def __hash__(self) -> int:
        return hash(self.value)

    def __eq__(self, other: Any) -> Any:
        return operator.eq(*self._get_operands(other, force_float=False))

    def __ne__(self, other: Any) -> Any:
        return not operator.eq(*self._get_operands(other, force_float=False))

    def __lt__(self, other: Any) -> Any:
        return operator.lt(*self._get_operands(other))

    def __le__(self, other: Any) -> Any:
        return operator.le(*self._get_operands(other))

    def __gt__(self, other: Any) -> Any:
        return operator.gt(*self._get_operands(other))

    def __ge__(self, other: Any) -> Any:
        return operator.ge(*self._get_operands(other))

    def __add__(self, other: Any) -> Any:
        return operator.add(*self._get_operands(other))
    __radd__ = __add__

    def __sub__(self, other: Any) -> Any:
        return operator.sub(*self._get_operands(other))

    def __rsub__(self, other: Any) -> Any:
        return operator.sub(*reversed(self._get_operands(other)))

    def __mul__(self, other: Any) -> Any:
        return operator.mul(*self._get_operands(other))
    __rmul__ = __mul__

    def __truediv__(self, other: Any) -> Any:
        return operator.truediv(*self._get_operands(other))

    def __rtruediv__(self, other: Any) -> Any:
        return operator.truediv(*reversed(self._get_operands(other)))

    def __int__(self) -> int:
        return int(self.value)

    def __float__(self) -> float:
        return float(self.value)

    def __bool__(self) -> bool:
        return bool(self.value)  # For effective boolean value, not for cast to xs:boolean.

    def __abs__(self) -> Decimal:
        return abs(Decimal(self.value))

    def __mod__(self, other: Any) -> Any:
        return operator.mod(*self._get_operands(other))

    def __str__(self) -> str:
        return self.value

    def __bytes__(self) -> bytes:
        return bytes(self.value, encoding='utf-8')
elementpath/datatypes/datetime.py
class Duration(AnyAtomicType):
    """
    Base class for the XSD duration types.

    :param months: an integer value that represents years and months.
    :param seconds: a decimal or an integer instance that represents \
    days, hours, minutes, seconds and fractions of seconds.
    """
    name = 'duration'
    pattern = re.compile(
        r'^(-)?P(?=[0-9]|T)(?:([0-9]+)Y)?(?:([0-9]+)M)?(?:([0-9]+)D)?'
        r'(?:T(?=[0-9])(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+(?:\.[0-9]+)?)S)?)?$'
    )

    def __init__(self, months: int = 0, seconds: Union[Decimal, int] = 0) -> None:
        if seconds < 0 < months or months < 0 < seconds:
            raise ValueError('signs differ: (months=%d, seconds=%d)' % (months, seconds))
        elif abs(months) > 2 ** 31:
            raise OverflowError("months duration overflow")
        elif abs(seconds) > 2 ** 63:  # type: ignore[operator]
            raise OverflowError("seconds duration overflow")

        self.months = months
        self.seconds = Decimal(seconds).quantize(Decimal('1.000000'))

    def __repr__(self) -> str:
        return '{}(months={!r}, seconds={})'.format(
            self.__class__.__name__, self.months, normalized_seconds(self.seconds)
        )

    def __str__(self) -> str:
        m = abs(self.months)
        years, months = m // 12, m % 12
        s = self.seconds.copy_abs()
        days = int(s // 86400)
        hours = int(s // 3600 % 24)
        minutes = int(s // 60 % 60)
        seconds = s % 60

        value = '-P' if self.sign else 'P'
        if years or months or days:
            if years:
                value += '%dY' % years
            if months:
                value += '%dM' % months
            if days:
                value += '%dD' % days

        if hours or minutes or seconds:
            value += 'T'
            if hours:
                value += '%dH' % hours
            if minutes:
                value += '%dM' % minutes
            if seconds:
                value += '%sS' % normalized_seconds(seconds)

        elif value[-1] == 'P':
            value += 'T0S'
        return value

    @classmethod
    def fromstring(cls, text: str) -> 'Duration':
        """
        Creates a Duration instance from a formatted XSD duration string.

        :param text: an ISO 8601 representation without week fragment and an optional decimal part \
        only for seconds fragment.
        """
        if not isinstance(text, str):
            msg = 'argument has an invalid type {!r}'
            raise TypeError(msg.format(type(text)))

        match = cls.pattern.match(text.strip())
        if match is None:
            raise ValueError('%r is not an xs:duration value' % text)

        sign, y, mo, d, h, mi, s = match.groups()
        seconds = Decimal(s or 0)
        minutes = int(mi or 0) + int(seconds // 60)
        seconds = seconds % 60
        hours = int(h or 0) + minutes // 60
        minutes = minutes % 60
        days = int(d or 0) + hours // 24
        hours = hours % 24
        months = int(mo or 0) + 12 * int(y or 0)

        if sign is None:
            seconds = seconds + (days * 24 + hours) * 3600 + minutes * 60
        else:
            months = -months
            seconds = -seconds - (days * 24 + hours) * 3600 - minutes * 60

        if cls is DayTimeDuration:
            if months:
                raise ValueError('months must be 0 for %r' % cls.__name__)
            return cls(seconds=seconds)
        elif cls is YearMonthDuration:
            if seconds:
                raise ValueError('seconds must be 0 for %r' % cls.__name__)
            return cls(months=months)
        return cls(months=months, seconds=seconds)

    @property
    def sign(self) -> str:
        return '-' if self.months < 0 or self.seconds < 0 else ''

    def _compare_durations(self, other: object, op: Callable[[Any, Any], Any]) -> bool:
        """
        Ordering is defined through comparison of four datetime.datetime values.

        Ref: https://www.w3.org/TR/2012/REC-xmlschema11-2-20120405/#duration
        """
        if not isinstance(other, self.__class__):
            raise TypeError("wrong type %r for operand %r" % (type(other), other))

        m1, s1 = self.months, int(self.seconds)
        m2, s2 = other.months, int(other.seconds)
        ms1, ms2 = int((self.seconds - s1) * 1000000), int((other.seconds - s2) * 1000000)
        return all([
            op(datetime.timedelta(months2days(1696, 9, m1), s1, ms1),
               datetime.timedelta(months2days(1696, 9, m2), s2, ms2)),
            op(datetime.timedelta(months2days(1697, 2, m1), s1, ms1),
               datetime.timedelta(months2days(1697, 2, m2), s2, ms2)),
            op(datetime.timedelta(months2days(1903, 3, m1), s1, ms1),
               datetime.timedelta(months2days(1903, 3, m2), s2, ms2)),
            op(datetime.timedelta(months2days(1903, 7, m1), s1, ms1),
               datetime.timedelta(months2days(1903, 7, m2), s2, ms2)),
        ])

    def __hash__(self) -> int:
        return hash((self.months, self.seconds))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, self.__class__):
            return self.months == other.months and self.seconds == other.seconds
        elif isinstance(other, UntypedAtomic):
            return self.__eq__(self.fromstring(other.value))
        else:
            return other == (self.months, self.seconds)

    def __ne__(self, other: object) -> bool:
        if isinstance(other, self.__class__):
            return self.months != other.months or self.seconds != other.seconds
        elif isinstance(other, UntypedAtomic):
            return self.__ne__(self.fromstring(other.value))
        else:
            return other != (self.months, self.seconds)

    def __lt__(self, other: object) -> bool:
        return self._compare_durations(other, operator.lt)

    def __le__(self, other: object) -> bool:
        return self == other or self._compare_durations(other, operator.le)

    def __gt__(self, other: object) -> bool:
        return self._compare_durations(other, operator.gt)

    def __ge__(self, other: object) -> bool:
        return self == other or self._compare_durations(other, operator.ge)
elementpath/datatypes/atomic_types.py
class AtomicTypeMeta(ABCMeta):
    """
    Metaclass for creating XSD atomic types. The created classes
    are decorated with missing attributes and methods. When a name
    attribute is provided the class is registered into a global map
    of XSD atomic types and also the expanded name is added.
    """
    xsd_version: str
    pattern: Pattern[str]
    name: Optional[str] = None

    def __new__(mcs, class_name: str, bases: Tuple[Type[Any], ...], dict_: Dict[str, Any]) \
            -> 'AtomicTypeMeta':
        try:
            name = dict_['name']
        except KeyError:
            name = dict_['name'] = None  # do not inherit name

        if name is not None and not isinstance(name, str):
            raise TypeError("attribute 'name' must be a string or None")

        dict_['is_valid'] = classmethod(mcs.is_valid)
        dict_['invalid_type'] = classmethod(mcs.invalid_type)
        dict_['invalid_value'] = classmethod(mcs.invalid_value)
        cls = super(AtomicTypeMeta, mcs).__new__(mcs, class_name, bases, dict_)

        # Add missing attributes and methods
        if not hasattr(cls, 'xsd_version'):
            cls.xsd_version = '1.0'
        if not hasattr(cls, 'pattern'):
            cls.pattern = re.compile(r'^$')

        # Register class with a name
        if name:
            expanded_name = '{%s}%s' % (XSD_NAMESPACE, name)
            if cls.xsd_version == '1.0':
                xsd10_atomic_types[name] = xsd10_atomic_types[expanded_name] = cls
            else:
                xsd11_atomic_types[name] = xsd11_atomic_types[expanded_name] = cls

        return cls

    def validate(cls, value: object) -> None:
        if isinstance(value, cls):
            return
        elif isinstance(value, str):
            if cls.pattern.match(value) is None:
                raise cls.invalid_value(value)
        else:
            raise cls.invalid_type(value)

    def is_valid(cls, value: object) -> bool:
        try:
            cls.validate(value)
        except (TypeError, ValueError):
            return False
        else:
            return True

    def invalid_type(cls, value: object) -> TypeError:
        if cls.name:
            return TypeError('invalid type {!r} for xs:{}'.format(type(value), cls.name))
        return TypeError('invalid type {!r} for {!r}'.format(type(value), cls))

    def invalid_value(cls, value: object) -> ValueError:
        if cls.name:
            return ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))
        return ValueError('invalid value {!r} for {!r}'.format(value, cls))
elementpath/helpers.py
INVALID_NUMERIC = frozenset(
    ('inf', '+inf', '-inf', 'nan', 'infinity', '+infinity', '-infinity')
)
elementpath/datatypes/numeric.py
class Integer(int, metaclass=AtomicTypeMeta):
    """A wrapper for emulating xs:integer and limited integer types."""
    name = 'integer'
    pattern = re.compile(r'^[\-+]?[0-9]+$')
    lower_bound: Optional[int] = None
    higher_bound: Optional[int] = None

    def __init__(self, value: Union[str, SupportsInt]) -> None:
        if self.lower_bound is not None and self < self.lower_bound:
            raise ValueError("value {} is too low for {!r}".format(value, self.__class__))
        elif self.higher_bound is not None and self >= self.higher_bound:
            raise ValueError("value {} is too high for {!r}".format(value, self.__class__))
        super(Integer, self).__init__()

    @classmethod
    def __subclasshook__(cls, subclass: Type[Any]) -> bool:
        if cls is Integer:
            return issubclass(subclass, int) and not issubclass(subclass, bool)
        return NotImplemented

    @classmethod
    def validate(cls, value: object) -> None:
        if isinstance(value, cls):
            return
        elif isinstance(value, str):
            if cls.pattern.match(value) is None:
                raise cls.invalid_value(value)
        else:
            raise cls.invalid_type(value)
elementpath/datatypes/numeric.py
class Float10(float, AnyAtomicType):
    name = 'float'
    xsd_version = '1.0'
    pattern = re.compile(
        r'^(?:[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[Ee][+-]?[0-9]+)? |[+-]?INF|NaN)$'
    )

    def __new__(cls, value: Union[str, SupportsFloat]) -> 'Float10':
        if isinstance(value, str):
            value = collapse_white_spaces(value)
            if value in NUMERIC_INF_OR_NAN or cls.xsd_version != '1.0' and value == '+INF':
                pass
            elif value.lower() in INVALID_NUMERIC:
                raise ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))

        _value = super().__new__(cls, value)
        if _value > 3.4028235E38:
            return super().__new__(cls, 'INF')
        elif _value < -3.4028235E38:
            return super().__new__(cls, '-INF')
        elif -1e-37 < _value < 1e-37:
            return super().__new__(cls, -0.0 if str(_value).startswith('-') else 0.0)
        return _value

    def __hash__(self) -> int:
        return super(Float10, self).__hash__()

    def __eq__(self, other: object) -> bool:
        if isinstance(other, self.__class__):
            if super(Float10, self).__eq__(other):
                return True
            return math.isclose(self, other, rel_tol=1e-7, abs_tol=0.0)
        return super(Float10, self).__eq__(other)

    def __ne__(self, other: object) -> bool:
        if isinstance(other, self.__class__):
            if super(Float10, self).__eq__(other):
                return False
            return not math.isclose(self, other, rel_tol=1e-7, abs_tol=0.0)
        return super(Float10, self).__ne__(other)

    def __add__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__add__(other))
        elif isinstance(other, float):
            return super(Float10, self).__add__(other)
        return NotImplemented

    def __radd__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__radd__(other))
        elif isinstance(other, float):
            return super(Float10, self).__radd__(other)
        return NotImplemented

    def __sub__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__sub__(other))
        elif isinstance(other, float):
            return super(Float10, self).__sub__(other)
        return NotImplemented

    def __rsub__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__rsub__(other))
        elif isinstance(other, float):
            return super(Float10, self).__rsub__(other)
        return NotImplemented

    def __mul__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__mul__(other))
        elif isinstance(other, float):
            return super(Float10, self).__mul__(other)
        return NotImplemented

    def __rmul__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__rmul__(other))
        elif isinstance(other, float):
            return super(Float10, self).__rmul__(other)
        return NotImplemented

    def __truediv__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__truediv__(other))
        elif isinstance(other, float):
            return super(Float10, self).__truediv__(other)
        return NotImplemented

    def __rtruediv__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__rtruediv__(other))
        elif isinstance(other, float):
            return super(Float10, self).__rtruediv__(other)
        return NotImplemented

    def __mod__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__mod__(other))
        elif isinstance(other, float):
            return super(Float10, self).__mod__(other)
        return NotImplemented

    def __rmod__(self, other: object) -> Union[float, 'Float10', 'Float']:
        if isinstance(other, (self.__class__, int)):
            return self.__class__(super(Float10, self).__rmod__(other))
        elif isinstance(other, float):
            return super(Float10, self).__rmod__(other)
        return NotImplemented

    def __abs__(self) -> Union['Float10', 'Float']:
        return self.__class__(super(Float10, self).__abs__())
elementpath/helpers.py
def collapse_white_spaces(s: str) -> str:
    return WHITESPACES_PATTERN.sub(' ', s).strip(' ')
import re
import math
from decimal import Decimal
from typing import Any, Union, SupportsFloat
from ..helpers import BOOLEAN_VALUES, NUMERIC_INF_OR_NAN, INVALID_NUMERIC, \
    collapse_white_spaces
from .atomic_types import AtomicTypeMeta
from .untyped import UntypedAtomic
from .numeric import Float10, Integer
from .datetime import AbstractDateTime, Duration
                raise cls.invalid_value(value)
        else:
            raise cls.invalid_type(value)

class DecimalProxy(metaclass=AtomicTypeMeta):
    name = 'decimal'
    pattern = re.compile(r'^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$')

    def __new__(cls, value: Any) -> Decimal:  # type: ignore[misc]
        if isinstance(value, (str, UntypedAtomic)):
            value = collapse_white_spaces(str(value)).replace(' ', '')
            if cls.pattern.match(value) is None:
                raise cls.invalid_value(value)
        elif isinstance(value, (float, Float10, Decimal)):
            if math.isinf(value) or math.isnan(value):
                raise cls.invalid_value(value)
        try:
            return Decimal(value)
        except (ValueError, ArithmeticError):
            msg = 'invalid value {!r} for xs:{}'
            raise ArithmeticError(msg.format(value, cls.name)) from None

    @classmethod
    def __subclasshook__(cls, subclass: type) -> bool:
        return issubclass(subclass, (int, Decimal, Integer)) and not issubclass(subclass, bool)

    @classmethod
    def validate(cls, value: object) -> None:
        if isinstance(value, Decimal):
            if math.isnan(value) or math.isinf(value):
                raise cls.invalid_value(value)
        elif isinstance(value, (int, Integer)) and not isinstance(value, bool):
            return
        elif isinstance(value, str):
            if cls.pattern.match(value) is None:
                raise cls.invalid_value(value)
        else:
            raise cls.invalid_type(value)

class DoubleProxy10(metaclass=AtomicTypeMeta):
    name = 'double'
    xsd_version = '1.0'
    pattern = re.compile(
        r'^(?:[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[Ee][+-]?[0-9]+)?|[+-]?INF|NaN)$'
    )

    def __new__(cls, value: Union[SupportsFloat, str]) -> float:  # type: ignore[misc]
        if isinstance(value, str):
            value = collapse_white_spaces(value)
            if value in NUMERIC_INF_OR_NAN or cls.xsd_version != '1.0' and value == '+INF':
                pass
            elif value.lower() in INVALID_NUMERIC:
                raise ValueError('invalid value {!r} for xs:{}'.format(value, cls.name))
        return float(value)

    @classmethod
    def __subclasshook__(cls, subclass: type) -> bool:
        return issubclass(subclass, float) and not issubclass(subclass, Float10)

    @classmethod
    def validate(cls, value: object) -> None:
        if isinstance(value, float) and not isinstance(value, Float10):
            return
        elif isinstance(value, str):
            if cls.pattern.match(value) is None:
                raise cls.invalid_value(value)
        else:
            raise cls.invalid_type(value)

class DoubleProxy(DoubleProxy10):
    name = 'double'
    xsd_version = '1.1'

class StringProxy(metaclass=AtomicTypeMeta):
    name = 'string'

    def __new__(cls, *args: object, **kwargs: object) -> str:  # type: ignore[misc]
        return str(*args, **kwargs)

    @classmethod
    def __subclasshook__(cls, subclass: type) -> bool:
        return issubclass(subclass, str)

    @classmethod
    def validate(cls, value: object) -> None:
        if not isinstance(value, str):
            raise cls.invalid_type(value)

####
# Type proxies for multiple type-checking in XPath expressions
class NumericTypeMeta(type):
    """Metaclass for checking numeric classes and instances."""

    def __instancecheck__(cls, instance: object) -> bool:
        return isinstance(instance, (int, float, Decimal)) and not isinstance(instance, bool)

    def __subclasscheck__(cls, subclass: type) -> bool:
        if issubclass(subclass, bool):
            return False
        return issubclass(subclass, int) or issubclass(subclass, float) \
            or issubclass(subclass, Decimal)

class NumericProxy(metaclass=NumericTypeMeta):
    """Proxy for xs:numeric related types. Builds xs:float instances."""

    def __new__(cls, *args: FloatArgType, **kwargs: FloatArgType) -> float:  # type: ignore[misc]
        return float(*args, **kwargs)

class ArithmeticTypeMeta(type):
    """Metaclass for checking numeric, datetime and duration classes/instances."""

    def __instancecheck__(cls, instance: object) -> bool:
        return isinstance(
Next line of code:


Kim Jong Nam's assassins killed him with a banned chemical weapon, Malaysian police revealed Friday. The country's police chief said toxicology reports on swabs from the face and eyes of the exiled North Korean found VX nerve agent, which the BBC notes is classed as a weapon of mass destruction by the United Nations. He said that one of two women believed to have rubbed the extremely toxic substance on Kim's face with their hands suffered from vomiting after the attack. The New York Times reports that VX agent can be created by mixing two compounds—and police suspect the two women put the substances on Kim's face, one after the other, to create a deadly dose. The police chief said the airport where Kim was attacked is now being decontaminated. North Korea—which is widely suspected to have been behind the killing of leader Kim Jong Un's half brother—never signed the Chemical Weapons Convention that banned VX, the AP notes. Pyongyang denies involvement and says Malaysia's investigation is full of "holes and contradictions." The father of one of the two women being held, Vietnamese citizen Doan Thi Huong, tells the Times his daughter trained as a pharmacist and he has seen little of her in recent years. (Police say that after Malaysia refused to give Kim's body to North Korean diplomats, somebody tried to break into the morgue.)

Prompt:
You are given several news passages. Write a one-page summary of all news.

News:
Passage 1:
In 1994 and 1995, the Japanese cult Aum Shinrikyo used homemade VX to attack three people, one of whom died. NEWLINE_CHAR NEWLINE_CHAR North Korea is estimated to have a chemical weapons production capability of up to 4,500 metric tons during a typical year and 12,000 tons during a period of extended crisis. It is widely reported to possess a large arsenal of chemical weapons, including mustard, phosgene and sarin gas, a United States Congressional Research Service report said last year. NEWLINE_CHAR NEWLINE_CHAR The announcement by Malaysia’s police chief came just a day after North Korea denied any responsibility for Mr. Kim’s death, accusing the Malaysian authorities of fabricating evidence of Pyongyang’s involvement under the influence of South Korea. NEWLINE_CHAR NEWLINE_CHAR With the North’s reclusive government on the defensive about the Feb. 13 killing of Mr. Kim, the estranged half brother of Kim Jong-un, at the airport for the Malaysian capital, Kuala Lumpur, a statement attributed to the North Korean Jurists Committee said the greatest share of responsibility for the death “rests with the government of Malaysia” because Kim Jong-nam died there. And in what could be seen as a threat to Malaysia, the statement noted that North Korea is a “nuclear weapons state.” NEWLINE_CHAR NEWLINE_CHAR But in a case that has been filled with mysteries and odd plot twists, North Korea still would not acknowledge that the man killed was indeed Kim Jong-nam. And it gave no indication that it would agree to Malaysia’s demands to question a senior staff member at the North Korean Embassy in Kuala Lumpur in the investigation into Mr. Kim’s death. NEWLINE_CHAR NEWLINE_CHAR Relatives and acquaintances of the two women Malaysia has accused of carrying out the killing, by applying poison to Kim-Jong-nam’s face as North Korean agents looked on, insisted they must have been duped into doing so, though the Malaysian authorities say otherwise. NEWLINE_CHAR NEWLINE_CHAR “I don’t believe Huong did such a thing,” said Doan Van Thanh, father of Doan Thi Huong, 28, a Vietnamese woman being held in Malaysia. “She was a very timid girl. When she saw a rat or frog, she would scream.”
Passage 2:
Media playback is unsupported on your device Media caption Rupert Wingfield-Hayes: Three reasons why the use of VX is so extraordinary NEWLINE_CHAR NEWLINE_CHAR Kim Jong-nam, the half-brother of North Korea's leader, was killed by a highly toxic nerve agent, says Malaysia. NEWLINE_CHAR NEWLINE_CHAR Mr Kim died last week after two women accosted him briefly in a check-in hall at a Kuala Lumpur airport. NEWLINE_CHAR NEWLINE_CHAR Malaysian toxicology reports indicate he was attacked using VX nerve agent, which is classified as a weapon of mass destruction by the United Nations. NEWLINE_CHAR NEWLINE_CHAR There is widespread suspicion that North Korea was responsible for the attack, which it fiercely denies. NEWLINE_CHAR NEWLINE_CHAR It responded furiously to Malaysia's insistence on conducting a post-mortem examination and has accused Malaysia of having "sinister" purposes. NEWLINE_CHAR NEWLINE_CHAR What does the toxicology report say? NEWLINE_CHAR NEWLINE_CHAR Malaysia's police chief Khalid Abu Bakar said on Friday that the presence of the nerve agent had been detected in swabs taken from Mr Kim's eyes and face. NEWLINE_CHAR NEWLINE_CHAR One of the women Mr Kim interacted with at the airport on 13 February had also fallen ill with vomiting afterwards, he added. NEWLINE_CHAR NEWLINE_CHAR Mr Khalid said other exhibits were still under analysis and that police were investigating how the banned substance might have entered Malaysia. NEWLINE_CHAR NEWLINE_CHAR "If the amount of the chemical brought in was small, it would be difficult for us to detect," he said. NEWLINE_CHAR NEWLINE_CHAR What is the deadly VX nerve agent? NEWLINE_CHAR NEWLINE_CHAR Image copyright Science Photo Library Image caption Molecular model of VX nerve agent shows atoms represented as spheres NEWLINE_CHAR NEWLINE_CHAR The most potent of the known chemical warfare agents, it is a clear, amber-coloured, oily liquid which is tasteless and odourless NEWLINE_CHAR NEWLINE_CHAR Works by penetrating the skin and disrupting the transmission of nerve impulses - a drop on the skin can kill in minutes. Lower doses can cause eye pain, blurred vision, drowsiness and vomiting NEWLINE_CHAR NEWLINE_CHAR It can be disseminated in a spray or vapour when used as a chemical weapon, or used to contaminate water, food, and agricultural products NEWLINE_CHAR NEWLINE_CHAR VX can be absorbed into the body by inhalation, ingestion, skin contact, or eye contact NEWLINE_CHAR NEWLINE_CHAR Clothing can carry VX for about 30 minutes after contact with the vapour, which can expose other people NEWLINE_CHAR NEWLINE_CHAR Banned by the 1993 Chemical Weapons Convention NEWLINE_CHAR NEWLINE_CHAR Read more about VX NEWLINE_CHAR NEWLINE_CHAR Who could be behind the attack? NEWLINE_CHAR NEWLINE_CHAR How could it have killed Mr Kim? NEWLINE_CHAR NEWLINE_CHAR Media playback is unsupported on your device Media caption CCTV footage appears to show the moment Kim Jong-nam is attacked NEWLINE_CHAR NEWLINE_CHAR Bruce Bennett, a weapons expert at the research institute the Rand Corporation, told the BBC it would have taken only a tiny amount of the substance to kill Mr Kim. NEWLINE_CHAR NEWLINE_CHAR He suggests a small quantity of VX - just a drop - was likely to have been put on cloths used by the attackers to touch his face. A separate spray may have been used as a diversion. NEWLINE_CHAR NEWLINE_CHAR Mr Khalid has previously said the fact the woman who accosted Mr Kim immediately went to wash her hands showed she was "very aware" that she had been handling a toxin. NEWLINE_CHAR NEWLINE_CHAR It would have begun affecting his nervous system immediately, causing first shaking and then death within minutes. NEWLINE_CHAR NEWLINE_CHAR More from expert Bruce Bennett NEWLINE_CHAR NEWLINE_CHAR Is Kuala Lumpur airport safe? NEWLINE_CHAR NEWLINE_CHAR The authorities say they intend to decontaminate the airport and areas the suspects are known to have visited. NEWLINE_CHAR NEWLINE_CHAR VX is a v-type nerve agent, which means the substance can remain lethal for a long period of time. NEWLINE_CHAR NEWLINE_CHAR "It's as persistent as motor oil. It's going to stay there for a long time... which means anyone coming in contact with this could be intoxicated from it," forensic toxicologist John Trestrail told the Associated Press news agency. NEWLINE_CHAR NEWLINE_CHAR No passengers, airport workers or medical staff who treated Mr Kim were reported to have become ill in the aftermath of the incident, the news agency adds. NEWLINE_CHAR NEWLINE_CHAR Tens of thousands of passengers are believed to have passed through the airport since the attack more than 10 days ago. NEWLINE_CHAR NEWLINE_CHAR Who was Kim Jong-nam? NEWLINE_CHAR NEWLINE_CHAR Image copyright AP Image caption North Korea has not identified the man who died as Kim Jong-nam, only as a North Korean citizen NEWLINE_CHAR NEWLINE_CHAR The well-travelled and multilingual oldest son of late North Korean leader Kim Jong-il, he was once considered a potential future leader. He has lived abroad for years and was bypassed in favour of his half-brother, Kim Jong-un. NEWLINE_CHAR NEWLINE_CHAR He had been travelling on a passport under the name Kim Chol. North Korea has yet to confirm that the deceased was actually Kim Jong-nam. NEWLINE_CHAR NEWLINE_CHAR For many years, it was believed Kim Jong-nam was being groomed to succeed his father as the next leader. NEWLINE_CHAR NEWLINE_CHAR But that appears to have come to an end in 2001 when Kim was caught sneaking into Japan on a fake passport. NEWLINE_CHAR NEWLINE_CHAR He later became one of the regime's most high-profile critics, openly questioning the Stalinist policies and dynastic succession his grandfather Kim Il-sung began crafting in 1948. NEWLINE_CHAR NEWLINE_CHAR Kim Jong-nam: North Korea's critic in exile NEWLINE_CHAR NEWLINE_CHAR How did he die? NEWLINE_CHAR NEWLINE_CHAR A woman was seen in CCTV footage approaching Mr Kim and wiping something across his face. He sought medical help at the airport, saying someone had splashed or sprayed him with liquid. NEWLINE_CHAR NEWLINE_CHAR He had a seizure and died on the way to hospital. NEWLINE_CHAR NEWLINE_CHAR His body remains in the hospital's mortuary, amid a diplomatic dispute over who should claim it. NEWLINE_CHAR NEWLINE_CHAR Main players in mysterious killing NEWLINE_CHAR NEWLINE_CHAR Who did it? NEWLINE_CHAR NEWLINE_CHAR Malaysia says it was clearly an attack by North Korean agents. Four people are in custody, including one North Korean and the two women he interacted with at the airport. Seven North Koreans are being sought, including a diplomat. NEWLINE_CHAR NEWLINE_CHAR There are a number of North Korean organisations capable of directing such an attack, including the exclusive Guard Command. NEWLINE_CHAR NEWLINE_CHAR The North hit back at Malaysia on Thursday, saying it was responsible for the death of one of its citizens. NEWLINE_CHAR NEWLINE_CHAR In response, Malaysian Foreign Minister Anifah Aman warned North Korean envoy Kang Chol on Friday that he would be expelled unless he stopped "spewing lies" about the attack. NEWLINE_CHAR NEWLINE_CHAR Who in North Korea could organise a VX murder? NEWLINE_CHAR NEWLINE_CHAR North Korea's history of foreign assassinations NEWLINE_CHAR NEWLINE_CHAR Does North Korea have VX? NEWLINE_CHAR NEWLINE_CHAR North Korea is one of just six countries not to have signed the Chemical Weapons Convention (CWC) arms control treaty banning the production, stockpiling and use of chemical weapons. NEWLINE_CHAR NEWLINE_CHAR According to the Nuclear Threat Initiative project, however, North Korea is thought to have the third largest stockpile of chemical weapons, after the US and Russia. NEWLINE_CHAR NEWLINE_CHAR South Korea's defence ministry estimated in 2014 that the North has somewhere between 2,500 and 5,000 tonnes of nerve agents in stock, with VX identified as among them.
Passage 3:
FILE - In this May 4, 2001, file photo, a man believed to be Kim Jong Nam, the eldest son of then North Korean leader Kim Jong Il, looks at a battery of photographers as he exits a police van to board... (Associated Press) NEWLINE_CHAR NEWLINE_CHAR FILE - In this May 4, 2001, file photo, a man believed to be Kim Jong Nam, the eldest son of then North Korean leader Kim Jong Il, looks at a battery of photographers as he exits a police van to board a plane to Beijing at Narita international airport in Narita, northeast of Tokyo. Police in Malaysia... (Associated Press) NEWLINE_CHAR NEWLINE_CHAR KUALA LUMPUR, Malaysia (AP) — The banned chemical weapon VX nerve agent was used to kill Kim Jong Nam, the North Korean ruler's outcast half brother who was poisoned last week at the airport in Kuala Lumpur, police said Friday. The announcement raised serious questions about public safety in a building that authorities went 11 days without decontaminating. NEWLINE_CHAR NEWLINE_CHAR The substance, deadly even in minute amounts, was detected on Kim's eyes and face, Malaysia's inspector general of police said in a written statement, citing a preliminary analysis from the country's Chemistry Department. NEWLINE_CHAR NEWLINE_CHAR "Our preliminary finding of the chemical that caused the death of Kim Chol was VX nerve," said Inspector-General of Police Khalid Abu Bakar. Kim Chol is the name on the passport found on the victim, but a Malaysian official previously confirmed he is North Korea leader Kim Jong Un's older half brother. NEWLINE_CHAR NEWLINE_CHAR Khalid told reporters that one of the two women accused of wiping the toxin on Kim's face was later sickened and suffered from vomiting. He declined to say which of the women — one Indonesian and one Vietnamese — had gotten sick. NEWLINE_CHAR NEWLINE_CHAR Khalid said police were still investigating how the lethal agent entered Malaysia. NEWLINE_CHAR NEWLINE_CHAR Police previously said the airport had not been decontaminated. Asked Friday in a text message whether that was still the case, Khalid said, "We are doing it now." Details were not immediately clear. NEWLINE_CHAR NEWLINE_CHAR Malaysian police also previously no one besides Kim Jong Nam had been sickened. NEWLINE_CHAR NEWLINE_CHAR If VX was used, it could have contaminated not only the airport but anyplace else Kim had been, including medical facilities and the ambulance he was transported in. The nerve agent, which has the consistency of motor oil, can take days or even weeks to evaporate. NEWLINE_CHAR NEWLINE_CHAR The death of Kim Jong Nam, whose daylight assassination in a crowded airport terminal seems straight out of a spy novel, has unleashed a diplomatic crisis that escalates by the day. With each new twist in the case, international speculation has grown that Pyongyang dispatched a hit squad to Malaysia to kill the exiled older sibling of North Korean leader Kim Jong Un. NEWLINE_CHAR NEWLINE_CHAR North Korea has denounced Malaysia's investigation as full of "holes and contradictions" and accused the authorities here of being in cahoots with Pyongyang's enemies. NEWLINE_CHAR NEWLINE_CHAR According to Malaysian investigators, the two female suspects coated their hands with chemicals and wiped them on Kim's face on Feb. 13 as he waited for a flight home to Macau, where he lived with his family. NEWLINE_CHAR NEWLINE_CHAR He sought help from airport staff but he fell into convulsions and died on the way to the hospital within two hours of the attack, police said. NEWLINE_CHAR NEWLINE_CHAR The case has perplexed toxicologists, who question how the two women could have walked away unscathed after handling a powerful poison, even if — as Malaysian police say — the women were instructed to wash their hands right after the attack. NEWLINE_CHAR NEWLINE_CHAR Dr. Bruce Goldberger, a leading toxicologist who heads the forensic medicine division at the University of Florida, said even a tiny amount of VX nerve agent — equal to a few grains of salt — is capable of killing. It can be administered through the skin, and there is an antidote that can be administered by injection. U.S. medics and military personnel carried kits with them on the battlefield during the Iraq war in case they were exposed to the chemical weapon. NEWLINE_CHAR NEWLINE_CHAR "It's a very toxic nerve agent. Very, very toxic," he said. "I'm intrigued that these two alleged assassins suffered no ill effect from exposure to VX. It is possible that both of these women were given the antidote." NEWLINE_CHAR NEWLINE_CHAR He said symptoms from VX would generally occur within seconds or minutes and could last for hours starting with confusion, possible drowsiness, headache, nausea, vomiting, runny nose and watery eyes. Prior to death, there would likely be convulsions, seizures, loss of consciousness and paralysis. NEWLINE_CHAR NEWLINE_CHAR VX is banned under the Chemical Weapons Convention, which North Korea never signed. The country is believed by outside experts to have the capacity to produce up to 4,500 metric tons of chemical weapons during a typical year, which it could increase to 12,000 tons per year during a period of crisis. Its current inventory has been estimated at 2,500 to 5,000 tons. NEWLINE_CHAR NEWLINE_CHAR It is suspected of being particularly focused on mustard, phosgene, sarin and V-type chemical agents — substances including VX that are designed to poison through contact and remain lethal for long periods of time. The North's development of such agents has been of special concern because of fears it might try to put them in artillery shells for an attack on South Korea's capital, potentially threatening the lives of millions. NEWLINE_CHAR NEWLINE_CHAR Joseph Bermudez, a well-known North Korea analyst, wrote an article for the respected 38 North website in 2013 that said the North is capable of not only employing "significant quantities and varieties of chemical weapons" across the Korean Peninsula but also using those weapons worldwide "using unconventional methods of delivery." NEWLINE_CHAR NEWLINE_CHAR He also said there is a "growing body of evidence" indicating the North has shared chemical weapons capabilities with Syria, Iran and others. NEWLINE_CHAR NEWLINE_CHAR Malaysia has three people in custody in connection with Kim Jong Nam's death, including the two suspected attackers. Authorities are also seeking several other people, including the second secretary of North Korea's embassy in Kuala Lumpur and an employee of North Korea's state-owned airline, Air Koryo. NEWLINE_CHAR NEWLINE_CHAR The case has marked a serious turnaround in relations between Malaysia and North Korea. While Malaysia isn't one of Pyongyang's key diplomatic partners, it is one of the few places in the world where North Koreans can travel without a visa. As a result, for years, it's been a quiet destination for Northerners looking for jobs, schools and business deals. NEWLINE_CHAR NEWLINE_CHAR ___ NEWLINE_CHAR NEWLINE_CHAR AP writers Margie Mason in Jakarta, Indonesia, and Eric Talmadge in Tokyo contributed to this report.

Now, write a one-page summary of all the news.

Summary:


object obj = this.ViewState["SubmitText"];

Prompt:
Please complete the code given below.
/********
 * This file is part of Ext.NET.
 *
 * Ext.NET is free software: you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Ext.NET is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with Ext.NET.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * @version   : 1.2.0 - Ext.NET Pro License
 * @author    : Ext.NET, Inc. http://www.ext.net/
 * @date      : 2011-09-12
 * @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
 * @license   : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0.
 *              See license.txt and http://www.ext.net/license/.
 *              See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt
 ********/
using System;
using System.ComponentModel;
using System.IO;
using System.Web.UI;
using Newtonsoft.Json;
using Ext.Net.Utilities;
namespace Ext.Net
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Meta]
    [Description("")]
    public abstract partial class MultiSelectBase<T> : Field, IStore where T : StateManagedItem
    {
        /// <summary>
        /// The data store to use.
        /// </summary>
        [Meta]
        [ConfigOption("store", JsonMode.ToClientID)]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [IDReferenceProperty(typeof(Store))]
        [Description("The data store to use.")]
        public virtual string StoreID
        {
            get
            {
                return (string)this.ViewState["StoreID"] ?? "";
            }
            set
            {
                this.ViewState["StoreID"] = value;
            }
        }
        private StoreCollection store;
        /// <summary>
        ///  The data store to use.
        /// </summary>
        [Meta]
        [ConfigOption("store>Primary")]
        [Category("7. MultiSelect")]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [Description("The data store to use.")]
        public virtual StoreCollection Store
        {
            get
            {
                if (this.store == null)
                {
                    this.store = new StoreCollection();
                    this.store.AfterItemAdd += this.AfterStoreAdd;
                    this.store.AfterItemRemove += this.AfterStoreRemove;
                }
                return this.store;
            }
        }
		/// <summary>
		///
		/// </summary>
		[Description("")]
        protected virtual void AfterStoreAdd(Store item)
        {
            this.Controls.AddAt(0, item);
            this.LazyItems.Insert(0, item);
        }
		/// <summary>
		///
		/// </summary>
		[Description("")]
        protected virtual void AfterStoreRemove(Store item)
        {
            this.Controls.Remove(item);
            this.LazyItems.Remove(item);
        }
        private ListItemCollection<T> items;
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [ViewStateMember]
        [Description("")]
        public ListItemCollection<T> Items
        {
            get
            {
                if (this.items == null)
                {
                    this.items = new ListItemCollection<T>();
                }
                return this.items;
            }
        }
		/// <summary>
		///
		/// </summary>
        [ConfigOption("store", JsonMode.Raw)]
        [DefaultValue("")]
		[Description("")]
        protected string ItemsProxy
        {
            get
            {
                if (this.StoreID.IsNotEmpty() || this.Store.Primary != null)
                {
                    return "";
                }
                return this.ItemsToStore;
            }
        }
        private string ItemsToStore
        {
            get
            {
                StringWriter sw = new StringWriter();
                JsonTextWriter jw = new JsonTextWriter(sw);
                ListItemCollectionJsonConverter converter = new ListItemCollectionJsonConverter();
                converter.WriteJson(jw, this.Items, null);
                return sw.GetStringBuilder().ToString();
            }
        }
        private SelectedListItemCollection selectedItems;
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [ViewStateMember]
        [Description("")]
        public SelectedListItemCollection SelectedItems
        {
            get
            {
                if (this.selectedItems == null)
                {
                    this.selectedItems = new SelectedListItemCollection();
                }
                return this.selectedItems;
            }
        }
        /// <summary>
        /// The underlying data field name to bind to this MultiSelect.
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("The underlying data field name to bind to this MultiSelect.")]
        public virtual string DisplayField
        {
            get
            {
                return (string)this.ViewState["DisplayField"] ?? "text";
            }
            set
            {
                this.ViewState["DisplayField"] = value;
            }
        }
        /// <summary>
        /// The underlying data value name to bind to this MultiSelect.
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("The underlying data value name to bind to this MultiSelect.")]
        public virtual string ValueField
        {
            get
            {
                return (string)this.ViewState["ValueField"] ?? "value";
            }
            set
            {
                this.ViewState["ValueField"] = value;
            }
        }
        /// <summary>
        /// False to validate that the value length > 0 (defaults to true).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(true)]
        [Description("False to validate that the value length > 0 (defaults to true).")]
        public virtual bool AllowBlank
        {
            get
            {
                object obj = this.ViewState["AllowBlank"];
                return (obj == null) ? true : (bool)obj;
            }
            set
            {
                this.ViewState["AllowBlank"] = value;
            }
        }
        /// <summary>
        /// Maximum input field length allowed (defaults to Number.MAX_VALUE).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(-1)]
        [Description("Maximum input field length allowed (defaults to Number.MAX_VALUE).")]
        public virtual int MaxLength
        {
            get
            {
                object obj = this.ViewState["MaxLength"];
                return (obj == null) ? -1 : (int)obj;
            }
            set
            {
                this.ViewState["MaxLength"] = value;
            }
        }
        /// <summary>
        /// Minimum input field length required (defaults to 0).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(0)]
        [Description("Minimum input field length required (defaults to 0).")]
        public virtual int MinLength
        {
            get
            {
                object obj = this.ViewState["MinLength"];
                return (obj == null) ? 0 : (int)obj;
            }
            set
            {
                this.ViewState["MinLength"] = value;
            }
        }
        /// <summary>
        /// Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}').
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Localizable(true)]
        [Description("Error text to display if the maximum length validation fails (defaults to 'The maximum length for this field is {maxLength}').")]
        public virtual string MaxLengthText
        {
            get
            {
                return (string)this.ViewState["MaxLengthText"] ?? "";
            }
            set
            {
                this.ViewState["MaxLengthText"] = value;
            }
        }
        /// <summary>
        /// Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}').
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Localizable(true)]
        [Description("Error text to display if the minimum length validation fails (defaults to 'The minimum length for this field is {minLength}').")]
        public virtual string MinLengthText
        {
            get
            {
                return (string)this.ViewState["MinLengthText"] ?? "";
            }
            set
            {
                this.ViewState["MinLengthText"] = value;
            }
        }
        /// <summary>
        /// Error text to display if the allow blank validation fails (defaults to 'This field is required').
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Localizable(true)]
        [Description("Error text to display if the allow blank validation fails (defaults to 'This field is required').")]
        public virtual string BlankText
        {
            get
            {
                return (string)this.ViewState["BlankText"] ?? "";
            }
            set
            {
                this.ViewState["BlankText"] = value;
            }
        }
        /// <summary>
        /// Causes drag operations to copy nodes rather than move (defaults to false).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(false)]
        [Description("Causes drag operations to copy nodes rather than move (defaults to false).")]
        public virtual bool Copy
        {
            get
            {
                object obj = this.ViewState["Copy"];
                return (obj == null) ? false : (bool)obj;
            }
            set
            {
                this.ViewState["Copy"] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [ConfigOption("allowDup")]
        [Category("6. MultiSelect")]
        [DefaultValue(false)]
        [Description("")]
        public virtual bool AllowDuplicates
        {
            get
            {
                object obj = this.ViewState["AllowDuplicates"];
                return (obj == null) ? false : (bool)obj;
            }
            set
            {
                this.ViewState["AllowDuplicates"] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(false)]
        [Description("")]
        public virtual bool AllowTrash
        {
            get
            {
                object obj = this.ViewState["AllowTrash"];
                return (obj == null) ? false : (bool)obj;
            }
            set
            {
                this.ViewState["AllowTrash"] = value;
            }
        }
        /// <summary>
        /// The title text to display in the panel header (defaults to '')
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("The title text to display in the panel header (defaults to '')")]
        public virtual string Legend
        {
            get
            {
                return (string)this.ViewState["Legend"] ?? "";
            }
            set
            {
                this.ViewState["Legend"] = value;
            }
        }
        /// <summary>
        /// The string used to delimit between items when set or returned as a string of values
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(",")]
        [Description("The string used to delimit between items when set or returned as a string of values")]
        public virtual string Delimiter
        {
            get
            {
                return (string)this.ViewState["Delimiter"] ?? ",";
            }
            set
            {
                this.ViewState["Delimiter"] = value;
            }
        }
        /// <summary>
        /// The ddgroup name(s) for the View's DragZone (defaults to undefined).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("The ddgroup name(s) for the View's DragZone (defaults to undefined).")]
        public virtual string DragGroup
        {
            get
            {
                return (string)this.ViewState["DragGroup"] ?? "";
            }
            set
            {
                this.ViewState["DragGroup"] = value;
            }
        }
        /// <summary>
        /// The ddgroup name(s) for the View's DropZone (defaults to undefined).
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("The ddgroup name(s) for the View's DropZone (defaults to undefined).")]
        public virtual string DropGroup
        {
            get
            {
                return (string)this.ViewState["DropGroup"] ?? "";
            }
            set
            {
                this.ViewState["DropGroup"] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(false)]
        [Description("")]
        public virtual bool AppendOnly
        {
            get
            {
                object obj = this.ViewState["AppendOnly"];
                return (obj == null) ? false : (bool)obj;
            }
            set
            {
                this.ViewState["AppendOnly"] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue("")]
        [Description("")]
        public virtual string SortField
        {
            get
            {
                return (string)this.ViewState["SortField"] ?? "";
            }
            set
            {
                this.ViewState["SortField"] = value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        [Meta]
        [ConfigOption(JsonMode.ToLower)]
        [DefaultValue(SortDirection.ASC)]
        [NotifyParentProperty(true)]
        [Description("")]
        public SortDirection Direction
        {
            get
            {
                object obj = this.ViewState["Direction"];
                return (obj == null) ? SortDirection.ASC : (SortDirection)obj;
            }
            set
            {
                this.ViewState["Direction"] = value;
            }
        }
        /// <summary>
        /// True to submit text of selected items
        /// </summary>
        [Meta]
        [ConfigOption]
        [Category("6. MultiSelect")]
        [DefaultValue(true)]
        [Description("True to submit text of selected items")]
        public virtual bool SubmitText
        {
            get
            {
Next line of code:


CloseHandle(handle)  # will raise exception if the handle is invalid

Prompt:
Please complete the code given below.
pywincffi/dev/testutil.py
class TestCase(_TestCase):  # pylint: disable=too-many-public-methods
    """
    A base class for all test cases.  By default the
    core test case just provides some extra functionality.
    """
    # A list of hosts and port to check for internet access on.  If we fail
    # to reach any of the hosts in `INTERNET_HOSTS` on `INTERNET_PORT` then
    # `HAS_INTERNET` will be set to False.
    INTERNET_PORT = 80
    INTERNET_HOSTS = ("github.com", "readthedocs.org", "example.com")
    REQUIRES_INTERNET = False
    HAS_INTERNET = None

    # Class level attributes used to access some specific Windows API
    # functions when testing.  This is kept separate from what `dist.load()`
    # produces so problems in the build don't break parts of the base TestCase.
    ffi = None
    kernel32 = None
    ws2_32 = None

    @classmethod
    def setUpClass(cls):
        # Reset everything back to the default values first.
        cls.ffi = None
        cls.kernel32 = None
        cls.ws2_32 = None
        cls.HAS_INTERNET = None

        # First run and this test case requires internet access.  Determine
        # if we have access to the internet then cache the value.
        if cls.REQUIRES_INTERNET and SharedState.HAS_INTERNET is None:
            original_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(1)

            try:
                for hostname in cls.INTERNET_HOSTS:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    try:
                        sock.connect((hostname, cls.INTERNET_PORT))
                        SharedState.HAS_INTERNET = True
                        break

                    # pylint: disable=broad-except
                    except Exception:  # pragma: no cover
                        pass

                    finally:
                        sock.close()
                else:  # pragma: no cover
                    SharedState.HAS_INTERNET = False
            finally:
                socket.setdefaulttimeout(original_timeout)

        if os.name == "nt" and SharedState.ffi is None:
            try:
                ffi = FFI()
                ffi.set_unicode(True)
                ffi.cdef(dedent("""
                // kernel32 functions
                DWORD GetLastError(void);
                void SetLastError(DWORD);

                // ws2_32 functions
                void WSASetLastError(int);
                int WSAGetLastError(void);
                """))
                SharedState.ffi = ffi
                SharedState.kernel32 = ffi.dlopen("kernel32")
                SharedState.ws2_32 = ffi.dlopen("ws2_32")

            # pylint: disable=broad-except
            except Exception as error:  # pragma: no cover
                if os.name == "nt":
                    SharedState.ffi = error

        cls.HAS_INTERNET = SharedState.HAS_INTERNET
        cls.ffi = SharedState.ffi
        cls.kernel32 = SharedState.kernel32
        cls.ws2_32 = SharedState.ws2_32

    def setUp(self):  # pragma: no cover
        if self.REQUIRES_INTERNET and not self.HAS_INTERNET:
            if os.environ.get("CI"):
                self.fail(
                    "%s requires internet but we do not seem to be "
                    "connected." % self.__class__.__name__)

            self.skipTest("Internet unavailable")

        if os.name != "nt":
            return

        if isinstance(self.ffi, Exception):
            self.fail("FFI module setup failed: %s" % self.ffi)

        self.assertIsNotNone(
            self.kernel32, "setUp() failed: missing kernel32")
        self.assertIsNotNone(
            self.ws2_32, "setUp() failed: missing ws2_32")

        self.addCleanup(self.unhandled_error_check)

        # Always reset the last error to 0 between tests.  This ensures
        # that if an unhandled API error occurs it won't impact the
        # currently running test.  The cleanup step above will ensure that
        # tests that do not exit cleanly will cause a failure.
        self.kernel32.SetLastError(0)
        self.ws2_32.WSASetLastError(0)

    def GetLastError(self):  # pylint: disable=invalid-name
        """
        Returns a tuple containing output from the Windows GetLastError
        function and the associated error message.  The error message will
        be None if GetLastError() returns 0.
        """
        errno = self.kernel32.GetLastError()
        return errno, self.ffi.getwinerror(errno) if errno != 0 else None

    def WSAGetLastError(self):  # pylint: disable=invalid-name
        """
        Returns a tuple containing output from the Windows WSAGetLastError
        function and the associated error message.  The error message will
        be None if WSAGetLastError() returns 0.
        """
        errno = self.ws2_32.WSAGetLastError()
        return errno, self.ffi.getwinerror(errno) if errno != 0 else None

    def WSASetLastError(self, errno):  # pylint: disable=invalid-name
        """Wrapper for WSASetLastError()"""
        self.ws2_32.WSASetLastError(errno)

    def SetLastError(self, errno):  # pylint: disable=invalid-name
        """Wrapper for SetLastError()"""
        self.kernel32.SetLastError(errno)

    def unhandled_error_check(self):
        """
        A cleanup step which ensures that there are not any uncaught API
        errors left over.  Unhandled errors could be a sign of an unhandled
        testing artifact, improper API usage or other problem.  In any case,
        unhandled errors are often a source of test flake.
        """
        # Check for kernel32 errors.
        k32_errno, k32_message = self.GetLastError()
        self.assertEqual(
            k32_errno, 0,
            msg="Unhandled kernel32 error. Errno: %r. Message: %r" % (
                k32_errno, k32_message))

        # Check for ws2_32 errors.
        ws2_errno, ws2_message = self.WSAGetLastError()
        self.assertEqual(
            ws2_errno, 0,
            msg="Unhandled ws2_32 error. Errno: %r. Message: %r" % (
                ws2_errno, ws2_message))

    def _terminate_process(self, process):  # pylint: disable=no-self-use
        """
        Calls terminnate() on ``process`` and ignores any errors produced.
        """
        try:
            process.terminate()

        # pylint: disable=broad-except
        except Exception:  # pragma: no cover
            pass

    def create_python_process(self, command):
        """Creates a Python process that run ``command``"""
        process = subprocess.Popen(
            [sys.executable, "-c", command],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.addCleanup(self._terminate_process, process)
        return process

    def random_string(self, length):
        """
        Returns a random string as long as ``length``.  The first character
        will always be a letter.  All other characters will be A-F,
        A-F or 0-9.
        """
        if length < 1:  # pragma: no cover
            self.fail("Length must be at least 1.")

        # First character should always be a letter so the string
        # can be used in object names.
        output = choice(ascii_lowercase)
        length -= 1

        while length:
            length -= 1
            output += choice(ascii_lowercase + ascii_uppercase + "0123456789")

        return output

    def assert_last_error(self, errno):
        """
        This function will assert that the last unhandled error
        was ``errno``.  After the check the last error will be reset to
        zero.

        :param int errno:
            The expected value from GetLastError.
        """
        last_error, _ = self.GetLastError()
        self.assertEqual(last_error, errno)
        self.SetLastError(0)

    def maybe_assert_last_error(self, errno):
        """
        This function is similar to :meth:`assert_last_error` except
        it won't fail if the current error number is already 0.
        """
        last_error, _ = self.GetLastError()
        self.assertIn(last_error, (0, errno))
        self.SetLastError(0)
pywincffi/kernel32/events.py
def SetEvent(hEvent):
    """
    Sets the specified event object to the signaled state.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms686211

    :param pywincffi.wintypes.HANDLE hEvent:
        A handle to the event object. The handle must have the
        ``EVENT_MODIFY_STATE`` access right.
    """
    input_check("hEvent", hEvent, HANDLE)

    _, library = dist.load()
    code = library.SetEvent(wintype_to_cdata(hEvent))
    error_check("SetEvent", code=code, expected=NON_ZERO)
pywincffi/kernel32/events.py
def CreateEvent(
        lpEventAttributes=None, bManualReset=True, bInitialState=False,
        lpName=None):
def OpenEvent(dwDesiredAccess, bInheritHandle, lpName):
def ResetEvent(hEvent):
def SetEvent(hEvent):
pywincffi/kernel32/events.py
def OpenEvent(dwDesiredAccess, bInheritHandle, lpName):
    """
    Opens an existing named event.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms684305

    :param int dwDesiredAccess:
        The access desired for the event object.

    :param bool bInheritHandle:
    :param str lpName:
        Type is ``unicode`` on Python 2, ``str`` on Python 3.

    :return:
        Returns a :class:`pywincffi.wintypes.HANDLE` to the event.
    """
    input_check("dwDesiredAccess", dwDesiredAccess, integer_types)
    input_check("bInheritHandle", bInheritHandle, bool)
    input_check("lpName", lpName, text_type)

    ffi, library = dist.load()

    handle = library.OpenEvent(
        ffi.cast("DWORD", dwDesiredAccess),
        ffi.cast("BOOL", bInheritHandle),
        lpName
    )
    error_check("OpenEvent")
    return HANDLE(handle)
pywincffi/kernel32/events.py
def ResetEvent(hEvent):
    """
    Sets the specified event object to the nonsignaled state.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms684305

    :param pywincffi.wintypes.HANDLE hEvent:
        A handle to the event object to be reset. The handle must
        have the ``EVENT_MODIFY_STATE`` access right.
    """
    input_check("hEvent", hEvent, HANDLE)

    _, library = dist.load()
    code = library.ResetEvent(wintype_to_cdata(hEvent))
    error_check("ResetEvent", code=code, expected=NON_ZERO)
pywincffi/kernel32/synchronization.py
def WaitForSingleObject(hHandle, dwMilliseconds):
    """
    Waits for the specified object to be in a signaled state
    or for ``dwMiliseconds`` to elapse.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms687032

    :param pywincffi.wintypes.HANDLE hHandle:
        The handle to wait on.

    :param int dwMilliseconds:
        The time-out interval.
    """
    input_check("hHandle", hHandle, HANDLE)
    input_check("dwMilliseconds", dwMilliseconds, integer_types)

    ffi, library = dist.load()
    result = library.WaitForSingleObject(
        wintype_to_cdata(hHandle), ffi.cast("DWORD", dwMilliseconds)
    )

    if result == library.WAIT_FAILED:
        raise WindowsAPIError(
            "WaitForSingleObject", "Wait Failed", ffi.getwinerror()[-1],
            return_code=result, expected_return_code="not %s" % result)

    error_check("WaitForSingleObject")

    return result
pywincffi/exceptions.py
class InputError(PyWinCFFIError):
    """
    A subclass of :class:`PyWinCFFIError` that's raised when invalid input
    is provided to a function.  Because we're passing inputs to C we have
    to be sure that the input(s) being provided are what we're expecting so
    we fail early and provide better error messages.

    :param str name:
        The name of the parameter being checked.

    :param value:
        The value of the parameter being checked.

    :keyword allowed_types:
        The expected type(s). If provided then the exception's message will
        be tailored to provide information about ``value``'s type and the
        possible input types.

    :keyword allowed_values:
        The expected value(s).  If provided then the exception's message will
        be tailored to provide information about what value(s) were allowed
        for ``value``.

    :keyword ffi:
        If ``value`` is a C object, ``ffi`` is provided and ``allowed_types``
        is provided as well then the provided ``ffi`` instance will be used
        to provide additional context.

    :keyword str message:
        A custom error message.  This will override the default error messages
        which :class:`InputError` would normally generate.  This can be
        helpful if there is a problem with a given input parameter to a
        function but it's unrelated to the type of input.
    """
    def __init__(  # pylint: disable=too-many-arguments
            self, name, value,
            allowed_types=None, allowed_values=None, ffi=None, message=None):
        if allowed_types is not None and allowed_values is not None:
            raise ValueError(
                "Please provide either `allowed_types` or `allowed_values`")

        if (allowed_types is None and allowed_values is None and
                message is None):
            raise ValueError(
                "Please provide `allowed_types`, `allowed_values` or "
                "`message`")

        self.name = name
        self.value = value
        self.allowed_types = allowed_types
        self.allowed_values = allowed_values
        self.message = message

        if self.message is None and self.allowed_types is not None:
            if ffi is None:
                typeof = repr(type(value))
            else:
                try:
                    ffi_exceptions = (TypeError, CDefError, ffi.error)
                except AttributeError:  # pragma: no cover
                    ffi_exceptions = (TypeError, CDefError)

                try:
                    typeof = ffi.typeof(value)
                except ffi_exceptions:
                    typeof = repr(type(value))
                else:
                    typeof = "{classname}(kind={kind}, cname={cname})".format(
                        classname=value.__class__.__name__,
                        kind=repr(typeof.kind), cname=repr(typeof.cname))

            self.message = \
                "Expected type(s) {expected} for {name}. Type of {name} " \
                "is {typeof}.".format(
                    expected=repr(allowed_types), name=repr(name),
                    typeof=typeof)

        elif self.message is None and self.allowed_values is not None:
            self.message = \
                "Expected the value of {name} to be in {values}. Value of " \
                "{name} is {value}.".format(
                    name=repr(name), values=allowed_values, value=repr(value))

        super(InputError, self).__init__(self.message)
pywincffi/core/dist.py
MODULE_NAME = "_pywincffi"
HEADER_FILES = (
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "typedefs.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "constants.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "structs.h")),
    resource_filename(
        "pywincffi", join("core", "cdefs", "headers", "functions.h")))
SOURCE_FILES = (
    resource_filename(
        "pywincffi", join("core", "cdefs", "sources", "main.c")), )
LIBRARIES = ("kernel32", "user32", "Ws2_32")
REGEX_SAL_ANNOTATION = re.compile(
    r"\b(_In_|_Inout_|_Out_|_Outptr_|_Reserved_)(opt_)?\b")
    _RUNTIME_CONSTANTS = dict(
        # Defined here because cffi can't handle negative values
        # in constants yet.
        INVALID_HANDLE_VALUE=-1,

        # The maximum length of the lpCommandLine input to a CreateProcess
        # call:
        #  https://msdn.microsoft.com/en-us/library/ms682425
        # Technically, this is not a Windows constant.  It's something that
        # pywincffi defines for ease of use and to limit the possibility of
        # typos.
        MAX_COMMAND_LINE=32768
    )
class LibraryWrapper(object):  # pylint: disable=too-few-public-methods
class Loader(object):
    def __init__(self, library):
    def __dir__(self):
    def __getattribute__(self, item):
    def __getattr__(self, item):
    def __repr__(self):  # pragma: no cover
    def set(cls, ffi, library):
    def get(cls):
def _import_path(path, module_name=MODULE_NAME):
def _read(*paths):
def _ffi(
        module_name=MODULE_NAME, headers=HEADER_FILES, sources=SOURCE_FILES,
        libraries=LIBRARIES):
def _compile(ffi, tmpdir=None, module_name=MODULE_NAME):
def load():
pywincffi/kernel32/events.py
def CreateEvent(
        lpEventAttributes=None, bManualReset=True, bInitialState=False,
        lpName=None):
    """
    Creates or opens an named or unnamed event object.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms682396

    :keyword :class:`pywincffi.wintypes.SECURITY_ATTRIBUTES` lpEventAttributes:
        If not provided then, by default, the handle cannot be inherited
        by a subprocess.

    :keyword bool bManualReset:
        If True then this function will create a manual reset
        event which must be manually reset with :func:`ResetEvent`.  Refer
        to the msdn documentation for full information.

        **Default:** ``True``

    :keyword bool bInitialState:
        If True the initial state will be 'signaled'.

        **Default:** ``False``

    :keyword str lpName:
        Type is ``unicode`` on Python 2, ``str`` on Python 3.
        The optional case-sensitive name of the event.  If not provided then
        the event will be created without an explicit name.

    :returns:
        Returns a :class:`pywincffi.wintypes.HANDLE` to the event. If an event
        by the given name already exists then it will be returned instead of
        creating a new event.
    """
    input_check("bManualReset", bManualReset, bool)
    input_check("bInitialState", bInitialState, bool)

    ffi, library = dist.load()

    if lpName is None:
        lpName = ffi.NULL
    else:
        input_check("lpName", lpName, text_type)

    input_check(
        "lpEventAttributes", lpEventAttributes,
        allowed_types=(SECURITY_ATTRIBUTES, NoneType)
    )

    handle = library.CreateEvent(
        wintype_to_cdata(lpEventAttributes),
        ffi.cast("BOOL", bManualReset),
        ffi.cast("BOOL", bInitialState),
        lpName
    )

    try:
        error_check("CreateEvent")
    except WindowsAPIError as error:
        if error.errno != library.ERROR_ALREADY_EXISTS:
            raise

    return HANDLE(handle)
pywincffi/kernel32/handle.py
def CloseHandle(hObject):
    """
    Closes an open object handle.

    .. seealso::

        https://msdn.microsoft.com/en-us/library/ms724211

    :type hObject: pywincffi.wintypes.HANDLE or pywincffi.wintypes.SOCKET
    :param hObject:
        The handle object to close.
    """
    input_check("hObject", hObject, (HANDLE, SOCKET))
    _, library = dist.load()

    code = library.CloseHandle(wintype_to_cdata(hObject))
    error_check("CloseHandle", code=code, expected=NON_ZERO)
pywincffi/exceptions.py
class WindowsAPIError(PyWinCFFIError):
    """
    A subclass of :class:`PyWinCFFIError` that's raised when there was a
    problem calling a Windows API function.

    :param str function:
        The Windows API function being called when the error was raised.

    :param str error:
        A string representation of the error message.

    :param int errno:
        An integer representing the error.  This usually represents
        a constant which Windows has produced in response to a problem.

    :keyword int return_code:
        If the return value of a function has been checked the resulting
        code will be set as this value.

    :keyword int expected_return_code:
        The value we expected to receive for ``code``.
    """
    # pylint: disable=too-many-arguments
    def __init__(self, function, error, errno,
                 return_code=None, expected_return_code=None):
        self.function = function
        self.error = error
        self.errno = errno
        self.return_code = return_code
        self.expected_return_code = expected_return_code

        if return_code is None and expected_return_code is None:
            self.message = \
                "Error when calling {0}. Message from Windows API was " \
                "{1!r} (errno: {2}).".format(self.function, self.error, errno)

        elif return_code is not None and expected_return_code is not None:
            self.message = (
                "Error when calling {0}.  Expected to receive {1!r} from {2} "
                "but got {3!r} instead. (error: {4!r})".format(
                    self.function, self.return_code, self.function,
                    self.expected_return_code, self.error
                )
            )

        # Generic implementation which we should probably handle
        # better so throw a warning.
        else:  # pragma: no cover
            warnings.warn(Warning(), "Pre-formatting not available")
            self.message = (
                "Error when calling {0}. (error: {1}, errno: {2}, "
                "return_code: {3!r}, expected_return_code: {4!r})".format(
                    self.function, self.error, self.errno, self.return_code,
                    self.expected_return_code
                )
            )

        super(WindowsAPIError, self).__init__(self.message)

    def __repr__(self):
        return (
            "{0}({1!r}, {2!r}, {3!r}, return_code={4!r}, "
            "expected_return_code={5!r})".format(
                self.__class__.__name__, self.function, self.error,
                self.errno, self.return_code, self.expected_return_code))
import sys
from mock import patch
from pywincffi.core import dist
from pywincffi.dev.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError, InputError
from pywincffi.kernel32 import events  # used by mocks
from pywincffi.kernel32 import (
    CloseHandle, CreateEvent, OpenEvent, ResetEvent, WaitForSingleObject,
    SetEvent)

# These tests cause TestPidExists and others to fail under Python 3.4 so for
# now we skip these tests.  Because we're only testing CreateEvent, and
# TestPidExists worked before TestCreateEvent exists, we'll skip these
# for now.
#  Traceback (most recent call last):
# [...]
#    File "c:\python34\lib\subprocess.py", line 754, in __init__
#      _cleanup()
#    File "c:\python34\lib\subprocess.py", line 474, in _cleanup
#      res = inst._internal_poll(_deadstate=sys.maxsize)
#    File "c:\python34\lib\subprocess.py", line 1147, in _internal_poll
#      if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
#  OSError: [WinError 6] The handle is invalid
# TODO: Need to figure out why this happens ^^^
class TestCreateEvent(TestCase):
    """
    Tests for :func:`pywincffi.kernel32.CreateEvent`
    """
    def setUp(self):
        super(TestCreateEvent, self).setUp()
        if sys.version_info[0:2] == (3, 4):
            self.skipTest("Skipped on Python 3.4, see comments.")

    def test_create_event_valid_handle(self):
        handle = CreateEvent(bManualReset=False, bInitialState=False)
Next line of code: