Python operator.add() Examples

The following are 30 code examples for showing how to use operator.add(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module operator , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 6 votes vote down vote up
def attach_grad(self, grad_req='write', stype=None):
        """Attach a gradient buffer to this NDArray, so that `backward`
        can compute gradient with respect to it.

        Parameters
        ----------
        grad_req : {'write', 'add', 'null'}
            How gradient will be accumulated.
            - 'write': gradient will be overwritten on every backward.
            - 'add': gradient will be added to existing value on every backward.
            - 'null': do not compute gradient for this NDArray.
        stype : str, optional
            The storage type of the gradient array. Defaults to the same stype of this NDArray.
        """
        from . import zeros as _zeros
        if stype is not None:
            grad = _zeros(self.shape, stype=stype)
        else:
            grad = op.zeros_like(self)  # pylint: disable=undefined-variable
        grad_req = _GRAD_REQ_MAP[grad_req]
        check_call(_LIB.MXAutogradMarkVariables(
            1, ctypes.pointer(self.handle),
            ctypes.pointer(mx_uint(grad_req)),
            ctypes.pointer(grad.handle))) 
Example 2
Project: tensortrade   Author: tensortrade-org   File: helpers.py    License: Apache License 2.0 6 votes vote down vote up
def create_internal_feed(portfolio: 'Portfolio'):

    base_symbol = portfolio.base_instrument.symbol
    sources = []

    for wallet in portfolio.wallets:
        symbol = wallet.instrument.symbol
        sources += [wallet.exchange]
        sources += [create_wallet_source(wallet, include_worth=(symbol != base_symbol))]

    worth_nodes = Condition(
        lambda node: node.name.endswith(base_symbol + ":/total") or node.name.endswith("worth")
    )(*sources)

    net_worth = Reduce(func=operator.add)(worth_nodes).rename("net_worth")

    sources += [net_worth]

    feed = DataFeed(sources).attach(portfolio)

    return feed 
Example 3
Project: recruit   Author: Frank-qlu   File: test_extint128.py    License: Apache License 2.0 6 votes vote down vote up
def test_safe_binop():
    # Test checked arithmetic routines

    ops = [
        (operator.add, 1),
        (operator.sub, 2),
        (operator.mul, 3)
    ]

    with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
        for xop, a, b in it:
            pyop, op = xop
            c = pyop(a, b)

            if not (INT64_MIN <= c <= INT64_MAX):
                assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
            else:
                d = mt.extint_safe_binop(a, b, op)
                if c != d:
                    # assert_equal is slow
                    assert_equal(d, c) 
Example 4
Project: recruit   Author: Frank-qlu   File: test_classes.py    License: Apache License 2.0 6 votes vote down vote up
def test_add(Poly):
    # This checks commutation, not numerical correctness
    c1 = list(random((4,)) + .5)
    c2 = list(random((3,)) + .5)
    p1 = Poly(c1)
    p2 = Poly(c2)
    p3 = p1 + p2
    assert_poly_almost_equal(p2 + p1, p3)
    assert_poly_almost_equal(p1 + c2, p3)
    assert_poly_almost_equal(c2 + p1, p3)
    assert_poly_almost_equal(p1 + tuple(c2), p3)
    assert_poly_almost_equal(tuple(c2) + p1, p3)
    assert_poly_almost_equal(p1 + np.array(c2), p3)
    assert_poly_almost_equal(np.array(c2) + p1, p3)
    assert_raises(TypeError, op.add, p1, Poly([0], domain=Poly.domain + 1))
    assert_raises(TypeError, op.add, p1, Poly([0], window=Poly.window + 1))
    if Poly is Polynomial:
        assert_raises(TypeError, op.add, p1, Chebyshev([0]))
    else:
        assert_raises(TypeError, op.add, p1, Polynomial([0])) 
Example 5
Project: recruit   Author: Frank-qlu   File: offsets.py    License: Apache License 2.0 6 votes vote down vote up
def apply_index(self, i):
        time = i.to_perioddelta('D')
        # to_period rolls forward to next BDay; track and
        # reduce n where it does when rolling forward
        asper = i.to_period('B')
        if not isinstance(asper._data, np.ndarray):
            # unwrap PeriodIndex --> PeriodArray
            asper = asper._data

        if self.n > 0:
            shifted = (i.to_perioddelta('B') - time).asi8 != 0

            # Integer-array addition is deprecated, so we use
            # _time_shift directly
            roll = np.where(shifted, self.n - 1, self.n)
            shifted = asper._addsub_int_array(roll, operator.add)
        else:
            # Integer addition is deprecated, so we use _time_shift directly
            roll = self.n
            shifted = asper._time_shift(roll)

        result = shifted.to_timestamp() + time
        return result 
Example 6
Project: recruit   Author: Frank-qlu   File: test_panel.py    License: Apache License 2.0 6 votes vote down vote up
def test_arith(self):
        self._test_op(self.panel, operator.add)
        self._test_op(self.panel, operator.sub)
        self._test_op(self.panel, operator.mul)
        self._test_op(self.panel, operator.truediv)
        self._test_op(self.panel, operator.floordiv)
        self._test_op(self.panel, operator.pow)

        self._test_op(self.panel, lambda x, y: y + x)
        self._test_op(self.panel, lambda x, y: y - x)
        self._test_op(self.panel, lambda x, y: y * x)
        self._test_op(self.panel, lambda x, y: y / x)
        self._test_op(self.panel, lambda x, y: y ** x)

        self._test_op(self.panel, lambda x, y: x + y)  # panel + 1
        self._test_op(self.panel, lambda x, y: x - y)  # panel - 1
        self._test_op(self.panel, lambda x, y: x * y)  # panel * 1
        self._test_op(self.panel, lambda x, y: x / y)  # panel / 1
        self._test_op(self.panel, lambda x, y: x ** y)  # panel ** 1

        pytest.raises(Exception, self.panel.__add__,
                      self.panel['ItemA']) 
Example 7
Project: recruit   Author: Frank-qlu   File: test_panel.py    License: Apache License 2.0 6 votes vote down vote up
def test_arith_flex_panel(self):
        ops = ['add', 'sub', 'mul', 'div',
               'truediv', 'pow', 'floordiv', 'mod']
        if not compat.PY3:
            aliases = {}
        else:
            aliases = {'div': 'truediv'}
        self.panel = self.panel.to_panel()

        for n in [np.random.randint(-50, -1), np.random.randint(1, 50), 0]:
            for op in ops:
                alias = aliases.get(op, op)
                f = getattr(operator, alias)
                exp = f(self.panel, n)
                result = getattr(self.panel, op)(n)
                assert_panel_equal(result, exp, check_panel_type=True)

                # rops
                r_f = lambda x, y: f(y, x)
                exp = r_f(self.panel, n)
                result = getattr(self.panel, 'r' + op)(n)
                assert_panel_equal(result, exp) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_series.py    License: Apache License 2.0 6 votes vote down vote up
def test_binary_operators(self):

        # skipping for now #####
        import pytest
        pytest.skip("skipping sparse binary operators test")

        def _check_inplace_op(iop, op):
            tmp = self.bseries.copy()

            expected = op(tmp, self.bseries)
            iop(tmp, self.bseries)
            tm.assert_sp_series_equal(tmp, expected)

        inplace_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow']
        for op in inplace_ops:
            _check_inplace_op(getattr(operator, "i%s" % op),
                              getattr(operator, op)) 
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: sparse.py    License: Apache License 2.0 5 votes vote down vote up
def __add__(self, other):
        return add(self, other) 
Example 10
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 5 votes vote down vote up
def __add__(self, other):
        """x.__add__(y) <=> x+y <=> mx.nd.add(x, y) """
        return add(self, other) 
Example 11
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: ndarray.py    License: Apache License 2.0 5 votes vote down vote up
def __iadd__(self, other):
        """x.__iadd__(y) <=> x+=y """
        if not self.writable:
            raise ValueError('trying to add to a readonly NDArray')
        if isinstance(other, NDArray):
            return op.broadcast_add(self, other, out=self)
        elif isinstance(other, numeric_types):
            return _internal._plus_scalar(self, float(other), out=self)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 12
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_stand_gym_env.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _transform_action_to_motor_command(self, action):
    """Method to transform the one dimensional action to rotate bottom two legs.

    Args:
      action: A double between -1 and 1, where 0 means keep the legs parallel
        to the body.
    Returns:
      actions: The angles for all motors.
    Raises:
      ValueError: The action dimension is not the same as the number of motors.
      ValueError: The magnitude of actions is out of bounds.
    """
    action = action[0]
    # Scale the action from [-1 to 1] to [-range to +range] (angle in radians).
    action *= RANGE_OF_LEG_MOTION
    action_all_legs = [
        math.pi,  # Upper leg pointing up.
        0,
        0,  # Bottom leg pointing down.
        math.pi,
        0,  # Upper leg pointing up.
        math.pi,
        math.pi,  # Bottom leg pointing down.
        0
    ]
    action_all_legs = [angle - 0.7 for angle in action_all_legs]

    # Use the one dimensional action to rotate both bottom legs.
    action_delta = [0, 0, -action, action, 0, 0, action, -action]
    action_all_legs = map(add, action_all_legs, action_delta)
    return action_all_legs 
Example 13
Project: lirpg   Author: Hwhitetooth   File: segment_tree.py    License: MIT License 5 votes vote down vote up
def __init__(self, capacity):
        super(SumSegmentTree, self).__init__(
            capacity=capacity,
            operation=operator.add,
            neutral_element=0.0
        ) 
Example 14
Project: SublimeKSP   Author: nojanath   File: simple_eval.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, operators=None, functions=None, names=None):
        '''
            Create the evaluator instance.  Set up valid operators (+,-, etc)
            functions (add, random, get_val, whatever) and names. '''

        if not operators:
            operators = DEFAULT_OPERATORS
        if not functions:
            functions = DEFAULT_FUNCTIONS
        if not names:
            names = DEFAULT_NAMES

        self.operators = operators
        self.functions = functions
        self.names = names 
