Verify arguments passed to the geom
160591
def _verify_arguments(self, kwargs):
        
        geom_stat_args = kwargs.keys() | self._stat._kwargs.keys()
        unknown = (geom_stat_args -
                   self.aesthetics() -                # geom aesthetics
                   self.DEFAULT_PARAMS.keys() -        # geom parameters
                   self._stat.aesthetics() -          # stat aesthetics
                   self._stat.DEFAULT_PARAMS.keys() -  # stat parameters
                   {'data', 'mapping',                # layer parameters
                    'show_legend', 'inherit_aes'})    # layer parameters
        if unknown:
            msg = ("Parameters {}, are not understood by "
                   "either the geom, stat or layer.")
            raise PlotnineError(msg.format(unknown))
1216016
def get_proj(geom, proj_list=None):
    
    out_srs = None
    if proj_list is None:
        proj_list = gen_proj_list()
    #Go through user-defined projeciton list
    for projbox in proj_list:
        if projbox.geom.Intersects(geom):
            out_srs = projbox.srs
            break
    #If geom doesn't fall in any of the user projection bbox, use UTM
    if out_srs is None:
        out_srs = getUTMsrs(geom)
    return out_srs
1187455
def _validate_params(self):
        
        # fit_intercep
        if not isinstance(self.fit_intercept, bool):
            raise ValueError('fit_intercept must be type bool, but found {}'\
                             .format(self.fit_intercept.__class__))

        # terms
        if (self.terms is not 'auto') and not (isinstance(self.terms, (TermList, Term, type(None)))):
            raise ValueError('terms must be a TermList, but found '\
                             'terms = {}'.format(self.terms))

        # max_iter
        self.max_iter = check_param(self.max_iter, param_name='max_iter',
                                    dtype='int', constraint='>=1',
                                    iterable=False)

        # distribution
        if not ((self.distribution in DISTRIBUTIONS)
                or isinstance(self.distribution, Distribution)):
            raise ValueError('unsupported distribution {}'.format(self.distribution))
        if self.distribution in DISTRIBUTIONS:
            self.distribution = DISTRIBUTIONS[self.distribution]()

        # link
        if not ((self.link in LINKS) or isinstance(self.link, Link)):
            raise ValueError('unsupported link {}'.format(self.link))
        if self.link in LINKS:
            self.link = LINKS[self.link]()

        # callbacks
        if not isiterable(self.callbacks):
            raise ValueError('Callbacks must be iterable, but found {}'\
                             .format(self.callbacks))

        if not all([c in CALLBACKS or
                    isinstance(c, CallBack) for c in self.callbacks]):
            raise ValueError('unsupported callback(s) {}'.format(self.callbacks))
        callbacks = list(self.callbacks)
        for i, c in enumerate(self.callbacks):
            if c in CALLBACKS:
                callbacks[i] = CALLBACKS[c]()
        self.callbacks = [validate_callback(c) for c in callbacks]
685157
def validate_args(args):
    """"""
    # Check correctness of similarity dataset names
    for dataset_name in args.similarity_datasets:
        if dataset_name.lower() not in map(
                str.lower,
                nlp.data.word_embedding_evaluation.word_similarity_datasets):
            print('{} is not a supported dataset.'.format(dataset_name))
            sys.exit(1)

    # Check correctness of analogy dataset names
    for dataset_name in args.analogy_datasets:
        if dataset_name.lower() not in map(
                str.lower,
                nlp.data.word_embedding_evaluation.word_analogy_datasets):
            print('{} is not a supported dataset.'.format(dataset_name))
            sys.exit(1)
1314936
def geom_check_axis(g, atwts, ax,
        nmax=_DEF.SYMM_MATCH_NMAX,
        tol=_DEF.SYMM_MATCH_TOL):
    

    # Imports
    import numpy as np

    # Store the max found rotation order of the geometry.
    order = geom_find_rotsymm(g, atwts, ax, \
                                        False, nmax, tol)[0]

    # Store the presence/absence of a reflection plane.
    refl = geom_symm_match(g, atwts, ax, 0, True) < tol

    # Return the pair of values for outside handling
    return order, refl
