Decorator to deal with zsym=True input; set odd=True if the function is an odd function of z (like zforce)
510968
def zsymDecorator(odd):
    """"""
    def wrapper(func):
        @wraps(func)
        def zsym_wrapper(*args,**kwargs):
            if args[0]._zsym:
                out= func(args[0],args[1],numpy.fabs(args[2]),**kwargs)
            else:
                out= func(*args,**kwargs)
            if odd and args[0]._zsym:
                return sign(args[2])*out
            else:
                return out
        return zsym_wrapper
    return wrapper
83975
def handle_combined_input(args):
    
    cur_args = args[:]
    while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
        cur_args = cur_args[0]
    return cur_args
568795
def next_instruction_is_function_or_class(lines):
    """"""
    for i, line in enumerate(lines):
        if not line.strip():  # empty line
            if i > 0 and not lines[i - 1].strip():
                return False
            continue
        if line.startswith('def ') or line.startswith('class '):
            return True
        if line.startswith(('#', '@', ' ')):
            continue
        return False

    return False
267393
def symbolic(self, e): # pylint:disable=R0201
        
        if type(e) in (int, bytes, float, bool):
            return False
        return e.symbolic
849322
def is_zsettable(s):
    """"""
    return all(map(lambda x: isinstance(x, (int, float, long)), s.values()))
1220250
def _default_verify_function(instance, answer, result_host, atol, verbose):
    """"""

    #first check if the length is the same
    if len(instance.arguments) != len(answer):
        raise TypeError("The length of argument list and provided results do not match.")
    #for each element in the argument list, check if the types match
    for i, arg in enumerate(instance.arguments):
        if answer[i] is not None: #skip None elements in the answer list
            if isinstance(answer[i], numpy.ndarray) and isinstance(arg, numpy.ndarray):
                if answer[i].dtype != arg.dtype:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list is not of the same dtype as the kernel output: "
                                    + str(answer[i].dtype) + " != " + str(arg.dtype) + ".")
                if answer[i].size != arg.size:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list has a size different from "
                                    + "the kernel argument: "
                                    + str(answer[i].size) + " != " + str(arg.size) + ".")
            elif isinstance(answer[i], numpy.number) and isinstance(arg, numpy.number):
                if answer[i].dtype != arg.dtype:
                    raise TypeError("Element " + str(i)
                                    + " of the expected results list is not the same as the kernel output: "
                                    + str(answer[i].dtype) + " != " + str(arg.dtype) + ".")
            else:
                #either answer[i] and argument have different types or answer[i] is not a numpy type
                if not isinstance(answer[i], numpy.ndarray) or not isinstance(answer[i], numpy.number):
                    raise TypeError("Element " + str(i)
                                    + " of expected results list is not a numpy array or numpy scalar.")
                else:
                    raise TypeError("Element " + str(i)
                                    + " of expected results list and kernel arguments have different types.")

    def _ravel(a):
        if hasattr(a, 'ravel') and len(a.shape) > 1:
            return a.ravel()
        return a

    def _flatten(a):
        if hasattr(a, 'flatten'):
            return a.flatten()
        return a

    correct = True
    for i, arg in enumerate(instance.arguments):
        expected = answer[i]
        if expected is not None:

            result = _ravel(result_host[i])
            expected = _flatten(expected)
            output_test = numpy.allclose(expected, result, atol=atol)

            if not output_test and verbose:
                print("Error: " + util.get_config_string(instance.params) + " detected during correctness check")
                print("this error occured when checking value of the %oth kernel argument" % (i,))
                print("Printing kernel output and expected result, set verbose=False to suppress this debug print")
                numpy.set_printoptions(edgeitems=50)
                print("Kernel output:")
                print(result)
                print("Expected:")
                print(expected)
            correct = correct and output_test

    if not correct:
        logging.debug('correctness check has found a correctness issue')
        raise Exception("Error: " + util.get_config_string(instance.params) + " failed correctness check")

    return correct
205069
def validate_args(f):
    

    def wrapper(self, args):
        arg_types = set([type(arg) for arg in args])
        if len(arg_types) > 1:
            raise TypeError("Mixed input types are not allowed")

        elif list(arg_types)[0] not in (dict, str):
            raise TypeError("Only dict and str types accepted")

        return f(self, args)

    return wrapper
