Пример #1
0
def test_floordiv(int_proxy: MagicProxy, str_proxy: MagicProxy):
    assert not int_proxy._hasError
    assert not str_proxy._hasError
    with pytest.raises(TypeError):
        operator.floordiv(int_proxy, str_proxy)
    assert int_proxy._hasError
    assert str_proxy._hasError
Пример #2
0
def is_swap(player_score, opponent_score):
    """
    Return whether the two scores should be swapped
    """
    # BEGIN PROBLEM 4
    "*** YOUR CODE HERE ***"
    from operator import mod, floordiv
    i = -1
    p_digits = [0] * 10
    o_digits = [0] * 10
    while player_score >= 1:
        i += 1
        p_digits[i] = mod(player_score, 10)
        player_score = floordiv(player_score, 10)
    p_mul = p_digits[0] * p_digits[i]
    n = -1
    while opponent_score >= 1:
        n += 1
        o_digits[n] = mod(opponent_score, 10)
        opponent_score = floordiv(opponent_score, 10)
    o_mul = o_digits[0] * o_digits[n]
    if o_mul == p_mul:
        return True
    else:
        return False
Пример #3
0
def main():
    a = -1
    b = 5.0
    c = 2
    d = 6

    for k, v in {"a": a, "b": b, "c": c, "d": d}.items():
        print(k + " =", v)

    print("\nPositive/Negative:")
    print("abs(a);", operator.abs(a))
    print("neg(a);", operator.neg(a))
    print("neg(b);", operator.neg(b))
    print("pos(a);", operator.pos(a))
    print("pos(b);", operator.pos(b))

    print("\nArithmetic:")
    print("add(a, b)     :", operator.add(a, b))
    print("floordiv(a, b):", operator.floordiv(a, b))
    print("floordiv(d, c):", operator.floordiv(d, c))
    print("mod(a, b)     :", operator.mod(a, b))
    print("mul(a, b)     :", operator.mul(a, b))
    print("pow(c, d)     :", operator.pow(c, d))
    print("sub(b, a)     :", operator.sub(b, a))
    print("truediv(a, b) :", operator.truediv(a, b))
    print("truediv(d, c) :", operator.truediv(d, c))

    print("\nBitwise:")
    print("and_(c, d)  :", operator.and_(c, d))
    print("invert(c)   :", operator.invert(c))
    print("lshift(c, d):", operator.lshift(c, d))
    print("or_(c, d)   :", operator.or_(c, d))
    print("rshift(d, c):", operator.rshift(d, c))
    print("xor(c, d)   :", operator.xor(c, d))
Пример #4
0
 def __rfloordiv__(self, other):
     try:
         return Vector2(operator.floordiv(other[0], self[0]),
                        operator.floordiv(other[1], self[1]))
     except TypeError:
         return Vector2(operator.floordiv(other, self[0]),
                        operator.floordiv(other, self[1]))
Пример #5
0
def power_mod(number: int, exponent: int, mod: int) -> int:
    """

    :param number:
    :param exponent:
    :param mod:

    .. doctest:: python

        >>> power_mod(2, 4, 3)
        2
        >>> power_mod(12, 3, 4)
        144
        >>> power_mod(123, 2, 3)
        123
        >>> power_mod(120, 6, 10)
        14400
        >>> power_mod(120, 6, 1)
        14400

    """
    if exponent > 0:
        if exponent % 2 == 0:
            return power_mod(number, floordiv(exponent, 2), mod)
        return power_mod(number, floordiv(exponent, 2), mod) * number
    else:
        return 1
Пример #6
0
 def __rfloordiv__(self, other):
     try:
         return Vector2(operator.floordiv(other[0], self[0]), 
                        operator.floordiv(other[1], self[1]))
     except TypeError:
         return Vector2(operator.floordiv(other, self[0]), 
                        operator.floordiv(other, self[1]))
Пример #7
0
 def test_floordiv_errors(self, obj):
     with pytest.raises(
             NotImplementedError,
             match="Dividing a unit by another unit is not allowed."):
         floordiv(Unit(17), obj)
     with pytest.raises(
             NotImplementedError,
             match="Dividing a unit by another unit is not allowed."):
         floordiv(obj, Unit(17))
Пример #8
0
def sum_digits(n):
    """Sum all the digits of n.

    >>> sum_digits(10) # 1 + 0 = 1
    1
    >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
    12
    >>> sum_digits(1234567890)
    45
    """
    fldiv, sum_digits = floordiv(n, 10), mod(n, 10)
    while fldiv > 0:
        sum_digits += mod(fldiv, 10)
        fldiv = floordiv(fldiv, 10)
    return sum_digits
Пример #9
0
def evaluate(expr):
	stack = [] 
	for arg in expr:
		if arg == OPENING:
			stack.append(arg)
		elif arg is not OPENING and arg is not CLOSING:
			stack.append(arg)
		elif arg == CLOSING:
			# stack.append(arg)
			b = int(stack.pop())
			op = stack.pop()
			a = int(stack.pop())
			if op is "+":
				stack.pop()
				stack.append(operator.add(a, b))
			if op is"-":
				stack.pop()
				stack.append(operator.sub(a, b))
			if op is "*":
				stack.pop()
				stack.append(operator.mul(a, b))
			if op is "/":
				# print "divide"
				stack.pop()
				stack.append(operator.floordiv(a, b))

	print stack
	if len(stack) == 1:
		return stack[0]
