def check_nodding(value): if not isinstance(value, list): raise v.ValidateError("expected list, found %s" % (value,)) feed_a = v.is_integer(value[0], min=0) feed_b = v.is_integer(value[1], min=0) duration = v.is_float(value[2], min=0) sequence = check_nodding_sequence(value[3][1:-1]) #strip [ and ] return NoddingScan((feed_a, feed_b), duration, sequence)
def is_octal(value, min_val=None, max_val=None): """ Coerces a value to octal """ if not isinstance(value, str): return validate.is_integer(value, min_val, max_val) try: value = int(value, 8) except ValueError: raise validate.VdtTypeError(value) return validate.is_integer(value, min_val, max_val)
def parse_extra_into_dict(lines, convert_bool=True): """ Creates a dictionary out of key=value lines. """ _extra = {} if lines: extra = ';'.join(lines.splitlines()) for line in extra.split(';'): original_line = line if line: line = line.split('=') if not len(line) == 2: raise ValueError('Each line must be a single key=value entry, not [{}]'.format(original_line)) key, value = line value = value.strip() if convert_bool: try: value = is_boolean(value) except VdtTypeError: # It's cool, not a boolean pass try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass _extra[key.strip()] = value return _extra
def parse_extra_into_dict(lines): """ Creates a dictionary out of key=value lines. """ _extra = {} if lines: extra = ';'.join(lines.splitlines()) for line in extra.split(';'): original_line = line if line: line = line.split('=') if not len(line) == 2: raise ValueError('Each line must be a single key=value entry, not [{}]'.format(original_line)) key, value = line value = value.strip() try: value = is_boolean(value) except VdtTypeError: # It's cool, not a boolean pass try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass _extra[key.strip()] = value return _extra
def check_skydip_scan(value): if not isinstance(value, list): raise v.ValidateError("expected list, found %s" % (value,)) start = angle_parser.check_angle(value[0]) stop = angle_parser.check_angle(value[1]) duration = v.is_integer(value[2], min=1) return SkydipScan(start, stop, duration)
def is_octal(value, min_val=None, max_val=None): """ Coerces a value to octal """ if sys.version_info[0] < 3: if not isinstance(value, StringTypes): return validate.is_integer(value, min_val, max_val) else: if not isinstance(value, str): return validate.is_integer(value, min_val, max_val) try: value = int(value, 8) except ValueError: raise validate.VdtTypeError(value) return validate.is_integer(value, min_val, max_val)
def _is_int_or_none(self, value, min=None, max=None): """ Validation function for an integer values or None. Reference: https://github.com/DiffSK/configobj/blob/master/src/configobj/validate.py """ if value in set((None, 'none', 'None')): return None else: return is_integer(value, min=min, max=max)
def integer_scalar_or_integer_numpy_array_check(value, min=None, max=None): """ Parse and validate `value` as an integer number if possible and, if not, parse it as a numpy array (of integers). Value can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. The difference regarding the `integer_numpy_array_check` function is that if value is a single number it will be parsed as a single integer value, instead of being parsed as an integer numpy array with a single element. Parameters ---------- value : str The string to be converted. This can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. min : int The minimum allowed value. If the converted value is (or have) lower than `min` then the VdtValueTooSmallError exception will be raised. max : int The maximum allowed value. If the converted value is (or have) greater than `man` then the VdtValueTooSmallError exception will be raised. Returns ------- numpy array The parsed numpy array. Notes ----- You can either separate the values with commas or spaces (any comma will have the same effect as a space). However, if you separate with spaces the values should be brackets, while if you separate with commands there should be no brackets. .. code:: max_iter = 5,10:20 max_iter = [0 5 10:20] """ try: value = validate.is_integer(value, min, max) except validate.VdtTypeError: value = integer_numpy_array_check(value, min, max) return value
def integer_scalar_or_integer_numpy_array_check( value: Union[str, List[str]], min: Optional[int] = None, max: Optional[int] = None) -> Union[int, List[int]]: """ Parse and validate `value` as an integer number if possible and, if not, parse it as a numpy array (of integers). Value can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. The difference regarding the `integer_numpy_array_check` function is that if value is a single number it will be parsed as a single integer value, instead of being parsed as an integer numpy array with a single element. Parameters ---------- value : str The string to be converted. This can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. min : int The minimum allowed value. If the converted value is (or have) lower than `min` then the VdtValueTooSmallError exception will be raised. max : int The maximum allowed value. If the converted value is (or have) greater than `man` then the VdtValueTooSmallError exception will be raised. Returns ------- int | List[int] The parsed numpy array. Notes ----- You can either separate the values with commas or spaces (any comma will have the same effect as a space). However, if you separate with spaces the values should be brackets, while if you separate with commands there should be no brackets. >> max_iter = 5,10:20 >> max_iter = [0 5 10:20] """ try: return cast(int, validate.is_integer(value, min, max)) except validate.VdtTypeError: return integer_numpy_array_check(value, min, max)
def parse_qs_value(self, value): try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass # Could be a dict or another simple type then try: value = literal_eval(value) except Exception: pass # OK, let's just treat it as string return value
def __init__(self, name, config, config_no_sensitive): self.name = name self.config = config self.logger = getLogger(self.__class__.__name__) # Safe for printing out to logs, any sensitive data has been shadowed self.config_no_sensitive = config_no_sensitive _extra = {} extra = self.config.get('extra') # Will be None at times if extra: extra = ';'.join(extra.splitlines()) for line in extra.split(';'): original_line = line if line: line = line.split('=') if not len(line) == 2: raise ValueError( 'Each line must be a single key=value entry, not [{}]' .format(original_line)) key, value = line value = value.strip() try: value = is_boolean(value) except VdtTypeError: # It's cool, not a boolean pass try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass _extra[key.strip()] = value engine_url = engine_def.format(**config) self.engine = create_engine(engine_url, pool_size=int(config['pool_size']), **_extra) event.listen(self.engine, 'checkin', self.on_checkin) event.listen(self.engine, 'checkout', self.on_checkout) event.listen(self.engine, 'connect', self.on_connect) event.listen(self.engine, 'first_connect', self.on_first_connect)
def any_checker(value): ''' Convert value to its built-in data type if possible Convert a string value to its built-in data type (integer, float, boolean, str or list of these) if possible Args: value (:obj:`object`): a value to be converted Returns: :obj:`type`: the converted value Raises: :obj:`VdtTypeError`: if the value cannot be converted ''' if not isinstance(value, float) or not math.isnan(value): # if statement needed because `_handle_value` doesn't seem to be able to handle nan value, _ = ConfigObj()._handle_value(value) # parse to integer try: return is_integer(value) except VdtTypeError: pass # parse to float try: return is_float(value) except VdtTypeError: pass # parse to bool try: return is_boolean(value) except VdtTypeError: pass # parse to list try: return [any_checker(val) for val in is_list(value)] except VdtTypeError: pass # parse to string return is_string(value)
def __init__(self, name, config, config_no_sensitive): self.name = name self.config = config self.logger = getLogger(self.__class__.__name__) # Safe for printing out to logs, any sensitive data has been shadowed self.config_no_sensitive = config_no_sensitive _extra = {} extra = self.config.get('extra') # Will be None at times if extra: extra = ';'.join(extra.splitlines()) for line in extra.split(';'): original_line = line if line: line = line.split('=') if not len(line) == 2: raise ValueError('Each line must be a single key=value entry, not [{}]'.format(original_line)) key, value = line value = value.strip() try: value = is_boolean(value) except VdtTypeError: # It's cool, not a boolean pass try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass _extra[key.strip()] = value engine_url = engine_def.format(**config) self.engine = create_engine(engine_url, pool_size=int(config['pool_size']), **_extra) event.listen(self.engine, 'checkin', self.on_checkin) event.listen(self.engine, 'checkout', self.on_checkout) event.listen(self.engine, 'connect', self.on_connect) event.listen(self.engine, 'first_connect', self.on_first_connect)
def parse_extra_into_dict(lines, convert_bool=True): """ Creates a dictionary out of key=value lines. """ _extra = {} if lines: extra = ';'.join(lines.splitlines()) for line in extra.split(';'): original_line = line if line: line = line.split('=') if not len(line) == 2: raise ValueError('Each line must be a single key=value entry, not [{}]'.format(original_line)) key, value = line value = value.strip() if convert_bool: try: value = is_boolean(value) except VdtTypeError: # It's cool, not a boolean pass try: value = is_integer(value) except VdtTypeError: # OK, not an integer pass # Could be a dict or another simple type then try: value = literal_eval(value) except Exception: pass # OK, let's just treat it as string _extra[key.strip()] = value return _extra
def check_raster_map(value): if not isinstance(value, list): raise v.ValidateError("expected list, found %s" % (value,)) _frame = check_frame(value[0]) scan_axis = value[1].upper() if not scan_axis in frame.axes: raise v.ValidateError("not a valid axis: %s" % (scan_axis,)) start_point = value[2].upper() if not start_point in START_POINTS: raise v.ValidateError("not a valid start point: %s" % (start_point,)) length_x = angle_parser.check_angle(value[3]) length_y = angle_parser.check_angle(value[4]) duration = v.is_float(value[5], min=0) try: spacing = angle_parser.check_angle(value[6]) except: logger.debug("RASTER map specify scans per beam") spacing = v.is_float(value[6], min=1) offset = v.is_integer(value[7], min=0) return RasterMapScan(_frame, start_point, scan_axis, length_x, length_y, spacing, duration, offset)
def _is_int_list(self, value, min=None, max=None): """ Validation function for a list of integer values. Replacement (extension) of the original 'is_int_list' function. Reference: https://github.com/DiffSK/configobj/blob/master/src/configobj/validate.py """ # Check if value is string if isinstance(value, str): # Convert string value try: value = ast.literal_eval(value) except ValueError: raise ValidateError( 'The value "{}" could not be converted!'.format(value)) except Exception as e: raise e if isinstance(value, list): return [is_integer(elem) for elem in is_list(value, min, max)] else: raise ValidateError( 'A value of type {} was passed when a integer list was expected!' .format(type(value)))
def integer_numpy_array_check(value, min=None, max=None): """ Parse and validate `value` as a numpy array (of integers). Value can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. Parameters ---------- value : str The string to be converted. This can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. min : int The minimum allowed value. If the converted value is (or have) lower than `min` then the VdtValueTooSmallError exception will be raised. max : int The maximum allowed value. If the converted value is (or have) greater than `man` then the VdtValueTooSmallError exception will be raised. Returns ------- numpy array The parsed numpy array. Notes ----- You can either separate the values with commas or spaces (any comma will have the same effect as a space). However, if you separate with spaces the values should be brackets, while if you separate with commands there should be no brackets. .. code:: max_iter = 5,10:20 max_iter = [0 5 10:20] """ if isinstance(value, str): # Remove '[' and ']' if they exist. if value[0] == '[' and value[-1] == ']': value = value[1:-1].strip() value = value.replace(',', ' ') # Replace any commas by a space value = value.split() # Split based on spaces # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Test if it is a list or not if isinstance(value, list): # If it is a list, each element can be either a number of a 'range # expression' that can be parsed with _parse_int_range_expr. We simple # apply integer_numpy_array_check on each element in the list to do # the work and stack horizontally all the results. value = [integer_numpy_array_check(a, min, max) for a in value] out = np.hstack(value) else: # It its not a list, it can be either a single number of a 'range # expression' that can be parsed with _parse_int_range_expr try: value = validate.is_integer(value) out = np.array([value]) except validate.VdtTypeError: out = _parse_int_range_expr(value) # xxxxxxxxxx Validate if minimum and maximum allowed values xxxxxxxxxxx if min is not None: # maybe "min" was passed as a string and thus we need to convert it # to a integer min = int(min) if out.min() < min: raise validate.VdtValueTooSmallError(out.min()) if max is not None: # maybe "min" was passed as a string and thus we need to convert it # to a integer max = int(max) if out.max() > max: raise validate.VdtValueTooBigError(out.max()) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx return out
def test_should_validate_integer(self): i = 10 isvalid = is_integer(i) self.assertTrue(isvalid)
def test_should_raise_exception_for_invalid_integer(self): with self.assertRaises(VdtTypeError): i = "as" is_integer(i)
def integer_numpy_array_check(value, min=None, max=None): """ Parse and validate `value` as a numpy array (of integers). Value can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. Parameters ---------- value : str The string to be converted. This can be either a single number, a range expression in the form of min:max or min:step:max, or even a list containing numbers and range expressions. min : int The minimum allowed value. If the converted value is (or have) lower than `min` then the VdtValueTooSmallError exception will be raised. max : int The maximum allowed value. If the converted value is (or have) greater than `man` then the VdtValueTooSmallError exception will be raised. Returns ------- np.ndarray The parsed numpy array. Notes ----- You can either separate the values with commas or spaces (any comma will have the same effect as a space). However, if you separate with spaces the values should be brackets, while if you separate with commands there should be no brackets. >> max_iter = 5,10:20 >> max_iter = [0 5 10:20] """ if isinstance(value, str): # Remove '[' and ']' if they exist. if value[0] == '[' and value[-1] == ']': value = value[1:-1].strip() value = value.replace(',', ' ') # Replace commas by spaces value = value.split() # Split based on spaces # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Test if it is a list or not if isinstance(value, list): # If it is a list, each element can be either a number of a # 'range expression' that can be parsed with # _parse_int_range_expr. We simple apply # integer_numpy_array_check on each element in the list to do # the work and stack horizontally all the results. value = [integer_numpy_array_check(a, min, max) for a in value] out = np.hstack(value) else: # It its not a list, it can be either a single number of a 'range # expression' that can be parsed with _parse_int_range_expr try: value = validate.is_integer(value) out = np.array([value]) except validate.VdtTypeError: out = _parse_int_range_expr(value) # xxxxxxxxxx Validate if minimum and maximum allowed values xxxxxxxxxxx if min is not None: # maybe "min" was passed as a string and thus we need to convert it # to a integer min = int(min) if out.min() < min: raise validate.VdtValueTooSmallError(out.min()) if max is not None: # maybe "min" was passed as a string and thus we need to convert it # to a integer max = int(max) if out.max() > max: raise validate.VdtValueTooBigError(out.max()) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx return out
def test_should_validate_range(self): i = 10 min_range = 0 max_range = 11 isvalid = is_integer(i, min_range, max_range) self.assertTrue(isvalid)
def is_preset_param(value): parsed = is_tuple(value, min=2, max=2) return is_boolean(parsed[0]), is_integer(parsed[1], min=0)
def test_should_raise_exception_for_integer_above_range(self): with self.assertRaises(VdtValueTooBigError): i = 12 min_range = 0 max_range = 11 is_integer(i, min_range, max_range)
if (j - 1) >= 0 and self.baseList[i][j - 1] == '*': neighbourCount = neighbourCount + 1 if (j + 1) < self.cols and self.baseList[i][j + 1] == '*': neighbourCount = neighbourCount + 1 return neighbourCount if __name__ == "__main__": #read the input try: rows = input("enter the number of rows >") cols = input("enter the number of cols >") except Exception, e: print "Enter valid input in integers", e else: if validate.is_integer(rows) and validate.is_integer(cols): #if rows baseTupleList = [['-' for x in xrange(cols + 2)] \ for x in xrange(rows + 2)] i = 1 while (i <= rows): j = 1 while (j <= cols): while True: x = str(raw_input('''enter the %dth row %dth col values >'''\ %(i,j) )) if not validate.is_seed(x): print "Please enter '*' and '-' meaning live and death" \ + "resp",x else: break
def test_should_raise_exception_for_integer_below_range(self): with self.assertRaises(VdtValueTooSmallError): i = 1 min_range = 2 max_range = 11 is_integer(i, min_range, max_range)