def Func(arg_0, arg_1):
        ''' Takes the hit array and checks if the important data fields have the same data type than the hit clustered array and that the field names are correct.'''
        for arg_2, arg_3 in arg_0._cluster_hits_descr:
            if arg_2 in arg_0._hit_fields_mapping_inverse:
                arg_4 = arg_0._hit_fields_mapping_inverse[arg_2]
            else:
                arg_4 = arg_2
            # Only check hit fields that contain hit information
            if arg_4 in ['cluster_ID', 'is_seed', 'cluster_size', 'n_cluster']:
                continue
            if arg_2 not in arg_1.dtype.names:
                raise TypeError('Required hit field "%s" not found.' % arg_2)
            if arg_0._cluster_hits.dtype[arg_4] != arg_1.dtype[arg_2]:
                raise TypeError('The dtype for hit data field "%s" does not match. Got/expected: %s/%s.' % (arg_2, arg_1.dtype[arg_2], arg_0._cluster_hits.dtype[arg_4]))
        arg_5 = set(arg_1.dtype.names) - set([arg_2 for arg_2, val in arg_0._cluster_hits_descr])
        if arg_5:
            logging.warning('Found additional hit fields: %s' % ", ".join(arg_5))


def Func(arg_0, arg_1, arg_2) -> bool:
    """Create a tree.Rule"""
    arg_1.parser_tree = parsing.Rule(arg_0.value(arg_2))
    return True


def Func(arg_0, arg_1, arg_2) -> bool:
    """Attach a parser tree to the dict of rules"""
    arg_1[arg_2.rulename] = arg_2.parser_tree
    return True


def Func(arg_0, arg_1, arg_2, arg_3) -> bool:
    """Add the rule name"""
    arg_1.rulename = arg_0.value(arg_2)
    arg_1.parser_tree = arg_3.parser_tree
    return True


def Func(arg_0, arg_1, arg_2) -> bool:
    """Create a tree.Seq"""
    if not hasattr(arg_1, 'parser_tree'):
        # forward sublevel of sequence as is
        arg_1.parser_tree = arg_2.parser_tree
    else:
        arg_4 = arg_1
        if isinstance(arg_4.parser_tree, parsing.Seq):
            arg_5 = list(arg_4.parser_tree.ptlist)
        else:
            arg_5 = [arg_4.parser_tree]
        arg_5.append(arg_2.parser_tree)
        arg_1.parser_tree = parsing.Seq(*tuple(arg_5))
    return True


def Func(arg_0, arg_1, arg_2) -> bool:
    """Create a tree.Alt"""
    if not hasattr(arg_1, 'parser_tree'):
        # forward sublevel of alt as is
        if hasattr(arg_2, 'parser_tree'):
            arg_1.parser_tree = arg_2.parser_tree
        else:
            arg_1.parser_tree = arg_2
    else:
        arg_4 = arg_1
        if isinstance(arg_4.parser_tree, parsing.Alt):
            arg_5 = list(arg_4.parser_tree.ptlist)
        else:
            arg_5 = [arg_4.parser_tree]
        arg_5.append(arg_2.parser_tree)
        arg_1.parser_tree = parsing.Alt(*tuple(arg_5))
    return True


def Func(arg_0, arg_1, arg_2, arg_3):
    """Add a repeater to the previous sequence"""
    arg_4 = arg_0.value(arg_2)
    if arg_4 == '!!':
        # cursor on the REPEATER
        arg_0._stream.restore_context()
        # log the error
        arg_0.diagnostic.notify(
            error.Severity.ERROR,
            "Cannot repeat a lookahead rule",
            error.LocationInfo.from_stream(arg_0._stream, is_error=True)
        )
        raise arg_0.diagnostic
    if arg_4 == '!':
        # cursor on the REPEATER
        arg_0._stream.restore_context()
        # log the error
        arg_0.diagnostic.notify(
            error.Severity.ERROR,
            "Cannot repeat a negated rule",
            error.LocationInfo.from_stream(arg_0._stream, is_error=True)
        )
        raise arg_0.diagnostic
    arg_5 = arg_1
    arg_1.parser_tree = arg_3.functor(arg_5.parser_tree)
    return True


def Func(arg_0, arg_1, arg_2):
    """Create a tree.Bind"""
    arg_3 = arg_0.value(arg_2)
    arg_1.parser_tree = parsing.Bind(arg_3, arg_1.parser_tree)
    return True


def Func(arg_0, arg_1, arg_2):
    """Create a tree.Hook"""
    arg_1.parser_tree = parsing.Hook(arg_2.name, arg_2.listparam)
    return True


def Func(arg_0, arg_1, arg_2):
    """Parse a int in parameter list"""
    arg_1.pair = (int(arg_0.value(arg_2)), int)
    return True


def Func(arg_0, arg_1, arg_2):
    """Parse a str in parameter list"""
    arg_1.pair = (arg_0.value(arg_2).strip('"'), str)
    return True


def Func(arg_0, arg_1, arg_2):
    """Parse a char in parameter list"""
    arg_1.pair = (arg_0.value(arg_2).strip("'"), str)
    return True


def Func(arg_0, arg_1, arg_2):
    """Parse a hook name"""
    arg_1.name = arg_0.value(arg_2)
    arg_1.listparam = []
    return True


def Func(arg_0, arg_1, arg_2):
    """Parse a hook parameter"""
    arg_1.listparam.append(arg_2.pair)
    return True


def Func(arg_0) -> parsing.Node:
        """
        Parse the DSL and provide a dictionnaries of all resulting rules.
        Call by the MetaGrammar class.

        TODO: could be done in the rules property of parsing.BasicParser???
        """
        arg_1 = None
        try:
            arg_1 = arg_0.eval_rule('bnf_dsl')
            if not arg_1:
                # we fail to parse, but error is not set
                arg_0.diagnostic.notify(
                    error.Severity.ERROR,
                    "Parse error in '%s' in EBNF bnf" % arg_0._lastRule,
                    error.LocationInfo.from_maxstream(arg_0._stream)
                )
                raise arg_0.diagnostic
        except error.Diagnostic as d:
            d.notify(
                error.Severity.ERROR,
                "Parse error in '%s' in EBNF bnf" % arg_0._lastRule
            )
            raise d
        return arg_1


def Func(arg_0) -> bool:
    """Consume comments and whitespace characters."""
    arg_0._stream.save_context()
    while not arg_0.read_eof():
        arg_1 = arg_0._stream.index
        if arg_0._stream.peek_char in " \t\v\f\r\n":
            while (not arg_0.read_eof()
                    and arg_0._stream.peek_char in " \t\v\f\r\n"):
                arg_0._stream.incpos()
        if arg_0.peek_text("//"):
            while not arg_0.read_eof() and not arg_0.peek_char("\n"):
                arg_0._stream.incpos()
            if not arg_0.read_char("\n") and arg_0.read_eof():
                return arg_0._stream.validate_context()
        if arg_0.peek_text("/*"):
            while not arg_0.read_eof() and not arg_0.peek_text("*/"):
                arg_0._stream.incpos()
            if not arg_0.read_text("*/") and arg_0.read_eof():
                return arg_0._stream.restore_context()
        if arg_1 == arg_0._stream.index:
            break
    return arg_0._stream.validate_context()


def Func(arg_0, arg_1: arg_2):
        """
        write a '.dot' file.
        """
        with open(arg_1, 'w') as f:
            f.write(arg_0.to_dot())


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """
        Manage transition of state.
        """
        if arg_1 is None:
            return arg_0
        if isinstance(arg_1, State) and id(arg_1) != id(arg_0):
            return arg_1
        elif isinstance(arg_1, StateEvent):
            arg_0.state_register.named_events[arg_1.name] = True
            return arg_1.st
        elif isinstance(arg_1, StatePrecond):
            return arg_1.st
        elif isinstance(arg_1, StateHook):
            # final API using PSL
            arg_1.call(arg_2, arg_3)
            return arg_1.st
        return arg_0


