Example #1
0
 def testGreaterThanEqual(self):
     """Test >=operator"""
     _dt = self.eDatetime - datetime.timedelta(1)
     _other = eventCalBase.event(2, 'event', _dt)
     self.failUnless(operator.ge(self.e, _other),
             'a1 => a2 failed.  a1=%s, a2=%s' % (self.e, _other))
     self.failUnless(operator.ge(_other, _other),
             'a1 => a2 failed.  a1=%s, a2=%s' % (_other, _other))
Example #2
0
            def evaluate(cond): # Method to evaluate the conditions
                if isinstance(cond,bool):
                    return cond
                left, oper, right = cond
                if not model or not left in model.mgroup.fields:  #check that the field exist
                    return False

                oper = self.OPERAND_MAPPER.get(oper.lower(), oper)
                if oper == '=':
                    res = operator.eq(model[left].get(model),right)
                elif oper == '!=':
                    res = operator.ne(model[left].get(model),right)
                elif oper == '<':
                    res = operator.lt(model[left].get(model),right)
                elif oper == '>':
                    res = operator.gt(model[left].get(model),right)
                elif oper == '<=':
                    res = operator.le(model[left].get(model),right)
                elif oper == '>=':
                    res = operator.ge(model[left].get(model),right)
                elif oper == 'in':
                    res = operator.contains(right, model[left].get(model))
                elif oper == 'not in':
                    res = operator.contains(right, model[left].get(model))
                    res = operator.not_(res)
                return res
Example #3
0
    def __init__(self):
        # xl to py formulas conversion for eval()
        self.__author__ = __author__
        self.__version__ = __version__

        # xl to py formula conversion
        self.fun_database = {
                    'IF' : lambda args : [args[0]*args[1]+(abs(args[0]-1)*args[2])][0],\
                    'AVERAGE' : lambda args : np.average(args[0]),\
                    'STDEV.P' : lambda args : np.std(args[0]),\
                    'TRANSPOSE' : lambda args : np.transpose(args[0]),\
                    'ABS' : lambda args : np.abs(args[0]),\
                    'MMULT' : lambda args : np.dot(*args),\
                    'IFERROR' : lambda args : self.pyxl_error(*args),\
                    'SUM' : lambda args : np.sum(args[0]),\
                    'COUNT' : lambda args : np.size(args[0]),\
                    'SQRT' : lambda args : np.sqrt(args[0]),\
                    '^' : lambda args : np.power(*args),\
                    '<' : lambda args : np.float64(op.lt(*args)),\
                    '>' : lambda args : np.float64(op.gt(*args)),\
                    '<=' : lambda args : np.float64(op.le(*args)),\
                    '>=' : lambda args : np.float64(op.ge(*args)),\
                    '<>' : lambda args : np.float64(op.ne(*args)),\
                    '=' : lambda args : np.float64(op.eq(*args)),\
                    '+' : lambda args : np.add(*args),\
                    '-' : lambda args : np.subtract(*args),\
                    '/' : lambda args : np.divide(*args),\
                    '*' : lambda args : np.multiply(*args)
                    }
Example #4
0
    def evaluate(self):
        result = None
        left = self.left.evaluate()
        right = self.right.evaluate()

        if self.operation == '+':
            result = operator.add(left, right)
        elif self.operation == '-':
            result = operator.sub(left, right)
        elif self.operation == '*':
            result = operator.mul(left, right)
        elif self.operation == '/':
            result = operator.div(left, right)
        elif self.operation == '^':
            result = operator.pow(left, right)
        elif self.operation == 'and':
            result = left and right
        elif self.operation == 'or':
            result = left or right
        elif self.operation == '<':
            result = operator.lt(left, right)
        elif self.operation == '<=':
            result = operator.le(left, right)
        elif self.operation == '==':
            result = operator.eq(left, right)
        elif self.operation == '!=':
            result = operator.ne(left, right)
        elif self.operation == '>':
            result = operator.gt(left, right)
        elif self.operation == '>=':
            result = operator.ge(left, right)
        elif self.operation == 'in':
            result = (left in right)
        return result
Example #5
0
 def specialcases(x):
     operator.lt(x,3)
     operator.le(x,3)
     operator.eq(x,3)
     operator.ne(x,3)
     operator.gt(x,3)
     operator.ge(x,3)
     is_operator(x,3)
     operator.__lt__(x,3)
     operator.__le__(x,3)
     operator.__eq__(x,3)
     operator.__ne__(x,3)
     operator.__gt__(x,3)
     operator.__ge__(x,3)
     # the following ones are constant-folded
     operator.eq(2,3)
     operator.__gt__(2,3)
Example #6
0
def cmp_ge(x,y): return _op.ge(x,y)

########################################################################
#
# Type casting functions
#

# Monomorphic casts
@cutype("a -> Int")
Example #7
0
def cmp_ge(x,y): return _op.ge(x,y)

########################################################################
#
# Python built-ins
#
# Reflect built-in Python functions that have special meaning to
# Copperhead.  These wrapper functions allow us to (a) annotate them
# with type attributes and (b) restrict arguments if necessary.
#

@cutype("( (a,a)->a, [a], a ) -> a")
 def test_ge(self):
     self.failUnless(operator.ge(1, 0))
     self.failUnless(operator.ge(1, 0.0))
     self.failUnless(operator.ge(1, 1))
     self.failUnless(operator.ge(1, 1.0))
     self.failIf(operator.ge(1, 2))
     self.failIf(operator.ge(1, 2.0))
Example #9
0
def get_comparision_verdict_with_text(comp_operator,
                                      actual_value,
                                      expected_value,
                                      expected_min_value,
                                      expected_max_value,
                                      property_name):
    """
    comp_operator: Enum comp_operator
    values: for comparision
    property_name: string used for verdict text message.
    Return dictionary with verdict as bool and verdict text
    """

    verdict = False
    expected_filter_string = 'None'
    if comp_operator == 'LESS_THAN':
        verdict = operator.lt(actual_value, expected_value)
        expected_filter_string = ' less than ' + str(expected_value)
    elif comp_operator == 'LESS_THAN_OR_EQUAL':
        verdict = operator.le(actual_value, expected_value)
        expected_filter_string = ' less than or equal to ' + str(expected_value)
    elif comp_operator == 'GREATER_THAN':
        verdict = operator.gt(actual_value, expected_value)
        expected_filter_string = ' greater than ' + str(expected_value)
    elif comp_operator == 'GREATER_THAN_OR_EQUAL':
        verdict = operator.ge(actual_value, expected_value)
        expected_filter_string = ' greater than or equal to ' + str(expected_value)
    elif comp_operator == 'EQUAL':
        verdict = operator.eq(actual_value, expected_value)
        expected_filter_string = ' equal to ' + str(expected_value)
    elif comp_operator == 'NOT_EQUAL':
        verdict = operator.ne(actual_value, expected_value)
        expected_filter_string = ' not equal to ' + str(expected_value)
    elif comp_operator == 'BETWEEN':
        verdict = operator.le(expected_min_value, actual_value) and \
            operator.le(actual_value, expected_max_value)
        expected_filter_string = ' between ' + str(expected_min_value) + \
            ' and ' + str(expected_max_value) + ', inclusive'
    else:
        raise Exception("Unsupported comparision operator {0}".format(comp_operator))

    pass_fail_text = ' does not match '
    if verdict is True:
        pass_fail_text = ' matches '
    verdict_text = 'Actual ' + property_name + pass_fail_text + 'expected ' + \
        property_name + '. Actual count: ' + str(actual_value) + \
        '; expected count:' + expected_filter_string + '.'

    data = {}
    data[ProviderConst.VERDICT] = verdict
    data[ProviderConst.VERDICT_TEXT] = verdict_text
    return data