53265
def geom_dup(geom):
    
    g = ogr.CreateGeometryFromWkt(geom.ExportToWkt())
    g.AssignSpatialReference(geom.GetSpatialReference())
    return g
631839
def _validate_params(self):
        
        self.distribution = GammaDist(scale=self.scale)
        super(GammaGAM, self)._validate_params()
1194445
def getArguments(parser):
    ""
    args = parser.parse_args()
    # get the number of dimensions in the image
    if args.example:
        args.example_image, args.example_header = load(args.example)
        dimensions = args.example_image.ndim
    else:
        dimensions = len(args.shape)
    
    # check and, if required, modify the spacing argument
    if isinstance(args.spacing, int):
        args.spacing = [args.spacing] * dimensions
    elif len(args.spacing) != dimensions:
        raise argparse.ArgumentTypeError('the grid spacing ({}) must contain the same number of elements as the output image has dimensions ({})'.format(','.join(map(str, args.spacing)), dimensions))
    
    # check further arguments
    if args.offset and len(args.offset) != dimensions:
        raise argparse.ArgumentTypeError('the offset ({}) must contain the same number of elements as the output image has dimensions ({})'.format(','.join(map(str, args.offset)), dimensions))
    if args.pixelspacing and len(args.pixelspacing) != dimensions:
        raise argparse.ArgumentTypeError('the supplied pixel spacing ({}) must contain the same number of elements as the output image has dimensions ({})'.format(','.join(map(str, args.pixelspacing)), dimensions))
    
    return args
692946
def get_goargs(self, go_args, prt):
        """"""
        goids = set()
        go2color = {}
        # Match on "GO ID" or "GO ID and color"
        re_gocolor = re.compile(r'(GO:\d{7})((?:#[0-9a-fA-F]{6})?)')
        for go_arg in go_args:
            mtch = re_gocolor.match(go_arg)
            if mtch:
                goid, color = mtch.groups()
                goids.add(goid)
                if color:
                    go2color[goid] = color
            elif go_arg in self.godagconsts.NS2GO:
                goids.add(self.godagconsts.NS2GO[go_arg])
            elif prt:
                prt.write("WARNING: UNRECOGNIZED ARG({})\n".format(go_arg))
        return goids
104098
def verify(x, t, y, pi, errorOnFail=True):
    
    # Unpack the proof
    p,_,_ = pi

    # Verify types
    assertType(x, str)
    assertType(t, str)
    assertType(y, G1Element)
    assertType(p, G2Element)

    # TODO: beta can be pre-computed while waiting for a server response.
    beta = hashG1(t, x)

    # Compute q = e( H(t,m), P)**kw two ways
    q1 = pair(beta, p)
    q2 = pair(y, generatorG2())

    # The BLS signature is valid when q1 == q2
    if q1 == q2:
        return True

    if errorOnFail:
        raise Exception("BLS signature failed verification")
    else:
        return False
1088741
def check_arg_types(funcname, *args):
    """"""
    hasstr = hasbytes = False
    for arg in args:
        if isinstance(arg, str):
            hasstr = True
        elif isinstance(arg, bytes):
            hasbytes = True
        else:
            raise TypeError('{0}() argument must be str or bytes, not {1}'
                            .format(funcname, arg.__class__.__name__))
    if hasstr and hasbytes:
        raise TypeError("Can't mix strings and bytes in path components")
1060483
def contains_geometric_info(var):
    
    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