Пример #10
0
 def test_arithmetic_returns_money_instance(self):
     assert type(Currency(3) + 2) is Currency
     assert type(3 + Currency(2)) is Currency
     assert type(Currency(3) - 2) is Currency
     assert type(3 - Currency(2)) is Currency
     assert type(Currency(3) * 2) is Currency
     assert type(3 * Currency(2)) is Currency
     assert type(floordiv(Currency(3), 2)) is Currency
     assert type(floordiv(3, Currency(2))) is Currency
     assert type(truediv(Currency(3), 2)) is Currency
     assert type(truediv(3, Currency(2))) is Currency
     assert type(Currency(3)**2) is Currency
     assert type(2**Currency(3)) is Currency
     assert type(+Currency(2)) is Currency
     assert type(-Currency(2)) is Currency
     assert type(abs(Currency(2))) is Currency
Пример #11
0
def EventObjectGenerator(plaso_storage, quiet=False):
    """Yields EventObject objects.

  Yields event_objects out of a StorageFile object. If the 'quiet' argument
  is not present, it also outputs 50 '.'s indicating progress.

  Args:
    plaso_storage: a storage.StorageFile object.
    quiet: boolean value indicating whether to suppress progress output.

  Yields:
    EventObject objects.
  """
    total_events = plaso_storage.GetNumberOfEvents()
    if total_events > 0:
        events_per_dot = operator.floordiv(total_events, 80)
        counter = 0
    else:
        quiet = True

    event_object = plaso_storage.GetSortedEntry()
    while event_object:
        if not quiet:
            counter += 1
            if counter % events_per_dot == 0:
                sys.stdout.write(u'.')
                sys.stdout.flush()
        yield event_object
        event_object = plaso_storage.GetSortedEntry()
Пример #12
0
 def operator_floordiv2(size):
     a = Array(size, 'double')
     b = Array(size, 'double')
     for i in range(size):
         a[i] = nb_types.double(i+10)
         b[i] = nb_types.double(i+3)
     return operator.floordiv(a, b)
Пример #13
0
class MathProcess(PostProcess):
    OPERATIONS = {
        "+": lambda x, y: operator.add(x, y),
        "-": lambda x, y: operator.sub(x, y),
        "/": lambda x, y: operator.truediv(x, y),
        "//": lambda x, y: operator.floordiv(x, y),
        "*": lambda x, y: operator.mul(x, y),
        "x": lambda x, y: operator.mul(x, y)
    }

    def __init__(self, query, value, *args, **kwargs):
        self.operator = query['operator']
        self.x = value
        self.y = query['y']

    @property
    def result(self):
        """ Query Model : {x: x, y:y, operation: (+-/*)}
        If x or y is using obtained data, use key::key_name"""
        try:
            x = float(self.x)
            y = float(self.y)
            operator = self.operator
            result_ = self.OPERATIONS[operator](x, y)
            return round(result_, 2)
        except Exception:
            return self.x
Пример #14
0
    def expr(self, p):
        op = p[1]
        left = self._sumDiceRolls(p.expr0)
        right = self._sumDiceRolls(p.expr1)

        if op == '+':
            return operator.add(left, right)
        elif op == '-':
            return operator.sub(left, right)
        elif op == '*':
            if (-self.MAX_MULT <= left <= self.MAX_MULT
                    and -self.MAX_MULT <= right <= self.MAX_MULT):
                return operator.mul(left, right)
            else:
                raise InvalidOperandsException(
                    'multiplication operands are larger than the maximum {}'.
                    format(self.MAX_MULT))
        elif op == '/':
            return operator.floordiv(left, right)
        elif op == '%':
            return operator.mod(left, right)
        elif op == '^':
            if (-self.MAX_EXPONENT <= left <= self.MAX_EXPONENT
                    and -self.MAX_EXPONENT <= right <= self.MAX_EXPONENT):
                return operator.pow(left, right)
            else:
                raise InvalidOperandsException(
                    'operand or exponent is larger than the maximum {}'.format(
                        self.MAX_EXPONENT))
Пример #15
0
def test_arithmetic_returns_money_instance():
    assert type(Money(3) + 2) is Money
    assert type(3 + Money(2)) is Money
    assert type(Money(3) - 2) is Money
    assert type(3 - Money(2)) is Money
    assert type(Money(3) * 2) is Money
    assert type(3 * Money(2)) is Money
    assert type(floordiv(Money(3), 2)) is Money
    assert type(floordiv(3, Money(2))) is Money
    assert type(truediv(Money(3), 2)) is Money
    assert type(truediv(3, Money(2))) is Money
    assert type(Money(3) ** 2) is Money
    assert type(2 ** Money(3)) is Money
    assert type(+Money(2)) is Money
    assert type(-Money(2)) is Money
    assert type(abs(Money(2))) is Money
Пример #16
0
 def test_arithmetic_returns_money_instance(self):
     assert type(Currency(3) + 2) is Currency
     assert type(3 + Currency(2)) is Currency
     assert type(Currency(3) - 2) is Currency
     assert type(3 - Currency(2)) is Currency
     assert type(Currency(3) * 2) is Currency
     assert type(3 * Currency(2)) is Currency
     assert type(floordiv(Currency(3), 2)) is Currency
     assert type(floordiv(3, Currency(2))) is Currency
     assert type(truediv(Currency(3), 2)) is Currency
     assert type(truediv(3, Currency(2))) is Currency
     assert type(Currency(3) ** 2) is Currency
     assert type(2 ** Currency(3)) is Currency
     assert type(+Currency(2)) is Currency
     assert type(-Currency(2)) is Currency
     assert type(abs(Currency(2))) is Currency