Example #10
0
 def test_ge(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.ge)
     self.assertTrue(operator.ge(1, 0))
     self.assertTrue(operator.ge(1, 0.0))
     self.assertTrue(operator.ge(1, 1))
     self.assertTrue(operator.ge(1, 1.0))
     self.assertFalse(operator.ge(1, 2))
     self.assertFalse(operator.ge(1, 2.0))
Example #11
0
 def test_ge(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.ge)
     self.assertTrue(operator.ge(1, 0))
     self.assertTrue(operator.ge(1, 0.0))
     self.assertTrue(operator.ge(1, 1))
     self.assertTrue(operator.ge(1, 1.0))
     self.assertFalse(operator.ge(1, 2))
     self.assertFalse(operator.ge(1, 2.0))
Example #12
0
 def test_ge(self):
     self.failUnlessRaises(TypeError, operator.ge)
     self.failUnlessRaises(TypeError, operator.ge, 1j, 2j)
     self.failUnless(operator.ge(1, 0))
     self.failUnless(operator.ge(1, 0.0))
     self.failUnless(operator.ge(1, 1))
     self.failUnless(operator.ge(1, 1.0))
     self.failIf(operator.ge(1, 2))
     self.failIf(operator.ge(1, 2.0))
Example #13
0
 def test_ge(self):
     self.assertRaises(TypeError, operator.ge)
     self.assertRaises(TypeError, operator.ge, 1j, 2j)
     self.assertTrue(operator.ge(1, 0))
     self.assertTrue(operator.ge(1, 0.0))
     self.assertTrue(operator.ge(1, 1))
     self.assertTrue(operator.ge(1, 1.0))
     self.assertFalse(operator.ge(1, 2))
     self.assertFalse(operator.ge(1, 2.0))
Example #14
0
 def test_ge(self):
     self.assertRaises(TypeError, operator.ge)
     self.assertRaises(TypeError, operator.ge, 1j, 2j)
     self.assertTrue(operator.ge(1, 0))
     self.assertTrue(operator.ge(1, 0.0))
     self.assertTrue(operator.ge(1, 1))
     self.assertTrue(operator.ge(1, 1.0))
     self.assertFalse(operator.ge(1, 2))
     self.assertFalse(operator.ge(1, 2.0))
Example #15
0
 def test_ge(self):
     self.failUnlessRaises(TypeError, operator.ge)
     self.failUnlessRaises(TypeError, operator.ge, 1j, 2j)
     self.failUnless(operator.ge(1, 0))
     self.failUnless(operator.ge(1, 0.0))
     self.failUnless(operator.ge(1, 1))
     self.failUnless(operator.ge(1, 1.0))
     self.failIf(operator.ge(1, 2))
     self.failIf(operator.ge(1, 2.0))
def _filter_criterion(filter: Filter) -> any:
    left = parse_parameter(filter.left)
    topic = get_topic_by_id(filter.left.topicId)
    factor = get_factor(filter.left.factorId, topic)
    right = parse_parameter(filter.right, factor)

    if filter.operator == "equals":
        if factor is not None and factor.type == "text":
            return operator.eq(left, right)
        else:
            return operator.eq(left, int(right))
    elif filter.operator == "not-equals":
        if factor is not None and factor.type == "text":
            return left.__ne__(right)
        else:
            return left.__ne__(int(right))
    elif filter.operator == 'empty':
        return left.isnull()
    elif filter.operator == 'not-empty':
        return left.notnull()
    elif filter.operator == "more":
        return operator.gt(left, int(right))
    elif filter.operator == "more-equals":
        return operator.ge(left, int(right))
    elif filter.operator == "less":
        return operator.lt(left, int(right))
    elif filter.operator == "less-equals":
        return operator.le(left, int(right))
    elif filter.operator == 'in':
        value_list = right.split(',')
        values: List = []
        for value in value_list:
            if value.isdigit():
                values.append(int(value))
            else:
                values.append(value)
        return left.isin(values)
    elif filter.operator == 'not-in':
        value_list = right.split(',')
        values: List = []
        for value in value_list:
            if value.isdigit():
                values.append(int(value))
            else:
                values.append(value)
        return left.notin(values)
    else:
        # TODO more operator support
        raise Exception("operator is not supported")
Example #17
0
    def getVehiclesAmount(self, amount, orderBy, invert=False):
        """Return a dictionary that contains 'amount' of Vehicle objects which 
        are at the beginning of the dictionary of vehicles, based on average of 
        the measure represented by 'orderBy'.

        If 'amount' is bigger than the number of vehicles in the dictionary, 
        returns the entire dictionary.

        Keyword arguments:
        amount -- an integer that quantifies the call
        orderBy -- an constant related to Vehicles
        invert -- swap the begin or end of the output

        """
        vehicles = {}
        if ge(amount, 0):
            if ge(amount, self.getSize()):
                return self.vehicles

            #keyOrder = lambda vehicle: sum(vehicle._id)/len(vehicle._id)
            #keyOrder = "_id" sum(vehicle._id)/len(vehicle._id)
            keyOrder = attrgetter("_id")
            #TODO: Arrumar isso
            if (eq(orderBy, VEHICLE_SPEED)):
                keyOrder = lambda vehicle: vehicle.average(VEHICLE_SPEED)

            key = 0
            for vehicle in (sorted(self.vehicles.values(),
                                   key=keyOrder,
                                   reverse=invert)):
                if ge(key, amount):
                    break
                vehicles[len(vehicles)] = vehicle
                key += 1

        return copy.deepcopy(vehicles)
Example #18
0
 def calculate(_oper, _p1, _p2):
     _p1 = int(_p1)
     _p2 = int(_p2)
     if _oper == "lt":
         return operator.lt(_p1, _p2)
     elif _oper == "le":
         return operator.le(_p1, _p2)
     elif _oper == "gt":
         return operator.gt(_p1, _p2)
     elif _oper == "ge":
         return operator.ge(_p1, _p2)
     elif _oper == "eq":
         return operator.eq(_p1, _p2)
     elif _oper == "ne":
         return operator.ne(_p1, _p2)
