示例#1
0
def path_keys(keys):
    """Convert keys used to access an object's path into the standard form: a
    list of keys.
    """
    # pylint: disable=redefined-outer-name
    if pyd.is_string(keys):
        # This matches "." as delimiter unless it is escaped by "//".
        re_dot_delim = re.compile(r'(?<!\\)(?:\\\\)*\.')

        # Since we can't tell whether a bare number is supposed to be dict key
        # or a list index, we support a special syntax where any string-integer
        # surrounded by brackets is treated as a list index and converted to an
        # integer.
        re_list_index = re.compile(r'\[[\d\]]')

        keys = [
            int(key[1:-1])
            if re_list_index.match(key) else unescape_path_key(key)
            for key in re_dot_delim.split(keys)
        ]
    elif pyd.is_number(keys):
        keys = [keys]
    elif keys is NoValue:
        keys = []

    return keys
示例#2
0
def power(x, n):
    """Calculate exponentiation of `x` raised to the `n` power.

    Args:
        x (number): Base number.
        n (number): Exponent.

    Returns:
        number: Result of calculation.

    Example:

        >>> power(5, 2)
        25
        >>> power(12.5, 3)
        1953.125

    .. versionadded:: 2.1.0

    .. versionchanged:: 4.0.0
        Removed alias ``pow_``.
    """
    if pyd.is_number(x):
        result = pow(x, n)
    elif pyd.is_list(x):
        result = [pow(item, n) for item in x]
    else:
        result = None

    return result
示例#3
0
def power(x, n):
    """Calculate exponentiation of `x` raised to the `n` power.

    Args:
        x (number): Base number.
        n (number): Exponent.

    Returns:
        number: Result of calculation.

    Example:

        >>> power(5, 2)
        25
        >>> power(12.5, 3)
        1953.125

    See Also:
        - :func:`power` (main definition)
        - :func:`pow_` (alias)

    .. versionadded:: 2.1.0
    """
    if pyd.is_number(x):
        result = pow(x, n)
    elif pyd.is_list(x):
        result = pyd.map_(x, lambda item: pow(item, n))
    else:
        result = None

    return result
示例#4
0
def round_(x, precision=0):
    """Round number to precision.

    Args:
        x (number): Number to round.
        precision (int, optional): Rounding precision. Defaults to ``0``.

    Returns:
        int: Rounded number.

    Example:

        >>> round_(3.275) == 3.0
        True
        >>> round_(3.275, 1) == 3.3
        True

    See Also:
        - :func:`round_` (main definition)
        - :func:`curve` (alias)

    .. versionadded:: 2.1.0
    """
    rounder = pyd.partial_right(round, precision)

    if pyd.is_number(x):
        result = rounder(x)
    elif pyd.is_list(x):
        # pylint: disable=unnecessary-lambda
        result = pyd.map_(x, lambda item: rounder(item))
    else:
        result = None

    return result
示例#5
0
文件: numerical.py 项目: urbn/pydash
def power(x, n):
    """Calculate exponentiation of `x` raised to the `n` power.

    Args:
        x (number): Base number.
        n (number): Exponent.

    Returns:
        number: Result of calculation.

    Example:

        >>> power(5, 2)
        25
        >>> power(12.5, 3)
        1953.125

    See Also:
        - :func:`power` (main definition)
        - :func:`pow_` (alias)

    .. versionadded:: 2.1.0
    """
    if pyd.is_number(x):
        result = pow(x, n)
    elif pyd.is_list(x):
        result = pyd.map_(x, lambda item: pow(item, n))
    else:
        result = None

    return result
示例#6
0
def call_math_operator(value1, value2, op, default):
    """Return the result of the math operation on the given values."""
    if not value1:
        value1 = default

    if not value2:
        value2 = default

    if not pyd.is_number(value1):
        try:
            value1 = float(value1)
        except Exception:
            pass

    if not pyd.is_number(value2):
        try:
            value2 = float(value2)
        except Exception:
            pass

    return op(value1, value2)
示例#7
0
    def __init__(self, func, wait, max_wait=False):
        self.func = func
        self.wait = wait
        self.max_wait = max_wait

        self.last_result = None

        # Initialize last_* times to be prior to the wait periods so that func
        # is primed to be executed on first call.
        self.last_call = pyd.now() - self.wait
        self.last_execution = pyd.now() - max_wait if pyd.is_number(
            max_wait) else None
示例#8
0
    def __init__(self, func, wait, max_wait=False):
        self.func = func
        self.wait = wait
        self.max_wait = max_wait

        self.last_result = None

        # Initialize last_* times to be prior to the wait periods so that func
        # is primed to be executed on first call.
        self.last_call = pyd.now() - self.wait
        self.last_execution = (pyd.now() - max_wait if pyd.is_number(max_wait)
                               else None)
示例#9
0
def add(collection, callback=None):
    """Sum each element in `collection`. If callback is passed, each element of
    `collection` is passed through a callback before the summation is computed.
    If `collection` and `callback` are numbers, they are added together.

    Args:
        collection (list|dict|number): Collection to process or first number to
            add.
        callback (mixed|number, optional): Callback applied per iteration or
            second number to add.

    Returns:
        number: Result of summation.

    Example:

        >>> add([1, 2, 3, 4])
        10
        >>> add([1, 2, 3, 4], lambda x: x ** 2)
        30
        >>> add(1, 5)
        6

    See Also:
        - :func:`add` (main definition)
        - :func:`sum_` (alias)

    .. versionadded:: 2.1.0

    .. versionchanged:: 3.3.0
        Support adding two numbers when passed as positional arguments.
    """
    if pyd.is_number(collection) and pyd.is_number(callback):
        return collection + callback
    else:
        return sum(result[0] for result in itercallback(collection, callback))