Пример #17
0
def combinatory(n, r):
    """Function that calculates the combinatorial
		c = (n-k)!/min(k,n-k)!"""
    r = min(r, n - r)
    numer = reduce(op.mul, range(n, n - r, -1), 1)
    demon = reduce(op.mul, range(1, r + 1), 1)
    return floordiv(numer, demon)
Пример #18
0
 def operator_floordiv(size):
     a = Array(size, 'int32')
     b = Array(size, 'int32')
     for i in range(size):
         a[i] = nb_types.int32(i+10)
         b[i] = nb_types.int32(i+3)
     return operator.floordiv(a, b)
Пример #19
0
def EventObjectGenerator(plaso_storage, quiet=False):
  """Yields EventObject objects.

  Yields event_objects out of a StorageFile object. If the 'quiet' argument
  is not present, it also outputs 50 '.'s indicating progress.

  Args:
    plaso_storage: a storage.StorageFile object.
    quiet: boolean value indicating whether to suppress progress output.

  Yields:
    EventObject objects.
  """
  total_events = plaso_storage.GetNumberOfEvents()
  if total_events > 0:
    events_per_dot = operator.floordiv(total_events, 80)
    counter = 0
  else:
    quiet = True

  event_object = plaso_storage.GetSortedEntry()
  while event_object:
    if not quiet:
      counter += 1
      if counter % events_per_dot == 0:
        sys.stdout.write(u'.')
        sys.stdout.flush()
    yield event_object
    event_object = plaso_storage.GetSortedEntry()
Пример #20
0
    def p_expression_binop(self, p):
        """expression : expression PLUS expression
                      | expression MINUS expression
                      | expression TIMES expression
                      | expression DIVIDE expression
                      | expression MODULUS expression
                      | expression EXPONENT expression"""

        op = p[2]
        left = self._sumDiceRolls(p[1])
        right = self._sumDiceRolls(p[3])

        if op == '+':
            p[0] = operator.add(left, right)
        elif op == '-':
            p[0] = operator.sub(left, right)
        elif op == '*':
            p[0] = operator.mul(left, right)
        elif op == '/':
            p[0] = operator.floordiv(left, right)
        elif op == '%':
            p[0] = operator.mod(left, right)
        elif op == '^':
            if -self._MAX_EXPONENT <= left <= self._MAX_EXPONENT and -self._MAX_EXPONENT <= right <= self._MAX_EXPONENT:
                p[0] = operator.pow(left, right)
            else:
                raise InvalidOperandsException(u'operand or exponent is larger than the maximum {}'
                                               .format(self._MAX_EXPONENT))
def calculator():
    clear()
    print(logo)
    firstNumber = float(input("What's the first number?: "))
    print("+\n-\n*\n/\n")
    continue_calc = True

    while continue_calc is True:
        selectedMathOperator = input("Pick an operation: ")
        secondNumber = float(input("What's the second Number?: "))
        mathOperators = {
            "+": operator.add(firstNumber, secondNumber),
            "-": operator.sub(firstNumber, secondNumber),
            "*": operator.mul(firstNumber, secondNumber),
            "/": operator.floordiv(firstNumber, secondNumber),
            }
        if selectedMathOperator in mathOperators:
            result = mathOperators[selectedMathOperator]
            print(f"{firstNumber} {selectedMathOperator} {secondNumber} = {result}")

        if input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculation: ") == 'y':
            firstNumber = result
        else:
            continue_calc = False
            calculator()
Пример #22
0
def partition_median_three(a, start, end):
	m1 = end - start
	midp = operator.floordiv(m1,2) + operator.mod(m1,2) - 1
	
	meow = [(a[start], start), (a[end-1], end-1), (a[start + midp], start + midp)]
	swap(a, start, sorted(meow)[1][1])

	return partition_first(a, start, end)
Пример #23
0
def apply_floordiv(left: Column, right):
    if type(right) == Column:
        result, index = apply_fast_floordiv(left.values, right.values,
                                            left.index, right.index)
        return Column(result, index)

    else:
        return Column(operator.floordiv(left.values, right), left.index)
Пример #24
0
 def finalize_total_row(tr):
     if tr['I/C Presented'] > 0:
         tr['Incoming Answered (%)'] = operator.truediv(
             tr['I/C Answered'], tr['I/C Presented'])
         tr['Incoming Lost (%)'] = operator.truediv(
             tr['I/C Lost'] + tr['Voice Mails'], tr['I/C Presented'])
         tr['PCA'] = operator.truediv(
             tr['Calls Ans Within 15'] + tr['Calls Ans Within 30'],
             tr['I/C Presented'])
         if tr['I/C Answered'] > 0:
             tr['Average Incoming Duration'] = operator.floordiv(
                 tr['Average Incoming Duration'], tr['I/C Answered'])
             tr['Average Wait Answered'] = operator.floordiv(
                 tr['Average Wait Answered'], tr['I/C Answered'])
         if tr['I/C Lost'] > 0:
             tr['Average Wait Lost'] = operator.floordiv(
                 tr['Average Wait Lost'], tr['I/C Lost'])
Пример #25
0
def power_mod(number, exponent, mod):
    """

    Args:
        number:
        exponent:
        mod:

    Returns:

    """
    if exponent > 0:
        if exponent%2 == 0:
            return power_mod(number, floordiv(exponent, 2), mod)
        return power_mod(number, floordiv(exponent, 2), mod)*number
    else:
        return 1