Example #19
0
def qemu_img_info(path, format=None):
    """Return an object containing the parsed output from qemu-img info."""
    # TODO(mikal): this code should not be referring to a libvirt specific
    # flag.
    if not os.path.exists(path) and CONF.libvirt.images_type != 'rbd':
        raise exception.DiskNotFound(location=path)

    try:
        # The following check is about ploop images that reside within
        # directories and always have DiskDescriptor.xml file beside them
        if (os.path.isdir(path)
                and os.path.exists(os.path.join(path, "DiskDescriptor.xml"))):
            path = os.path.join(path, "root.hds")

        cmd = ('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', path)
        if format is not None:
            cmd = cmd + ('-f', format)
        # Check to see if the qemu version is >= 2.10 because if so, we need
        # to add the --force-share flag.
        if QEMU_VERSION and operator.ge(QEMU_VERSION, QEMU_VERSION_REQ_SHARED):
            cmd = cmd + ('--force-share', )
        out, err = utils.execute(*cmd, prlimit=QEMU_IMG_LIMITS)
    except processutils.ProcessExecutionError as exp:
        if exp.stderr and "No such file or directory" in exp.stderr:
            raise exception.DiskNotFound(location=path)

        # this means we hit prlimits, make the exception more specific
        if exp.exit_code == -9:
            msg = (_("qemu-img aborted by prlimits when inspecting "
                     "%(path)s : %(exp)s") % {
                         'path': path,
                         'exp': exp
                     })
        else:
            msg = (_("qemu-img failed to execute on %(path)s : %(exp)s") % {
                'path': path,
                'exp': exp
            })
        raise exception.InvalidDiskInfo(reason=msg)

    if not out:
        msg = (_("Failed to run qemu-img info on %(path)s : %(error)s") % {
            'path': path,
            'error': err
        })
        raise exception.InvalidDiskInfo(reason=msg)

    return imageutils.QemuImgInfo(out)
Example #20
0
def _filter_criterion(filter: Filter) -> any:
    left = parse_parameter(filter.left)
    # print("left", left)
    right = parse_parameter(filter.right)
    # print("right", right)
    if filter.operator == "equals":
        if right.isdigit():
            return operator.eq(left, int(right))
        else:
            return operator.eq(left, right)
    elif filter.operator == "not-equals":
        if right.isdigit():
            return left.__ne__(int(right))
        else:
            return left.__ne__(right)
    elif filter.operator == 'empty':
        return left.isnull()
    elif filter.operator == 'not-empty':
        return left.notnull()
    elif filter.operator == "more":
        return operator.gt(left, int(right))
    elif filter.operator == "more-equals":
        return operator.ge(left, int(right))
    elif filter.operator == "less":
        return operator.lt(left, int(right))
    elif filter.operator == "less-equals":
        return operator.le(left, int(right))
    elif filter.operator == 'in':
        value_list = right.split(',')
        values: List = []
        for value in value_list:
            if value.isdigit():
                values.append(int(value))
            else:
                values.append(value)
        return left.isin(values)
    elif filter.operator == 'not-in':
        value_list = right.split(',')
        values: List = []
        for value in value_list:
            if value.isdigit():
                values.append(int(value))
            else:
                values.append(value)
        return left.notin(values)
    else:
        # TODO more operator support
        raise Exception("operator is not supported")
Example #21
0
def evalCondition(nameRegister, ope, value):
    register = registerByName(nameRegister)
    print("operateur {} ".format(ope))
    if ope == ">":
        return gt(register, int(value))
    elif ope == "<":
        return lt(register, int(value))
    elif ope == "==":
        return eq(register, int(value))
    elif ope == "!=":
        return ne(register, int(value))
    elif ope == ">=":
        return ge(register, int(value))
    else:
        return le(register, int(value))
    return True
def conditionchecking(opera, a, b):

    if (opera == '>'):
        return operator.gt(a, b)
    elif (opera == '>='):
        return operator.ge(a, b)
    elif (opera == '<'):
        return operator.lt(a, b)
    elif (opera == '<='):
        return operator.le(a, b)
    elif (opera == '<>' or opera == '!='):
        return operator.ne(a, b)
    elif (opera == '='):
        return operator.eq(a, b)
    else:
        print "Wrong operator used. Supported operators are : >, >=, <, <=, <>, !=, = ."
        sys.exit(0)
    def query(self, args):

        c, f, v = args

        df = self._main_model.object_data
        roi_class = False

        if (c == "Size in pixels"):
            try:
                v = float(v)
            except ValueError:
                return None

            if f == "<":
                return df[operator.lt(df[c], v)]
            elif f == ">":
                return df[operator.gt(df[c], v)]
            elif f == "<=":
                return df[operator.le(df[c], v)]
            elif f == ">=":
                return df[operator.ge(df[c], v)]
            elif f == "=":
                return df[operator.eq(df[c], v)]
        else:

            if c in self._main_model.rois.keys():

                path = self.roi_to_path(self._main_model.rois[c][1])

                x = df['Center of the object_1'].values
                y = df['Center of the object_0'].values
                centers = np.transpose(np.vstack([x, y]))
                contains_centers = path.contains_points(centers)
                roi_class = True

            if (f == "INCLUDE") or (f == "="):
                if roi_class:
                    return df.loc[contains_centers]
                else:
                    return df[df['Predicted Class'] == c]
            elif f == "NOT INCLUDE":
                if roi_class:
                    return df.loc[[not x for x in contains_centers]]
                return df[df['Predicted Class'] != c]

        return None
Example #24
0
def secondarySequenceStructure():
    i = 0
    secondary_sequence = ""
    while op.lt(i, len(inputProteinSequence)):
        if op.and_(op.eq(Helix[i], False), op.eq(Strand[i], False)):
            j = i
            while j < len(inputProteinSequence) and op.eq(
                    Helix[j], False) and op.eq(Strand[j], False):
                secondary_sequence += 'T'  #the Turns is signified with T, reporting the empty regions
                j = op.add(j, 1)
            i = j

        elif op.and_(op.eq(Helix[i], True), op.eq(Strand[i], False)):
            j = i
            while op.le(j, len(inputProteinSequence)) and op.eq(
                    Helix[j], True) and op.eq(Strand[j], False):
                secondary_sequence += 'H'  #this is responsible for filling the possible alpha helices
                j = op.add(j, 1)
            i = j

        elif op.and_(op.eq(Helix[i], False), op.eq(Strand[i], True)):
            j = i
            while op.lt(j, len(inputProteinSequence)) and op.eq(
                    Helix[j], False) and op.eq(Strand[j], True):
                secondary_sequence += 'S'  # this loop is responsible for filling the possible beta strands
                j = op.add(j, 1)
            i = j

        elif op.and_(op.eq(Helix[i], True), op.eq(Strand[i], True)):
            j = i
            Helix_sum = 0
            Strand_sum = 0
            while op.lt(j, len(inputProteinSequence)) and op.eq(
                    Helix[j], True) and op.eq(Strand[j], True):
                Helix_sum = op.add(
                    Helix_sum, alphaValues[aminoAcid[inputProteinSequence[j]]])
                Strand_sum = op.add(
                    Strand_sum, betaValues[aminoAcid[inputProteinSequence[j]]])
                j = op.add(j, 1)
            for z in range(i, j):
                if op.ge(Helix_sum, Strand_sum):
                    secondary_sequence = op.add(secondary_sequence, 'H')
                else:
                    secondary_sequence = op.add(secondary_sequence, 'S')
            i = j
    return secondary_sequence
Example #25
0
    def operator_ge(self, app_data, test_data):
        """Compare app data is greater than or equal to tests data.

        Args:
            app_data (dict, list, str): The data created by the App.
            test_data (dict, list, str): The data provided in the test case.

        Returns:
            bool, str: The results of the operator and any error message
        """
        app_data = self._string_to_int_float(app_data)
        test_data = self._string_to_int_float(test_data)
        results = operator.ge(app_data, test_data)
        details = ''
        if not results:
            details = f'{app_data} {type(app_data)} !(>=) {test_data} {type(test_data)}'
        return results, details
