File size: 9,234 Bytes
079c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import math
import operator
from typing import Optional, Union, Callable, Any

from .base import Loader, ILoaderClass
from .utils import keep, check_only

NUMBER_TYPES = (int, float)
NUMBER_TYPING = Union[int, float]


def numeric(int_ok: bool = True, float_ok: bool = True, inf_ok: bool = True) -> ILoaderClass:
    """
    Overview:
        Create a numeric loader.
    Arguments:
        - int_ok (:obj:`bool`): Whether int is allowed.
        - float_ok (:obj:`bool`): Whether float is allowed.
        - inf_ok (:obj:`bool`): Whether inf is allowed.
    """

    if not int_ok and not float_ok:
        raise ValueError('Either int or float should be allowed.')

    def _load(value) -> NUMBER_TYPING:
        if isinstance(value, NUMBER_TYPES):
            if math.isnan(value):
                raise ValueError('nan is not numeric value')
            if isinstance(value, int) and not int_ok:
                raise TypeError('int is not allowed but {actual} found'.format(actual=repr(value)))
            if isinstance(value, float) and not float_ok:
                raise TypeError('float is not allowed but {actual} found'.format(actual=repr(value)))
            if math.isinf(value) and not inf_ok:
                raise ValueError('inf is not allowed but {actual} found'.format(actual=repr(value)))

            return value
        else:
            raise TypeError(
                'numeric value should be either int, float or str, but {actual} found'.format(
                    actual=repr(type(value).__name__)
                )
            )

    return Loader(_load)


def interval(
        left: Optional[NUMBER_TYPING] = None,
        right: Optional[NUMBER_TYPING] = None,
        left_ok: bool = True,
        right_ok: bool = True,
        eps=0.0
) -> ILoaderClass:
    """
    Overview:
        Create a interval loader.
    Arguments:
        - left (:obj:`Optional[NUMBER_TYPING]`): The left bound.
        - right (:obj:`Optional[NUMBER_TYPING]`): The right bound.
        - left_ok (:obj:`bool`): Whether left bound is allowed.
        - right_ok (:obj:`bool`): Whether right bound is allowed.
        - eps (:obj:`float`): The epsilon.
    """

    if left is None:
        left = -math.inf
    if right is None:
        right = +math.inf
    if left > right:
        raise ValueError(
            "Left bound should no more than right bound, but {left} > {right}.".format(
                left=repr(left), right=repr(right)
            )
        )
    eps = math.fabs(eps)

    def _value_compare_with_eps(a, b) -> int:
        if math.fabs(a - b) <= eps:
            return 0
        elif a < b:
            return -1
        else:
            return 1

    def _load(value) -> NUMBER_TYPING:
        _left_check = _value_compare_with_eps(value, left)
        if _left_check < 0:
            raise ValueError(
                'value should be no less than {left} but {value} found'.format(left=repr(left), value=repr(value))
            )
        elif not left_ok and _left_check == 0:
            raise ValueError(
                'value should not be equal to left bound {left} but {value} found'.format(
                    left=repr(left), value=repr(value)
                )
            )

        _right_check = _value_compare_with_eps(value, right)
        if _right_check > 0:
            raise ValueError(
                'value should be no more than {right} but {value} found'.format(right=repr(right), value=repr(value))
            )
        elif not right_ok and _right_check == 0:
            raise ValueError(
                'value should not be equal to right bound {right} but {value} found'.format(
                    right=repr(right), value=repr(value)
                )
            )

        return value

    return Loader(_load)


def is_negative() -> ILoaderClass:
    """
    Overview:
        Create a negative loader.
    """

    return Loader((lambda x: x < 0, lambda x: ValueError('negative required but {value} found'.format(value=repr(x)))))


def is_positive() -> ILoaderClass:
    """
    Overview:
        Create a positive loader.
    """

    return Loader((lambda x: x > 0, lambda x: ValueError('positive required but {value} found'.format(value=repr(x)))))


def non_negative() -> ILoaderClass:
    """
    Overview:
        Create a non-negative loader.
    """

    return Loader(
        (lambda x: x >= 0, lambda x: ValueError('non-negative required but {value} found'.format(value=repr(x))))
    )


def non_positive() -> ILoaderClass:
    """
    Overview:
        Create a non-positive loader.
    """

    return Loader(
        (lambda x: x <= 0, lambda x: ValueError('non-positive required but {value} found'.format(value=repr(x))))
    )


def negative() -> ILoaderClass:
    """
    Overview:
        Create a negative loader.
    """

    return Loader(lambda x: -x)