Пример #26
0
 def fhook(self, ops, vm):
     val_one, val_two = get_stack_operands(vm)
     if val_two == 0:
         raise DivisionZero()
     result = opfunc.floordiv(abs(val_one), abs(val_two))
     check_overflow(result, vm)
     vm.stack[hex(vm.get_sp()).split('x')[-1].upper()] = result
     vm.inc_sp()
Пример #27
0
def calculate(op, op1, op2):
    operators = {
        "+": operator.add(op1, op2),
        "-": operator.sub(op1, op2),
        "*": operator.mul(op1, op2),
        "/": operator.floordiv(op1, op2),
    }
    return operators.get(op)
Пример #28
0
 def fhook(self, ops, vm):
     check_num_args(self.name, ops, 3)
     check_reg_only(self.name, ops)
     ops[0].set_val(
         check_overflow(
             opfunc.floordiv(abs(ops[1].get_val()), abs(ops[2].get_val())),
             vm))
     vm.changes.add(ops[0].get_nm())
 def finalize_total_row(tr):
     if tr['I/C Presented'] > 0:
         tr['Incoming Live Answered (%)'] = operator.truediv(tr['I/C Answered'],
                                                        tr['I/C Presented'])
         tr['Incoming Abandoned (%)'] = operator.truediv(tr['I/C Lost'], tr['I/C Presented'])
         tr['Incoming Received (%)'] = operator.truediv(tr['I/C Answered'] + tr['Voice Mails'],
                                                        tr['I/C Presented'])
         tr['PCA'] = operator.truediv(tr['Calls Ans Within 15'] + tr['Calls Ans Within 30'],
                                      tr['I/C Presented'])
         if tr['I/C Answered'] > 0:
             tr['Average Incoming Duration'] = operator.floordiv(tr['Average Incoming Duration'],
                                                                 tr['I/C Answered'])
             tr['Average Wait Answered'] = operator.floordiv(tr['Average Wait Answered'],
                                                             tr['I/C Answered'])
         if tr['I/C Lost'] > 0:
             tr['Average Wait Lost'] = operator.floordiv(tr['Average Wait Lost'],
                                                         tr['I/C Lost'])
def main():
    ns = [float(a) for a in input('Digite dois números: ').split()]
    soma = float(sum(ns))
    diferença = float(sub(*ns))
    produto = float(mul(*ns))
    quociente = floordiv(*ns)
    print(f'soma: {soma:0.2f} diferença: {diferença:0.2f} '
         f'produto: {produto:0.2f} quociente: {quociente:0.2f}')
Пример #31
0
 def WriteDateTime(self, Year, Month, Day, DayOfWeek, Hour, Minute, Second):
     # Initiate DS1302 communication.
     self.InitiateDS1302()
     # Write address byte.
     self.WriteByte(int("10111110", 2))
     # Write seconds data.
     self.WriteByte(
         operator.mod(Second, 10) | operator.floordiv(Second, 10) * 16)
     # Write minute data.
     self.WriteByte(
         operator.mod(Minute, 10) | operator.floordiv(Minute, 10) * 16)
     # Write hour data.
     self.WriteByte(
         operator.mod(Hour, 10) | operator.floordiv(Hour, 10) * 16)
     # Write day data.
     self.WriteByte(operator.mod(Day, 10) | operator.floordiv(Day, 10) * 16)
     # Write month data.
     self.WriteByte(
         operator.mod(Month, 10) | operator.floordiv(Month, 10) * 16)
     # Write day of week data.
     self.WriteByte(
         operator.mod(DayOfWeek, 10)
         | operator.floordiv(DayOfWeek, 10) * 16)
     # Write year of week data.
     self.WriteByte(
         operator.mod(Year, 10) | operator.floordiv(Year, 10) * 16)
     # Make sure write protect is turned off.
     self.WriteByte(int("00000000", 2))
     # Make sure trickle charge mode is turned off.
     self.WriteByte(int("00000000", 2))
     # End DS1302 communication.
     self.EndDS1302()
def longestPalindrome(s):

    if (s == None or len(s) < 1):
        return ""

    start, end = 0, 0

    for i in range(0, len(s)):
        len1 = expandAroundCenter(s, i, i)
        len2 = expandAroundCenter(s, i, i + 1)

        flen = max(len1, len2)

        if flen > (end - start):
            start = int(i - (floordiv((flen - 1), 2)))
            end = int(i + (floordiv(flen, 2)))

    return s[start:end + 1]
Пример #33
0
 def operate(A, B, o):
     if o == '+':
         return operator.add(A, B)
     elif o == '-':
         return operator.sub(A, B)
     elif o == '*':
         return operator.mul(A, B)
     elif o == '/':
         return operator.floordiv(A, B)
Пример #34
0
def divide(n, d):
    """
    >>> q, r = divide(2013, 10)
    >>> q
    201
    >>> r
    3
    """
    return floordiv(n, d), mod(n, d)
Пример #35
0
def div_n_d(w, v):
    """return the quation and remainder of dividing w by v
    >>> a,b=div_n_d(5,3)
    >>> a
    1
    >>> b
    2
    """
    return floordiv(w, v), mod(w, v)
Пример #36
0
def divide_exact(n, d):
    """Return the quotient and remainder of dividing N by D.
    >>> q, r = divide_exact(2013, 10)
    >>> q
    201
    >>> r
    3
    """
    return floordiv(n, d), mod(n, d)