Example 15
Project: HardRLWithYoutube   Author: MaxSobolMark   File: segment_tree.py    License: MIT License 5 votes vote down vote up
def __init__(self, capacity):
        super(SumSegmentTree, self).__init__(
            capacity=capacity,
            operation=operator.add,
            neutral_element=0.0
        ) 
Example 16
Project: myhdl   Author: myhdl   File: test_concat.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def ConcatToSizedBase(self, bases, extslist):
        for base, basestr in zip(bases, self.bases):
            for exts, extstr in zip(extslist, self.extslist):
                bv = concat(base, *exts)
                refstr = basestr + reduce(operator.add, extstr)
                reflen = len(refstr)
                ref = int(refstr, 2)
                assert bv == ref
                assert len(bv) == reflen 
Example 17
Project: myhdl   Author: myhdl   File: test_concat.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def ConcatToUnsizedBase(self, bases, extslist):
        for base, basestr in zip(bases, self.bases):
            for exts, extstr in zip(extslist, self.extslist):
                bv = concat(base, *exts)
                refstr = basestr + reduce(operator.add, extstr)
                ref = int(refstr, 2)
                assert bv == ref
                assert len(bv) == 0 
Example 18
Project: myhdl   Author: myhdl   File: test_Signal.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def testAdd(self):
        self.binaryCheck(operator.add) 
