def neighbour(self, lat_aux, lon_aux): """ This module performs nearest neighbour interpolation for a given curvilinear grid to a retilinear grid. param lat_aux: laititude of the target grid (should be 1D) param lon_aux: longtitude of the target grid (should be 1D) """ if lat_aux.shape != 1: msg = "The given latitude is not a one dimensional vector." raise configargparse.ArgumentTypeError(msg) if lon_aux.shape != 1: msg = "The given longitude is not a one dimensional vector." raise configargparse.ArgumentTypeError(msg) # assemble target cube lat_tar = iris.coords.DimCoord(lat_aux, standard_name='latitude', units='degrees_north', coord_system='GeogCS') lon_tar = iris.coords.DimCoord(lon_aux, standard_name='longitude', units='degrees_east', coord_system='GeogCS') dummy_data = np.zeros((len(lat_aux), len(lon_aux))) cube_tar = iris.cube.Cube(dummy_data,dim_coords_and_dims=[(lat_tar, 0), (lon_tar, 1)]) # create the coordinate system for the target cube cube_tar.coord('latitude').guess_bounds() cube_tar.coord('longitude').guess_bounds() cube_tar.coord('latitude').coord_system = coord_sys cube_tar.coord('longitude').coord_system = coord_sys # create a weight matrix for regridding weights = np.ones(self.cube.shape) # get regridder from given cubes base = iris.analysis.UnstructuredNearest() regridder = base.regridder(self.cube,cube_tar) # Transform cube to target projection cube_regrid = regridder(self.cube) return cube_regrid
def check_vid(value): if not os.path.isfile(value): raise configargparse.ArgumentTypeError("File '%s' does not exist" % value) if not supported_filetype(value): raise configargparse.ArgumentTypeError( f"File '{file}' should be a file with one of the following supported extensions: {', '.join(fileTypes)}" ) return value
def float_range_checker(arg): try: f = float(arg) except ValueError: raise configargparse.ArgumentTypeError( "Must be a floating point number") if f < mini or f > maxi: raise configargparse.ArgumentTypeError( "Must be in range [%s .. %s]" % (mini, maxi)) return (f)
def is_writable_dir(dirname): """Check if a path is a writable directory.""" if not os.path.isdir(dirname): msg = "{0} is not a directory".format(dirname) raise configargparse.ArgumentTypeError(msg) if not os.access(dirname, os.W_OK): msg = "{0} is not writable".format(dirname) raise configargparse.ArgumentTypeError(msg) else: return dirname
def int_range_checker(arg): try: f = int(arg) except ValueError: raise configargparse.ArgumentTypeError("Must be an integer") if f < mini or f > maxi_val: raise configargparse.ArgumentTypeError( "Must be in range [%s .. %s (%s)]" % (mini, maxi, maxi_val)) return (f)
def layers_dict(text): try: return OrderedDict([(x.split('=')[0], [int(y) for y in x.split('=')[1].split(',')]) for x in text.split(' ')]) except: raise argparse.ArgumentTypeError("Format must be 'name1=h1,w1,i1,o1 name2=h2,w2,12,02 name3=i3,o3" " name4=i4,o4 ...'")
def writable_dir(path): """ A custom type for writable directory. Raises: ArgumentTypeError: If the 'path' argument is not a valid or writable directory """ if not os.path.isdir(path): raise configargparse.ArgumentTypeError( "The path '{}' is not a valid directory.".format(path)) if os.access(path, os.W_OK): return path else: raise configargparse.ArgumentTypeError( "The path '{}' is not a writable directory.".format(path))
def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.')
def parse_swap_key(s): arglist = s.split(",") if len(arglist) != 2: raise argparse.ArgumentTypeError( "Dualkeys must consist of two keycodes, like (a, b).") t = list(map(parse_single_key, arglist)) return tuple(t)
def str2bool(v): if v.lower() == 'true': return True elif v.lower() == 'false': return False else: raise configargparse.ArgumentTypeError('Boolean value expected')
def time_interval(str_interval): try: quant, unit = re.match(r'\A([\d.]+) ?(h|m(?:in)?|s)?\Z', str_interval).groups() translate = {'h': 'hours', 'm': 'minutes', 'min': 'minutes', 's': 'seconds'} return timedelta(**{translate[unit or 's']: float(quant)}) except (AttributeError, ValueError): raise configargparse.ArgumentTypeError('Invalid time interval (e.g. 12[s|min|h]): %s' % str_interval)
def parse_upstream_auth(auth): pattern = re.compile(".+:") if pattern.search(auth) is None: raise configargparse.ArgumentTypeError( "Invalid upstream auth specification: %s" % auth ) return "Basic" + " " + base64.b64encode(auth)
def commitpoint_type(x): x = int(x) if x < const.MIN_COMMIT_POINT: raise configargparse.ArgumentTypeError( "Minimum allowed commitpoint is: {}".format( const.MIN_COMMIT_POINT)) return x
def parse_server_spec(url): p = netlib.utils.parse_url(url) if not p or not p[1] or p[0] not in ("http", "https"): raise configargparse.ArgumentTypeError( "Invalid server specification: %s" % url) address = Address(p[1:3]) scheme = p[0].lower() return config.ServerSpec(scheme, address)
def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise configargparse.ArgumentTypeError( f'{v} is not a valid value')
def type_heurist_char_replace(string): try: with open(string, "r", encoding="utf8") as inputfile: json_str = inputfile.read() json_str = json.loads(json_str) return [(entry["char"], entry["replace"]) for entry in json_str] except IOError: raise configargparse.ArgumentTypeError(" file \"%s\" not found" % string)
def _str2bool(v): """Convert an argument string to a boolean value.""" if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise _argparse.ArgumentTypeError("Boolean value expected.")
def _init_weights(s): """ Handle the None value in VALID_INIT_WEIGHTS """ if s not in RimeSolverConfig.VALID_INIT_WEIGHTS: import configargparse raise configargparse.ArgumentTypeError("\'{iw}\'' must be one of {viw}" .format(iw=INIT_WEIGHTS, viw=RimeSolverConfig.VALID_INIT_WEIGHTS)) return s
def parse_bool(v): if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise configargparse.ArgumentTypeError('Boolean value expected.')
def parse_single_key(k): k = k.strip().upper() if not k.startswith("KEY_") and not k.startswith("BTN_"): k = "KEY_" + k event = libevdev.evbit(k) if event is None: raise argparse.ArgumentTypeError( f"{k} is not a valid key identifier, you might want to try Dualkeys.py -p " "to obtain valid identifiers.") return event.value
def str2bool(v): """ from https://stackoverflow.com/a/43357954/1361529 """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise configargparse.ArgumentTypeError('Boolean value expected.')
def check_positive_float(value, minval=0.0): """Validate integer input in arguments. Args: value: input value to check minval: value must be equal to or larger than minval Returns: True is sanity check passes, raises error otherwise """ try: fvalue = float(value) except: raise configargparse.ArgumentTypeError(f"{value} is not a float") if fvalue <= minval: raise configargparse.ArgumentTypeError( f"{value} is an invalid float value. Must be >= {minval}") return fvalue
def parse_server_spec(spec): try: p = url.parse(spec) if p[0] not in ("http", "https"): raise ValueError() except ValueError: raise configargparse.ArgumentTypeError( "Invalid server specification: %s" % spec) address = tcp.Address(p[1:3]) scheme = p[0].lower() return config.ServerSpec(scheme, address)
def parse_server_spec(url): p = http.parse_url(url) if not p or not p[1] or p[0] not in ("http", "https"): raise configargparse.ArgumentTypeError( "Invalid server specification: %s" % url) if p[0].lower() == "https": ssl = [True, True] else: ssl = [False, False] return ssl + list(p[1:3])
def parse_multi_key(s): arglist = s.split(",") if len(arglist) not in [3, 4]: raise argparse.ArgumentTypeError( "Dualkeys must consist of three key symbols, like (space, space, leftcontrol)," "with an optional bool if it should be triggered on a down press, " "like (space, space, leftcontrol, True)") t = list(map(parse_single_key, arglist[:3])) if len(arglist) == 4: down_press = bool(arglist[3]) t += [down_press] return tuple(t)
def check_key_length(value): """Check that a valid key length has been provided. Args: value (str): The command line argument provided by the user Returns: int: The key length Raises: configargparse.ArgumentError: If the supplied key length was invalid """ valid_key_lengths = [2048, 4096, 8192] try: new_value = int(value) except Exception: raise configargparse.ArgumentTypeError( "{} is an invalid key length. Must be an integer.".format(value)) if new_value not in valid_key_lengths: raise configargparse.ArgumentTypeError( "{} is an invalid key length. Must be either 2048, 4096 or 8192.". format(value)) return new_value
def str2bool(v): """Parse the supplied command line arguments into a boolean. Returns: Boolean: The parsed and validated command line arguments. Defaults to False. """ if isinstance(v, bool): return v if v.lower() in ("yes", "true", "1"): return True elif v.lower() in ("no", "false", "0"): return False else: raise configargparse.ArgumentTypeError("Boolean value expected.")
def parse_bool(v): """ Parse-able bool type. Bool type to set in add in parser.add_argument to fix not parsing of False. See: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Args: v (str): a string that indicates true ('yes', 'true', 't', 'y', '1') or false ('no', 'false', 'f', 'n', '0'). """ import configargparse if v.lower().strip() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower().strip() in ('no', 'false', 'f', 'n', '0'): return False else: raise configargparse.ArgumentTypeError('Boolean value expected.')
def get_common_options(options): stickycookie, stickyauth = None, None if options.stickycookie_filt: stickycookie = options.stickycookie_filt if options.stickyauth_filt: stickyauth = options.stickyauth_filt stream_large_bodies = utils.parse_size(options.stream_large_bodies) reps = [] for i in options.replace: try: p = parse_replace_hook(i) except ParseException, e: raise configargparse.ArgumentTypeError(e.message) reps.append(p)
def str2bool(v): """ Boolean ArgParse options are confusing by default: They just just --some-option _without_ giving a True or False value; if the switch is present, such as --some-option, then it becomes True. If someone gives '--some-option False' the option will still evaluate as True! This method changes this default behavior so that boolean command line args match expected behavior: '--some-option=True' will evaluate to True and '--some-option=False' will evaluate to False. """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise configargparse.ArgumentTypeError('Boolean value expected.')