Пример #37
0
  def NoDuplicates(self, dump_filename):
    """Saves a de-duped Plaso Storage.

    This goes through the Plaso storage file, and saves a new dump with
    duplicates removed. The filename is '.[dump_hash]_dedup', and is returned
    at the end of the function. Note that if this function is interrupted,
    incomplete results are recorded and this file must be deleted or subsequent
    runs will use this incomplete data.

    Args:
      dump_filename: the filename of the Plaso Storage to be deduped.
    """
    sys.stdout.write(u'Removing duplicates...\n')
    sys.stdout.flush()
    # Whether these incremental files should remain a feature or not is still
    # being decided. They're just here for now to make development faster.
    nodup_filename = '.{0:s}_dedup'.format(self.plaso_hash)
    if os.path.isfile(nodup_filename):
      sys.stdout.write(u'Using previously calculated results.\n')
    else:
      with SetupStorage(dump_filename) as store:
        total_events = store.GetNumberOfEvents()
        events_per_dot = operator.floordiv(total_events, 80)

        formatter_mediator = self.GetFormatterMediator()

        try:
          formatter_mediator.SetPreferredLanguageIdentifier(
              self._preferred_language)
        except (KeyError, TypeError) as exception:
          raise RuntimeError(exception)

        # TODO: When storage refactor is done change this so that we do not
        # always choose pstorage but whatever storage mechanism that was used
        # to begin with (as in if the storage is SQLite then use SQLite for
        # output).
        output_mediator_object = output_mediator.OutputMediator(
            formatter_mediator, store)

        output_module = output_manager.OutputManager.NewOutputModule(
            u'pstorage', output_mediator_object, filehandle=nodup_filename)

        with output_interface.EventBuffer(
            output_module, check_dedups=True) as output_buffer:
          event_object = store.GetSortedEntry()
          counter = 0
          while event_object:
            output_buffer.Append(event_object)
            counter += 1
            if counter % events_per_dot == 0:
              sys.stdout.write(u'.')
              sys.stdout.flush()
            event_object = store.GetSortedEntry()

      sys.stdout.write(u'\n')
    return nodup_filename
Пример #38
0
def divide_exact(n, d):
    """Return the quotient and remainder of dividing N by D.

    >>> quotient, remainder = divide_exact(2013, 10)
    >>> quotient
    201
    >>> remainder
    3
    """
    return floordiv(n, d), mod(n, d)
Пример #39
0
def divide_exact(n, d=10):
    """Return the quotient and remainder of dividing N by D.

    >>> quotient, remainder = divide_exact(618, 10)
    >>> quotient
    61
    >>> remainder
    8
    """
    return floordiv(n, d), mod(n, d)
Пример #40
0
def divide_exact(n, d=10):
    """Return the quotient and remainder of dividing N by D.

    >>> q, r = divide_exact(2013)
    >>> q
    201
    >>> r
    3
    """
    return floordiv(n, d), mod(n, d)
Пример #41
0
def divide(a, b):
    """
    `a / b` with python 2 semantics:

        - floordiv() integer division
        - truediv() float division
    """
    if isinstance(a, (int, long)) and isinstance(b, (int, long)):
        return operator.floordiv(a, b)
    else:
        return operator.truediv(a, b)
Пример #42
0
def encrypt(plaintext, password, nBits):
    blockSize = 16
    if not nBits in (128, 192, 256):
        return ""
    #    plaintext = plaintext.encode("utf-8")
    #    password  = password.encode("utf-8")
    # use floordiv
    nBytes = floordiv(nBits, 8)
    pwBytes = mul([0], nBytes)
    for i in range(nBytes):
        pwBytes[i] = 0 if i >= len(password) else ord(password[i])
    key = Cipher(pwBytes, KeyExpansion(pwBytes))
    key += key[: nBytes - 16]

    counterBlock = [0] * blockSize
    now = datetime.datetime.now()
    nonce = time.mktime(now.timetuple()) * 1000 + now.microsecond // 1000
    nonceSec = int(nonce // 1000)
    nonceMs = int(nonce % 1000)

    for i in range(4):
        counterBlock[i] = urs(nonceSec, i * 8) & 0xFF
    for i in range(4):
        counterBlock[i + 4] = nonceMs & 0xFF

    ctrTxt = ""
    for i in range(8):
        ctrTxt += chr(counterBlock[i])

    keySchedule = KeyExpansion(key)

    blockCount = int(math.ceil(float(len(plaintext)) / float(blockSize)))
    ciphertxt = [0] * blockCount

    for b in range(blockCount):
        for c in range(4):
            counterBlock[15 - c] = urs(b, c * 8) & 0xFF
        for c in range(4):
            counterBlock[15 - c - 4] = urs(b / 0x100000000, c * 8)

        cipherCntr = Cipher(counterBlock, keySchedule)

        blockLength = blockSize if b < blockCount - 1 else (len(plaintext) - 1) % blockSize + 1
        cipherChar = [0] * blockLength

        for i in range(blockLength):
            cipherChar[i] = cipherCntr[i] ^ ord(plaintext[b * blockSize + i])
            cipherChar[i] = chr(cipherChar[i])
        ciphertxt[b] = "".join(cipherChar)

    ciphertext = ctrTxt + "".join(ciphertxt)
    ciphertext = base64.b64encode(ciphertext)

    return ciphertext
Пример #43
0
        def check(a, b):
            _check_op(a, b, operator.add)
            _check_op(a, b, operator.sub)
            _check_op(a, b, operator.truediv)
            _check_op(a, b, operator.floordiv)
            _check_op(a, b, operator.mul)

            _check_op(a, b, lambda x, y: operator.add(y, x))
            _check_op(a, b, lambda x, y: operator.sub(y, x))
            _check_op(a, b, lambda x, y: operator.truediv(y, x))
            _check_op(a, b, lambda x, y: operator.floordiv(y, x))
            _check_op(a, b, lambda x, y: operator.mul(y, x))
Пример #44
0
        def check(other):
            _check_op(other, operator.add)
            _check_op(other, operator.sub)
            _check_op(other, operator.truediv)
            _check_op(other, operator.floordiv)
            _check_op(other, operator.mul)
            _check_op(other, operator.pow)

            _check_op(other, lambda x, y: operator.add(y, x))
            _check_op(other, lambda x, y: operator.sub(y, x))
            _check_op(other, lambda x, y: operator.truediv(y, x))
            _check_op(other, lambda x, y: operator.floordiv(y, x))
            _check_op(other, lambda x, y: operator.mul(y, x))
            _check_op(other, lambda x, y: operator.pow(y, x))
Пример #45
0
 def __floordiv__(self, other):
     try:
         return Vector3(operator.floordiv(self[0], other[0]), 
                        operator.floordiv(self[1], other[1]),
                        operator.floordiv(self[2], other[2]))
     except TypeError:
         return Vector3(operator.floordiv(self[0], other), 
                        operator.floordiv(self[1], other),
                        operator.floordiv(self[2], other))
Пример #46
0
        def check(series, other):
            simple_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'mod']

            for opname in simple_ops:
                _check_op(series, other, getattr(operator, opname))

            _check_op(series, other, operator.pow, pos_only=True)

            _check_op(series, other, lambda x, y: operator.add(y, x))
            _check_op(series, other, lambda x, y: operator.sub(y, x))
            _check_op(series, other, lambda x, y: operator.truediv(y, x))
            _check_op(series, other, lambda x, y: operator.floordiv(y, x))
            _check_op(series, other, lambda x, y: operator.mul(y, x))
            _check_op(series, other, lambda x, y: operator.pow(y, x),
                      pos_only=True)
            _check_op(series, other, lambda x, y: operator.mod(y, x))