Example 19
Project: myhdl   Author: myhdl   File: test_intbv.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def testAdd(self):
        self.binaryCheck(operator.add) 
Example 20
Project: tensortrade   Author: tensortrade-org   File: quantity.py    License: Apache License 2.0 5 votes vote down vote up
def __add__(self, other: Union['Quantity', float, int]) -> 'Quantity':
        return Quantity._math_operation(self, other, operator.add) 
Example 21
Project: flask-spark-docker   Author: mjhea0   File: tasks.py    License: MIT License 5 votes vote down vote up
def create_task(words):
    conf = SparkConf().setAppName('letter count')
    sc = SparkContext(conf=conf)
    seq = words.split()
    data = sc.parallelize(seq)
    counts = data.map(lambda word: (word, 1)).reduceByKey(add).collect()
    sc.stop()
    return dict(counts) 
Example 22
Project: gnocchi   Author: gnocchixyz   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def set_resp_link_hdr(marker, *args):
    # NOTE(sileht): This comes from rfc5988.
    # Setting prev, last is too costly/complicated, so just set next for now.
    options = {}
    for arg in args:
        options.update(arg)
    if "sorts" in options:
        options["sort"] = options["sorts"]
        del options["sorts"]
    options["marker"] = marker
    # NOTE(sileht): To always have the same orders
    options = sorted(options.items())
    params = urllib_parse.urlencode(options, doseq=True)
    pecan.response.headers.add("Link", '<%s?%s>; rel="next"' %
                               (pecan.request.path_url, params)) 