Example #26
0
 def select_data_by_threshold(self):
     values_for_plot = []
     column_name = self.choose_column_name()
     comparision_sign = self.input_comparision_sign()
     threshold = self.input_threshold()
     for index in range(len(self.data_frame().index)):
         value = self.data_frame().at[index, column_name]
         comparision_function = {"<": op.lt(value, threshold),
                                 "<=": op.le(value, threshold),
                                 "=": op.eq(value, threshold),
                                 ">=": op.ge(value, threshold),
                                 ">": op.gt(value, threshold)}
         if comparision_function[comparision_sign] == True:
             values_for_plot.append(value)
         else:
             pass
     return values_for_plot
Example #27
0
    def segment(self, message):
        forward_token = self.forward_tokenizer.segment(message)
        backward_token = self.backward_tokenizer.segment(message)

        token_result = [forward_token, backward_token]

        token_count = operator.le(*map(self.compute_token_count, token_result))

        token_granularity = operator.ge(
            *map(self.compute_token_granularity, token_result))

        token_len_variability = operator.le(
            *map(self.compute_token_len_variability, token_result))

        if token_count + token_granularity + token_len_variability >= 2:
            return forward_token
        else:
            return backward_token
Example #28
0
def check_condition(operand_a, oper, operand_b):
    """
    Checks condition:
    \t**operand_a op operand_b**

    where:
    \t\t*operand_a*, *operand_b* - numbers\n
    \t\t*op* - operator = [< | > | <= | >= | == | =]
    Returns True if condition is met, False otherwise.

    :param operand_a: number
    :type operand_a: int
    :param oper: operator = [< | > | <= | >= | == | =]
    :type oper: str
    :param operand_b: number
    :type operand_b: int
    :returns: True if condition is met, False otherwise.
    :raise Exception: when operator is not in [< | > | <= | >= | == | =]
    """

    if isinstance(operand_a, int):
    # if type(operand_a) is not int:
        a_n = int(operand_a)
    else:
        a_n = operand_a

    if isinstance(operand_b, int):
    # if type(operand_b) is not int:
        b_n = int(operand_b)
    else:
        b_n = operand_b

    if oper == "=" or  oper == "==":
        return operator.eq(a_n, b_n)
    elif oper == "<=":
        return operator.le(a_n, b_n)
    elif oper == "<":
        return operator.lt(a_n, b_n)
    elif oper == ">=":
        return operator.ge(a_n, b_n)
    elif oper == ">":
        return operator.gt(a_n, b_n)
    else:
        raise Exception("Not supported operator: " + oper)
Example #29
0
def check_condition(operand_a, oper, operand_b):
    """
    Checks condition:
    \t**operand_a op operand_b**

    where:
    \t\t*operand_a*, *operand_b* - numbers\n
    \t\t*op* - operator = [< | > | <= | >= | == | =]
    Returns True if condition is met, False otherwise.

    :param operand_a: number
    :type operand_a: int
    :param oper: operator = [< | > | <= | >= | == | =]
    :type oper: str
    :param operand_b: number
    :type operand_b: int
    :returns: True if condition is met, False otherwise.
    :raise Exception: when operator is not in [< | > | <= | >= | == | =]
    """

    if isinstance(operand_a, int):
        # if type(operand_a) is not int:
        a_n = int(operand_a)
    else:
        a_n = operand_a

    if isinstance(operand_b, int):
        # if type(operand_b) is not int:
        b_n = int(operand_b)
    else:
        b_n = operand_b

    if oper == "=" or oper == "==":
        return operator.eq(a_n, b_n)
    elif oper == "<=":
        return operator.le(a_n, b_n)
    elif oper == "<":
        return operator.lt(a_n, b_n)
    elif oper == ">=":
        return operator.ge(a_n, b_n)
    elif oper == ">":
        return operator.gt(a_n, b_n)
    else:
        raise Exception("Not supported operator: " + oper)
Example #30
0
def unprivileged_qemu_img_info(path, format=None, qemu_version=None):
    """Return an object containing the parsed output from qemu-img info."""
    try:
        # The following check is about ploop images that reside within
        # directories and always have DiskDescriptor.xml file beside them
        if (os.path.isdir(path)
                and os.path.exists(os.path.join(path, "DiskDescriptor.xml"))):
            path = os.path.join(path, "root.hds")

        cmd = ('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', path)
        if format is not None:
            cmd = cmd + ('-f', format)
        # Check to see if the qemu version is >= 2.10 because if so, we need
        # to add the --force-share flag.
        if qemu_version and operator.ge(qemu_version, QEMU_VERSION_REQ_SHARED):
            cmd = cmd + ('--force-share', )
        out, err = processutils.execute(*cmd, prlimit=QEMU_IMG_LIMITS)
    except processutils.ProcessExecutionError as exp:
        if exp.exit_code == -9:
            # this means we hit prlimits, make the exception more specific
            msg = (_("qemu-img aborted by prlimits when inspecting "
                     "%(path)s : %(exp)s") % {
                         'path': path,
                         'exp': exp
                     })
        elif exp.exit_code == 1 and 'No such file or directory' in exp.stderr:
            # The os.path.exists check above can race so this is a simple
            # best effort at catching that type of failure and raising a more
            # specific error.
            raise exception.DiskNotFound(location=path)
        else:
            msg = (_("qemu-img failed to execute on %(path)s : %(exp)s") % {
                'path': path,
                'exp': exp
            })
        raise exception.InvalidDiskInfo(reason=msg)

    if not out:
        msg = (_("Failed to run qemu-img info on %(path)s : %(error)s") % {
            'path': path,
            'error': err
        })
        raise exception.InvalidDiskInfo(reason=msg)
    return out
Example #31
0
def custom_operator(value1, oper, value2):
    operators = ['=', '!=', '>', '<', '>=', '<=']
    if not oper in operators:
        raise ValueError("Invalid Opeator - Supported operators are only: " +
                         str(operators))
    bool = None
    if oper == '=':
        bool = operator.eq(value1, value2)
    elif oper == '!=':
        bool = operator.ne(value1, value2)
    elif oper == '>':
        bool = operator.gt(value1, value2)
    elif oper == '>=':
        bool = operator.ge(value1, value2)
    elif oper == '<':
        bool = operator.lt(value1, value2)
    elif oper == '<=':
        bool = operator.le(value1, value2)
    return bool
Example #32
0
def qemu_img_info(path, format=None):
    """Return an object containing the parsed output from qemu-img info."""
    # TODO(mikal): this code should not be referring to a libvirt specific
    # flag.
    if not os.path.exists(path) and CONF.libvirt.images_type != 'rbd':
        raise exception.DiskNotFound(location=path)

    try:
        # The following check is about ploop images that reside within
        # directories and always have DiskDescriptor.xml file beside them
        if (os.path.isdir(path) and
            os.path.exists(os.path.join(path, "DiskDescriptor.xml"))):
            path = os.path.join(path, "root.hds")

        cmd = ('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', path)
        if format is not None:
            cmd = cmd + ('-f', format)
        # Check to see if the qemu version is >= 2.10 because if so, we need
        # to add the --force-share flag.
        if QEMU_VERSION and operator.ge(QEMU_VERSION, QEMU_VERSION_REQ_SHARED):
            cmd = cmd + ('--force-share',)
        out, err = utils.execute(*cmd, prlimit=QEMU_IMG_LIMITS)
    except processutils.ProcessExecutionError as exp:
        if exp.exit_code == -9:
            # this means we hit prlimits, make the exception more specific
            msg = (_("qemu-img aborted by prlimits when inspecting "
                    "%(path)s : %(exp)s") % {'path': path, 'exp': exp})
        elif exp.exit_code == 1 and 'No such file or directory' in exp.stderr:
            # The os.path.exists check above can race so this is a simple
            # best effort at catching that type of failure and raising a more
            # specific error.
            raise exception.DiskNotFound(location=path)
        else:
            msg = (_("qemu-img failed to execute on %(path)s : %(exp)s") %
                   {'path': path, 'exp': exp})
        raise exception.InvalidDiskInfo(reason=msg)

    if not out:
        msg = (_("Failed to run qemu-img info on %(path)s : %(error)s") %
               {'path': path, 'error': err})
        raise exception.InvalidDiskInfo(reason=msg)

    return imageutils.QemuImgInfo(out)