675508
def _get_valid_stan_args(base_args=None):
    
    args = base_args.copy() if base_args is not None else {}
    # Default arguments, c.f. rstan/rstan/inst/include/rstan/stan_args.hpp
    # values in args are going to be converted into C++ objects so
    # prepare them accordingly---e.g., unicode -> bytes -> std::string
    args['chain_id'] = args.get('chain_id', 1)
    args['append_samples'] = args.get('append_samples', False)
    if args.get('method') is None or args['method'] == "sampling":
        args['method'] = stan_args_method_t.SAMPLING
    elif args['method'] == "optim":
        args['method'] = stan_args_method_t.OPTIM
    elif args['method'] == 'test_grad':
        args['method'] = stan_args_method_t.TEST_GRADIENT
    elif args['method'] == 'variational':
        args['method'] = stan_args_method_t.VARIATIONAL
    else:
        args['method'] = stan_args_method_t.SAMPLING
    args['sample_file_flag'] = True if args.get('sample_file') else False
    args['sample_file'] = args.get('sample_file', '').encode('ascii')
    args['diagnostic_file_flag'] = True if args.get('diagnostic_file') else False
    args['diagnostic_file'] = args.get('diagnostic_file', '').encode('ascii')
    # NB: argument named "seed" not "random_seed"
    args['random_seed'] = args.get('seed', int(time.time()))

    if args['method'] == stan_args_method_t.VARIATIONAL:
        # variational does not use a `control` map like sampling
        args['ctrl'] = args.get('ctrl', dict(variational=dict()))
        args['ctrl']['variational']['iter'] = args.get('iter', 10000)
        args['ctrl']['variational']['grad_samples'] = args.get('grad_samples', 1)
        args['ctrl']['variational']['elbo_samples'] = args.get('elbo_samples', 100)
        args['ctrl']['variational']['eval_elbo'] = args.get('eval_elbo', 100)
        args['ctrl']['variational']['output_samples'] = args.get('output_samples', 1000)
        args['ctrl']['variational']['adapt_iter'] = args.get('adapt_iter', 50)
        args['ctrl']['variational']['eta'] = args.get('eta', 1.0)
        args['ctrl']['variational']['adapt_engaged'] = args.get('adapt_engaged', True)
        args['ctrl']['variational']['tol_rel_obj'] = args.get('tol_rel_obj', 0.01)
        if args.get('algorithm', '').lower() == 'fullrank':
            args['ctrl']['variational']['algorithm'] = variational_algo_t.FULLRANK
        else:
            args['ctrl']['variational']['algorithm'] = variational_algo_t.MEANFIELD
    elif args['method'] == stan_args_method_t.SAMPLING:
        args['ctrl'] = args.get('ctrl', dict(sampling=dict()))
        args['ctrl']['sampling']['iter'] = iter = args.get('iter', 2000)
        args['ctrl']['sampling']['warmup'] = warmup = args.get('warmup', iter // 2)
        calculated_thin = iter - warmup // 1000
        if calculated_thin < 1:
            calculated_thin = 1
        args['ctrl']['sampling']['thin'] = thin = args.get('thin', calculated_thin)
        args['ctrl']['sampling']['save_warmup'] = True  # always True now
        args['ctrl']['sampling']['iter_save_wo_warmup'] = iter_save_wo_warmup = 1 + (iter - warmup - 1) // thin
        args['ctrl']['sampling']['iter_save'] = iter_save_wo_warmup + 1 + (warmup - 1) // thin
        refresh = iter // 10 if iter >= 20 else 1
        args['ctrl']['sampling']['refresh'] = args.get('refresh', refresh)

        ctrl_lst = args.get('control', dict())
        ctrl_sampling = args['ctrl']['sampling']
        # NB: if these defaults change, remember to update docstrings
        ctrl_sampling['adapt_engaged'] = ctrl_lst.get("adapt_engaged", True)
        ctrl_sampling['adapt_gamma'] = ctrl_lst.get("adapt_gamma", 0.05)
        ctrl_sampling['adapt_delta'] = ctrl_lst.get("adapt_delta", 0.8)
        ctrl_sampling['adapt_kappa'] = ctrl_lst.get("adapt_kappa", 0.75)
        ctrl_sampling['adapt_t0'] = ctrl_lst.get("adapt_t0", 10.0)
        ctrl_sampling['adapt_init_buffer'] = ctrl_lst.get("adapt_init_buffer", 75)
        ctrl_sampling['adapt_term_buffer'] = ctrl_lst.get("adapt_term_buffer", 50)
        ctrl_sampling['adapt_window'] = ctrl_lst.get("adapt_window", 25)
        ctrl_sampling['stepsize'] = ctrl_lst.get("stepsize", 1.0)
        ctrl_sampling['stepsize_jitter'] = ctrl_lst.get("stepsize_jitter", 0.0)

        algorithm = args.get('algorithm', 'NUTS')
        if algorithm == 'HMC':
            args['ctrl']['sampling']['algorithm'] = sampling_algo_t.HMC
        elif algorithm == 'Metropolis':
            args['ctrl']['sampling']['algorithm'] = sampling_algo_t.Metropolis
        elif algorithm == 'NUTS':
            args['ctrl']['sampling']['algorithm'] = sampling_algo_t.NUTS
        elif algorithm == 'Fixed_param':
            args['ctrl']['sampling']['algorithm'] = sampling_algo_t.Fixed_param
            # TODO: Setting adapt_engaged to False solves the segfault reported
            # in issue #200; find out why this hack is needed. RStan deals with
            # the setting elsewhere.
            ctrl_sampling['adapt_engaged'] = False
        else:
            msg = "Invalid value for parameter algorithm (found {}; " \
                "require HMC, Metropolis, NUTS, or Fixed_param).".format(algorithm)
            raise ValueError(msg)

        metric = ctrl_lst.get('metric', 'diag_e')
        if metric == "unit_e":
            ctrl_sampling['metric'] = sampling_metric_t.UNIT_E
        elif metric == "diag_e":
            ctrl_sampling['metric'] = sampling_metric_t.DIAG_E
        elif metric == "dense_e":
            ctrl_sampling['metric'] = sampling_metric_t.DENSE_E

        if ctrl_sampling['algorithm'] == sampling_algo_t.NUTS:
            ctrl_sampling['max_treedepth'] = ctrl_lst.get("max_treedepth", 10)
        elif ctrl_sampling['algorithm'] == sampling_algo_t.HMC:
            ctrl_sampling['int_time'] = ctrl_lst.get('int_time', 6.283185307179586476925286766559005768e+00)
        elif ctrl_sampling['algorithm'] == sampling_algo_t.Metropolis:
            pass
        elif ctrl_sampling['algorithm'] == sampling_algo_t.Fixed_param:
            pass

    elif args['method'] == stan_args_method_t.OPTIM:
        args['ctrl'] = args.get('ctrl', dict(optim=dict()))
        args['ctrl']['optim']['iter'] = iter = args.get('iter', 2000)
        algorithm = args.get('algorithm', 'LBFGS')
        if algorithm == "BFGS":
            args['ctrl']['optim']['algorithm'] = optim_algo_t.BFGS
        elif algorithm == "Newton":
            args['ctrl']['optim']['algorithm'] = optim_algo_t.Newton
        elif algorithm == "LBFGS":
            args['ctrl']['optim']['algorithm'] = optim_algo_t.LBFGS
        else:
            msg = "Invalid value for parameter algorithm (found {}; " \
                  "require (L)BFGS or Newton).".format(algorithm)
            raise ValueError(msg)
        refresh = args['ctrl']['optim']['iter'] // 100
        args['ctrl']['optim']['refresh'] = args.get('refresh', refresh)
        if args['ctrl']['optim']['refresh'] < 1:
            args['ctrl']['optim']['refresh'] = 1
        args['ctrl']['optim']['init_alpha'] = args.get("init_alpha", 0.001)
        args['ctrl']['optim']['tol_obj'] = args.get("tol_obj", 1e-12)
        args['ctrl']['optim']['tol_grad'] = args.get("tol_grad", 1e-8)
        args['ctrl']['optim']['tol_param'] = args.get("tol_param", 1e-8)
        args['ctrl']['optim']['tol_rel_obj'] = args.get("tol_rel_obj", 1e4)
        args['ctrl']['optim']['tol_rel_grad'] = args.get("tol_rel_grad", 1e7)
        args['ctrl']['optim']['save_iterations'] = args.get("save_iterations", True)
        args['ctrl']['optim']['history_size'] = args.get("history_size", 5)
    elif args['method'] == stan_args_method_t.TEST_GRADIENT:
        args['ctrl'] = args.get('ctrl', dict(test_grad=dict()))
        args['ctrl']['test_grad']['epsilon'] = args.get("epsilon", 1e-6)
        args['ctrl']['test_grad']['error'] = args.get("error", 1e-6)

    init = args.get('init', "random")
    if isinstance(init, string_types):
        args['init'] = init.encode('ascii')
    elif isinstance(init, dict):
        args['init'] = "user".encode('ascii')
        # while the name is 'init_list', it is a dict; the name comes from rstan,
        # where list elements can have names
        args['init_list'] = init
    else:
        args['init'] = "random".encode('ascii')

    args['init_radius'] = args.get('init_r', 2.0)
    if (args['init_radius'] <= 0):
        args['init'] = b"0"

    # 0 initialization requires init_radius = 0
    if (args['init'] == b"0" or args['init'] == 0):
        args['init_radius'] = 0.0

    args['enable_random_init'] = args.get('enable_random_init', True)
    # RStan calls validate_args() here
    return args
808905
private void verifyArguments(JmxExecRequest request, OperationAndParamType pTypes, int pNrParams, List<Object> pArgs) {
        if ( (pNrParams > 0 && pArgs == null) || (pArgs != null && pArgs.size() != pNrParams)) {
            throw new IllegalArgumentException("Invalid number of operation arguments. Operation " +
                    request.getOperation() + " on " + request.getObjectName() + " requires " + pTypes.paramClasses.length +
                    " parameters, not " + (pArgs == null ? 0 : pArgs.size()) + " as given");
        }
    }
413196
def check_geo(geo):
    
    geo = copy.copy(geo)

    def fix_item(item):
        if isinstance(item, six.binary_type):
            return item.decode()
        return item

    def fix_list(lst):
        return [fix_item(i) for i in lst]
    if isinstance(geo.reduce, six.binary_type):
        geo.reduce = geo.reduce.decode()
    for key in geo.kwargs.keys():
        if geo.kwargs[key] is not None:
            if isinstance(geo.kwargs[key], (list, np.ndarray)):
                geo.kwargs[key] = fix_list(geo.kwargs[key])
            elif isinstance(geo.kwargs[key], six.binary_type):
                geo.kwargs[key] = fix_item(geo.kwargs[key])
    return geo
499061
def verify_geospatial_bounds(self, ds):
        """"""
        var = getattr(ds, 'geospatial_bounds', None)
        check = var is not None
        if not check:
            return ratable_result(False,
                                  "Global Attributes", # grouped with Globals
                                  ["geospatial_bounds not present"])

        try:
            # TODO: verify that WKT is valid given CRS (defaults to EPSG:4326
            #       in ACDD.
            from_wkt(ds.geospatial_bounds)
        except AttributeError:
            return ratable_result(False,
                                  "Global Attributes", # grouped with Globals
                                  ['Could not parse WKT, possible bad value for WKT'])
        # parsed OK
        else:
            return ratable_result(True, "Global Attributes", tuple())
1203579
def _validate_params(priors, means, covars):
    

    for i,(p,m,cv) in enumerate(zip(priors, means, covars)):
        if np.any(np.isinf(p)) or np.any(np.isnan(p)):
            raise ValueError("Component %d of priors is not valid " % i)

        if np.any(np.isinf(m)) or np.any(np.isnan(m)):
            raise ValueError("Component %d of means is not valid " % i)

        if np.any(np.isinf(cv)) or np.any(np.isnan(cv)):
            raise ValueError("Component %d of covars is not valid " % i)

        if (not np.allclose(cv, cv.T) or np.any(scipy.linalg.eigvalsh(cv) <= 0)):
            raise ValueError("Component %d of covars must be positive-definite" % i)