Example 23
Project: jawfish   Author: war-and-code   File: itertools.py    License: MIT License 5 votes vote down vote up
def __init__(self, iterable, func = operator.add):
        self.it = iter(iterable)
        self._total = None
        self.func = func 
Example 24
Project: razzy-spinner   Author: rafasashi   File: discourse.py    License: GNU General Public License v3.0 5 votes vote down vote up
def combine_readings(self, readings):
        """:see: ReadingCommand.combine_readings()"""
        thread_reading = reduce(add, readings)
        return resolve_anaphora(thread_reading.simplify()) 
Example 25
Project: shopify_python   Author: Shopify   File: lambda_func.py    License: MIT License 5 votes vote down vote up
def foo4():
    return f.reduce(o.add, [1, 2, 3, 4]) 
Example 26
Project: rift-python   Author: brunorijsman   File: stats.py    License: Apache License 2.0 5 votes vote down vote up
def add_values(self, add_values):
        assert isinstance(add_values, list)
        assert len(add_values) == len(self._values)
        # pylint:disable=attribute-defined-outside-init
        self._values = list(map(operator.add, self._values, add_values))
        sample = (TIME_FUNCTION(), self._values)
        self._samples.append(sample)
        for sum_stat in self._sum_stats:
            sum_stat.add_values(add_values) 
Example 27
Project: rift-python   Author: brunorijsman   File: stats.py    License: Apache License 2.0 5 votes vote down vote up
def add(self, add_values):
        self.add_values(add_values) 
Example 28
Project: rift-python   Author: brunorijsman   File: stats.py    License: Apache License 2.0 5 votes vote down vote up
def add(self, add_value):
        self.add_values([add_value]) 
Example 29
Project: misp42splunk   Author: remg427   File: sortedlist.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def recursive_repr(fillvalue='...'):
    "Decorator to make a repr function return fillvalue for a recursive call."
    # pylint: disable=missing-docstring
    # Copied from reprlib in Python 3
    # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py

    def decorating_function(user_function):
        repr_running = set()

        @wraps(user_function)
        def wrapper(self):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)
            return result

        return wrapper

    return decorating_function

###############################################################################
# END Python 2/3 Shims
############################################################################### 
Example 30
Project: misp42splunk   Author: remg427   File: sortedlist.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def add(self, value):
        """Add `value` to sorted list.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList()
        >>> sl.add(3)
        >>> sl.add(1)
        >>> sl.add(2)
        >>> sl
        SortedList([1, 2, 3])

        :param value: value to add to sorted list

        """
        _lists = self._lists
        _maxes = self._maxes

        if _maxes:
            pos = bisect_right(_maxes, value)

            if pos == len(_maxes):
                pos -= 1
                _lists[pos].append(value)
                _maxes[pos] = value
            else:
                insort(_lists[pos], value)

            self._expand(pos)
        else:
            _lists.append([value])
            _maxes.append(value)

        self._len += 1