Example #33
0
def _query_chunks(query, model, orderings, chunk_size):
  """Paginate query by chunks of specific size.

  The main difference here from util functions generating chunkyfied query
  provided in utils module is that here no offset is used. Chunks are queried
  here using filters which is faster comparing to offsets in case of large
  number of records in query.

  Args:
      query: Query to be paginated.
      model: Model used in `query`.
      orderings: Orderings used in `query`.
      chunk_size: Size of chunks.

  Yields:
      Objects in chunks from query query.
  """
  filters = [sa.true() for _ in orderings]
  count = query.count()
  for _ in range(0, count, chunk_size):
    # Pagination is performed by filtering here insted of using offset since
    # using offset with large values is much slower than plain filtering.
    paginated_q = query.from_self().filter(*filters).limit(chunk_size)
    chunk = paginated_q.all()
    yield chunk
    if chunk:
      # Filters should be recalculated here to return new chunk on next iter.
      # New filters should be in form "ordering field >= last in chunk" except
      # for the last field in orderings - this one should be > last in chunk.
      ge_filter_fields, gt_filter_field = orderings[:-1], orderings[-1]
      last_in_chunk = chunk[-1]

      filters = [
          op.ge(getattr(model, field), getattr(last_in_chunk, field))
          for field in ge_filter_fields
      ]
      filters.append(
          op.gt(
              getattr(model, gt_filter_field),
              getattr(last_in_chunk, gt_filter_field),
          )
      )
Example #34
0
def checkOP(op, a, b):
    # print(a, b)
    if op == ">":
        # print("GREATER THAN")
        return (operator.gt(a, b))
    elif op == "<":
        # print("LESS THAN")
        return (operator.lt(a, b))
    elif op == ">=":
        # print("GREATER EQUAL")
        return (operator.ge(a, b))
    elif op == "<=":
        # print("LESS EQUAL")
        return (operator.le(a, b))
    elif op == "==":
        # print("EQUAL")
        return (operator.eq(a, b))
    elif op == "!=":
        # print("NOT EQUAL")
        return (operator.ne(a, b))
Example #35
0
async def blink(canvas, row, column, behaviors, init_delay, symbol):

    assert all(ge(i, 0) for i in (row, column, init_delay)), AssertionError(
        "row, column and delay have to be non-negative")
    assert symbol.isprintable(), AssertionError("Star symbol has to be printable")

    # init star
    _, *star_attr = next(behaviors)
    canvas.addstr(row, column, symbol, *star_attr)

    # delay for randomizing time of start star's blinking
    for _ in range(init_delay):
        await asyncio.sleep(0)

    for timeout, *star_attr in behaviors:

        canvas.addstr(row, column, symbol, *star_attr)

        for _ in range(timeout):
            await asyncio.sleep(0)
def relatnl_opr(opr, a, b):
    # print opr[0]
    if (opr[0] == '>'):
        if (len(opr) == 1):
            ans = operator.gt(a, b)
        else:
            ans = operator.ge(a, b)
    elif (opr[0] == '<'):
        if (len(opr) == 1):
            ans = operator.lt(a, b)
        else:
            ans = operator.le(a, b)

    elif (opr == '='):
        ans = operator.eq(a, b)
    elif (opr == '<>' or opr == '!='):
        ans = operator.ne(a, b)
    else:
        print "check operators.Supported operators are : >, >=, <, <=, <>, !=, = ."
        sys.exit(0)
    return ans
 def generate_state(self):
     start_len = len(self.user_create.alluser_sequence)
     capacility = copy.deepcopy(self.capacility_create.capacility_state)
     if len(self.user_create.alluser_sequence) > 0:
         # print(len(self.user_create.alluser_sequence))
         nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         i = 0;
         while i < len(self.user_create.alluser_sequence):
             user_attributes = self.user_create.alluser_sequence[i]
             user_leavetime = user_attributes[-1]
             if op.ge(nowTime, user_leavetime):
                 self.user_create.alluser_sequence.remove(user_attributes)
                 actions = self.user_create.alluser_action[i]
                 del self.user_create.alluser_action[i]
                 self.capacility_create.compute_increase_capacility(actions)
                 i-=1
             i+=1
     end_len = len(self.user_create.alluser_sequence)
     print(end_len-start_len,self.capacility_create.capacility_state-capacility)
     self.user_create.Imitate_User()
     self.user_create.alluser_sequence.extend(self.user_create.currentuser_sequence)
Example #38
0
    def get_mapped_value(
            cls,
            collection,
            original_val,
            arithmetic_type=cons.ARITHMETIC_LEFT_CLOSE_RIGHT_OPEN):
        """
        从指定的数据集合中,获取映射之后的值;
        运算类型支持左开右闭、左闭右开,默认是左闭右开;

        :param collection  要使用的映射的集合,数据结构需要满足如下格式:
            [("博士", 1), ("硕士", 2)] 或者 [([0, 100], 1), ([100, 10000], 2)]

        :param original_val  被映射的原始值
        :param arithmetic_type  运算类型,默认是左闭右开,映射只是一对一映射时,此参数无效

        :return: 被映射之后的值
        """
        if not isinstance(collection, Iterable):
            raise

        mapped_value = None

        for item in collection:
            if isinstance(item, tuple) and \
                    operator.ge(len(item), cls.mapped_tuple_length):
                mapped_option = item[0]
                if isinstance(mapped_option, basestring):
                    if mapped_option == original_val:
                        mapped_value = item[1]
                        break
                elif isinstance(mapped_option, list):
                    is_hit = cls._arithmetic_by_type(
                        mapped_option,
                        original_val,
                        arithmetic_type=arithmetic_type)
                    if is_hit:
                        mapped_value = item[1]
                        break

        return mapped_value
Example #39
0
    def filter_out_values(self, filtering_variable, filtering_value, filtering_operator):

        column_of_filtering_variable = self.pre_processed_dataset[filtering_variable]
        dataset = self.pre_processed_dataset
        if self.pre_processed_column_types_pd_series[filtering_variable].kind == 'f':
            filtering_value = float(filtering_value)
        if self.pre_processed_column_types_pd_series[filtering_variable].kind == 'i':
            filtering_value = int(filtering_value)
        if filtering_operator == 'Equal to':
            self.pre_processed_dataset = dataset[~operator.eq(column_of_filtering_variable, filtering_value)]
        elif filtering_operator == 'Not equal to':
            self.pre_processed_dataset = dataset[~operator.ne(column_of_filtering_variable, filtering_value)]
        elif filtering_operator == 'Less than':
            self.pre_processed_dataset = dataset[~operator.lt(column_of_filtering_variable, filtering_value)]
        elif filtering_operator == 'Less than or equal to':
            self.pre_processed_dataset =dataset[~operator.le(column_of_filtering_variable, filtering_value)]
        elif filtering_operator == 'Greater than':
            self.pre_processed_dataset = dataset[~operator.gt(column_of_filtering_variable, filtering_value)]
        elif filtering_operator == 'Greater than or equal to':
            self.pre_processed_dataset =dataset[~operator.ge(column_of_filtering_variable, filtering_value)]

        self.update_datasets_info()