249761
def accepts_numpy(func):
    
    #@ignores_exc_tb
    #@wraps(func)
    def wrp_accepts_numpy(self, input_, *args, **kwargs):
        if not (util_type.HAVE_NUMPY and isinstance(input_, np.ndarray)):
            # If the input is not numpy, just call the function
            return func(self, input_, *args, **kwargs)
        else:
            # TODO: use a variant of util_list.unflat_unique_rowid_map
            # If the input is a numpy array, and return the output with the same
            # shape as the input
            if UNIQUE_NUMPY:
                # Remove redundant input (because we are passing it to SQL)
                input_list, inverse_unique = np.unique(input_, return_inverse=True)
            else:
                input_list = input_.flatten()
            # Call the function in list format
            # TODO: is this necessary?
            input_list = input_list.tolist()
            output_list = func(self, input_list, *args, **kwargs)
            # Put the output back into numpy
            if UNIQUE_NUMPY:
                # Reconstruct redundant queries
                output_arr = np.array(output_list)[inverse_unique]
                output_shape = tuple(list(input_.shape) + list(output_arr.shape[1:]))
                return np.array(output_arr).reshape(output_shape)
            else:
                return np.array(output_list).reshape(input_.shape)
    wrp_accepts_numpy = preserve_sig(wrp_accepts_numpy, func)
    return wrp_accepts_numpy
1125500
def func(nargs: Optional[int] = None, nouts: Optional[int] = None, ndefs: Optional[int] = None):
    
    return lambda f: wraps(f)(WrappedFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
20959
def Z(self, value):
        
        if isinstance(value, (int, float,
                              long, types.NoneType)):
            self._z = value
1298751
def _pys2macros(self, line):
        """"""

        if self.code_array.dict_grid.macros and \
           self.code_array.dict_grid.macros[-1] != "\n":
            # The last macro line does not end with \n
            # Therefore, if not new line is inserted, the codeis broken
            self.code_array.dict_grid.macros += "\n"

        self.code_array.dict_grid.macros += line.decode("utf-8")
589906
def type_check(arg_name, pos, reqd_type):
    

    def decorator(fn):

        # brevity compromised in favour of readability
        def logic(*args, **kwargs):
            arg_count = len(args)
            if arg_count:
                if pos < arg_count:
                    if isinstance(args[pos], reqd_type):
                        return fn(*args, **kwargs)
                    else:
                        raise TypeError("'{0}' at position {1} not of type {2}".format(args[pos], pos, reqd_type))
                else:
                    if arg_name in kwargs:
                        value = kwargs[arg_name]
                        if isinstance(value, reqd_type):
                            return fn(*args, **kwargs)
                        else:
                            raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))
                    else:
                        # partially applied functions because of incomplete args, let python handle this
                        return fn(*args, **kwargs)
            else:
                if arg_name in kwargs:
                    value = kwargs[arg_name]
                    if isinstance(value, reqd_type):
                        return fn(*args, **kwargs)
                else:
                    raise TypeError("'{0}' is not of type {1}".format(arg_name, reqd_type))

        return logic

    return decorator
1132016
def function(name, range=False, sync=False, allow_nested=False, eval=None):
    """"""
    def dec(f):
        f._nvim_rpc_method_name = 'function:{}'.format(name)
        f._nvim_rpc_sync = sync
        f._nvim_bind = True
        f._nvim_prefix_plugin_path = True

        opts = {}

        if range:
            opts['range'] = '' if range is True else str(range)

        if eval:
            opts['eval'] = eval

        if not sync and allow_nested:
            rpc_sync = "urgent"
        else:
            rpc_sync = sync

        f._nvim_rpc_spec = {
            'type': 'function',
            'name': name,
            'sync': rpc_sync,
            'opts': opts
        }
        return f
    return dec
522207
def logical_xor(f1, f2):  # function factory
    '''
    '''
    def f(value):
        return np.logical_xor(f1(value), f2(value))
    f.__name__ = "(" + f1.__name__ + "_xor_" + f2.__name__ + ")"
    return f
924221
function(param_, test) {
  var param = param_.replace(/\s+/g, '')
    , cap;

  if (param === 'even') {
    param = '2n+0';
  } else if (param === 'odd') {
    param = '2n+1';
  } else if (param.indexOf('n') === -1) {
    param = '0n' + param;
  }

  cap = /^([+-])?(\d+)?n([+-])?(\d+)?$/.exec(param);

  return {
    group: cap[1] === '-'
      ? -(cap[2] || 1)
      : +(cap[2] || 1),
    offset: cap[4]
      ? (cap[3] === '-' ? -cap[4] : +cap[4])
      : 0
  };
}
602633
def ensure_unicode_args(function):
    '''
    
    '''
    @wraps(function)
    def wrapped(*args, **kwargs):
        if six.PY2:
            return function(
                *salt.utils.data.decode_list(args),
                **salt.utils.data.decode_dict(kwargs)
            )
        else:
            return function(*args, **kwargs)
    return wrapped
233640
def create_bool(help_string=NO_HELP, default=NO_DEFAULT):
        # type: (str, Union[bool, NO_DEFAULT_TYPE]) -> bool
        
        # noinspection PyTypeChecker
        return ParamFunctions(
            help_string=help_string,
            default=default,
            type_name="bool",
            function_s2t=convert_string_to_bool,
            function_t2s=convert_bool_to_string,
        )