示例#10
0
文件: numerical.py 项目: urbn/pydash
def add(collection, callback=None):
    """Sum each element in `collection`. If callback is passed, each element of
    `collection` is passed through a callback before the summation is computed.
    If `collection` and `callback` are numbers, they are added together.

    Args:
        collection (list|dict|number): Collection to process or first number to
            add.
        callback (mixed|number, optional): Callback applied per iteration or
            second number to add.

    Returns:
        number: Result of summation.

    Example:

        >>> add([1, 2, 3, 4])
        10
        >>> add([1, 2, 3, 4], lambda x: x ** 2)
        30
        >>> add(1, 5)
        6

    See Also:
        - :func:`add` (main definition)
        - :func:`sum_` (alias)

    .. versionadded:: 2.1.0

    .. versionchanged:: 3.3.0
        Support adding two numbers when passed as positional arguments.
    """
    if pyd.is_number(collection) and pyd.is_number(callback):
        return collection + callback
    else:
        return sum(result[0] for result in itercallback(collection, callback))
示例#11
0
def rounder(func, x, precision):
    precision = pow(10, precision)

    def rounder_func(item):
        return func(item * precision) / precision

    result = None

    if pyd.is_number(x):
        result = rounder_func(x)
    elif pyd.is_iterable(x):
        try:
            result = [rounder_func(item) for item in x]
        except TypeError:
            pass

    return result
示例#12
0
def to_path_tokens(value):
    """Parse `value` into :class:`PathToken` objects."""
    if pyd.is_string(value) and ('.' in value or '[' in value):
        # Since we can't tell whether a bare number is supposed to be dict key
        # or a list index, we support a special syntax where any string-integer
        # surrounded by brackets is treated as a list index and converted to an
        # integer.
        keys = [PathToken(int(key[1:-1]), default_factory=list)
                if RE_PATH_LIST_INDEX.match(key)
                else PathToken(unescape_path_key(key), default_factory=dict)
                for key in filter(None, RE_PATH_KEY_DELIM.split(value))]
    elif pyd.is_string(value) or pyd.is_number(value):
        keys = [PathToken(value, default_factory=dict)]
    elif value is NoValue:
        keys = []
    else:
        keys = value

    return keys
示例#13
0
def to_path_tokens(value):
    """Parse `value` into :class:`PathToken` objects."""
    if pyd.is_string(value) and ('.' in value or '[' in value):
        # Since we can't tell whether a bare number is supposed to be dict key
        # or a list index, we support a special syntax where any string-integer
        # surrounded by brackets is treated as a list index and converted to an
        # integer.
        keys = [PathToken(int(key[1:-1]), default_factory=list)
                if RE_PATH_LIST_INDEX.match(key)
                else PathToken(unescape_path_key(key), default_factory=dict)
                for key in filter(None, RE_PATH_KEY_DELIM.split(value))]
    elif pyd.is_string(value) or pyd.is_number(value):
        keys = [PathToken(value, default_factory=dict)]
    elif value is NoValue:
        keys = []
    else:
        keys = value

    return keys
示例#14
0
def path_keys(keys):
    """Convert keys used to access an object's path into the standard form: a
    list of keys.
    """
    # pylint: disable=redefined-outer-name
    if pyd.is_string(keys) and ('.' in keys or '[' in keys):
        # Since we can't tell whether a bare number is supposed to be dict key
        # or a list index, we support a special syntax where any string-integer
        # surrounded by brackets is treated as a list index and converted to an
        # integer.
        keys = [int(key[1:-1]) if RE_PATH_LIST_INDEX.match(key)
                else unescape_path_key(key)
                for key in filter(None, RE_PATH_KEY_DELIM.split(keys))]
    elif pyd.is_string(keys) or pyd.is_number(keys):
        keys = [keys]
    elif keys is NoValue:
        keys = []

    return keys
示例#15
0
文件: objects.py 项目: eRajsh/pydash
def path_keys(keys):
    """Convert keys used to access an object's path into the standard form: a
    list of keys.
    """
    # pylint: disable=redefined-outer-name
    if pyd.is_string(keys):
        # This matches "." as delimiter unless it is escaped by "//".
        re_dot_delim = re.compile(r'(?<!\\)(?:\\\\)*\.')

        # Since we can't tell whether a bare number is supposed to be dict key
        # or a list index, we support a special syntax where any string-integer
        # surrounded by brackets is treated as a list index and converted to an
        # integer.
        re_list_index = re.compile(r'\[[\d\]]')

        keys = [int(key[1:-1]) if re_list_index.match(key)
                else unescape_path_key(key)
                for key in re_dot_delim.split(keys)]
    elif pyd.is_number(keys):
        keys = [keys]
    elif keys is NoValue:
        keys = []

    return keys
示例#16
0
def test_is_number(case, expected):
    assert _.is_number(case) == expected