Пример #47
0
def standard_env():
    _env = Env()
    _env.update(vars(math))  # sin, cos, sqrt, pi, ...
    _env.update(vars(cmath))
    _env.update({
        "+": lambda a, b: op.add(a, b), "-": lambda a, b: op.sub(a, b),
        "/": lambda a, b: op.truediv(a, b), "*": lambda a, b: op.mul(a, b),
        "//": lambda a, b: op.floordiv(a, b), "%": lambda a, b: op.mod(a, b),
        "pow": lambda x, p: x ** p,

        "^": lambda a, b: op.xor(a, b), "|": lambda a, b: op.or_(a, b),
        "&": lambda a, b: op.and_(a, b), "~": lambda x: ~x,
        ">>": lambda x, dc: x >> dc, "<<": lambda x, dc: x << dc,

        '>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '=': op.eq, '!=': op.ne,
        'not': op.not_, 'eq?': op.is_, 'equal?': op.eq,

        'ord': ord, 'chr': chr,

        '#': op.getitem, '#=': op.setitem, '#~': op.delitem, 'length': len,
        'list': lambda *x: list(x), 'list?': lambda x: isinstance(x, list),
        'append': op.add, 'car': lambda x: x[0], 'cdr': lambda x: x[1:], 'cons': lambda x, y: [x] + y,
        'join': lambda char, li: char.join(str(e) for e in li),

        'time': time.time, 'round': round, 'abs': abs, 'zip': lambda *x: list(zip(*x)),
        'type': lambda x: type(x).__name__, 'range': lambda start, stop: [_ for _ in range(start, stop + 1)],
        'map': lambda *x: list(map(*x)), 'max': max, 'min': min,

        'open-input-file': open, 'open-output-file': lambda f: open(f, 'w'), 'close-file': lambda f: f.close(),
        'read-file': lambda f: f.read(), 'write-in-file': lambda f, s: f.write(s),
        'load-file': lambda f: load(f),

        'null': None, 'null?': lambda x: bool(x),
        'int': lambda x: int(x), 'float': lambda x: float(x), 'number?': lambda x: isinstance(x, (int, float)),
        'bool': lambda x: bool(x), 'bool?': lambda x: isinstance(x, bool),
        'procedure?': callable,
        'symbol?': lambda x: isinstance(x, str),

        'call/cc': callcc
    })
    return _env
Пример #48
0
  def NoDuplicates(self, dump_filename):
    """Saves a de-duped Plaso Storage.

    This goes through the Plaso storage file, and saves a new dump with
    duplicates removed. The filename is '.[dump_hash]_dedup', and is returned
    at the end of the function. Note that if this function is interrupted,
    incomplete results are recorded and this file must be deleted or subsequent
    runs will use this incomplete data.

    Args:
      dump_filename: the filename of the Plaso Storage to be deduped.
    """
    sys.stdout.write(u'Removing duplicates...\n')
    sys.stdout.flush()
    # Whether these incremental files should remain a feature or not is still
    # being decided. They're just here for now to make development faster.
    nodup_filename = '.{}_dedup'.format(self.plaso_hash)
    if os.path.isfile(nodup_filename):
      sys.stdout.write(u'Using previously calculated results.\n')
    else:
      with SetupStorage(dump_filename) as store:
        total_events = store.GetNumberOfEvents()
        events_per_dot = operator.floordiv(total_events, 80)
        formatter_cls = output_lib.GetOutputFormatter('Pstorage')
        store_dedup = open(nodup_filename, 'wb')
        formatter = formatter_cls(store, store_dedup)
        with output_lib.EventBuffer(
            formatter, check_dedups=True) as output_buffer:
          event_object = formatter.FetchEntry()
          counter = 0
          while event_object:
            output_buffer.Append(event_object)
            counter += 1
            if counter % events_per_dot == 0:
              sys.stdout.write(u'.')
              sys.stdout.flush()
            event_object = formatter.FetchEntry()
      sys.stdout.write(u'\n')
    return nodup_filename