Example #40
0
    def find_highlight_site(self, content, grade):
        # self.highlight_list, self.synonyms = self.load_dictionary()
        new_highlight = self.remove_synonyms(content, grade)
        repeat_list = list()  # Duplicate word list
        for m in range(len(new_highlight)):
            flag = new_highlight[m]
            for n in range(m + 1, len(new_highlight)):
                target = new_highlight[n]
                if flag in target or target in flag:
                    # repeat = "".join([flag[i] for i in range(len(flag)) if flag[i] == target[i]])
                    repeat = self.getNumofCommonSubStr(target, flag)
                    if flag == repeat:
                        repeat_list.append(new_highlight[m])
                        break
                    elif target == repeat:
                        repeat_list.append(new_highlight[n])
                        break
        new_list = list()  # New list of highlighted words
        for every in new_highlight:
            if every not in repeat_list:
                new_list.append(every)

        highlight_site = list()
        high_num = 0
        for high in new_list:
            index = re.search(
                r'(?<= )' + high + r'(?!=[a-zA-Z])', content
            )  # Find the position of the highlighted word in the essay
            position = list(index.span())
            zip_list = dict(zip(high, position))
            highlight_site.append([high, position])
            # highlist_sort = highlight_res.sort(key=lambda elem:elem[1])
            high_num += 1
            if operator.ge(high_num, 10):
                high_num = 10
            elif operator.lt(high_num, 10):
                high_num = high_num
        highlight_site.sort(key=lambda x: int(x[1][0]))
        return highlight_site, high_num
def get_numeric_filter(value: str, field):
    '''
        Gets numeric or date filter from string value.

        Args:
            value (str): A string value. May start with '<=,>=,<, or >'
            field (any): A field object that we can apply an operation on. Examples are pypika fields, and pysnow fields.
        Returns:
            (any): A criterion object. Examples are pypika Criterion, and pysnow Criterion.
    '''
    if value.startswith('>='):
        f = op.ge(field, value[2:])
    elif value.startswith('<='):
        f = op.le(field, value[2:])
    elif value.startswith('>'):
        f = op.gt(field, value[1:])
    elif value.startswith('<'):
        f = op.lt(field, value[1:])
    else:
        f = field == value

    return f
Example #42
0
def __version_compare_tuple(t1, compare, t2):

    # Make both versions the same length
    if len(t1) < len(t2):
        for i in range(len(t1), len(t2)):
            t1.append(0)
    elif len(t2) < len(t1):
        for i in range(len(t2), len(t1)):
            t2.append(0)

    if compare == '<':
        return operator.lt(t1, t2)
    elif compare == '<=':
        return operator.le(t1, t2)
    elif compare == '=' or compare == '==':
        return operator.eq(t1, t2)
    elif compare == '!=':
        return operator.ne(t1, t2)
    elif compare == '>=':
        return operator.ge(t1, t2)
    elif compare == '>':
        return operator.gt(t1, t2)
    else:
        raise ValueError('Invalid operator')
Example #43
0
	def execute_binary_operator(cls, val, x, y):
		"""Execute binary operators
		
		Execute binary operator
		
		Arguments:
			val {int} -- int
			x {int} -- int
			y {int} -- int
		
		Returns:
			int -- operation result
		"""

		if val == 0:
			return operator.add(x,y)
		elif val == 1:
			return operator.sub(x,y)
		elif val == 2:
			return operator.mul(x,y)
		elif val == 3:
			return operator.div(x,y)
		elif val == 4:
			return operator.lt(x,y)
		elif val == 5:
			return operator.gt(x,y)
		elif val == 6:
			return operator.le(x,y)
		elif val == 7:
			return operator.ge(x,y)
		elif val == 8:
			return operator.eq(x,y)
		elif val == 9:
			return operator.ne(x,y)
		elif val == 12:
			return operator.mod(x,y)
from functools import reduce
import sys, platform
import time, os, json, re, datetime, math, operator
import concurrent.futures
import requests
import argparse
from pathlib import Path
import dateutil.parser

if platform.system() == 'Windows':
    if operator.ge(*map(lambda version: list(map(int, version.split('.'))),
                        [platform.version(), '10.0.14393'])):
        os.system('')
    else:
        import colorama
        colorama.init()

try:
    requests.packages.urllib3.disable_warnings(
        requests.packages.urllib3.exceptions.InsecureRequestWarning)
except:
    pass

parser = argparse.ArgumentParser(prog='weiboPicDownloader')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-u',
                   metavar='user',
                   dest='users',
                   nargs='+',
                   help='specify nickname or id of weibo users')