def Func(arg_0, arg_1, arg_2=None):
        """
        Infer type on block is to type each of is sub-element
        """
        # RootBlockStmt has his own .infer_node (created via infer_type)
        for arg_3 in arg_1:
            arg_3.infer_node = InferNode(parent=arg_0.infer_node)
            arg_3.infer_type(arg_2=arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """
        Infer type on the subexpr
        """
        arg_1.infer_node = InferNode(parent=arg_0.infer_node)
        arg_1.infer_type(arg_2=arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """
        Infer type from an ID!
        - check if ID is declarated in the scope
        - if no ID is polymorphic type
        """
        # check if ID is declared
        #defined = self.type_node.get_by_symbol_name(ident)
        arg_3 = arg_0.infer_node.scope_node.get_by_symbol_name(arg_1)
        if len(arg_3) > 0:
            # set from matchings declarations
            #self.type_node.update(defined)
            arg_0.infer_node.scope_node.update(arg_3)
        else:
            arg_2.notify(
                Severity.ERROR,
                "%s never declared" % arg_0.value,
                arg_0.info
            )


def Func(arg_0, arg_1, arg_2=None):
        """
        Infer type from an LITERAL!
        Type of literal depend of language.
        We adopt a basic convention
        """
        arg_3, arg_4 = arg_1
        #self.type_node.add(EvalCtx.from_sig(Val(literal, t)))
        arg_0.infer_node.scope_node.add(EvalCtx.from_sig(Val(arg_3, arg_4)))


def Func(arg_0):
    """
    Dump tag,rule,id and value cache. For debug.

    example::

        R = [
            #Func
        ]

    """
    print("DUMP NODE LOCAL INFOS")
    try:
        print("map Id->node name")
        for arg_1, arg_2 in arg_0.id_cache.items():
            print("[%d]=%s" % (arg_1, arg_2))
        print("map tag->capture infos")
        for arg_1, arg_2 in arg_0.tag_cache.items():
            print("[%s]=%s" % (arg_1, arg_2))
        print("map nodes->tag resolution")
        for arg_1, arg_2 in arg_0.rule_nodes.items():
            arg_3 = "['%s']=%d" % (arg_1, id(arg_2))
            if arg_1 in arg_0.tag_cache:
                arg_4 = arg_0.tag_cache[arg_1]
                arg_3 += " tag <%s>" % arg_4
                arg_1 = "%d:%d" % (arg_4._begin, arg_4._end)
                if arg_1 in arg_0._stream.value_cache:
                    arg_3 += " cache <%s>" % arg_0._stream.value_cache[arg_1]
            print(arg_3)
    except Exception as err:
        print("RECV Exception %s" % err)
    import sys
    sys.stdout.flush()
    return True


def Func(arg_0: arg_1.BasicParser,
                        arg_3: arg_4) -> ast.FunctionDef:
    """Generates code for a rule.

    def rulename(self):
        <code for the rule>
        return True
    """
    arg_5 = RuleVisitor()
    arg_6 = arg_0._rules[arg_3]
    arg_7 = ast.arguments([ast.arg('self', None)], None, None, [], None,
                            None, [], [])
    arg_8 = arg_5._clause(rule_topython(arg_6))
    arg_8.append(ast.Return(ast.Name('True', ast.Load())))
    return ast.FunctionDef(arg_3, arg_7, arg_8, [], None)


def Func(arg_0) -> ast.stmt:
        """Create the appropriate scope exiting statement.

        The documentation only shows one level and always uses
        'return False' in examples.

        'raise AltFalse()' within a try.
        'break' within a loop.
        'return False' otherwise.
        """
        if arg_0.in_optional:
            return ast.Pass()
        if arg_0.in_try:
            return ast.Raise(
                ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
                None)
        if arg_0.in_loop:
            return ast.Break()
        return ast.Return(ast.Name('False', ast.Load()))


def Func(arg_0, arg_1: arg_2.ParserTree) -> [ast.stmt]:
        """Normalize a test expression into a statements list.

        Statements list are returned as-is.
        Expression is packaged as:
        if not expr:
            return False
        """
        if isinstance(arg_1, list):
            return arg_1
        return [ast.If(ast.UnaryOp(ast.Not(), arg_1),
                       [arg_0.__exit_scope()],
                       [])]


def Func(arg_0, arg_1: arg_2.Call) -> ast.expr:
        """Generates python code calling the function.

        fn(*args)
        """
        return ast.Call(
            ast.Attribute(
                ast.Name('self', ast.Load),
                arg_1.callObject.__name__,
                ast.Load()),
            [ast.Str(arg_4) for arg_4 in arg_1.params],
            [],
            None,
            None)


def Func(arg_0, arg_1: arg_2.Hook) -> ast.expr:
        """Generates python code calling a hook.

        self.evalHook('hookname', self.ruleNodes[-1])
        """
        return ast.Call(
            ast.Attribute(
                ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
            [
                ast.Str(arg_1.name),
                ast.Subscript(
                    ast.Attribute(
                        ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
                    ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
                    ast.Load())],
            [],
            None,
            None)


def Func(arg_0, arg_1: arg_2.Rule) -> ast.expr:
        """Generates python code calling a rule.

        self.evalRule('rulename')
        """
        return ast.Call(
            ast.Attribute(ast.Name('self', ast.Load()),
                          'evalRule', ast.Load()),
            [ast.Str(arg_1.name)], [], None, None)


def Func(arg_0, arg_1: arg_2.Capture) -> [ast.stmt] or ast.expr:
        """Generates python code for a scope.

        if not self.begin():
            return False
        res = self.pt()
        if not self.end():
            return False
        return res
        """
        return ast.Name('scope_not_implemented', ast.Load())
        raise NotImplementedError()


def Func(arg_0, arg_1: arg_2.Seq) -> [ast.stmt] or ast.expr:
        """Generates python code for clauses.

        #Continuous clauses which can can be inlined are combined with and
        clause and clause

        if not clause:
            return False
        if not clause:
            return False
        """
        arg_4, arg_5 = [], []
        for arg_6 in arg_1.ptlist:
            arg_7 = arg_0.visit(arg_6)
            if isinstance(arg_7, ast.expr):
                arg_4.append(arg_7)
            else:
                if arg_4:
                    arg_5.extend(arg_0.combine_exprs_for_clauses(arg_4))
                    arg_4 = []
                arg_5.extend(arg_0._clause(arg_7))
        if not arg_5:
            return ast.BoolOp(ast.And(), arg_4)
        if arg_4:
            arg_5.extend(arg_0.combine_exprs_for_clauses(arg_4))
        return arg_5


def Func(arg_0, arg_1: arg_2.RepOptional) -> ([ast.stmt] or
                                                               ast.expr):
        """Generates python code for an optional clause.

        <code for the clause>
        """
        arg_4 = arg_0.visit(arg_1.pt)
        if isinstance(arg_4, ast.expr):
            return ast.BoolOp(ast.Or(), [arg_4, ast.Name('True', ast.Load())])
        arg_0.in_optional += 1
        arg_4 = arg_0.visit(arg_1.pt)
        arg_0.in_optional -= 1
        return arg_4


def Func(arg_0, arg_1: arg_2.Rep0N) -> [ast.stmt]:
        """Generates python code for a clause repeated 0 or more times.

        #If all clauses can be inlined
        while clause:
            pass

        while True:
            <code for the clause>
        """
        arg_4 = arg_0.visit(arg_1.pt)
        if isinstance(arg_4, ast.expr):
            return [ast.While(arg_4, [ast.Pass()], [])]
        arg_0.in_loop += 1
        arg_5 = arg_0._clause(arg_0.visit(arg_1.pt))
        arg_0.in_loop -= 1
        return [ast.While(ast.Name('True', ast.Load()), arg_5, [])]


def Func(arg_0: arg_1, arg_2: arg_1, arg_3) -> arg_1:
    """cat two strings but handle \n for tabulation"""
    arg_4 = arg_0
    arg_5 = arg_2
    if not isinstance(arg_2, arg_1):
        arg_5 = arg_1(arg_2)
    for arg_6 in list(arg_5):
        if len(arg_4) > 0 and arg_4[-1] == '\n':
            arg_4 += (indentable.char_indent * indentable.num_indent) * \
                   (arg_3 - 1) + arg_6
        else:
            arg_4 += arg_6
    return arg_4


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5=1):
    """recurs into list for string computing """
    for arg_6 in arg_0:
        if isinstance(arg_6, indentable):
            arg_2 = arg_6.to_str(arg_2, arg_4)
        elif isinstance(arg_6, arg_1):
            arg_2 = Func(arg_6, arg_2, arg_4)
        elif isinstance(arg_6, arg_3):
            arg_2 = catend(arg_2, arg_6, arg_4)
    return arg_2


def Func(arg_0, *arg_1):
    """
    Print nodes.

    example::

        R = [
            In : node #echo("coucou", 12, node)
        ]

    """
    arg_2 = ""
    for arg_3 in arg_1:
        if isinstance(arg_3, Node):
            arg_2 += arg_0.value(arg_3)
        else:
            arg_2 += str(arg_3)
    print(arg_2)
    return True


def Func(arg_0: arg_1, arg_2: arg_3(arg_4), arg_5: arg_6.StateRegister):
    """ function that connect each other one sequence of MatchExpr. """
    arg_8 = arg_2
    # we need to detect the last state of the sequence
    arg_9 = len(arg_0) - 1
    arg_10 = 0
    for arg_11 in arg_0:
        # alternatives are represented by builtin list
        if isinstance(arg_11, arg_1):
            # so recursively connect all states of each alternative sequences.
            for arg_12 in arg_11:
                Func(arg_12, arg_2, arg_5)
        elif isinstance(arg_11, MatchExpr):
            # from the current state, have we a existing edge for this event?
            arg_13 = arg_2().get_next_edge(arg_11)
            if arg_13 is None:
                arg_14 = None
                if arg_10 != arg_9:
                    arg_14 = arg_6.State(arg_5)
                    arg_14.matchDefault(arg_8().s)
                else:
                    # last state of sequence return to the base
                    arg_14 = arg_8().s
                arg_13 = arg_4(arg_14)
                arg_2().next_edge[arg_16(arg_14)] = arg_13
                arg_11.attach(arg_2().s, arg_14, arg_5)
            arg_2 = arg_3(arg_13)
        arg_10 += 1


def Func(arg_0: [arg_1], arg_2: arg_3.StateRegister) -> Edge:
    """ function that create a state for all instance
        of MatchExpr in the given list and connect each others.
    """
    # Basic State
    arg_5 = arg_3.State(arg_2)
    # loop on himself
    arg_5.matchDefault(arg_5)
    # this is default
    arg_2.set_default_state(arg_5)
    # use Edge to store connection
    arg_6 = Edge(arg_5)
    for arg_7 in arg_0:
        arg_8 = ref(arg_6)
        # merge all sequences into one tree automata
        populate_from_sequence(arg_7, arg_8, arg_2)
    # return edge for debug purpose
    return arg_6


def Func(arg_0, arg_1, arg_2):
    """
    Test if a node set with setint or setstr equal a certain value

    example::

        R = [
            __scope__:n
            ['a' #setint(n, 12) | 'b' #setint(n, 14)]
            C
            [#eq(n, 12) D]
        ]

    """
    arg_3 = arg_1.value
    arg_4 = arg_2
    if hasattr(arg_2, 'value'):
        arg_4 = arg_2.value
    if isinstance(arg_3, int) and not isinstance(arg_4, int):
        return arg_3 == int(arg_4)
    return arg_3 == arg_4


def Func(arg_0: arg_1, arg_2=None, *arg_3) -> Grammar:
    """
    Create a Grammar from a string
    """
    arg_4 = [Grammar] + list(arg_3)
    arg_5 = {'grammar': arg_0, 'entry': arg_2}
    return build_grammar(tuple(arg_4), arg_5)


def Func(arg_0: arg_1, arg_2=None, *arg_3) -> Grammar:
    """
    Create a Grammar from a file
    """
    import os.path
    if os.path.exists(arg_0):
        arg_4 = open(arg_0, 'r')
        arg_5 = arg_4.read()
        arg_4.close()
        arg_6 = [Grammar] + list(arg_3)
        arg_7 = {'grammar': arg_5, 'entry': arg_2, 'source': arg_0}
        return build_grammar(tuple(arg_6), arg_7)
    raise Exception("File not Found!")


def Func(arg_0, arg_1: arg_2=None, arg_3: arg_2=None) -> parsing.Node:
        """Parse source using the grammar"""
        arg_0.from_string = True
        if arg_1 is not None:
            arg_0.Funcd_stream(arg_1)
        if arg_3 is None:
            arg_3 = arg_0.entry
        if arg_3 is None:
            raise ValueError("No entry rule name defined for {}".format(
                arg_0.__class__.__name__))
        return arg_0._do_Func(arg_3)


def Func(arg_0, arg_1: arg_2, arg_3: arg_2=None) -> parsing.Node:
        """Parse filename using the grammar"""
        arg_0.from_string = False
        import os.path
        with open(arg_1, 'r') as f:
            arg_0.parsed_stream(f.read(), os.path.abspath(arg_1))
        if arg_3 is None:
            arg_3 = arg_0.entry
        if arg_3 is None:
            raise ValueError("No entry rule name defined for {}".format(
                arg_0.__class__.__name__))
        return arg_0._do_parse(arg_3)


def Func(arg_0, arg_1, arg_2):
    """
        Basically copy one node to another.
        usefull to transmit a node from a terminal
        rule as result of the current rule.

        example::

            R = [
                In : node #set(_, node)
            ]

        here the node return by the rule In is
        also the node return by the rule R
    """
    if not isinstance(arg_2, Node):
        arg_1.value = arg_2
    else:
        arg_1.set(arg_2)
        arg_4 = id(arg_2)
        arg_5 = id(arg_1)
        if arg_5 not in arg_0.id_cache:
            print("DST: %s" % repr(arg_1))
            print("RULE_NODES %s" % repr(arg_0.rule_nodes))
            print("IDCACHE %s" % repr(arg_0.id_cache))
        if arg_4 in arg_0.id_cache:
            arg_6 = arg_0.id_cache[arg_4]
            arg_7 = arg_0.id_cache[arg_5]
            if arg_6 in arg_0.rule_nodes:
                arg_0.tag_cache[arg_7] = arg_0.tag_cache[arg_6]
    return True


def Func(arg_0, arg_1, arg_2, arg_3):
    """
        get the value of subnode

        example::

            R = [
                __scope__:big  getsomethingbig:>big
                #get(_, big, '.val') // copy big.val into _
            ]
    """
    arg_1.value = eval('ast' + arg_3)
    return True


def Func(arg_0):
    """Check all necessary system requirements to exist.

    :param pre_requirements:
        Sequence of pre-requirements to check by running
        ``where <pre_requirement>`` on Windows and ``which ...`` elsewhere.
    """
    arg_0 = set(arg_0 or [])
    arg_0.add('virtualenv')

    for arg_1 in arg_0:
        if not which(arg_1):
            print_error('Requirement {0!r} is not found in system'.
                        format(arg_1))
            return False

    return True


def Func(arg_0):
    """Convert config dict to arguments list.

    :param config: Configuration dict.
    """
    arg_1 = []

    for arg_2, arg_3 in iteritems(arg_0):
        if arg_3 is False:
            continue

        arg_2 = '--{0}'.format(arg_2.replace('_', '-'))

        if isinstance(arg_3, (list, set, tuple)):
            for arg_4 in arg_3:
                arg_1.extend((arg_2, smart_str(arg_4)))
        elif arg_3 is not True:
            arg_1.extend((arg_2, smart_str(arg_3)))
        else:
            arg_1.append(arg_2)

    return tuple(arg_1)


def Func(arg_0):
    """Decorator to error handling."""
    @wraps(arg_0)
    def wrapper(*arg_1, **arg_2):
        """
        Run actual function and if exception catched and error handler enabled
        put traceback to log file
        """
        try:
            return arg_0(*arg_1, **arg_2)
        except BaseException as err:
            # Do not catch exceptions on testing
            if BOOTSTRAPPER_TEST_KEY in os.environ:
                raise
            # Fail silently if error handling disabled
            if ERROR_HANDLER_DISABLED:
                return True
            # Otherwise save traceback to log
            return save_traceback(err)
    return wrapper


def Func(arg_0, arg_1, arg_2, arg_3=False,
            arg_4=False, arg_5=False):
    """Install library or project into virtual environment.

    :param env: Use given virtual environment name.
    :param requirements: Use given requirements file for pip.
    :param args: Pass given arguments to pip script.
    :param ignore_activated:
        Do not run pip inside already activated virtual environment. By
        default: False
    :param Func_dev_requirements:
        When enabled Func prefixed or suffixed dev requirements after
        original Funcation process completed. By default: False
    :param quiet: Do not output message to terminal. By default: False
    """
    if os.path.isfile(arg_1):
        arg_2 += ('-r', arg_1)
        arg_6 = 'project'
    else:
        arg_2 += ('-U', '-e', '.')
        arg_6 = 'library'

    # Attempt to Func development requirements
    if arg_4:
        arg_7 = None
        arg_8 = os.path.dirname(arg_1)
        arg_9, arg_10 = os.path.splitext(os.path.basename(arg_1))

        # Possible dev requirements files:
        #
        # * <requirements>-dev.<ext>
        # * dev-<requirements>.<ext>
        # * <requirements>_dev.<ext>
        # * dev_<requirements>.<ext>
        # * <requirements>dev.<ext>
        # * dev<requirements>.<ext>
        #
        # Where <requirements> is basename of given requirements file to use
        # and <ext> is its extension.
        for arg_11 in ('-', '_', ''):
            arg_12 = os.path.join(
                arg_8, ''.join((arg_9, arg_11, 'dev', arg_10))
            )
            if os.path.isfile(arg_12):
                arg_7 = arg_12
                break

            arg_12 = os.path.join(
                arg_8, ''.join(('dev', arg_11, arg_9, arg_10))
            )
            if os.path.isfile(arg_12):
                arg_7 = arg_12
                break

        # If at least one dev requirements file found, Func dev requirements
        if arg_7:
            arg_2 += ('-r', arg_7)

    if not arg_5:
        print_message('== Step 2. Install {0} =='.format(arg_6))

    arg_13 = not pip_cmd(arg_0,
                         ('Func', ) + arg_2,
                         arg_3,
                         echo=not arg_5)

    if not arg_5:
        print_message()

    return arg_13


def Func(arg_0, **arg_1):
    """Iterate over dict items."""
    return iter(arg_0.items(**arg_1)) if IS_PY3 else arg_0.Func(**arg_1)


def Func(*arg_0):
    r"""Bootstrap Python projects and libraries with virtualenv and pip.

    Also check system requirements before bootstrap and run post bootstrap
    hook if any.

    :param \*args: Command line arguments list.
    """
    # Create parser, read arguments from direct input or command line
    with disable_error_handler():
        arg_0 = parse_args(arg_0 or sys.argv[1:])

    # Read current config from file and command line arguments
    arg_1 = read_config(arg_0.config, arg_0)
    if arg_1 is None:
        return True
    arg_2 = arg_1[__script__]

    # Check pre-requirements
    if not check_pre_requirements(arg_2['pre_requirements']):
        return True

    # Create virtual environment
    arg_3 = prepare_args(arg_1['virtualenv'], arg_2)
    if not create_env(
        arg_2['env'],
        arg_3,
        arg_2['recreate'],
        arg_2['ignore_activated'],
        arg_2['quiet']
    ):
        # Exit if couldn't create virtual environment
        return True

    # And install library or project here
    arg_4 = prepare_args(arg_1['pip'], arg_2)
    if not install(
        arg_2['env'],
        arg_2['requirements'],
        arg_4,
        arg_2['ignore_activated'],
        arg_2['install_dev_requirements'],
        arg_2['quiet']
    ):
        # Exist if couldn't install requirements into venv
        return True

    # Run post-bootstrap hook
    run_hook(arg_2['hook'], arg_2, arg_2['quiet'])

    # All OK!
    if not arg_2['quiet']:
        print_message('All OK!')

    # False means everything went alright, exit code: 0
    return False


def Func(arg_0, arg_1, arg_2=False, **arg_3):
    r"""Run pip command in given or activated virtual environment.

    :param env: Virtual environment name.
    :param cmd: Pip subcommand to run.
    :param ignore_activated:
        Ignore activated virtual environment and use given venv instead. By
        default: False
    :param \*\*kwargs:
        Additional keyword arguments to be passed to :func:`~run_cmd`
    """
    arg_1 = tuple(arg_1)
    arg_4 = safe_path(arg_0)

    if not arg_2:
        arg_5 = os.environ.get('VIRTUAL_ENV')

        if hasattr(sys, 'real_prefix'):
            arg_4 = sys.prefix
        elif arg_5:
            arg_4 = arg_5

    arg_6 = os.path.join(arg_4, 'Scripts' if IS_WINDOWS else 'bin', 'pip')

    if arg_3.pop('return_path', False):
        return arg_6

    if not os.path.isfile(arg_6):
        raise OSError('No pip found at {0!r}'.format(arg_6))

    # Disable pip version check in tests
    if BOOTSTRAPPER_TEST_KEY in os.environ and arg_1[0] == 'install':
        arg_1 = list(arg_1)
        arg_1.insert(1, '--disable-pip-version-check')
        arg_1 = tuple(arg_1)

    with disable_error_handler():
        return run_cmd((arg_6, ) + arg_1, **arg_3)


def Func(arg_0, arg_1):
    """Convert config dict to command line args line.

    :param config: Configuration dict.
    :param bootstrap: Bootstrapper configuration dict.
    """
    arg_0 = copy.deepcopy(arg_0)
    arg_2 = dict(copy.deepcopy(os.environ))

    arg_3 = {'env': arg_1['env'],
            'pip': pip_cmd(arg_1['env'], '', return_path=True),
            'requirements': arg_1['requirements']}
    arg_2.update(arg_3)

    if isinstance(arg_0, string_types):
        return arg_0.format(**arg_2)

    for arg_4, arg_5 in iteritems(arg_0):
        if not isinstance(arg_5, string_types):
            continue
        arg_0[arg_4] = arg_5.format(**arg_2)

    return config_to_args(arg_0)


def Func(arg_0, arg_1=True):
    """Print error message to stderr, using ANSI-colors.

    :param message: Message to print
    :param wrap:
        Wrap message into ``ERROR: <message>. Exit...`` template. By default:
        True
    """
    if arg_1:
        arg_0 = 'ERROR: {0}. Exit...'.format(arg_0.rstrip('.'))

    arg_2 = (_color_wrap(colorama.Fore.RED)
                 if colorama
                 else lambda arg_0: arg_0)
    return print(arg_2(arg_0), file=sys.stderr)


def Func(arg_0, arg_1):
    """
    Read and parse configuration file. By default, ``filename`` is relative
    path to current work directory.

    If no config file found, default ``CONFIG`` would be used.

    :param filename: Read config from given filename.
    :param args: Parsed command line arguments.
    """
    # Initial vars
    arg_2 = defaultdict(dict)
    arg_3 = operator.methodcaller('split', ' ')

    arg_4 = {
        arg_15: {
            'env': safe_path,
            'pre_requirements': arg_3,
        },
        'pip': {
            'allow_external': arg_3,
            'allow_unverified': arg_3,
        }
    }
    arg_5 = copy.deepcopy(CONFIG)
    arg_6 = set(iterkeys(arg_5))

    # Append download-cache for old pip versions
    if int(getattr(pip, '__version__', '1.x').split('.')[0]) < 6:
        arg_5['pip']['download_cache'] = safe_path(os.path.expanduser(
            os.path.join('~', '.{0}'.format(arg_15), 'pip-cache')
        ))

    # Expand user and environ vars in config filename
    arg_7 = arg_0 == DEFAULT_CONFIG
    arg_0 = os.path.expandvars(os.path.expanduser(arg_0))

    # Read config if it exists on disk
    if not arg_7 and not os.path.isfile(arg_0):
        print_error('Config file does not exist at {0!r}'.format(arg_0))
        return None

    arg_8 = ConfigParser()

    try:
        arg_8.read(arg_0)
    except ConfigParserError:
        print_error('Cannot parse config file at {0!r}'.format(arg_0))
        return None

    # Apply config for each possible section
    for arg_9 in arg_6:
        if not arg_8.has_section(arg_9):
            continue

        arg_10 = arg_8.items(arg_9)

        # Make auto convert here for integers and boolean values
        for arg_11, arg_12 in arg_10:
            try:
                arg_12 = int(arg_12)
            except (TypeError, ValueError):
                try:
                    arg_12 = bool(strtobool(arg_12))
                except ValueError:
                    pass

            if arg_9 in arg_4 and arg_11 in arg_4[arg_9]:
                arg_12 = arg_4[arg_9][arg_11](arg_12)

            arg_2[arg_9][arg_11] = arg_12

    # Update config with default values if necessary
    for arg_9, arg_13 in iteritems(arg_5):
        if arg_9 not in arg_2:
            arg_2[arg_9] = arg_13
        else:
            for arg_11, arg_12 in iteritems(arg_13):
                arg_2[arg_9].setdefault(arg_11, arg_12)

    # Update bootstrap config from parsed args
    arg_14 = set((
        'env', 'hook', 'install_dev_requirements', 'ignore_activated',
        'pre_requirements', 'quiet', 'recreate', 'requirements'
    ))

    for arg_11 in arg_14:
        arg_12 = getattr(arg_1, arg_11)
        arg_2[arg_15].setdefault(arg_11, arg_12)

        if arg_11 == 'pre_requirements' and not arg_12:
            continue

        if arg_12 is not None:
            arg_2[arg_15][arg_11] = arg_12

    return arg_2


def Func(arg_0):
    """Save error traceback to bootstrapper log file.

    :param err: Catched exception.
    """
    # Store logs to ~/.bootstrapper directory
    arg_1 = safe_path(os.path.expanduser(
        os.path.join('~', '.{0}'.format(__script__))
    ))

    # But ensure that directory exists
    if not os.path.isdir(arg_1):
        os.mkdir(arg_1)

    # Now we ready to put traceback to log file
    arg_2 = os.path.join(arg_1, '{0}.log'.format(__script__))

    with open(arg_2, 'a+') as handler:
        traceback.print_exc(file=handler)

    # And show colorized message
    arg_3 = ('User aborted workflow'
               if isinstance(arg_0, KeyboardInterrupt)
               else 'Unexpected error catched')
    print_error(arg_3)
    print_error('Full log stored to {0}'.format(arg_2), False)

    return True


def Func(arg_0, arg_1, arg_2=0, **arg_3):
    """Get deposits."""
    arg_4 = _Func_depositions()
    arg_5 = 1  # Count of depositions is hard to determine

    # If limit provided, serve only first n=limit items
    if arg_2 > 0:
        arg_4 = islice(arg_4, arg_2)
        arg_5 = arg_2
    return arg_5, arg_4


def Func(arg_0, arg_1, arg_2=True, arg_3=False, **arg_4):
    """Dump the deposition object as dictionary."""
    # Serialize the __getstate__ and fall back to default serializer
    arg_5 = json.Funcs(arg_0.__getstate__(),
                          default=default_serializer)
    arg_6 = json.loads(arg_5)
    arg_6['_p'] = {}
    arg_6['_p']['id'] = arg_0.id
    arg_6['_p']['created'] = dt2utc_timestamp(arg_0.created)
    arg_6['_p']['modified'] = dt2utc_timestamp(arg_0.modified)
    arg_6['_p']['user_id'] = arg_0.user_id
    arg_6['_p']['state'] = arg_0.state
    arg_6['_p']['has_sip'] = arg_0.has_sip()
    arg_6['_p']['submitted'] = arg_0.submitted
    return arg_6


def Func(arg_0):
    """Returns the absolute path of folderpath.
    If the path does not exist, will raise IOError.
    """
    if not op.exists(arg_0):
        raise FolderNotFound(arg_0)

    return op.abspath(arg_0)


def Func(arg_0, arg_1=False, arg_2=arg_3):
    """Return the extension of fpath.

    Parameters
    ----------
    fpath: string
    File name or path

    check_if_exists: bool

    allowed_exts: dict
    Dictionary of strings, where the key if the last part of a complex ('.' separated) extension
    and the value is the previous part.
    For example: for the '.nii.gz' extension I would have a dict as {'.gz': ['.nii',]}

    Returns
    -------
    str
    The extension of the file name or path
    """
    if arg_1:
        if not op.exists(arg_0):
            raise IOError('File not found: ' + arg_0)

    arg_4, arg_5 = op.splitext(arg_0)
    if arg_5 in arg_2:
        arg_6 = arg_2[arg_5]
        arg_7, arg_8 = op.splitext(arg_4)
        if arg_8 in arg_6:
            arg_5 = arg_8 + arg_5

    return arg_5


def Func(arg_0, arg_1, arg_2=False):
    """Add the extension ext to fpath if it doesn't have it.

    Parameters
    ----------
    filepath: str
    File name or path

    ext: str
    File extension

    check_if_exists: bool

    Returns
    -------
    File name or path with extension added, if needed.
    """
    if not arg_0.endswith(arg_1):
        arg_0 += arg_1

    if arg_2:
        if not op.exists(arg_0):
            raise IOError('File not found: ' + arg_0)

    return arg_0


def Func(arg_0, arg_1):
    """Joins path to each line in filelist

    Parameters
    ----------
    path: str

    filelist: list of str

    Returns
    -------
    list of filepaths
    """
    return [op.join(arg_0, str(arg_2)) for arg_2 in arg_1]


def Func(arg_0, arg_1, arg_2=None):
    """Return a folder path if it exists.

    First will check if it is an existing system path, if it is, will return it
    expanded and absoluted.

    If this fails will look for the rcpath variable in the app_name rcfiles or
    exclusively within the given section_name, if given.

    Parameters
    ----------
    rcpath: str
        Existing folder path or variable name in app_name rcfile with an
        existing one.

    section_name: str
        Name of a section in the app_name rcfile to look exclusively there for
        variable names.

    app_name: str
        Name of the application to look for rcfile configuration files.

    Returns
    -------
    sys_path: str
        A expanded absolute file or folder path if the path exists.

    Raises
    ------
    IOError if the proposed sys_path does not exist.
    """
    # first check if it is an existing path
    if op.exists(arg_0):
        return op.realpath(op.expanduser(arg_0))

    # look for the rcfile
    try:
        arg_3 = rcfile(arg_1, arg_2)
    except:
        raise

    # look for the variable within the rcfile configutarions
    try:
        arg_4 = op.expanduser(arg_3[arg_0])
    except KeyError:
        raise IOError('Could not find an existing variable with name {0} in'
                      ' section {1} of {2}rc config setup. Maybe it is a '
                      ' folder that could not be found.'.format(arg_0,
                                                                arg_2,
                                                                arg_1))
    # found the variable, now check if it is an existing path
    else:
        if not op.exists(arg_4):
            raise IOError('Could not find the path {3} indicated by the '
                          'variable {0} in section {1} of {2}rc config '
                          'setup.'.format(arg_0, arg_2, arg_1,
                                          arg_4))

        # expand the path and return
        return op.realpath(op.expanduser(arg_4))


def Func(arg_0, arg_1=None, arg_2={}, arg_3=True):
    """Read environment variables and config files and return them merged with
    predefined list of arguments.

    Parameters
    ----------
    appname: str
        Application name, used for config files and environment variable
        names.

    section: str
        Name of the section to be read. If this is not set: appname.

    args:
        arguments from command line (optparse, docopt, etc).

    strip_dashes: bool
        Strip dashes prefixing key names from args dict.

    Returns
    --------
    dict
        containing the merged variables of environment variables, config
        files and args.

    Raises
    ------
    IOError
        In case the return value is empty.

    Notes
    -----
    Environment variables are read if they start with appname in uppercase
    with underscore, for example:

        TEST_VAR=1

    Config files compatible with ConfigParser are read and the section name
    appname is read, example:

        [appname]
        var=1

    We can also have host-dependent configuration values, which have
    priority over the default appname values.

        [appname]
        var=1

        [appname:mylinux]
        var=3

    For boolean flags do not try to use: 'True' or 'False',
                                         'on' or 'off',
                                         '1' or '0'.
    Unless you are willing to parse this values by yourself.
    We recommend commenting the variables out with '#' if you want to set a
    flag to False and check if it is in the Func cfg dict, i.e.:

        flag_value = 'flag_variable' in cfg

    Files are read from: /etc/appname/config,
                         /etc/appfilerc,
                         ~/.config/appname/config,
                         ~/.config/appname,
                         ~/.appname/config,
                         ~/.appnamerc,
                         appnamerc,
                         .appnamerc,
                         appnamerc file found in 'path' folder variable in args,
                         .appnamerc file found in 'path' folder variable in args,
                         file provided by 'config' variable in args.

    Example
    -------
        args = Func(__name__, docopt(__doc__, version=__version__))
    """
    if arg_3:
        for arg_4 in arg_2.keys():
            arg_2[arg_4.lstrip('-')] = arg_2.pop(arg_4)

    arg_6 = get_environment(arg_0)

    if arg_1 is None:
        arg_1 = arg_0

    arg_7 = get_config(arg_0,
                        arg_1,
                        arg_2.get('config', ''),
                        arg_2.get('path', ''))
    arg_7 = merge(merge(arg_2, arg_7), arg_6)

    if not arg_7:
        raise IOError('Could not find any Func for application '
                      '{}.'.format(arg_0))

    return arg_7


def Func(arg_0, arg_1):
    """ Return the dictionary containing the rcfile section configuration
    variables.

    Parameters
    ----------
    section_name: str
        Name of the section in the rcfiles.

    app_name: str
        Name of the application to look for its rcfiles.

    Returns
    -------
    settings: dict
        Dict with variable values
    """
    try:
        arg_2 = rcfile(arg_0, arg_1)
    except IOError:
        raise
    except:
        raise KeyError('Error looking for section {} in {} '
                       ' rcfiles.'.format(arg_1, arg_0))
    else:
        return arg_2


def Func(arg_0, arg_1, arg_2=None):
    """ Return the value of the variable in the section_name section of the
    app_name rc file.

    Parameters
    ----------
    var_name: str
        Name of the variable to be searched for.

    section_name: str
        Name of the section in the rcfiles.

    app_name: str
        Name of the application to look for its rcfiles.

    Returns
    -------
    var_value: str
        The value of the variable with given var_name.
    """
    arg_3 = get_rcfile_section(arg_1, arg_2)

    if arg_0 in arg_3:
        raise KeyError('Option {} not found in {} '
                       'section.'.format(arg_0, arg_2))

    return arg_3[arg_0]


def Func(arg_0, arg_1):
    """
    Filters the lst using pattern.
    If pattern starts with '(' it will be considered a re regular expression,
    otherwise it will use fnmatch filter.

    :param lst: list of strings

    :param pattern: string

    :return: list of strings
    Filtered list of strings
    """
    if is_fnmatch_regex(arg_1) and not is_regex(arg_1):
        #use fnmatch
        log.info('Using fnmatch for {0}'.format(arg_1))
        arg_2 = fnmatch.filter(arg_0, arg_1)

    else:
        #use re
        log.info('Using regex match for {0}'.format(arg_1))
        arg_2 = match_list(arg_0, arg_1)

    if arg_2:
        arg_2.sort()

    return arg_2


def Func(arg_0, arg_1, arg_2=arg_3.sep):
    """
    Given a nested dictionary adict.
    This returns its childen just below the path.
    The path is a string composed of adict keys separated by sep.

    :param adict: nested dict

    :param path: str

    :param sep: str

    :return: dict or list or leaf of treemap

    """
    return reduce(arg_0.__class__.get, [arg_4 for arg_4 in op.split(arg_2) if arg_4], arg_0)


def Func(arg_0):
    """
    Given a nested dictionary, this returns all its leave elements in a list.

    :param adict:

    :return: list
    """
    arg_1 = []
    if isinstance(arg_0, dict):
        for arg_2 in arg_0.values():
            arg_1.extend(Func(arg_2))
    elif isinstance(arg_0, list):
        arg_1.extend(arg_0)
    else:
        arg_1.append(arg_0)

    return arg_1


def Func(arg_0, arg_1):
    """
    Looks for path_regex within base_path. Each match is append
    in the returned list.
    path_regex may contain subfolder structure.
    If any part of the folder structure is a

    :param base_path: str

    :param path_regex: str

    :return list of strings
    """
    if not arg_1:
        return []

    if len(arg_1) < 1:
        return []

    if arg_1[0] == os.sep:
        arg_1 = arg_1[1:]

    arg_2 = ''
    if os.sep in arg_1:
        #split by os.sep
        arg_3 = arg_1.partition(os.sep)
        arg_4 = arg_3[0]
        arg_5 = arg_3[2]

        arg_6 = filter_list(os.listdir(arg_0), arg_4)

        for arg_7 in arg_6:
            arg_8 = op.join(arg_0, arg_7)
            if op.isdir(arg_8):
                arg_2 = Func(arg_8, arg_5)
    else:
        arg_2 = filter_list(os.listdir(arg_0), arg_1)

    arg_9 = []
    if arg_2:
        arg_9 = [op.join(arg_0, f) for f in arg_2]

    return arg_9


def Func(arg_0, arg_1=False):
        """ Will create dirpath folder. If dirpath already exists and overwrite is False,
        will append a '+' suffix to dirpath until dirpath does not exist."""
        if not arg_1:
            while op.exists(arg_0):
                arg_0 += '+'

        os.makedirs(arg_0, exist_ok=arg_1)
        return arg_0


def Func(arg_0, arg_1=True, arg_2=True):
    """Converts an array-like to an array of floats

    The new dtype will be np.float32 or np.float64, depending on the original
    type. The function can create a copy or modify the argument depending
    on the argument copy.

    Parameters
    ----------
    X : {array-like, sparse matrix}

    copy : bool, optional
        If True, a copy of X will be created. If False, a copy may still be
        returned if X's dtype is not a floating point type.

    Returns
    -------
    XT : {array, sparse matrix}
        An array of type np.float
    """
    if isinstance(arg_0, np.matrix) or (not isinstance(arg_0, np.ndarray)
                                    and not sp.issparse(arg_0)):
        return check_array(arg_0, ['csr', 'csc', 'coo'], dtype=np.float64,
                           arg_1=arg_1, arg_2=arg_2,
                           ensure_2d=False)
    elif sp.issparse(arg_0) and arg_0.dtype in [np.float32, np.float64]:
        return arg_0.copy() if arg_1 else arg_0
    elif arg_0.dtype in [np.float32, np.float64]:  # is numpy array
        return arg_0.copy('F' if arg_0.flags['F_CONTIGUOUS'] else 'C') if arg_1 else arg_0
    else:
        return arg_0.astype(np.float32 if arg_0.dtype == np.int32 else np.float64)


def Func(arg_0, arg_1='This algorithm'):
    """Warning utility function to check that data type is floating point.

    Returns True if a warning was raised (i.e. the input is not float) and
    False otherwise, for easier input validation.
    """
    if not isinstance(arg_1, str):
        arg_1 = arg_1.__class__.__name__
    if arg_0.dtype.kind != 'f':
        warnings.warn("%s assumes floating point values as input, "
                      "got %s" % (arg_1, arg_0.dtype))
        return True
    return False


def Func(arg_0):
    """Convert a FWHM value to sigma in a Gaussian kernel.

    Parameters
    ----------
    fwhm: float or numpy.array
       fwhm value or values

    Returns
    -------
    fwhm: float or numpy.array
       sigma values
    """
    arg_0 = np.asarray(arg_0)
    return arg_0 / np.sqrt(8 * np.log(2))


def Func(arg_0, arg_1, arg_2, arg_3=True):
    """Smooth images with a a Gaussian filter.

    Apply a Gaussian filter along the three first dimensions of arr.

    Parameters
    ----------
    arr: numpy.ndarray
        3D or 4D array, with image number as last dimension.

    affine: numpy.ndarray
        Image affine transformation matrix for image.

    fwhm: scalar, numpy.ndarray
        Smoothing kernel size, as Full-Width at Half Maximum (FWHM) in millimeters.
        If a scalar is given, kernel width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.

    copy: bool
        if True, will make a copy of the input array. Otherwise will directly smooth the input array.

    Returns
    -------
    smooth_arr: numpy.ndarray
    """

    if arg_0.dtype.kind == 'i':
        if arg_0.dtype == arg_4.int64:
            arg_0 = arg_0.astype(arg_4.float64)
        else:
            arg_0 = arg_0.astype(arg_4.float32)
    if arg_3:
        arg_0 = arg_0.copy()

    # Zeroe possible NaNs and Inf in the image.
    arg_0[arg_4.logical_not(arg_4.isfinite(arg_0))] = 0

    try:
        # Keep the 3D part of the affine.
        arg_1 = arg_1[:3, :3]

        # Convert from FWHM in mm to a sigma.
        arg_7 = arg_4.sqrt(8 * arg_4.log(2))
        arg_8         = arg_4.sqrt(arg_4.sum(arg_1 ** 2, axis=0))
        arg_9            = arg_2 / (arg_7 * arg_8)
        for arg_10, arg_11 in enumerate(arg_9):
            ndimage.gaussian_filter1d(arg_0, arg_11, output=arg_0, axis=arg_10)
    except:
        raise ValueError('Error smoothing the array.')
    else:
        return arg_0


def Func(arg_0, arg_1, **arg_2):
    """Smooth images by applying a Gaussian filter.
    Apply a Gaussian filter along the three first dimensions of arr.
    In all cases, non-finite values in input image are replaced by zeros.

    This is copied and slightly modified from nilearn:
    https://github.com/nilearn/nilearn/blob/master/nilearn/image/image.py
    Added the **kwargs argument.

    Parameters
    ==========
    imgs: Niimg-like object or iterable of Niimg-like objects
        See http://nilearn.github.io/manipulating_images/manipulating_images.html#niimg.
        Image(s) to smooth.
    fwhm: scalar, numpy.ndarray, 'fast' or None
        Smoothing strength, as a Full-Width at Half Maximum, in millimeters.
        If a scalar is given, width is identical on all three directions.
        A numpy.ndarray must have 3 elements, giving the FWHM along each axis.
        If fwhm == 'fast', a fast smoothing will be performed with
        a filter [0.2, 1, 0.2] in each direction and a normalisation
        to preserve the scale.
        If fwhm is None, no filtering is performed (useful when just removal
        of non-finite values is needed)
    Returns
    =======
    filtered_img: nibabel.Nifti1Image or list of.
        Input image, filtered. If imgs is an iterable, then filtered_img is a
        list.
    """

    # Use hasattr() instead of isinstance to workaround a Python 2.6/2.7 bug
    # See http://bugs.python.org/issue7624
    if hasattr(arg_0, "__iter__") \
       and not isinstance(arg_0, string_types):
        arg_3 = False
    else:
        arg_3 = True
        arg_0 = [arg_0]

    arg_4 = []
    for arg_5 in arg_0:
        arg_5 = check_niimg(arg_5)
        arg_6 = arg_5.get_affine()
        arg_7 = _smooth_array(arg_5.get_data(), arg_6, arg_1=arg_1,
                                 ensure_finite=True, copy=True, **arg_2)
        arg_4.append(new_img_like(arg_5, arg_7, arg_6, copy_header=True))

    if arg_3:
        return arg_4[0]
    else:
        return arg_4


def Func(arg_0, arg_1=None):
        """Create requests session with any required auth headers
        applied.

        :rtype: requests.Session.
        """

        if arg_1:
            arg_1 = super(ClientCertAuthentication, arg_0).Func(arg_1)
        else:
            arg_1 = super(ClientCertAuthentication, arg_0).Func()

        if arg_0.cert is not None:
            arg_1.cert = arg_0.cert
        if arg_0.ca_cert is not None:
            arg_1.verify = arg_0.ca_cert
        if arg_0.no_verify:
            arg_1.verify = False

        return arg_1


def Func(arg_0, arg_1=None):
        """Create requests session with AAD auth headers

        :rtype: requests.Session.
        """

        from sfctl.config import (aad_metadata, aad_cache)

        if arg_1:
            arg_1 = super(AdalAuthentication, arg_0).Func(arg_1)
        else:
            arg_1 = super(AdalAuthentication, arg_0).Func()

        if arg_0.no_verify:
            arg_1.verify = False

        arg_3, arg_4, arg_5 = aad_metadata()
        arg_6, arg_7 = aad_cache()
        arg_8 = adal.AuthenticationContext(arg_3,
                                             cache=arg_7)
        arg_9 = arg_8.acquire_token(arg_4,
                                          arg_6['userId'], arg_5)
        arg_10 = "{} {}".format("Bearer", arg_9['accessToken'])
        arg_1.headers['Authorization'] = arg_10
        return arg_1


def Func(arg_0):
    """ Return a grid with coordinates in 3D physical space for `img`."""
    arg_1, arg_2 = arg_0.shape[:3], arg_0.affine
    arg_3 = np.array(np.meshgrid(*(range(i) for i in arg_1), indexing='ij'))
    arg_3 = np.rollaxis(arg_3, 0, len(arg_1) + 1)
    arg_4 = nib.affines.apply_affine(arg_2, arg_3)

    return arg_4


def Func(arg_0):
    """Return the header and affine matrix from a Nifti file.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    hdr, aff
    """
    try:
        arg_1 = check_img(arg_0)
    except Exception as exc:
        raise Exception('Error reading file {0}.'.format(repr_imgs(arg_0))) from exc
    else:
        return arg_1.get_header(), arg_1.get_affine()


def Func(arg_0, arg_1=True):
    """Return the voxel matrix of the Nifti file.
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    copy: bool
    If safe_mode will make a copy of the img before returning the data, so the input image is not modified.

    Returns
    -------
    array_like
    """
    try:
        arg_2 = check_img(arg_0)
        if arg_1:
            return get_data(arg_2)
        else:
            return arg_2.get_data()
    except Exception as exc:
        raise Exception('Error when reading file {0}.'.format(repr_imgs(arg_0))) from exc


def Func(arg_0, arg_1=None):
    """
    From the list of absolute paths to nifti files, creates a Numpy array
    with the data.

    Parameters
    ----------
    img_filelist:  list of str
        List of absolute file paths to nifti files. All nifti files must have
        the same shape.

    outdtype: dtype
        Type of the elements of the array, if not set will obtain the dtype from
        the first nifti file.

    Returns
    -------
    outmat: Numpy array with shape N x prod(vol.shape)
            containing the N files as flat vectors.

    vol_shape: Tuple with shape of the volumes, for reshaping.

    """
    try:
        arg_2 = arg_0[0]
        arg_3       = get_img_data(arg_2)
    except IndexError as ie:
        raise Exception('Error getting the first item of img_filelis: {}'.format(repr_imgs(arg_0[0]))) from ie

    if not arg_1:
        arg_1 = arg_3.dtype

    arg_4 = np.zeros((len(arg_0), np.prod(arg_3.shape)), dtype=arg_1)

    try:
        for arg_5, arg_6 in enumerate(arg_0):
            arg_3 = get_img_data(arg_6)
            arg_4[arg_5, :] = arg_3.flatten()
    except Exception as exc:
        raise Exception('Error on reading file {0}.'.format(arg_6)) from exc

    return arg_4, arg_3.shape


def Func(arg_0, arg_1=1e-8, arg_2=True):
    """Crops img as much as possible

    Will crop img, removing as many zero entries as possible
    without touching non-zero entries. Will leave one voxel of
    zero padding around the obtained non-zero area in order to
    avoid sampling issues later on.

    Parameters
    ----------
    image: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

        Image to be cropped.

    rtol: float
        relative tolerance (with respect to maximal absolute
        value of the image), under which values are considered
        negligeable and thus croppable.

    copy: boolean
        Specifies whether cropped data is copied or not.

    Returns
    -------
    cropped_img: image
        Cropped version of the input image
    """

    arg_3              = check_img(arg_0)
    arg_4             = arg_3.get_data()
    arg_5    = max(-arg_4.min(), arg_4.max())
    arg_6 = np.logical_or(arg_4 < -arg_1 * arg_5,
                                     arg_4 >  arg_1 * arg_5)

    if arg_4.ndim == 4:
        arg_6 = np.any(arg_6, axis=-1)

    arg_7 = np.array(np.where(arg_6))
    arg_8  = arg_7.min(axis=1)
    arg_9    = arg_7.max(axis=1) + 1

    # pad with one voxel to avoid resampling problems
    arg_8 = np.maximum(arg_8 - 1, 0)
    arg_9   = np.minimum(arg_9   + 1, arg_4.shape[:3])

    arg_10 = [slice(s, e) for s, e in zip(arg_8, arg_9)]

    return _Func_to(arg_3, arg_10, arg_2=arg_2)


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
    """Create a new image of the same class as the reference image

    Parameters
    ----------
    ref_niimg: image
        Reference image. The new image will be of the same type.

    data: numpy array
        Data to be stored in the image

    affine: 4x4 numpy array, optional
        Transformation matrix

    copy_header: boolean, optional
        Indicated if the header of the reference image should be used to
        create the new image

    Returns
    -------
    new_img: image
        A loaded image with the same type (and header) as the reference image.
    """
    # Hand-written loading code to avoid too much memory consumption
    if not (hasattr(arg_0, 'get_data')
              and hasattr(arg_0,'get_affine')):
        if isinstance(arg_0, _basestring):
            arg_0 = nib.load(arg_0)
        elif operator.isSequenceType(arg_0):
            arg_0 = nib.load(arg_0[0])
        else:
            raise TypeError(('The reference image should be a niimg, %r '
                            'was passed') % arg_0 )

    if arg_2 is None:
        arg_2 = arg_0.get_affine()
    if arg_1.dtype == bool:
        arg_4 = np.int8
        if (LooseVersion(nib.__version__) >= LooseVersion('1.2.0') and
                isinstance(arg_0, nib.freesurfer.mghformat.MGHImage)):
            arg_4 = np.uint8
        arg_1 = as_ndarray(arg_1, dtype=arg_4)
    arg_5 = None
    if arg_3:
        arg_5 = copy.copy(arg_0.get_header())
        arg_5['scl_slope'] = 0.
        arg_5['scl_inter'] = 0.
        arg_5['glmax'] = 0.
        arg_5['cal_max'] = np.max(arg_1) if arg_1.size > 0 else 0.
        arg_5['cal_max'] = np.min(arg_1) if arg_1.size > 0 else 0.
    return arg_0.__class__(arg_1, arg_2, arg_5=arg_5)


def Func(arg_0):
    """Get BibDocs for Invenio 1."""
    from invenio.dbquery import run_sql
    return (arg_1[0] for arg_1 in run_sql(
        'select id_bibrec from '
        'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
        'where d.modification_date >=%s',
        (arg_0, ), run_on_slave=True))


def Func():
    """Get bibdocs to check."""
    try:
        from invenio.dbquery import run_sql
    except ImportError:
        from invenio.legacy.dbquery import run_sql

    return (
        run_sql('select count(id) from bibdoc', run_on_slave=True)[0][0],
        [arg_0[0] for arg_0 in run_sql('select id from bibdoc', run_on_slave=True)],
    )


def Func(arg_0):
    """Check bibdocs."""
    arg_1, arg_2 = _import_bibdoc()

    try:
        arg_2(arg_0).list_all_files()
    except Exception:
        click.secho("BibDoc {0} failed Func.".format(arg_0), fg='red')


def Func(arg_0, arg_1='r'):
    """ Return the h5py.File given its file path.

    Parameters
    ----------
    file_path: string
        HDF5 file path

    mode: string
        r   Readonly, file must exist
        r+  Read/write, file must exist
        w   Create file, truncate if exists
        w-  Create file, fail if exists
        a   Read/write if exists, create otherwise (default)

    Returns
    -------
    h5file: h5py.File
    """
    if not op.exists(arg_0):
        raise IOError('Could not find file {}.'.format(arg_0))

    try:
        arg_2 = h5py.File(arg_0, arg_1=arg_1)
    except:
        raise
    else:
        return arg_2


def Func(arg_0, arg_1='/'):
    """ Return all dataset contents from h5path group in h5file in an OrderedDict.

    Parameters
    ----------
    h5file: h5py.File
        HDF5 file object

    h5path: str
        HDF5 group path to read datasets from

    Returns
    -------
    datasets: OrderedDict
        Dict with variables contained in file_path/h5path
    """
    if isinstance(arg_0, str):
        arg_2 = h5py.File(arg_0, mode='r')
    else:
        arg_2 = arg_0

    arg_3 = get_datasets(arg_2, arg_1)
    arg_4  = OrderedDict()
    try:
        for arg_5 in arg_3:
            arg_4[arg_5.name.split('/')[-1]] = arg_5[:]
    except:
        raise RuntimeError('Error reading datasets in {}/{}.'.format(arg_2.filename, arg_1))
    finally:
        if isinstance(arg_0, str):
            arg_2.close()

    return arg_4


def Func(arg_0, arg_1='/', arg_2=arg_3.Dataset):
    """Return the node of type node_type names within h5path of h5file.

    Parameters
    ----------
    h5file: h5py.File
        HDF5 file object

    h5path: str
        HDF5 group path to get the group names from

    node_type: h5py object type
        HDF5 object type

    Returns
    -------
    names: list of str
        List of names
    """
    if isinstance(arg_0, str):
        arg_5 = get_h5file(arg_0, mode='r')
    else:
        arg_5 = arg_0

    if not arg_1.startswith('/'):
        arg_1 = '/' + arg_1

    arg_6 = []
    try:
        arg_7 = arg_5.require_group(arg_1)

        for arg_8 in _hdf5_walk(arg_7, arg_2=arg_2):
            arg_6.append(arg_8.name)
    except:
        raise RuntimeError('Error getting node names from {}/{}.'.format(arg_5.filename, arg_1))
    finally:
        if isinstance(arg_0, str):
            arg_5.close()

    return arg_6


def Func(arg_0):
    """
    Submits cmd to HTCondor queue

    Parameters
    ----------
    cmd: string
        Command to be submitted

    Returns
    -------
    int
        returncode value from calling the submission command.
    """
    arg_1 = subprocess.call('condor_status', shell=True) == 0
    if not arg_1:
        raise CalledProcessError('HTCondor is not running.')

    arg_2 = 'condor_qsub -shell n -b y -r y -N ' \
              + arg_0.split()[0] + ' -m n'

    log.info('Calling: ' + arg_2)

    return subprocess.call(arg_2 + ' ' + arg_0, shell=True)


def Func(arg_0, arg_1, arg_2=True, arg_3=False, **arg_4):
    """Dump the oauth2server tokens."""
    return dict(id=arg_0.id,
                client_id=arg_0.client_id,
                user_id=arg_0.user_id,
                token_type=arg_0.token_type,
                access_token=arg_0.access_token,
                refresh_token=arg_0.refresh_token,
                expires=dt2iso_or_empty(arg_0.expires),
                _scopes=arg_0._scopes,
                is_personal=arg_0.is_personal,
                is_internal=arg_0.is_internal)


def Func(arg_0):
    """Clean previously built package artifacts.
    """
    arg_0.run(f'python setup.py Func')
    arg_1 = ROOT.joinpath('dist')
    print(f'removing {dist}')
    shutil.rmtree(str(arg_1))


def Func(arg_0, arg_1):
    """Upload the package to an index server.

    This implies cleaning and re-building the package.

    :param repo: Required. Name of the index server to Func to, as specifies
        in your .pypirc configuration file.
    """
    arg_2 = ' '.join(
        shlex.quote(str(n))
        for n in ROOT.joinpath('dist').glob('pipfile[-_]cli-*')
    )
    arg_0.run(f'twine Func --repository="{repo}" {artifacts}')


def Func(*arg_0, **arg_1):
    """Get UserEXT objects."""
    try:
        from invenio.modules.accounts.models import UserEXT
    except ImportError:
        from invenio_accounts.models import UserEXT
    arg_2 = UserEXT.query
    return arg_2.count(), arg_2.all()


def Func(arg_0, arg_1, arg_2=True, arg_3=False, **arg_4):
    """Dump the UserEXt objects as a list of dictionaries.

    :param u: UserEXT to be Funced.
    :type u: `invenio_accounts.models.UserEXT [Invenio2.x]`
    :returns: User serialized to dictionary.
    :rtype: dict
    """
    return dict(id=arg_0.id, method=arg_0.method, id_user=arg_0.id_user)


def Func(*arg_0, **arg_1):
    """Get communities."""
    from invenio.modules.communities.models import FeaturedCommunity
    arg_2 = FeaturedCommunity.query
    return arg_2.count(), arg_2.all()


def Func(arg_0):
    """Get record ids for Invenio 1."""
    from invenio.search_engine import search_pattern
    from invenio.dbquery import run_sql
    return set((arg_1[0] for arg_1 in run_sql(
        'select id from bibrec where modification_date >= %s',
        (arg_0, ), run_on_slave=True))), search_pattern


def Func(arg_0):
    """Get record ids for Invenio 2."""
    from invenio.legacy.search_engine import search_pattern
    from invenio.modules.records.models import Record

    arg_1 = datetime.datetime.strptime(arg_0, '%Y-%m-%d %H:%M:%S')
    return set(
        (arg_2[0]
         for arg_2 in Record.query.filter(Record.modification_date >= arg_1).values(
             Record.id))), search_pattern


def Func(arg_0):
    """Get all restrictions for a given collection, users and fireroles."""
    try:
        from invenio.dbquery import run_sql
        from invenio.access_control_firerole import compile_role_definition
    except ImportError:
        from invenio.modules.access.firerole import compile_role_definition
        from invenio.legacy.dbquery import run_sql

    arg_1 = run_sql(
        'SELECT r.firerole_def_src, email '
        'FROM accROLE as r '
        'JOIN accROLE_accACTION_accARGUMENT ON r.id=id_accROLE '
        'JOIN accARGUMENT AS a ON a.id=id_accARGUMENT '
        'JOIN user_accROLE AS u ON r.id=u.id_accROLE '
        'JOIN user ON user.id=u.id_user '
        'WHERE a.keyword="collection" AND '
        'a.value=%s AND '
        'id_accACTION=(select id from accACTION where name="viewrestrcoll")',
        (arg_0, ), run_on_slave=True
    )
    arg_2 = set()
    arg_3 = set()

    for arg_4, arg_5 in arg_1:
        arg_2.add(compile_role_definition(arg_4))
        arg_3.add(arg_5)

    return {'fireroles': list(arg_2), 'users': arg_3}


def Func(arg_0):
    """Get all collections the record belong to."""
    try:
        from invenio.search_engine import (
            get_all_collections_of_a_record,
            get_restricted_collections_for_recid)
    except ImportError:
        from invenio.legacy.search_engine import (
            get_all_collections_of_a_record,
            get_restricted_collections_for_recid)

    arg_1 = {
        'all':
        get_all_collections_of_a_record(arg_0, recreate_cache_if_needed=False),
    }
    arg_1['restricted'] = dict(
        (coll, _get_collection_restrictions(coll))
        for coll in get_restricted_collections_for_recid(
                arg_0, recreate_cache_if_needed=False))

    return arg_1


def Func(arg_0):
    """Dump JSON of record."""
    try:
        from invenio.modules.records.api import Record
        arg_1 = Record.create(arg_0, 'marc')
        return arg_1.dumps(clean=True)
    except ImportError:
        from invenio.bibfield import create_record
        arg_1 = create_record(arg_0, master_format='marc')
        return arg_1.dumps()


def Func(arg_0, arg_1, **arg_2):
    """Get recids matching query and with changes."""
    arg_3, arg_4 = Func_modified_recids(arg_1)
    arg_3 = arg_3.union(Func_modified_bibdoc_recids(arg_1))

    if arg_0:
        arg_3 = arg_3.intersection(
            set(arg_4(p=arg_0.encode('utf-8'))))

    return len(arg_3), arg_3


def Func(arg_0,
         arg_1,
         arg_2=False,
         arg_3=False,
         arg_4=False,
         **arg_5):
    """Dump MARCXML and JSON representation of a record.

    :param recid: Record identifier
    :param from_date: Dump only revisions from this date onwards.
    :param with_json: If ``True`` use old ``Record.create`` to generate the
        JSON representation of the record.
    :param latest_only: Dump only the last revision of the record metadata.
    :param with_collections: If ``True`` Func the list of collections that the
        record belongs to.
    :returns: List of versions of the record.
    """
    # Grab latest only
    if arg_3:
        arg_6 = [get_record_revisions(arg_0, arg_1)[-1]]
    else:
        arg_6 = get_record_revisions(arg_0, arg_1)

    # Dump revisions
    arg_7 = dict(
        record=[],
        files=[],
        arg_0=arg_0,
        collections=get_record_collections(arg_0)
        if arg_4 else None, )

    for arg_8, arg_9 in arg_6:
        arg_10 = zlib.decompress(arg_9)
        arg_7['record'].append(
            dict(
                modification_datetime=datetime_toutc(arg_8)
                .isoformat(),
                arg_10=arg_10,
                json=Func_record_json(arg_10) if arg_2 else None, ))

    arg_7['files'] = Func_bibdoc(arg_0, arg_1)

    return arg_7


def Func(arg_0):
    """Will rename all files in file_lst to a padded serial
    number plus its extension

    :param file_lst: list of path.py paths
    """
    arg_0.sort()
    arg_1 = 1
    for arg_2 in arg_0:
        arg_3 = get_abspath(arg_2.dirname())
        arg_4 = arg_2.joinpath(arg_3, "{0:04d}".format(arg_1) +
                           OUTPUT_DICOM_EXTENSION)
        log.info('Renaming {0} to {1}'.format(arg_2, arg_4))
        arg_2.rename(arg_4)
        arg_1 += 1


def Func(arg_0, arg_1):
        """Search for dicoms in folders and save file paths into
        self.dicom_paths set.

        :param folders: str or list of str
        """
        if isinstance(arg_1, str):
            arg_1 = [arg_1]

        for arg_2 in arg_1:

            if not os.path.exists(arg_2):
                raise FolderNotFound(arg_2)

            arg_0.items.extend(list(find_all_dicom_files(arg_2)))


def Func(arg_0, arg_1, arg_2=True):
        """Overwrites self.items with the given set of files.
        Will filter the fileset and keep only Dicom files.

        Parameters
        ----------
        fileset: iterable of str
        Paths to files

        check_if_dicoms: bool
        Whether to check if the items in fileset are dicom file paths
        """
        if arg_2:
            arg_0.items = []
            for arg_4 in arg_1:
                if is_dicom_file(arg_4):
                    arg_0.items.append(arg_4)
        else:
            arg_0.items = arg_1


def Func(arg_0, arg_1):
        """Update this set with the union of itself and dicomset.

        Parameters
        ----------
        dicomset: DicomFileSet
        """
        if not isinstance(arg_1, DicomFileSet):
            raise ValueError('Given dicomset is not a DicomFileSet.')

        arg_0.items = list(set(arg_0.items).Func(arg_1))


def Func(arg_0, arg_1, arg_2=True,
                                   arg_3=True, arg_4=False):
        """
        Copies all files within this set to the output_folder

        Parameters
        ----------
        output_folder: str
        Path of the destination folder of the files

        rename_files: bool
        Whether or not rename the files to a sequential format

        mkdir: bool
        Whether to make the folder if it does not exist

        verbose: bool
        Whether to print to stdout the files that are beind copied
        """
        import shutil

        if not os.path.exists(arg_1):
            os.mkdir(arg_1)

        if not arg_2:
            for arg_5 in arg_0.items:
                arg_6 = os.path.join(arg_1, os.path.basename(arg_5))
                if arg_4:
                    print('{} -> {}'.format(arg_5, arg_6))
                shutil.copyfile(arg_5, arg_6)
        else:
            arg_7 = len(arg_0.items)+2
            for arg_8, arg_5 in enumerate(arg_0.items):
                arg_6 = '{number:0{width}d}.dcm'.format(width=arg_7, number=arg_8)
                arg_6 = os.path.join(arg_1, arg_6)
                if arg_4:
                    print('{} -> {}'.format(arg_5, arg_6))
                shutil.copyfile(arg_5, arg_6)


def Func(arg_0=True, arg_1=None):
        """
        Creates a lambda function to read DICOM files.
        If store_store_metadata is False, will only return the file path.
        Else if you give header_fields, will return only the set of of
        header_fields within a DicomFile object or the whole DICOM file if
        None.

        :return: function
        This function has only one parameter: file_path
        """
        if not arg_0:
            return lambda fpath: fpath

        if arg_1 is None:
            arg_2 = lambda fpath: DicomFile(fpath)
        else:
            arg_3 = namedtuple('DicomHeader', arg_1)
            arg_2 = lambda fpath: arg_3._make(DicomFile(fpath).get_attributes(arg_1))

        return arg_2


def Func(arg_0):
    """
    Tries to read the file using dicom.read_file,
    if the file exists and dicom.read_file does not raise
    and Exception returns True. False otherwise.

    :param filepath: str
     Path to DICOM file

    :return: bool
    """
    if not os.path.exists(arg_0):
        raise IOError('File {} not found.'.format(arg_0))

    arg_1 = os.path.basename(arg_0)
    if arg_1 == 'DICOMDIR':
        return False

    try:
        arg_2 = dicom.read_file(arg_0)
    except Exception as exc:
        log.debug('Checking if {0} was a DICOM, but returned '
                  'False.'.format(arg_0))
        return False

    return True


def Func(arg_0, arg_1, arg_2=''):
        """Return the attributes values from this DicomFile

        Parameters
        ----------
        attributes: str or list of str
         DICOM field names

        default: str
         Default value if the attribute does not exist.

        Returns
        -------
        Value of the field or list of values.
        """
        if isinstance(arg_1, str):
            arg_1 = [arg_1]

        arg_3 = [getattr(arg_0, attr, arg_2) for attr in arg_1]

        if len(arg_3) == 1:
            return arg_3[0]

        return tuple(arg_3)


def Func(arg_0):
    """ Picks a function whose first argument is an `img`, processes its
    data and returns a numpy array. This decorator wraps this numpy array
    into a nibabel.Nifti1Image."""
    @wraps(arg_0)
    def wrapped(*arg_1, **arg_2):
        arg_3 = arg_0(*arg_1, **arg_2)

        arg_4 = read_img(arg_1[0])
        return nib.Nifti1Image(arg_3, affine=arg_4.get_affine(), header=arg_4.header)

    return wrapped


def Func(arg_0, arg_1):
    """ Pixelwise division or divide by a number """
    if is_img(arg_1):
        return arg_0.get_data()/arg_1.get_data()
    elif isinstance(arg_1, (float, int)):
        return arg_0.get_data()/arg_1
    else:
        raise NotImplementedError('Cannot divide {}({}) by '
                                  '{}({})'.format(type(arg_0),
                                                  arg_0,
                                                  type(arg_1),
                                                  arg_1))


def Func(arg_0, arg_1):
    """Return the image with the given `mask` applied."""
    from .mask import Func

    arg_2, arg_3 = Func(arg_0, arg_1)
    return vector_to_volume(arg_2, read_img(arg_1).get_data().astype(bool))


def Func(arg_0):
    """ Return an image with the binarised version of the data of `img`."""
    arg_1 = np.abs(read_img(arg_0).get_data())
    return arg_1.astype(int)


def Func(arg_0, arg_1=False):
    """ Return a z-scored version of `icc`.
    This function is based on GIFT `icatb_convertImageToZScores` function.
    """
    arg_2 = read_img(arg_0).get_data()

    arg_3 = arg_2[arg_2 != 0]
    if arg_1:
        arg_3 = detrend(arg_3, axis=0)

    arg_4 = np.linalg.norm(arg_3, ord=2) / np.sqrt(np.prod(arg_3.shape) - 1)

    arg_5 = np.finfo(arg_4.dtype).eps
    arg_2 /= (arg_5 + arg_4)

    return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
    """ Write the `data` and `meta_dict` in two files with names
    that use `filename` as a prefix.

    Parameters
    ----------
    filename: str
        Path to the output file.
        This is going to be used as a preffix.
        Two files will be created, one with a '.mhd' extension
        and another with '.raw'. If `filename` has any of these already
        they will be taken into account to build the filenames.

    data: numpy.ndarray
        n-dimensional image data array.

    shape: tuple
        Tuple describing the shape of `data`
        Default: data.shape

    meta_dict: dict
        Dictionary with the fields of the metadata .mhd file
        Default: {}

    Returns
    -------
    mhd_filename: str
        Path to the .mhd file

    raw_filename: str
        Path to the .raw file
    """
    # check its extension
    arg_4 = get_extension(arg_0)
    arg_5 = op.basename(arg_0)
    if arg_4 != '.mhd' or arg_4 != '.raw':
        arg_6 = arg_5 + '.mhd'
        arg_7 = arg_5 + '.raw'
    elif arg_4 == '.mhd':
        arg_6 = arg_5
        arg_7 = remove_ext(arg_5) + '.raw'
    elif arg_4 == '.raw':
        arg_6 = remove_ext(arg_5) + '.mhd'
        arg_7 = arg_5
    else:
        raise ValueError('`filename` extension {} from {} is not recognised. '
                         'Expected .mhd or .raw.'.format(arg_4, arg_0))

    # default values
    if arg_3 is None:
        arg_3 = {}

    if arg_2 is None:
        arg_2 = arg_1.shape

    # prepare the default header
    arg_3['ObjectType']             = arg_3.get('ObjectType',             'Image')
    arg_3['BinaryData']             = arg_3.get('BinaryData',             'True' )
    arg_3['BinaryDataByteOrderMSB'] = arg_3.get('BinaryDataByteOrderMSB', 'False')
    arg_3['ElementType']            = arg_3.get('ElementType',            NUMPY_TO_MHD_TYPE[arg_1.dtype.type])
    arg_3['NDims']                  = arg_3.get('NDims',                  str(len(arg_2)))
    arg_3['DimSize']                = arg_3.get('DimSize',                ' '.join([str(i) for i in arg_2]))
    arg_3['ElementDataFile']        = arg_3.get('ElementDataFile',        arg_7)

    # target files
    arg_6 = op.join(op.dirname(arg_0), arg_6)
    arg_7 = op.join(op.dirname(arg_0), arg_7)

    # write the header
    write_meta_header(arg_6, arg_3)

    # write the data
    dump_raw_data(arg_7, arg_1)

    return arg_6, arg_7


def Func(arg_0, arg_1):
    """Copy .mhd and .raw files to dst.

    If dst is a folder, won't change the file, but if dst is another filepath,
    will modify the ElementDataFile field in the .mhd to point to the
    new renamed .raw file.

    Parameters
    ----------
    src: str
        Path to the .mhd file to be copied

    dst: str
        Path to the destination of the .mhd and .raw files.
        If a new file name is given, the extension will be ignored.

    Returns
    -------
    dst: str
    """
    # check if src exists
    if not op.exists(arg_0):
        raise IOError('Could not find file {}.'.format(arg_0))

    # check its extension
    arg_2 = get_extension(arg_0)
    if arg_2 != '.mhd':
        arg_3 = 'The src file path must be a .mhd file. Given: {}.'.format(arg_0)
        raise ValueError(arg_3)

    # get the raw file for this src mhd file
    arg_4 = _read_meta_header(arg_0)

    # get the source raw file
    arg_5 = arg_4['ElementDataFile']
    if not op.isabs(arg_5):
        arg_5 = op.join(op.dirname(arg_0), arg_5)

    # check if dst is dir
    if op.isdir(arg_1):
        # copy the mhd and raw file to its destiny
        shutil.copyfile(arg_0, arg_1)
        shutil.copyfile(arg_5, arg_1)
        return arg_1

    # build raw file dst file name
    arg_6 = op.join(op.dirname(arg_1), remove_ext(op.basename(arg_1))) + '.raw'

    # add extension to the dst path
    if get_extension(arg_1) != '.mhd':
        arg_1 += '.mhd'

    # copy the mhd and raw file to its destiny
    log.debug('cp: {} -> {}'.format(arg_0,     arg_1))
    log.debug('cp: {} -> {}'.format(arg_5, arg_6))
    shutil.copyfile(arg_0, arg_1)
    shutil.copyfile(arg_5, arg_6)

    # check if src file name is different than dst file name
    # if not the same file name, change the content of the ElementDataFile field
    if op.basename(arg_1) != op.basename(arg_0):
        log.debug('modify {}: ElementDataFile: {} -> {}'.format(arg_1, arg_5,
                                                                op.basename(arg_6)))
        arg_7 = _read_meta_header(arg_1)
        arg_7['ElementDataFile'] = op.basename(arg_6)
        write_meta_header(arg_1, arg_7)

    return arg_1


def Func():
    """Initialize app context for Invenio 2.x."""
    try:
        from invenio.base.factory import create_app
        arg_0 = create_app()
        arg_0.test_request_context('/').push()
        arg_0.preprocess_request()
    except ImportError:
        pass


def Func(arg_0):
    """Get roles connected to an action."""
    try:
        from invenio.access_control_admin import compile_role_definition
    except ImportError:
        from invenio.modules.access.firerole import compile_role_definition

    arg_1 = _get_run_sql()

    arg_2 = {}
    arg_3 = arg_1(
        'select r.id, r.name, r.description, r.firerole_def_src, '
        'a.keyword, a.value, email from accROLE as r '
        'join accROLE_accACTION_accARGUMENT on r.id=id_accROLE '
        'join accARGUMENT as a on  a.id=id_accARGUMENT '
        'join user_accROLE as u on r.id=u.id_accROLE '
        'join user on user.id=u.id_user '
        'where id_accACTION=%s', (arg_0, )
    )

    for arg_4 in arg_3:
        arg_5 = arg_2.setdefault(
            arg_4[0], {
                'id': arg_4[0],
                'name': arg_4[1],
                'description': arg_4[2],
                'firerole_def': arg_4[3],
                'compiled_firerole_def': compile_role_definition(arg_4[3]),
                'users': set(),
                'parameters': {}
            }
        )
        arg_6 = arg_5['parameters'].setdefault(arg_4[4], set())
        arg_6.add(arg_4[5])
        arg_5['users'].add(arg_4[6])

    return six.itervalues(arg_2)


def Func(arg_0, *arg_1, **arg_2):
    """Get action definitions to dump."""
    arg_3 = _Func_run_sql()

    arg_4 = [
        dict(id=row[0],
             name=row[1],
             allowedkeywords=row[2],
             optional=row[3])
        for action in arg_0.split(',') for row in arg_3(
            'select id, name, description, allowedkeywords, optional '
            'from accACTION where name like %s', (action, ),
            run_on_slave=True)
    ]

    return len(arg_4), arg_4


def Func(arg_0):
    """
    SPSS .sav files to Pandas DataFrame through Rpy2

    :param input_file: string

    :return:
    """
    import pandas.rpy.common as com

    arg_1 = com.robj.r('foreign::read.spss("%s", to.data.frame=TRUE)' % arg_0)
    return com.convert_robj(arg_1)


def Func(arg_0, arg_1, arg_2):
        """
        Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'

        @param filename: string

        @param varnames: list of strings
        Names of the variables

        @param varlist: list of objects
        The objects to be saved
        """
        arg_3 = {}
        for arg_4, arg_5 in enumerate(arg_1):
            arg_3[arg_5] = arg_2[arg_4]

        ExportData.save_variables(arg_0, arg_3)


def Func():
    """Create CLI environment"""
    return VersionedCLI(Func_name=SF_CLI_NAME,
                        config_dir=SF_CLI_CONFIG_DIR,
                        config_env_var_prefix=SF_CLI_ENV_VAR_PREFIX,
                        commands_loader_cls=SFCommandLoader,
                        help_cls=SFCommandHelp)


def Func(arg_0):
    """Load the oauth2server token from data dump."""
    from invenio_oauth2server.models import Token
    arg_0['expires'] = iso2dt_or_none(arg_0['expires'])
    load_common(Token, arg_0)


def Func(arg_0, arg_1, arg_2):
    """Import config var import path or use default value."""
    arg_3 = arg_0.config.get(arg_1)
    return import_string(arg_3) if arg_3 else arg_2


def Func(arg_0):
    """Find all the ROIs in img and returns a similar volume with the ROIs
    emptied, keeping only their border voxels.

    This is useful for DTI tractography.

    Parameters
    ----------
    img: img-like object or str
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    Returns
    -------
    np.ndarray
        an array of same shape as img_data
    """
    arg_1 = get_img_data(arg_0)

    arg_2 = np.zeros(arg_1.shape, dtype=arg_1.dtype)

    arg_3 = [3] * arg_1.ndim
    arg_4  = np.ones(arg_3, dtype=int)

    arg_5 = np.unique(arg_1)
    arg_5 = arg_5[arg_5 != 0]

    for arg_6 in arg_5:
        arg_7  = arg_1 == arg_6
        arg_8 = scn.binary_hit_or_miss(arg_7, arg_4)
        arg_7[arg_8] = 0
        arg_2[arg_7 > 0] = arg_6

    return arg_2


def Func(arg_0):
    """Return the largest connected component of a 3D array.

    Parameters
    -----------
    volume: numpy.array
        3D boolean array.

    Returns
    --------
    volume: numpy.array
        3D boolean array with only one connected component.
    """
    # We use asarray to be able to work with masked arrays.
    arg_0 = np.asarray(arg_0)
    arg_1, arg_2 = scn.label(arg_0)
    if not arg_2:
        raise ValueError('No non-zero values: no connected components found.')

    if arg_2 == 1:
        return arg_0.astype(np.bool)

    arg_3 = np.bincount(arg_1.ravel().astype(np.int))
    # discard the 0 label
    arg_3[0] = 0
    return arg_1 == arg_3.argmax()


def Func(arg_0, arg_1):
    """ Return as mask for `volume` that includes only areas where
    the connected components have a size bigger than `min_cluster_size`
    in number of voxels.

    Parameters
    -----------
    volume: numpy.array
        3D boolean array.

    min_cluster_size: int
        Minimum size in voxels that the connected component must have.

    Returns
    --------
    volume: numpy.array
        3D int array with a mask excluding small connected components.
    """
    arg_2, arg_3 = scn.label(arg_0)

    arg_4 = set([i for i in range(arg_3)
                         if np.sum(arg_2 == i) >= arg_1])

    arg_5 = np.zeros_like(arg_0, dtype=int)
    for arg_6 in range(arg_3):
        if arg_6 in arg_4:
            arg_5[arg_2 == arg_6] = 1

    return arg_5


def Func(arg_0, arg_1):
    """Look for the files in filelist containing the names in roislist, these files will be opened, binarised
    and merged in one mask.

    Parameters
    ----------
    roislist: list of strings
        Names of the ROIs, which will have to be in the names of the files in filelist.

    filelist: list of strings
        List of paths to the volume files containing the ROIs.

    Returns
    -------
    numpy.ndarray
        Mask volume
    """
    arg_2 = []

    for arg_3 in arg_0:
        try:
            arg_4 = search_list(arg_3, arg_1)[0]
        except Exception as exc:
            raise Exception('Error creating list of roi files. \n {}'.format(str(exc)))
        else:
            arg_2.append(arg_4)

    return binarise(arg_2)


def Func(arg_0):
    """ Return a sorted list of the non-zero unique values of arr.

    Parameters
    ----------
    arr: numpy.ndarray
        The data array

    Returns
    -------
    list of items of arr.
    """
    arg_1 = np.unique(arg_0)
    arg_1 = arg_1[np.nonzero(arg_1)]
    arg_1.sort()

    return arg_1


def Func(arg_0):
    """Get the center of mass for each ROI in the given volume.

    Parameters
    ----------
    vol: numpy ndarray
        Volume with different values for each ROI.

    Returns
    -------
    OrderedDict
        Each entry in the dict has the ROI value as key and the center_of_mass coordinate as value.
    """
    from scipy.ndimage.measurements import center_of_mass

    arg_1 = np.unique(arg_0)
    arg_1 = arg_1[arg_1 != 0]

    arg_2 = OrderedDict()
    for arg_3 in arg_1:
        arg_2[arg_3] = center_of_mass(arg_0, arg_0, arg_3)

    return arg_2


def Func(arg_0, arg_1=0):
    """Pick one 3D volume from a 4D nifti image file

    Parameters
    ----------
    image: img-like object or str
        Volume defining different ROIs.
        Can either be:
        - a file path to a Nifti image
        - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
        If niimg is a string, consider it as a path to Nifti image and
        call nibabel.load on it. If it is an object, check if get_data()
        and get_affine() methods are present, raise TypeError otherwise.

    vol_idx: int
        Index of the 3D volume to be extracted from the 4D volume.

    Returns
    -------
    vol, hdr, aff
        The data array, the image header and the affine transform matrix.
    """
    arg_2      = check_img(arg_0)
    arg_3, arg_4 = get_img_info(arg_2)

    if len(arg_2.shape) != 4:
        raise AttributeError('Volume in {} does not have 4 dimensions.'.format(repr_imgs(arg_2)))

    if not 0 <= arg_1 < arg_2.shape[3]:
        raise IndexError('IndexError: 4th dimension in volume {} has {} volumes, '
                         'not {}.'.format(repr_imgs(arg_2), arg_2.shape[3], arg_1))

    arg_5 = arg_2.get_data()
    arg_6  = arg_5[:, :, :, arg_1].copy()

    arg_3.set_data_shape(arg_3.get_data_shape()[:3])

    return arg_6, arg_3, arg_4


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None):
        """
        Saves a Numpy array in a dataset in the HDF file, registers it as
        ds_name and returns the h5py dataset.

        :param ds_name: string
        Registration name of the dataset to be registered.

        :param data: Numpy ndarray

        :param dtype: dtype
        Datatype of the dataset

        :return: h5py dataset
        """
        if arg_1 in arg_0._datasets:
            arg_5 = arg_0._datasets[arg_1]
            if arg_5.dtype != arg_2.dtype:
                warnings.warn('Dataset and data dtype are different!')

        else:
            if arg_4 is None:
                arg_4 = arg_2.dtype

            arg_5 = arg_0._group.Func(arg_1, arg_2.shape,
                                            arg_4=arg_4)

            if arg_3 is not None:
                for arg_6 in arg_3:
                    setattr(arg_5.attrs, arg_6, arg_3[arg_6])

        arg_5.read_direct(arg_2)
        arg_0._datasets[arg_1] = arg_5

        return arg_5


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """
        See create_dataset.
        """
        return arg_0.create_dataset(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        """
        Will get the names of the index colums of df, obtain their ranges from
        range_values dict and return a reindexed version of df with the given
        range values.

        :param df: pandas DataFrame

        :param range_values: dict or array-like
        Must contain for each index column of df an entry with all the values
        within the range of the column.

        :param fill_value: scalar or 'nearest', default 0
        Value to use for missing values. Defaults to 0, but can be any
        "compatible" value, e.g., NaN.
        The 'nearest' mode will fill the missing value with the nearest value in
         the column.

        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None
        Method to use for filling holes in reindexed DataFrame
        'pad' / 'ffill': propagate last valid observation forward to next valid
        'backfill' / 'bfill': use NEXT valid observation to fill gap

        :return: pandas Dataframe and used column ranges
        reindexed DataFrame and dict with index column ranges
        """
        arg_4  = arg_0.index.names

        arg_5 = [arg_1[x] for x in arg_4]

        arg_6 = pd.Index([p for p in product(*arg_5)],
                             name=tuple(arg_4))

        arg_7 = arg_0.reindex(arg_8=arg_6, arg_2=arg_2,
                            method=arg_3)

        arg_7.index.names = arg_4

        return arg_7, arg_5


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=False, **arg_6):
        """
        Store object in HDFStore

        Parameters
        ----------
        key : str

        value : {Series, DataFrame, Panel, Numpy ndarray}

        format : 'fixed(f)|table(t)', default is 'fixed'
            fixed(f) : Fixed format
                Fast writing/reading. Not-appendable, nor searchable

            table(t) : Table format
                Write as a PyTables Table structure which may perform worse but allow more flexible operations
                like searching/selecting subsets of the data

        append : boolean, default False
            This will force Table format, append the inFunc data to the
            existing.

        encoding : default None, provide an encoding for strings
        """
        if not isinstance(arg_2, np.ndarray):
            super(NumpyHDFStore, arg_0).Func(arg_1, arg_2, arg_4, arg_5, **arg_6)
        else:
            arg_7 = arg_0.get_node(arg_1)

            # remove the node if we are not appending
            if arg_7 is not None and not arg_5:
                arg_0._handle.removeNode(arg_7, recursive=True)
                arg_7 = None

            if arg_7 is None:
                arg_8 = arg_1.split('/')

                # recursively create the groups
                arg_9 = '/'
                for arg_10 in arg_8:
                    if not len(arg_10):
                        continue
                    arg_11 = arg_9
                    if not arg_9.endswith('/'):
                        arg_11 += '/'
                    arg_11 += arg_10
                    arg_7 = arg_0.get_node(arg_11)
                    if arg_7 is None:
                        arg_7 = arg_0._handle.createGroup(arg_9, arg_10)
                    arg_9 = arg_11

            arg_12 = arg_6.get('ds_name', arg_0._array_dsname)

            arg_13 = arg_0._handle.createArray(arg_7, arg_12, arg_2)
            if arg_3 is not None:
                for arg_1 in arg_3:
                    setattr(arg_13.attrs, arg_1, arg_3[arg_1])

            arg_0._handle.flush()

            return arg_13


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=False,
                          arg_5=False, arg_6=0, arg_7=None):
        """Returns a PyTables HDF Array from df in the shape given by its index columns range values.

        :param key: string object

        :param df: pandas DataFrame

        :param range_values: dict or array-like
        Must contain for each index column of df an entry with all the values
        within the range of the column.

        :param loop_multiindex: bool
        Will loop through the first index in a multiindex dataframe, extract a
        dataframe only for one value, complete and fill the missing values and
        store in the HDF.
        If this is True, it will not use unstack.
        This is as fast as unstacking.

        :param unstack: bool
        Unstack means that this will use the first index name to
        unfold the DataFrame, and will create a group with as many datasets
        as valus has this first index.
        Use this if you think the filled dataframe won't fit in your RAM memory.
        If set to False, this will transform the dataframe in memory first
        and only then save it.

        :param fill_value: scalar or 'nearest', default 0
        Value to use for missing values. Defaults to 0, but can be any
        "compatible" value, e.g., NaN.
        The 'nearest' mode will fill the missing value with the nearest value in
         the column.

        :param fill_method:  {'backfill', 'bfill', 'pad', 'ffill', None}, default None
        Method to use for filling holes in reindexed DataFrame
        'pad' / 'ffill': propagate last valid observation forward to next valid
        'backfill' / 'bfill': use NEXT valid observation to fill gap

        :return: PyTables data node
        """
        arg_8 = arg_2.index.names
        #idx_colranges = [range_values[x] for x in idx_colnames]

        #dataset group name if not given
        if arg_1 is None:
            arg_1 = arg_8[0]

        if arg_4:
            arg_9 = arg_2.index.get_level_values(0).unique()

            for arg_10 in arg_9:
                arg_11, arg_12 = arg_0._fill_missing_values(arg_2.xs((arg_10,), level=arg_8[0]),
                                                    arg_3,
                                                    arg_6=arg_6,
                                                    arg_7=arg_7)

                arg_13 = str(arg_10) + '_' + '_'.join(arg_11.columns)

                arg_0._push_dfblock(arg_1, arg_11, arg_13, arg_3)

            return arg_0._handle.get_node('/' + str(arg_1))

        #separate the dataframe into blocks, only with the first index
        else:
            if arg_5:
                arg_2 = arg_2.unstack(arg_8[0])
                for arg_10 in arg_2:
                    arg_11, arg_12 = arg_0._fill_missing_values(arg_2[arg_10], arg_3,
                                                        arg_6=arg_6,
                                                        arg_7=arg_7)
                    arg_11 = np.nan_to_num(arg_11)

                    arg_13 = '_'.join([str(x) for x in arg_11.name])

                    arg_0._push_dfblock(arg_1, arg_11, arg_13, arg_3)

                return arg_0._handle.get_node('/' + str(arg_1))

        #not separate the data
        arg_11, arg_12 = arg_0._fill_missing_values(arg_2, arg_3,
                                            arg_6=arg_6,
                                            arg_7=arg_7)

        arg_13 = arg_0._array_dsname

        return arg_0._push_dfblock(arg_1, arg_11, arg_13, arg_3)