Пример #49
0
 def retrieve_test_results(self):
     """Split the tree."""
     for child in self.root:
         child.set(
             'case',
             child.get('name').split('_')[-1]
         )
         child.set(
             'test',
             self.find_test_id(child.get('case'), self.test_set)
         )
         sub = list(child.iter())
         if len(sub) >= 2:
             if sub[1].tag == 'system-out':
                 child.set('status', 'passed')
             else:
                 child.set('status', sub[1].tag)
             message = sub[1].get('message') if 'message' in \
                 sub[1].attrib else ''
             parts = message.split(
                 '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ' +
                 '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _'
             )
             reorder = 'Break Point:' + Result.NEW_LINE + \
                       parts[0] + Result.NEW_LINE
             if len(parts) > 1:
                 final = str(parts[len(parts) - 1])
                 reorder = reorder + Result.NEW_LINE + \
                     'Reason:' + Result.NEW_LINE
                 reorder = reorder + \
                     final[:-operator.floordiv(len(final), 4)]
                 reorder = reorder + Result.NEW_LINE
             child.set('message', reorder)
             child.set('text', sub[1].text)
         else:
             child.set('status', 'passed')
             child.set('message', '')
             child.set('text', '')
Пример #50
0
def Cipher(input, w):
    Nb = 4
    Nr = len(w) / Nb - 1

    state = [[0] * 4 for i in range(4)]
    for i in range(0, Nb * Nb):
        state[mod(i, Nb)][floordiv(i, Nb)] = input[i]

    state = AddRoundKey(state, w, 0, Nb)

    for round in range(1, Nr):
        state = SubBytes(state, Nb)
        state = ShiftRows(state, Nb)
        state = MixColumns(state, Nb)
        state = AddRoundKey(state, w, round, Nb)

    state = SubBytes(state, Nb)
    state = ShiftRows(state, Nb)
    state = AddRoundKey(state, w, Nr, Nb)

    output = [0] * 4 * Nb
    for i in range(4 * Nb):
        output[i] = state[i % 4][i // 4]
    return output
Пример #51
0
 def test_floordiv(self):
     self.failUnlessRaises(TypeError, operator.floordiv, 5)
     self.failUnlessRaises(TypeError, operator.floordiv, None, None)
     self.failUnless(operator.floordiv(5, 2) == 2)
Пример #52
0
        self.assertTrue(self._def != None)


_BINOPS = (
    ('lt', operator.lt),
    ('le', operator.le),
    ('eq', operator.eq),
    ('ne', operator.ne),
    ('ge', operator.ge),
    ('gt', operator.gt),
    ('add', operator.add),
    ('radd', lambda a, b: operator.add(b, a)),
    ('and', operator.and_),
    ('rand', lambda a, b: operator.and_(b, a)),
    ('floordiv', operator.floordiv),
    ('rfloordiv', lambda a, b: operator.floordiv(b, a)),
    ('lshift', operator.lshift),
    ('rlshift', lambda a, b: operator.lshift(b, a)),
    ('mod', operator.mod),
    ('rmod', lambda a, b: operator.mod(b, a)),
    ('mul', operator.mul),
    ('rmul', lambda a, b: operator.mul(b, a)),
    ('or', operator.or_),
    ('ror', lambda a, b: operator.or_(b, a)),
    ('pow', operator.pow),
    ('rpow', lambda a, b: operator.pow(b, a)),
    ('rshift', operator.rshift),
    ('rrshift', lambda a, b: operator.rshift(b, a)),
    ('sub', operator.sub),
    ('rsub', lambda a, b: operator.sub(b, a)),
    ('truediv', operator.truediv),
Пример #53
0
 def floordiv_usecase(x, y):
     return operator.floordiv(x, y)
Пример #54
0
 def test_floordiv(self):
     self.assertRaises(TypeError, operator.floordiv, 5)
     self.assertRaises(TypeError, operator.floordiv, None, None)
     self.assertTrue(operator.floordiv(5, 2) == 2)
Пример #55
0
 def __rfloordiv__(self, other):
     assert type(other) in (int, long, float)
     return Vector3(operator.floordiv(other, self.x),
                    operator.floordiv(other, self.y),
                    operator.floordiv(other, self.z))
Пример #56
0
 def __floordiv__(self, other):
     assert type(other) in (int, long, float)
     return Vector3(operator.floordiv(self.x, other),
                    operator.floordiv(self.y, other),
                    operator.floordiv(self.z, other))
Пример #57
0
 def __rfloordiv__(self, y):
   return NonStandardInteger(operator.floordiv(y, self.val))
Пример #58
0
def _create_methods(arith_method, radd_func, comp_method, bool_method,
                    use_numexpr, special=False, default_axis='columns'):
    # creates actual methods based upon arithmetic, comp and bool method
    # constructors.

    # NOTE: Only frame cares about default_axis, specifically: special methods
    # have default axis None, whereas flex methods have default axis 'columns'
    # if we're not using numexpr, then don't pass a str_rep
    if use_numexpr:
        op = lambda x: x
    else:
        op = lambda x: None
    if special:
        def names(x):
            if x[-1] == "_":
                return "__%s_" % x
            else:
                return "__%s__" % x
    else:
        names = lambda x: x
    radd_func = radd_func or operator.add
    # Inframe, all special methods have default_axis=None, flex methods have
    # default_axis set to the default (columns)
    new_methods = dict(
        add=arith_method(operator.add, names('add'), op('+'),
                         default_axis=default_axis),
        radd=arith_method(radd_func, names('radd'), op('+'),
                          default_axis=default_axis),
        sub=arith_method(operator.sub, names('sub'), op('-'),
                         default_axis=default_axis),
        mul=arith_method(operator.mul, names('mul'), op('*'),
                         default_axis=default_axis),
        truediv=arith_method(operator.truediv, names('truediv'), op('/'),
                             truediv=True, fill_zeros=np.inf,
                             default_axis=default_axis),
        floordiv=arith_method(operator.floordiv, names('floordiv'), op('//'),
                              default_axis=default_axis, fill_zeros=np.inf),
        # Causes a floating point exception in the tests when numexpr
        # enabled, so for now no speedup
        mod=arith_method(operator.mod, names('mod'), None,
                         default_axis=default_axis, fill_zeros=np.nan),
        pow=arith_method(operator.pow, names('pow'), op('**'),
                         default_axis=default_axis),
        # not entirely sure why this is necessary, but previously was included
        # so it's here to maintain compatibility
        rmul=arith_method(operator.mul, names('rmul'), op('*'),
                          default_axis=default_axis, reversed=True),
        rsub=arith_method(lambda x, y: y - x, names('rsub'), op('-'),
                          default_axis=default_axis, reversed=True),
        rtruediv=arith_method(lambda x, y: operator.truediv(y, x),
                              names('rtruediv'), op('/'), truediv=True,
                              fill_zeros=np.inf, default_axis=default_axis,
                              reversed=True),
        rfloordiv=arith_method(lambda x, y: operator.floordiv(y, x),
                               names('rfloordiv'), op('//'),
                               default_axis=default_axis, fill_zeros=np.inf,
                               reversed=True),
        rpow=arith_method(lambda x, y: y ** x, names('rpow'), op('**'),
                          default_axis=default_axis, reversed=True),
        rmod=arith_method(lambda x, y: y % x, names('rmod'), op('%'),
                          default_axis=default_axis, fill_zeros=np.nan,
                          reversed=True),
    )
    new_methods['div'] = new_methods['truediv']
    new_methods['rdiv'] = new_methods['rtruediv']

    # Comp methods never had a default axis set
    if comp_method:
        new_methods.update(dict(
            eq=comp_method(operator.eq, names('eq'), op('==')),
            ne=comp_method(operator.ne, names('ne'), op('!='), masker=True),
            lt=comp_method(operator.lt, names('lt'), op('<')),
            gt=comp_method(operator.gt, names('gt'), op('>')),
            le=comp_method(operator.le, names('le'), op('<=')),
            ge=comp_method(operator.ge, names('ge'), op('>=')),
        ))
    if bool_method:
        new_methods.update(dict(
            and_=bool_method(operator.and_, names('and_'), op('&')),
            or_=bool_method(operator.or_, names('or_'), op('|')),
            # For some reason ``^`` wasn't used in original.
            xor=bool_method(operator.xor, names('xor'), op('^')),
            rand_=bool_method(lambda x, y: operator.and_(y, x),
                              names('rand_'), op('&')),
            ror_=bool_method(lambda x, y: operator.or_(y, x), names('ror_'), op('|')),
            rxor=bool_method(lambda x, y: operator.xor(y, x), names('rxor'), op('^'))
        ))

    new_methods = dict((names(k), v) for k, v in new_methods.items())
    return new_methods
Пример #59
0
def floordiv_ovf(x, y):
    return ovfcheck(operator.floordiv(x, y))
Пример #60
0
                openFile = open(subFolderPath + "\\" + file, "r")
                readFile= openFile.read()
                # pattern matching to extract specific portion of the file
                ## Use regular expressions to identify the portion of text file to extract
                pattern2 = re.compile("(?<=\n#Mann=).+(?![A-z]+)")
                pattern3 = re.compile(r"(?<=Type RM Length L Ch R =).+(\d+)")
                manningsCoeff = pattern2.finditer(readFile)
                stations = pattern3.finditer(readFile)

                stationsList = []
                for station in stations:
                    if int(station.group().split(",")[0].strip()) == 1:
                        stationsList.append(station.group().split())
                manningsCoeffList = []
                for coeffs in manningsCoeff:
                    numberOfIter = floordiv(int(coeffs.group().split(",")[0])-1, 3) + 1
                    newStartLocation = coeffs.start() + readFile[coeffs.start():].find("\n") + 1
                    TempList = []
                    while numberOfIter > 0:
                        line = readFile[newStartLocation:newStartLocation + readFile[newStartLocation:].find("\n")]
                        newStartLocation = newStartLocation + readFile[newStartLocation:].find("\n") + 1
                        numberOfIter = numberOfIter - 1
                        for item in line.split():
                            TempList.append(item)
                    manningsCoeffList.append(TempList)
                streamGeometryData = map(list.__add__,stationsList,manningsCoeffList)
                streamGeometry[file] = streamGeometryData

##CSV generation
#outputCheckMannings = csv.writer(open(folderLocation + "\\" +'streamGeometry'+ str(time.gmtime().tm_sec) + '.csv', 'wb'))
#list = []