group.add_argument('-f',
Example #45
0
def ge(a, b):
    return operator.ge(a, b)
Example #46
0
 def ge_usecase(x, y):
     return operator.ge(x, y)
Example #47
0
	return """<a href="/desk#!Form/%(doctype)s/%(name)s">%(label)s</a>""" % locals()

operator_map = {
	# startswith
	"^": lambda (a, b): (a or "").startswith(b),

	# in or not in a list
	"in": lambda (a, b): operator.contains(b, a),
	"not in": lambda (a, b): not operator.contains(b, a),

	# comparison operators
	"=": lambda (a, b): operator.eq(a, b),
	"!=": lambda (a, b): operator.ne(a, b),
	">": lambda (a, b): operator.gt(a, b),
	"<": lambda (a, b): operator.lt(a, b),
	">=": lambda (a, b): operator.ge(a, b),
	"<=": lambda (a, b): operator.le(a, b),
	"not None": lambda (a, b): a and True or False,
	"None": lambda (a, b): (not a) and True or False
}

def compare(val1, condition, val2):
	ret = False
	if condition in operator_map:
		ret = operator_map[condition]((val1, val2))

	return ret

def scrub_urls(html):
	html = expand_relative_urls(html)
	html = quote_urls(html)
Example #48
0
 def __operator__(self, attr, value_list):
     if value_list[0] and not value_list[1]:
         return operator.ge(attr, value_list[0])
     elif value_list[1] and not value_list[0]:
         return operator.le(attr, value_list[1])
     return attr.between(value_list[0], value_list[1])
Example #49
0
    def mt_filter(self):
        number_of_rows = self.mtTableWidget.rowCount()
        for row_index in xrange(number_of_rows):

            # Retrieve text / value of filter widgets
            sequence_filter = str(self.mtFilterBySequenceComboBox.currentText())
            shot_filter = str(self.mtFilterByShotComboBox.currentText())
            department_filter = self.mtFilterByDeptComboBox.currentText()
            status_filter = self.mtFilterByStatusComboBox.currentText()
            member_filter = self.mtFilterByMemberComboBox.currentText()
            daysleft_filter = self.mtFilterByDaysLeftSpinBox.value()
            daysleft_operation = self.mtDaysLeftComboBox.currentText()
            bid_filter = self.mtFilterByBidComboBox.value()
            bid_operation = self.mtBidOperationComboBox.currentText()

            if self.mtMeOnlyCheckBox.checkState():
                member_filter = self.members[self.username]

            # Retrieve value of current row items
            task_id = str(self.mtTableWidget.item(row_index, 0).text())
            task = self.Task(self, task_id)
            task.get_infos_from_id()

            # If task is not confirmed, hide it:
            if task.confirmation == "0" and task.status != "Done":
                self.mtTableWidget.hideRow(row_index)
                continue

            # If filters are set to default value, set the filters variables to the current row values
            if sequence_filter == "None": sequence_filter = task.sequence
            if shot_filter == "None": shot_filter = task.shot
            if department_filter == "None": department_filter = task.department
            if status_filter == "None" : status_filter = task.status
            if member_filter == "None" : member_filter = task.assignation
            for shortname, longname in self.members.iteritems():
                if longname == member_filter:
                    member_filter = shortname

            days_left = QtCore.QDate.currentDate().daysTo(QtCore.QDate.fromString(task.end, "dd/MM/yyyy"))
            if daysleft_filter == 0:
                daysleft_filter = days_left

            if bid_filter == 0: bid_filter = task.bid

            if str(bid_operation) == ">=": bid_result = operator.le(int(bid_filter), int(task.bid))
            elif str(bid_operation) == "<=": bid_result = operator.ge(int(bid_filter), int(task.bid))

            if str(daysleft_operation) == ">=": days_left_result = operator.le(int(daysleft_filter), int(days_left))
            elif str(daysleft_operation) == "<=": days_left_result = operator.ge(int(daysleft_filter), int(days_left))

            if sequence_filter == task.sequence and shot_filter == task.shot and department_filter == task.department and status_filter == task.status and str(member_filter) == str(task.assignation) and bid_result and days_left_result:
                if self.mtHideDoneCheckBox.isChecked():
                    if task.status == "Done":
                        self.mtTableWidget.hideRow(row_index)
                    else:
                        self.mtTableWidget.showRow(row_index)
                else:
                    self.mtTableWidget.showRow(row_index)
            else:
                self.mtTableWidget.hideRow(row_index)

        self.mtTableWidget.resizeColumnsToContents()
        self.mtTableWidget.horizontalHeader().setResizeMode(1, QtGui.QHeaderView.Stretch)
Example #50
0
 def __call__(self, x, y):
     return operator.ge(x, y)
Example #51
0
 def __ge__(self, other): return operator.ge(self.value, other)
 def __le__(self, other): return operator.le(self.value, other)
    def _satisfies_extra_specs(self, capabilities, instance_type):
        """Check that the capabilities provided by the compute service
        satisfy the extra specs associated with the instance type"""
        if 'extra_specs' not in instance_type:
            return True

        # Now, it can do various operations:
        #   =, s==, s!=, s>=, s>, s<=, s<, <in>, <or>, ==, !=, >=, <=
        op_methods = {'=': lambda x, y: (float(x) >= float(y)),
                      '=+': lambda x, y: (float(x) >= float(y)),
                      '=-': lambda x, y: (float(x) >= float(y)),
                      '<in>': lambda x, y: (x.find(y) != -1),
                      '==': lambda x, y: (float(x) == float(y)),
                      '==+': lambda x, y: (float(x) == float(y)),
                      '==-': lambda x, y: (float(x) == float(y)),
                      '!=': lambda x, y: (float(x) != float(y)),
                      '!=+': lambda x, y: (float(x) != float(y)),
                      '!=-': lambda x, y: (float(x) != float(y)),
                      '>=': lambda x, y: (float(x) >= float(y)),
                      '>=+': lambda x, y: (float(x) >= float(y)),
                      '>=-': lambda x, y: (float(x) >= float(y)),
                      '<=': lambda x, y: (float(x) <= float(y)),
                      '<=+': lambda x, y: (float(x) <= float(y)),
                      '<=-': lambda x, y: (float(x) <= float(y)),
                      's==': lambda x, y: operator.eq(x, y),
                      's!=': lambda x, y: operator.ne(x, y),
                      's<': lambda x, y: operator.lt(x, y),
                      's<=': lambda x, y: operator.le(x, y),
                      's>': lambda x, y: operator.gt(x, y),
                      's>=': lambda x, y: operator.ge(x, y)}

        cap_extra_specs = capabilities.get('instance_type_extra_specs', None)
        for key, req in instance_type['extra_specs'].iteritems():
            cap = cap_extra_specs.get(key, None)
            if cap == None:
                return False
            if (type(req) == BooleanType or type(req) == IntType or
                type(req) == LongType or type(req) == FloatType):
                    if cap != req:
                        return False
            else:
                words = req.split()
                if len(words) == 1:
                    if cap != req:
                        return False
                else:
                    op = words[0]
                    method = op_methods.get(op)
                    new_req = words[1]
                    for i in range(2, len(words)):
                        new_req += words[i]

                    if op == '<or>':  # Ex: <or> v1 <or> v2 <or> v3
                        found = 0
                        for idx in range(1, len(words), 2):
                            if words[idx] == cap:
                                found = 1
                                break
                        if found == 0:
                            return False
                    elif method:
                        if method(cap, new_req) == False:
                            return False
                    else:
                        if cap != req:
                            return False
        return True
Example #53
0
		return get_url(uri = "desk#query-report/{0}".format(quoted(name)))

operator_map = {
	# startswith
	"^": lambda a, b: (a or "").startswith(b),

	# in or not in a list
	"in": lambda a, b: operator.contains(b, a),
	"not in": lambda a, b: not operator.contains(b, a),

	# comparison operators
	"=": lambda a, b: operator.eq(a, b),
	"!=": lambda a, b: operator.ne(a, b),
	">": lambda a, b: operator.gt(a, b),
	"<": lambda a, b: operator.lt(a, b),
	">=": lambda a, b: operator.ge(a, b),
	"<=": lambda a, b: operator.le(a, b),
	"not None": lambda a, b: a and True or False,
	"None": lambda a, b: (not a) and True or False
}

def evaluate_filters(doc, filters):
	'''Returns true if doc matches filters'''
	if isinstance(filters, dict):
		for key, value in iteritems(filters):
			f = get_filter(None, {key:value})
			if not compare(doc.get(f.fieldname), f.operator, f.value):
				return False

	elif isinstance(filters, (list, tuple)):
		for d in filters:
Example #54
0
    def filter(self):

        number_of_rows = self.tmTableWidget.rowCount()
        for row_index in xrange(number_of_rows):
            # Retrieve text / value of filter widgets
            sequence_filter = str(self.tmFilterBySequenceComboBox.currentText())
            shot_filter = str(self.tmFilterByShotComboBox.currentText())
            department_filter = self.tmFilterByDeptComboBox.currentText()
            status_filter = self.tmFilterByStatusComboBox.currentText()
            member_filter = self.tmFilterByMemberComboBox.currentText()
            daysleft_filter = self.tmFilterByDaysLeftComboBox.value()
            daysleft_operation = self.tmDaysLeftOperationComboBox.currentText()
            bid_filter = self.tmFilterByBidComboBox.value()
            bid_operation = self.tmBidOperationComboBox.currentText()

            task_id = str(self.tmTableWidget.item(row_index, 0).text())
            task = self.Task(self, task_id)
            task.get_infos_from_id()

            # If filters are set to default value, set the filters variables to the current row values
            if sequence_filter == "None": sequence_filter = task.sequence
            if shot_filter == "None": shot_filter = task.shot
            if department_filter == "None": department_filter = task.department
            if status_filter == "None" : status_filter = task.status
            if member_filter == "None" : member_filter = self.members[task.assignation]
            if bid_filter == 0: bid_filter = task.bid
            days_left = QtCore.QDate.currentDate().daysTo(QtCore.QDate.fromString(task.end, "dd/MM/yyyy"))
            if daysleft_filter == 0:
                daysleft_filter = days_left

            if str(bid_operation) == ">=": bid_result = operator.le(int(bid_filter), int(task.bid))
            elif str(bid_operation) == "<=": bid_result = operator.ge(int(bid_filter), int(task.bid))

            if str(daysleft_operation) == ">=": days_left_result = operator.le(int(daysleft_filter), int(days_left))
            elif str(daysleft_operation) == "<=": days_left_result = operator.ge(int(daysleft_filter), int(days_left))

            if sequence_filter == task.sequence and shot_filter == task.shot and department_filter == task.department and status_filter == task.status and member_filter == self.members[task.assignation] and bid_result and days_left_result:
                # Check each row for "Done" and "Confirmed"
                if self.tmHideDoneCheckBox.isChecked() and self.tmHideConfirmedCheckBox.isChecked():
                    if task.status == "Done":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    if task.confirmation == "1":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                # Check each row for "Done" only
                elif self.tmHideDoneCheckBox.isChecked() and not self.tmHideConfirmedCheckBox.isChecked():
                    if task.status == "Done":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                # Check each row for "Confirmed" only
                elif not self.tmHideDoneCheckBox.isChecked() and self.tmHideConfirmedCheckBox.isChecked():
                    if task.confirmation == "1":
                        self.tmTableWidget.hideRow(row_index)
                        continue
                    self.tmTableWidget.showRow(row_index)
                else:
                    self.tmTableWidget.showRow(row_index)
            else:
                self.tmTableWidget.hideRow(row_index)

        self.tmTableWidget.resizeColumnsToContents()
        self.tmTableWidget.horizontalHeader().setResizeMode(1, QtGui.QHeaderView.Stretch)
    def test_view_set(self):
        oc = NSDictionary(a=1, b=2, c=3, d=4, e=5)

        v = oc.viewkeys() | {'a', 'f' }
        self.assertEqual(v, {'a', 'b', 'c', 'd', 'e', 'f' })
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.or_, ('a', 'f'), oc.keys())

        v = oc.viewkeys() & {'a', 'f' }
        self.assertEqual(v, {'a'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.and_, ('a', 'f'), oc.keys())

        v = oc.viewkeys() ^ {'a', 'f' }
        self.assertEqual(v, {'b', 'c', 'd', 'e', 'f'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.xor, ('a', 'f'), oc.keys())

        v = oc.viewkeys() - {'a', 'f' }
        self.assertEqual(v, {'b', 'c', 'd', 'e'})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewkeys(), ('a', 'f'))
        self.assertRaises(TypeError, operator.sub, ('a', 'f'), oc.keys())

        self.assertTrue(operator.lt(oc.viewkeys(), ('a', 'f')))
        self.assertTrue(operator.le(oc.viewkeys(), ('a', 'f')))
        self.assertFalse(operator.gt(oc.viewkeys(), ('a', 'f')))
        self.assertFalse(operator.ge(oc.viewkeys(), ('a', 'f')))



        v = oc.viewvalues() | {1, 9 }
        self.assertEqual(v, {1,2,3,4,5,9})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.or_, (1, 9), oc.viewvalues())

        v = oc.viewvalues() & {1, 9 }
        self.assertEqual(v, {1})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.and_, (1, 9), oc.viewvalues())

        v = oc.viewvalues() ^ {1, 9 }
        self.assertEqual(v, {2, 3, 4, 5, 9})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.xor, (1, 9), oc.viewvalues())

        v = oc.viewvalues() - {1, 9 }
        self.assertEqual(v, {2,3,4,5})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewvalues(), (1, 9))
        self.assertRaises(TypeError, operator.sub, (1, 9), oc.viewvalues())

        self.assertTrue(operator.lt(oc.viewvalues(), (1, 9)))
        self.assertTrue(operator.le(oc.viewvalues(), (1, 9)))
        self.assertFalse(operator.gt(oc.viewvalues(), (1, 9)))
        self.assertFalse(operator.ge(oc.viewvalues(), (1, 9)))



        v = oc.viewitems() | {('a', 1), ('f', 9) }
        self.assertEqual(v, {('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 9)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.or_, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.or_, (1, 9), oc.viewitems())

        v = oc.viewitems() & {('a',1), ('f',9)}
        self.assertEqual(v, {('a', 1)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.and_, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.and_, (('a', 1), ('f', 9)), oc.viewitems())

        v = oc.viewitems() ^ {('a',1), ('f',9)}
        self.assertEqual(v, {('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 9)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.xor, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.xor, (('a', 1), ('f', 9)), oc.viewitems())

        v = oc.viewitems() - {('a',1), ('f',9)}
        self.assertEqual(v, {('b', 2), ('c', 3), ('d', 4), ('e', 5)})
        self.assertIsInstance(v, set)
        self.assertRaises(TypeError, operator.sub, oc.viewitems(), (('a', 1), ('f', 9)))
        self.assertRaises(TypeError, operator.sub, (('a', 1), ('f', 9)), oc.viewitems())

        self.assertTrue(operator.lt(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertTrue(operator.le(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertFalse(operator.gt(oc.viewitems(), (('a', 1), ('f', 9))))
        self.assertFalse(operator.ge(oc.viewitems(), (('a', 1), ('f', 9))))
Example #56
0
 def __le__(self, other):
     return operator.ge(self.obj, other.obj)
from sys import version_info

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

if version_info[0] > 2:
    raise AnsibleError(('Trellis does not yet support Python {}.{}.{}. \n'
        'Please use Python 2.7.').format(version_info[0], version_info[1], version_info[2]))

version_requirement = '2.4.0.0'
version_tested_max = '2.5.3'

if not ge(LooseVersion(__version__), LooseVersion(version_requirement)):
    raise AnsibleError(('Trellis no longer supports Ansible {}.\n'
        'Please upgrade to Ansible {} or higher.').format(__version__, version_requirement))
elif gt(LooseVersion(__version__), LooseVersion(version_tested_max)):
    display.warning(u'You Ansible version is {} but this version of Trellis has only been tested for '
            u'compatability with Ansible {} -> {}. It is advisable to check for Trellis updates or '
            u'downgrade your Ansible version.'.format(__version__, version_requirement, version_tested_max))

if eq(LooseVersion(__version__), LooseVersion('2.5.0')):
    display.warning(u'You Ansible version is {}. Consider upgrading your Ansible version to avoid '
            u'erroneous warnings such as `Removed restricted key from module data...`'.format(__version__))

# Import BaseVarsPlugin after Ansible version check.
# Otherwise import error for Ansible versions older than 2.4 would prevent display of version check message.
from ansible.plugins.vars import BaseVarsPlugin
Example #58
0
 def __ge__(self, other):
     return operator.ge(self.to_timestamp(), other.to_timestamp())