def positive() -> ILoaderClass:
    """
    Overview:
        Create a positive loader.
    """

    return Loader(lambda x: +x)


def _math_binary(func: Callable[[Any, Any], Any], attachment) -> ILoaderClass:
    """
    Overview:
        Create a math binary loader.
    Arguments:
        - func (:obj:`Callable[[Any, Any], Any]`): The function.
        - attachment (:obj:`Any`): The attachment.
    """

    return Loader(lambda x: func(x, Loader(attachment)(x)))


def plus(addend) -> ILoaderClass:
    """
    Overview:
        Create a plus loader.
    Arguments:
        - addend (:obj:`Any`): The addend.
    """

    return _math_binary(lambda x, y: x + y, addend)


def minus(subtrahend) -> ILoaderClass:
    """
    Overview:
        Create a minus loader.
    Arguments:
        - subtrahend (:obj:`Any`): The subtrahend.
    """

    return _math_binary(lambda x, y: x - y, subtrahend)


def minus_with(minuend) -> ILoaderClass:
    """
    Overview:
        Create a minus loader.
    Arguments:
        - minuend (:obj:`Any`): The minuend.
    """

    return _math_binary(lambda x, y: y - x, minuend)


def multi(multiplier) -> ILoaderClass:
    """
    Overview:
        Create a multi loader.
    Arguments:
        - multiplier (:obj:`Any`): The multiplier.
    """

    return _math_binary(lambda x, y: x * y, multiplier)


def divide(divisor) -> ILoaderClass:
    """
    Overview:
        Create a divide loader.
    Arguments:
        - divisor (:obj:`Any`): The divisor.
    """

    return _math_binary(lambda x, y: x / y, divisor)


def divide_with(dividend) -> ILoaderClass:
    """
    Overview:
        Create a divide loader.
    Arguments:
        - dividend (:obj:`Any`): The dividend.
    """

    return _math_binary(lambda x, y: y / x, dividend)


def power(index) -> ILoaderClass:
    """
    Overview:
        Create a power loader.
    Arguments:
        - index (:obj:`Any`): The index.
    """

    return _math_binary(lambda x, y: x ** y, index)


def power_with(base) -> ILoaderClass:
    """
    Overview:
        Create a power loader.
    Arguments:
        - base (:obj:`Any`): The base.
    """

    return _math_binary(lambda x, y: y ** x, base)


def msum(*items) -> ILoaderClass:
    """
    Overview:
        Create a sum loader.
    Arguments:
        - items (:obj:`tuple`): The items.
    """

    def _load(value):
        return sum([item(value) for item in items])

    return Loader(_load)


def mmulti(*items) -> ILoaderClass:
    """
    Overview:
        Create a multi loader.
    Arguments:
        - items (:obj:`tuple`): The items.
    """

    def _load(value):
        _result = 1
        for item in items:
            _result *= item(value)
        return _result

    return Loader(_load)


_COMPARE_OPERATORS = {
    '!=': operator.__ne__,
    '==': operator.__eq__,
    '<': operator.__lt__,
    '<=': operator.__le__,
    '>': operator.__gt__,
    '>=': operator.__ge__,
}


def _msinglecmp(first, op, second) -> ILoaderClass:
    """
    Overview:
        Create a single compare loader.
    Arguments:
        - first (:obj:`Any`): The first item.
        - op (:obj:`str`): The operator.
        - second (:obj:`Any`): The second item.
    """

    first = Loader(first)
    second = Loader(second)

    if op in _COMPARE_OPERATORS.keys():
        return Loader(
            (
                lambda x: _COMPARE_OPERATORS[op](first(x), second(x)), lambda x: ValueError(
                    'comparison failed for {first} {op} {second}'.format(
                        first=repr(first(x)),
                        second=repr(second(x)),
                        op=op,
                    )
                )
            )
        )
    else:
        raise KeyError('Invalid compare operator - {op}.'.format(op=repr(op)))


def mcmp(first, *items) -> ILoaderClass:
    """
    Overview:
        Create a multi compare loader.
    Arguments:
        - first (:obj:`Any`): The first item.
        - items (:obj:`tuple`): The items.
    """

    if len(items) % 2 == 1:
        raise ValueError('Count of items should be odd number but {number} found.'.format(number=len(items) + 1))

    ops, items = items[0::2], items[1::2]

    _result = keep()
    for first, op, second in zip((first, ) + items[:-1], ops, items):
        _result &= _msinglecmp(first, op, second)

    return check_only(_result)