def Func(arg_0, arg_1, arg_2):
        """ Finds a single run index given a particular condition on parameters.

        ONLY useful for a single run if ``v_full_copy` was set to ``True``.
        Otherwise a TypeError is thrown.

        :param name_list:

            A list of parameter names the predicate applies to, if you have only a single
            parameter name you can omit the list brackets.

        :param predicate:

            A lambda predicate for filtering that evaluates to either ``True`` or  ``False``

        :return: A generator yielding the matching single run indices

        Example:

        >>> predicate = lambda param1, param2: param1==4 and param2 in [1.0, 2.0]
        >>> iterator = traj.Func(['groupA.param1', 'groupA.param2'], predicate)
        >>> [x for x in iterator]
        [0, 2, 17, 36]

        """
        if arg_0._is_run and not arg_0.v_full_copy:
            raise TypeError('You cannot use this function during a multiprocessing signle run and '
                            'not having ``v_full_copy=True``.')
        if isinstance(arg_1, str):
            arg_1 = [arg_1]

        # First create a list of iterators, each over the range of the matched parameters
        arg_3 = []
        for arg_4 in arg_1:
            arg_5 = arg_0.f_get(arg_4)
            if not arg_5.v_is_parameter:
                raise TypeError('`%s` is not a parameter it is a %s, find idx is not applicable' %
                                (arg_4, str(type(arg_5))))

            if arg_5.f_has_range():
                arg_3.append(iter(arg_5.f_get_range(copy=False)))
            else:
                arg_3.append(itools.repeat(arg_5.f_get(), len(arg_0)))

        # Create a logical iterator returning `True` or `False`
        # whether the user's predicate matches the parameter data
        arg_6 = map(arg_2, *arg_3)

        # Now the run indices are the the indices where `logic_iter` evaluates to `True`
        for arg_7, arg_8 in enumerate(arg_6):
            if arg_8:
                yield arg_7


def Func(arg_0, arg_1=None, arg_2=True):
        """ Can be used to manually allow running of an experiment without using an environment.

        :param run_name_or_idx:

            Can manually set a trajectory to a particular run. If `None` the current run
            the trajectory is set to is used.

        :param turn_into_run:

            Turns the trajectory into a run, i.e. reduces functionality but makes storing
            more efficient.

        """
        if arg_0._run_started:
            return arg_0

        if arg_1 is None:
            if arg_0.v_idx == -1:
                raise ValueError('Cannot start run if trajectory is not set to a particular run')
        else:
            arg_0.f_set_crun(arg_1)

        arg_0._run_started = True

        if arg_2:
            arg_0._make_single_run()

        arg_0._set_start()

        return arg_0


def Func(arg_0):
        """ Sets the start timestamp and formatted time to the current time. """
        arg_1 = time.time()
        arg_2 = datetime.datetime.fromtimestamp(arg_1).strftime('%Y_%m_%d_%Hh%Mm%Ss')
        arg_3 = arg_0._run_information[arg_0.v_crun]
        arg_3['timestamp'] = arg_1
        arg_3['time'] = arg_2
        if arg_0._environment_hexsha is not None:
            arg_3['short_environment_hexsha'] = arg_0._environment_hexsha[0:7]


def Func(arg_0, arg_1, arg_2):
        """Returns a dictionary containing either all parameters, all explored parameters,
        all config, all derived parameters, or all results.

        :param param_dict: The dictionary which is about to be returned
        :param fast_access: Whether to use fast access
        :param copy: If the original dict should be returned or a shallow copy

        :return: The dictionary

        :raises: ValueError if `copy=False` and fast_access=True`

        """

        if not arg_2 and arg_1:
            raise ValueError('You cannot access the original dictionary and use fast access at the'
                             ' same time!')
        if not arg_1:
            if arg_2:
                return arg_0.copy()
            else:
                return arg_0
        else:
            arg_3 = {}
            for arg_4 in arg_0:
                arg_5 = arg_0[arg_4]

                arg_6 = arg_5.f_get()
                arg_3[arg_4] = arg_6

            return arg_3


def Func(arg_0):
        """Called by the environment after storing to perform some rollback operations.

        All results and derived parameters created in the current run are removed.

        Important for single processing to not blow up the parent trajectory with the results
        of all runs.

        """
        arg_0._run_information[arg_0.v_crun]['completed'] = 1
        while len(arg_0._new_links):
            arg_3, arg_4 = arg_0._new_links.popitem(last=False)
            arg_5, arg_6 = arg_4
            arg_6, arg_7 = arg_3
            arg_5.f_remove_child(arg_7)

        while len(arg_0._new_nodes):
            arg_6, arg_4 = arg_0._new_nodes.popitem(last=False)
            arg_8, arg_9 = arg_4
            arg_10 = arg_9.v_name
            arg_8.f_remove_child(arg_10, recursive=True)


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Stores individual items to disk.

        This function is useful if you calculated very large results (or large derived parameters)
        during runtime and you want to write these to disk immediately and empty them afterwards
        to free some memory.

        Instead of storing individual parameters or results you can also store whole subtrees with
        :func:`~pypet.naturalnaming.NNGroupNode.f_store_child`.

        You can pass the following arguments to `Func`:

        :param iterator:

            An iterable containing the parameters or results to store, either their
            names or the instances. You can also pass group instances or names here
            to store the annotations of the groups.

        :param non_empties:

            Optional keyword argument (boolean),
            if `True` will only store the subset of provided items that are not empty.
            Empty parameters or results found in `iterator` are simply ignored.

        :param args: Additional arguments passed to the storage service

        :param kwargs:

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword argument:

            :param overwrite:

                List names of parts of your item that should
                be erased and overwritten by the new data in your leaf.
                You can also set `overwrite=True`
                to overwrite all parts.

                For instance:

                    >>> traj.f_add_result('mygroup.myresult', partA=42, partB=44, partC=46)
                    >>> traj.f_store()
                    >>> traj.mygroup.myresult.partA = 333
                    >>> traj.mygroup.myresult.partB = 'I am going to change to a string'
                    >>> traj.f_store_item('mygroup.myresult', overwrite=['partA', 'partB'])

                Will store `'mygroup.myresult'` to disk again and overwrite the parts
                `'partA'` and `'partB'` with the new values `333` and
                `'I am going to change to a string'`.
                The data stored as `partC` is not changed.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                Note that massive overwriting will fragment and blow up your HDF5 file.
                Try to avoid changing data on disk whenever you can.

        :raises:

            TypeError:

                If the (parent) trajectory has never been stored to disk. In this case
                use :func:`pypet.trajectory.f_store` first.

            ValueError: If no item could be found to be stored.

        Note if you use the standard hdf5 storage service, there are no additional arguments
        or keyword arguments to pass!

        """

        if not arg_0._stored:
            raise TypeError('Cannot store stuff for a trajectory that has never been '
                            'stored to disk. Please call traj.f_store(only_init=True) first.')

        arg_4 = arg_0._nn_interface._fetch_items(STORE, arg_1, arg_2, arg_3)

        if arg_4:
            arg_0._storage_service.store(pypetconstants.LIST, arg_4,
                                        trajectory_name=arg_0.v_name)
        else:
            raise ValueError('Your storage was not successful, could not find a single item '
                             'to store.')


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Loads parameters and results specified in `iterator`.

        You can directly list the Parameter objects or just their names.

        If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the
        parameters or results in the trajectory. Accordingly, the parameters and results
        you want to load must already exist in your trajectory (in RAM), probably they
        are just empty skeletons waiting desperately to handle data.
        If they do not exist in RAM yet, but have been stored to disk before,
        you can call :func:`~pypet.trajectory.Trajectory.f_load_skeleton` in order to
        bring your trajectory tree skeleton up to date. In case of a single run you can
        use the :func:`~pypet.naturalnaming.NNGroupNode.f_load_child` method to recursively
        load a subtree without any data.
        Then you can load the data of individual results or parameters one by one.

        If want to load the whole trajectory at once or ALL results and parameters that are
        still empty take a look at :func:`~pypet.trajectory.Trajectory.f_load`.
        As mentioned before, to load subtrees of your trajectory you might want to check out
        :func:`~pypet.naturalnaming.NNGroupNode.f_load_child`.

        To load a list of parameters or results with `Func` you can pass
        the following arguments:

        :param iterator: A list with parameters or results to be loaded.

        :param only_empties:

            Optional keyword argument (boolean),
            if `True` only empty parameters or results are passed
            to the storage service to get loaded. Non-empty parameters or results found in
            `iterator` are simply ignored.

        :param args: Additional arguments directly passed to the storage service

        :param kwargs:

            Additional keyword arguments directly passed to the storage service
            (except the kwarg `only_empties`)

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword arguments:

            :param load_only:

                If you load a result, you can partially load it and ignore the rest of data items.
                Just specify the name of the data you want to load. You can also provide a list,
                for example `load_only='spikes'`, `load_only=['spikes','membrane_potential']`.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                A warning is issued if data specified in `load_only` cannot be found in the
                instances specified in `iterator`.

            :param load_except:

                Analogous to the above, but everything is loaded except names or parts
                specified in `load_except`.
                You cannot use `load_only` and `load_except` at the same time. If you do
                a ValueError is thrown.

                A warning is issued if names listed in `load_except` are not part of the
                items to load.

        """

        if not arg_0._stored:
            raise TypeError(
                'Cannot load stuff from disk for a trajectory that has never been stored.')

        arg_4 = arg_0._nn_interface._fetch_items(LOAD, arg_1, arg_2, arg_3)
        if arg_4:
            arg_0._storage_service.load(pypetconstants.LIST, arg_4,
                                       trajectory_name=arg_0.v_name)
        else:
            arg_0._logger.warning('Your loading was not successful, could not find a single item '
                                 'to load.')


def Func(arg_0, arg_1, arg_2=False):
        """Removes parameters, results or groups from the trajectory.

        This function ONLY removes items from your current trajectory and does not delete
        data stored to disk. If you want to delete data from disk, take a look at
        :func:`~pypet.trajectory.Trajectory.f_delete_items`.

        This will also remove all links if items are linked.

        :param iterator:

            A sequence of items you want to remove. Either the instances themselves
            or strings with the names of the items.

        :param recursive:

            In case you want to remove group nodes, if the children should be removed, too.

        """

        # Will format the request in a form that is understood by the storage service
        # aka (msg, item, args, kwargs)
        arg_3 = arg_0._nn_interface._fetch_items(REMOVE, arg_1, (), {})

        if arg_3:
            for arg_4, arg_5, arg_6, arg_7 in arg_3:
                arg_0._nn_interface._remove_node_or_leaf(arg_5, arg_2=arg_2)

        else:
            arg_0._logger.warning('Your removal was not successful, could not find a single '
                                 'item to remove.')


def Func(arg_0, arg_1=True, arg_2=None):
        """Recursively removes all children of the trajectory

        :param recursive:

            Only here for consistency with signature of parent method. Cannot be set
            to `False` because the trajectory root node cannot be removed.

        :param predicate:

            Predicate which can evaluate for each node to ``True`` in order to remove the node or
            ``False`` if the node should be kept. Leave ``None`` if you want to remove all nodes.

        """
        if not arg_1:
            raise ValueError('Nice try ;-)')

        for arg_3 in list(arg_0._children.keys()):
            arg_0.Func_child(arg_3, arg_1=True, arg_2=arg_2)


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Deletes items from storage on disk.

        Per default the item is NOT removed from the trajectory.

        Links are NOT deleted on the hard disk, please delete links manually before deleting
        data!

        :param iterator:

            A sequence of items you want to remove. Either the instances themselves
            or strings with the names of the items.

        :param remove_from_trajectory:

            If items should also be removed from trajectory. Default is `False`.

        :param args: Additional arguments passed to the storage service

        :param kwargs: Additional keyword arguments passed to the storage service

            If you use the standard hdf5 storage service, you can pass the following additional
            keyword argument:

            :param delete_only:

                You can partially delete leaf nodes. Specify a list of parts of the result node
                that should be deleted like `delete_only=['mystuff','otherstuff']`.
                This wil only delete the hdf5 sub parts `mystuff` and `otherstuff` from disk.
                BE CAREFUL,
                erasing data partly happens at your own risk. Depending on how complex the
                loading process of your result node is, you might not be able to reconstruct
                any data due to partially deleting some of it.

                Be aware that you need to specify the names of parts as they were stored
                to HDF5. Depending on how your leaf construction works, this may differ
                from the names the data might have in your leaf in the trajectory container.

                If the hdf5 nodes you specified in `delete_only` cannot be found a warning
                is issued.

                Note that massive deletion will fragment your HDF5 file.
                Try to avoid changing data on disk whenever you can.

                If you want to erase a full node, simply ignore this argument or set to `None`.

            :param remove_from_item:

                If data that you want to delete from storage should also be removed from
                the items in `iterator` if they contain these. Default is `False`.

            :param recursive:

                If you want to delete a group node and it has children you need to
                set `recursive` to `True. Default is `False`.

        """

        arg_4 = arg_3.pop('remove_from_trajectory', False)
        arg_5 = arg_3.get('recursive', False)

        # Will format the request in a form that is understood by the storage service
        # aka (msg, item, args, kwargs)
        arg_6 = arg_0._nn_interface._fetch_items(REMOVE, arg_1, arg_2, arg_3)

        if arg_6:

            try:
                arg_0._storage_service.store(pypetconstants.LIST, arg_6,
                                            trajectory_name=arg_0.v_name)
            except:
                arg_0._logger.error('Could not remove `%s` from the trajectory. Maybe the'
                                   ' item(s) was/were never stored to disk.' % str(arg_6))
                raise

            for arg_7, arg_8, arg_9, arg_10 in arg_6:
                if arg_4:
                    arg_0._nn_interface._remove_node_or_leaf(arg_8, arg_5=arg_5)
                else:
                    arg_8._stored = False

        else:
            arg_0._logger.warning('Your removal was not successful, could not find a single '
                                 'item to remove.')


def Func(arg_0, arg_1):
	"""A class to replace the Func in datetime package or time module.
	Identical to Func behavior in those modules except supports any
	year.
	Also supports datetime.datetime times.
	Also supports milliseconds using %s
	Also supports microseconds using %u"""
	if isinstance(arg_1, (time.struct_time, tuple)):
		arg_1 = datetime.datetime(*arg_1[:6])
	assert isinstance(arg_1, (datetime.datetime, datetime.time, datetime.date))
	try:
		arg_2 = arg_1.year
		if arg_2 < 1900:
			arg_1 = arg_1.replace(arg_2=1900)
	except AttributeError:
		arg_2 = 1900
	arg_3 = (
		('%Y', '%04d' % arg_2),
		('%y', '%02d' % (arg_2 % 100)),
		('%s', '%03d' % (arg_1.microsecond // 1000)),
		('%u', '%03d' % (arg_1.microsecond % 1000))
	)

	def doSub(arg_4, arg_5):
		return arg_4.replace(*arg_5)

	def doSubs(arg_4):
		return functools.reduce(doSub, arg_3, arg_4)

	arg_0 = '%%'.join(map(doSubs, arg_0.split('%%')))
	return arg_1.Func(arg_0)


def Func(arg_0, arg_1, arg_2=None):
	"""
	A function to replace Func in the time module.  Should behave
	identically to the Func function except it returns a datetime.datetime
	object instead of a time.struct_time object.
	Also takes an optional tzinfo parameter which is a time zone info object.
	"""
	arg_3 = time.Func(arg_0, arg_1)
	return datetime.datetime(arg_2=arg_2, *arg_3[:6])


def Func(arg_0):
	"""
	Returns the nearest year to now inferred from a Julian date.
	"""
	arg_1 = time.gmtime()
	arg_2 = arg_1.tm_year
	# if the day is far greater than today, it must be from last year
	if arg_0 - arg_1.tm_yday > 365 // 2:
		arg_2 -= 1
	# if the day is far less than today, it must be for next year.
	if arg_1.tm_yday - arg_0 > 365 // 2:
		arg_2 += 1
	return arg_2


def Func(arg_0):
	"""
	return the number of seconds in the specified period

	>>> Func('day')
	86400
	>>> Func(86400)
	86400
	>>> Func(datetime.timedelta(hours=24))
	86400
	>>> Func('day + os.system("rm -Rf *")')
	Traceback (most recent call last):
	...
	ValueError: period not in (second, minute, hour, day, month, year)
	"""
	if isinstance(arg_0, six.string_types):
		try:
			arg_1 = 'seconds_per_' + arg_0.lower()
			arg_2 = globals()[arg_1]
		except KeyError:
			arg_3 = "period not in (second, minute, hour, day, month, year)"
			raise ValueError(arg_3)
	elif isinstance(arg_0, numbers.Number):
		arg_2 = arg_0
	elif isinstance(arg_0, datetime.timedelta):
		arg_2 = arg_0.days * Func('day') + arg_0.seconds
	else:
		raise TypeError('period must be a string or integer')
	return arg_2


def Func(arg_0, arg_1):
	"""
	Divide a timedelta by a float value

	>>> one_day = datetime.timedelta(days=1)
	>>> half_day = datetime.timedelta(days=.5)
	>>> Func(one_day, 2.0) == half_day
	True
	>>> Func(one_day, 2) == half_day
	True
	"""
	# td is comprised of days, seconds, microseconds
	arg_2 = [getattr(arg_0, attr) for attr in ('days', 'seconds', 'microseconds')]
	arg_2 = map(lambda elem: elem / arg_1, arg_2)
	return datetime.timedelta(*arg_2)


def Func(arg_0):
	"""
	Take a string representing a span of time and parse it to a time delta.
	Accepts any string of comma-separated numbers each with a unit indicator.

	>>> Func('1 day')
	datetime.timedelta(days=1)

	>>> Func('1 day, 30 seconds')
	datetime.timedelta(days=1, seconds=30)

	>>> Func('47.32 days, 20 minutes, 15.4 milliseconds')
	datetime.timedelta(days=47, seconds=28848, microseconds=15400)

	Supports weeks, months, years

	>>> Func('1 week')
	datetime.timedelta(days=7)

	>>> Func('1 year, 1 month')
	datetime.timedelta(days=395, seconds=58685)

	Note that months and years strict intervals, not aligned
	to a calendar:

	>>> now = datetime.datetime.now()
	>>> later = now + Func('1 year')
	>>> diff = later.replace(year=now.year) - now
	>>> diff.seconds
	20940
	"""
	arg_1 = (_Func_part(part.strip()) for part in arg_0.split(','))
	return sum(arg_1, datetime.timedelta())


def Func(arg_0, arg_1):
	"""
	Get the ratio of two timedeltas

	>>> one_day = datetime.timedelta(days=1)
	>>> one_hour = datetime.timedelta(hours=1)
	>>> Func(one_hour, one_day) == 1 / 24
	True
	"""
	try:
		return arg_0 / arg_1
	except TypeError:
		# Python 3.2 gets division
		# http://bugs.python.org/issue2706
		return arg_0.total_seconds() / arg_1.total_seconds()


def Func(arg_0, *arg_1, **arg_2):
		"""Construct a datetime.datetime from a number of different time
		types found in python and pythonwin"""
		if len(arg_1) == 1:
			arg_3 = arg_1[0]
			arg_4 = arg_0.__get_dt_constructor(
				type(arg_3).__module__,
				type(arg_3).__name__,
			)
			arg_5 = arg_4(arg_3)
			try:
				arg_5 = arg_5.replace(tzinfo=arg_2.pop('tzinfo'))
			except KeyError:
				pass
			if arg_2:
				arg_6 = arg_2.keys()[0]
				arg_7 = (
					"{first_key} is an invalid keyword "
					"argument for this function."
				)
				raise TypeError(arg_7.format(**locals()))
		else:
			arg_5 = datetime.datetime(*arg_1, **arg_2)
		return arg_5


def Func(arg_0):
    """Starts a pool single run and passes the storage service"""
    arg_1 = arg_0['wrap_mode']
    arg_2 = arg_0['traj']
    arg_2.v_storage_service = Func.storage_service
    if arg_1 == pypetconstants.WRAP_MODE_LOCAL:
        # Free references from previous runs
        arg_2.v_storage_service.free_references()
    return _sigint_handling_single_run(arg_0)


def Func(arg_0):
    """Single run wrapper for the frozen pool, makes a single run and passes kwargs"""
    arg_1 = arg_0.pop('idx')
    arg_2 = Func.kwargs
    arg_2.update(arg_0)  # in case of `run_map`
    # we need to update job's args and kwargs
    arg_3 = arg_2['traj']
    arg_3.f_set_crun(arg_1)
    return _sigint_handling_single_run(arg_2)


def Func(arg_0):
    """Configures the pool and keeps the storage service"""
    arg_1.storage_service = arg_0['storage_service']
    _configure_niceness(arg_0)
    _configure_logging(arg_0, extract=False)


def Func(arg_0):
    """Configures the frozen pool and keeps all kwargs"""
    arg_1.kwargs = arg_0
    _configure_niceness(arg_0)
    _configure_logging(arg_0, extract=False)
    # Reset full copy to it's old value
    arg_2 = arg_0['traj']
    arg_2.v_full_copy = arg_0['full_copy']


def Func(arg_0):
    """Wrapper function that configures a frozen SCOOP set up.

    Deletes of data if necessary.

    """
    def _delete_old_scoop_rev_data(arg_1):
        if arg_1 is not None:
            try:
                arg_2 = shared.elements
                for arg_3 in arg_2:
                    arg_4 = arg_2[arg_3]
                    if arg_1 in arg_4:
                        del arg_4[arg_1]
                logging.getLogger('pypet.scoop').debug('Deleted old SCOOP data from '
                                                       'revolution `%s`.' % arg_1)
            except AttributeError:
                logging.getLogger('pypet.scoop').error('Could not delete old SCOOP data from '
                                                       'revolution `%s`.' % arg_1)
    arg_5 = arg_0.pop('scoop_rev')
    # Check if we need to reconfigure SCOOP
    try:
        arg_1 = arg_7.kwargs['scoop_rev']
        arg_6 = arg_1 == arg_5
    except (AttributeError, KeyError):
        arg_1 = None
        arg_6 = False
    if not arg_6:
        arg_7.kwargs = shared.getConst(arg_5, timeout=424.2)
        arg_8 = arg_7.kwargs
        arg_8['scoop_rev'] = arg_5
        arg_8['traj'].v_full_copy = arg_8['full_copy']
        if not scoop.IS_ORIGIN:
            _configure_niceness(arg_8)
            _configure_logging(arg_8, extract=False)
        _delete_old_scoop_rev_data(arg_1)
        logging.getLogger('pypet.scoop').info('Configured Worker %s' % str(scoop.worker))


def Func(arg_0):
    """ Starts running a queue handler and creates a log file for the queue."""
    _configure_logging(arg_0, extract=False)
    # Main job, make the listener to the queue start receiving message for writing to disk.
    arg_1=arg_0['handler']
    arg_2 = arg_0['graceful_exit']
    # import cProfile as profile
    # profiler = profile.Profile()
    # profiler.enable()
    if arg_2:
        sigint_handling.start()
    arg_1.run()


def Func(arg_0):
        """String summary of the value handled by the parameter.

        Note that representing the parameter as a string accesses its value,
        but for simpler debugging, this does not lock the parameter or counts as usage!

        Calls `__repr__` of the contained value.

        """
        arg_1 = arg_0._locked
        try:
            return repr(arg_0.f_get())
        except Exception:
            return 'No Evaluation possible (yet)!'
        finally:
            arg_0._locked = arg_1


def Func(arg_0, arg_1):
        """Explores the parameter according to the iterable.

        Raises ParameterLockedException if the parameter is locked.
        Raises TypeError if the parameter does not support the data,
        the types of the data in the iterable are not the same as the type of the default value,
        or the parameter has already an exploration range.

        Note that the parameter will iterate over the whole iterable once and store
        the individual data values into a tuple. Thus, the whole exploration range is
        explicitly stored in memory.

        :param explore_iterable: An iterable specifying the exploration range

        For example:

        >>> param.Func([3.0,2.0,1.0])
        >>> param.f_get_range()
        (3.0, 2.0, 1.0)

        :raises TypeError,ParameterLockedException

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        if arg_0.f_has_range():
            raise TypeError('Your parameter `%s` is already explored, '
                            'cannot Func it further!' % arg_0._name)

        if arg_0._data is None:
            raise TypeError('Your parameter `%s` has no default value, please specify one '
                            'via `f_set` before exploration. ' % arg_0.v_full_name)

        arg_2 = arg_0._data_sanity_checks(arg_1)

        arg_0.Funcd_range = arg_2
        arg_0.Funcd = True
        arg_0.f_lock()


def Func(arg_0, arg_1):
        """Explores the parameter according to the iterable and appends to the exploration range.

        Raises ParameterLockedException if the parameter is locked.
        Raises TypeError if the parameter does not support the data,
        the types of the data in the iterable are not the same as the type of the default value,
        or the parameter did not have an array before.

        Note that the parameter will iterate over the whole iterable once and store
        the individual data values into a tuple. Thus, the whole exploration range is
        explicitly stored in memory.

        :param explore_iterable: An iterable specifying the exploration range

         For example:

         >>> param = Parameter('Im.an.example', data=33.33, comment='Wooohoo!')
         >>> param._explore([3.0,2.0,1.0])
         >>> param.Func([42.0, 43.42])
         >>> param.f_get_range()
         >>> [3.0, 2.0, 1.0, 42.0, 43.42]

        :raises TypeError, ParameterLockedException

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        if not arg_0.f_has_range():
            raise TypeError('Your Parameter `%s` is not an array and can therefore '
                            'not be expanded.' % arg_0._name)

        arg_2 = arg_0._data_sanity_checks(arg_1)

        arg_0._explored_range.extend(arg_2)
        arg_0.f_lock()


def Func(arg_0, arg_1):
        """Loads the data and exploration range from the `load_dict`.

        The `load_dict` needs to be in the same format as the result of the
        :func:`~pypet.parameter.Parameter._store` method.

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        if 'data' in arg_1:
            arg_0._data = arg_1['data']['data'][0]
            arg_0._default = arg_0._data
        else:
            arg_0._logger.warning('Your parameter `%s` is empty, '
                                 'I did not find any data on disk.' % arg_0.v_full_name)

        if 'explored_data' in arg_1:
            arg_0._explored_range = [x for x in arg_1['explored_data']['data'].tolist()]
            arg_0._explored = True

        arg_0._locked = True


def Func(arg_0, arg_1):
        """Reconstructs the data and exploration array.

        Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
        If not calls :class:`~pypet.parameter.Parameter.Func` of the parent class.

        If the parameter is explored, the exploration range of arrays is reconstructed
        as it was stored in :func:`~pypet.parameter.ArrayParameter._store`.

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        try:
            arg_0._data = arg_1['data' + ArrayParameter.IDENTIFIER]

            if 'explored_data' + ArrayParameter.IDENTIFIER in arg_1:
                arg_3 = arg_1['explored_data' + ArrayParameter.IDENTIFIER]

                arg_4 = arg_3['idx']

                arg_5 = []

                # Recall the arrays in the order stored in the ObjectTable 'explored_data__rr__'
                for arg_6 in arg_4:
                    arg_7 = arg_0._build_name(arg_6)
                    arg_5.append(arg_1[arg_7])

                arg_0._explored_range = [x for x in arg_5]
                arg_0._explored = True

        except KeyError:
            super(ArrayParameter, arg_0).Func(arg_1)

        arg_0._default = arg_0._data
        arg_0._locked = True


def Func(arg_0, arg_1, arg_2):
        """Matrices are equal if they hash to the same value."""
        if arg_0._is_supported_matrix(arg_1):
            if arg_0._is_supported_matrix(arg_2):

                arg_3, arg_3, arg_4 = arg_0._serialize_matrix(arg_1)
                arg_3, arg_3, arg_5 = arg_0._serialize_matrix(arg_2)

                return hash(arg_4) == hash(arg_5)
            else:
                return False
        else:
            return super(SparseParameter, arg_0).Func(arg_1, arg_2)


def Func(arg_0):
        """Extracts data from a sparse matrix to make it serializable in a human readable format.

        :return: Tuple with following elements:

            1.

                A list containing data that is necessary to reconstruct the matrix.
                For csr, csc, and bsr matrices the following attributes are extracted:
                `format`, `data`, `indices`, `indptr`, `shape`.
                Where format is simply one of the strings 'csr', 'csc', or 'bsr'.

                For dia matrices the following attributes are extracted:
                `format`, `data`, `offsets`, `shape`.
                Where `format` is simply the string 'dia'.

            2.

                A list containing the names of the extracted attributes.
                For csr, csc, and bsr:

                    [`format`, `data`, `indices`, `indptr`, `shape`]

                For dia:

                    [`format`, `data`, `offsets`, `shape`]

            3.

                A tuple containing the hashable parts of (1) in order to use the tuple as
                a key for a dictionary. Accordingly, the numpy arrays of (1) are
                changed to read-only.

        """
        if (spsp.isspmatrix_csc(arg_0) or
                spsp.isspmatrix_csr(arg_0) or
                spsp.isspmatrix_bsr(arg_0)):
            if arg_0.size > 0:
                arg_1 = [arg_0.data, arg_0.indices, arg_0.indptr, arg_0.shape]
            else:
                # For empty matrices we only need the shape
                arg_1 = ['__empty__', (), (), arg_0.shape]

            arg_2 = SparseParameter.OTHER_NAME_LIST

            if spsp.isspmatrix_csc(arg_0):
                arg_1 = ['csc'] + arg_1
            elif spsp.isspmatrix_csr(arg_0):
                arg_1 = ['csr'] + arg_1
            elif spsp.isspmatrix_bsr(arg_0):
                arg_1 = ['bsr'] + arg_1
            else:
                raise RuntimeError('You shall not pass!')

        elif spsp.isspmatrix_dia(arg_0):
            if arg_0.size > 0:
                arg_1 = ['dia', arg_0.data, arg_0.offsets, arg_0.shape]
            else:
                # For empty matrices we only need the shape
                arg_1 = ['dia', '__empty__', (), arg_0.shape]

            arg_2 = SparseParameter.DIA_NAME_LIST
        else:
            raise RuntimeError('You shall not pass!')

        arg_3 = []

        # Extract the `data` property of a read-only numpy array in order to have something
        # hashable.
        for arg_4 in arg_1:
            if type(arg_4) is np.ndarray:
                # item.flags.writeable = False
                arg_3.append(HashArray(arg_4))
            else:
                arg_3.append(arg_4)

        return arg_1, arg_2, tuple(arg_3)


def Func(arg_0):
        """Reconstructs a matrix from a list containing sparse matrix extracted properties

        `data_list` needs to be formatted as the first result of
        :func:`~pypet.parameter.SparseParameter._serialize_matrix`

        """
        arg_1 = arg_0[0]
        arg_2 = arg_0[1]
        arg_3 = isinstance(arg_2, str) and arg_2 == '__empty__'

        if arg_1 == 'csc':
            if arg_3:
                return spsp.csc_matrix(arg_0[4])
            else:
                return spsp.csc_matrix(tuple(arg_0[1:4]), shape=arg_0[4])
        elif arg_1 == 'csr':
            if arg_3:
                return spsp.csr_matrix(arg_0[4])
            else:
                return spsp.csr_matrix(tuple(arg_0[1:4]), shape=arg_0[4])
        elif arg_1 == 'bsr':
            if arg_3:
                # We have an empty matrix, that cannot be build as in elee case
                return spsp.bsr_matrix(arg_0[4])
            else:
                return spsp.bsr_matrix(tuple(arg_0[1:4]), shape=arg_0[4])
        elif arg_1 == 'dia':
            if arg_3:
                return spsp.dia_matrix(arg_0[3])
            else:
                return spsp.dia_matrix(tuple(arg_0[1:3]), shape=arg_0[3])
        else:
            raise RuntimeError('You shall not pass!')


def Func(arg_0, arg_1):
        """Reconstructs the data and exploration array

        Checks if it can find the array identifier in the `load_dict`, i.e. '__spsp__'.
        If not, calls :class:`~pypet.parameter.ArrayParameter.Func` of the parent class.

        If the parameter is explored, the exploration range of matrices is reconstructed
        as it was stored in :func:`~pypet.parameter.SparseParameter._store`.

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        try:
            arg_2 = arg_1['data%sis_dia' % SparseParameter.IDENTIFIER]

            arg_3 = arg_0._get_name_list(arg_2)
            arg_4 = ['data%s%s' % (SparseParameter.IDENTIFIER, name)
                           for name in arg_3]

            arg_5 = [arg_1[name] for name in arg_4]
            arg_0._data = arg_0._reconstruct_matrix(arg_5)

            if 'explored_data' + SparseParameter.IDENTIFIER in arg_1:
                arg_7 = arg_1['explored_data' + SparseParameter.IDENTIFIER]

                arg_8 = arg_7['idx']
                arg_9 = arg_7['is_dia']

                arg_10 = []
                for arg_11, arg_12 in enumerate(arg_8):
                    arg_2 = arg_9[arg_11]

                    # To make everything work with the old format we have the try catch block
                    try:
                        arg_3 = arg_0._build_names(arg_12, arg_2)
                        arg_5 = [arg_1[name] for name in arg_3]
                    except KeyError:
                        arg_3 = arg_0._build_names_old(arg_12, arg_2)
                        arg_5 = [arg_1[name] for name in arg_3]

                    arg_13 = arg_0._reconstruct_matrix(arg_5)
                    arg_10.append(arg_13)

                arg_0._explored_range = arg_10
                arg_0._explored = True

        except KeyError:
            super(SparseParameter, arg_0).Func(arg_1)

        arg_0._default = arg_0._data
        arg_0._locked = True


def Func(arg_0):
        """Returns a dictionary for storage.

        Every element in the dictionary except for 'explored_data' is a pickle dump.

        Reusage of objects is identified over the object id, i.e. python's built-in id function.

        'explored_data' contains the references to the objects to be able to recall the
        order of objects later on.

        """
        arg_1 = {}

        if arg_0._data is not None:
            arg_2 = pickle.dumps(arg_0._data, protocol=arg_0.v_protocol)
            arg_1['data'] = arg_2
            arg_1[arg_3.PROTOCOL] = arg_0.v_protocol

        if arg_0.f_has_range():

            arg_1['explored_data'] = \
                ObjectTable(columns=['idx'], index=list(range(len(arg_0))))

            arg_5 = {}
            arg_6 = 0

            for arg_7, arg_8 in enumerate(arg_0._explored_range):

                arg_9 = id(arg_8)

                if arg_9 in arg_5:
                    arg_10 = arg_5[arg_9]
                    arg_11 = False
                else:
                    arg_10 = arg_6
                    arg_11 = True

                arg_12 = arg_0._build_name(arg_10)
                arg_1['explored_data']['idx'][arg_7] = arg_10

                if arg_11:
                    arg_1[arg_12] = pickle.dumps(arg_8, protocol=arg_0.v_protocol)
                    arg_5[arg_9] = arg_10
                    arg_6 += 1

        arg_0._locked = True

        return arg_1


def Func(arg_0, arg_1):
        """Reconstructs objects from the pickle dumps in `load_dict`.

        The 'explored_data' entry in `load_dict` is used to reconstruct
        the exploration range in the correct order.

        Sets the `v_protocol` property to the protocol used to store 'data'.

        """
        if arg_0.v_locked:
            raise pex.ParameterLockedException('Parameter `%s` is locked!' % arg_0.v_full_name)

        if 'data' in arg_1:
            arg_2 = arg_1['data']
            arg_0._data = pickle.loads(arg_2)
        else:
            arg_0._logger.warning('Your parameter `%s` is empty, '
                                 'I did not find any data on disk.' % arg_0.v_full_name)

        try:
            arg_0.v_protocol = arg_1[PickleParameter.PROTOCOL]
        except KeyError:
            # For backwards compatibility
            arg_0.v_protocol = PickleParameter._get_protocol(arg_2)

        if 'explored_data' in arg_1:
            arg_5 = arg_1['explored_data']

            arg_6 = arg_5['idx']

            arg_7 = []
            for arg_8 in arg_6:
                arg_9 = arg_0._build_name(arg_8)
                arg_10 = pickle.loads(arg_1[arg_9])
                arg_7.append(arg_10)

            arg_0._explored_range = arg_7
            arg_0._explored = True

        arg_0._default = arg_0._data
        arg_0._locked = True


def Func(arg_0, arg_1):
        """Translates integer indices into the appropriate names"""
        if isinstance(arg_1, int):
            if arg_1 == 0:
                arg_1 = arg_0.v_name
            else:
                arg_1 = arg_0.v_name + '_%d' % arg_1
        return arg_1


def Func(arg_0, arg_1=True):
        """Returns all handled data as a dictionary.

        :param copy:

            Whether the original dictionary or a shallow copy is returned.

        :return: Data dictionary

        """
        if arg_1:
            return arg_0._data.copy()
        else:
            return arg_0._data


def Func(arg_0, *arg_1, **arg_2):
        """ Method to put data into the result.

        :param args:

            The first positional argument is stored with the name of the result.
            Following arguments are stored with `name_X` where `X` is the position
            of the argument.

        :param kwargs: Arguments are stored with the key as name.

        :raises: TypeError if outer data structure is not understood.

        Example usage:

        >>> res = Result('supergroup.subgroup.myresult', comment='I am a neat example!')
        >>> res.Func(333,42.0, mystring='String!')
        >>> res.f_get('myresult')
        333
        >>> res.f_get('myresult_1')
        42.0
        >>> res.f_get(1)
        42.0
        >>> res.f_get('mystring')
        'String!'

        """
        if arg_1 and arg_0.v_name is None:
            raise AttributeError('Cannot set positional value because I do not have a name!')
        for arg_3, arg_4 in enumerate(arg_1):
            arg_5 = arg_0.f_translate_key(arg_3)
            arg_0.Func_single(arg_5, arg_4)

        for arg_6, arg_4 in arg_2.items():
            arg_0.Func_single(arg_6, arg_4)


def Func(arg_0, arg_1, arg_2):
        """Sets a single data item of the result.

        Raises TypeError if the type of the outer data structure is not understood.
        Note that the type check is shallow. For example, if the data item is a list,
        the individual list elements are NOT checked whether their types are appropriate.

        :param name: The name of the data item

        :param item: The data item

        :raises: TypeError

        Example usage:

        >>> res.Func('answer', 42)
        >>> res.f_get('answer')
        42

        """

        if arg_0.v_stored:
            arg_0._logger.debug('You are changing an already stored result. If '
                                 'you not explicitly overwrite the data on disk, this change '
                                 'might be lost and not propagated to disk.')

        if arg_0._supports(arg_2):

            # self._check_if_empty(item, name) # No longer needed

            if arg_1 in arg_0._data:
                arg_0._logger.debug('Replacing `%s` in result `%s`.' % (arg_1, arg_0.v_full_name))

            arg_0._data[arg_1] = arg_2
        else:
            raise TypeError('Your result `%s` of type `%s` is not supported.' %
                            (arg_1, str(type(arg_2))))


def Func(arg_0, arg_1):
        """Supports everything of parent class and csr, csc, bsr, and dia sparse matrices."""
        if SparseParameter._is_supported_matrix(arg_1):
            return True
        else:
            return super(SparseResult, arg_0).Func(arg_1)


def Func(arg_0):
        """Returns a storage dictionary understood by the storage service.

        Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
        marked with the identifier `__spsp__`.

        """
        arg_1 = {}
        for arg_2 in arg_0._data:
            arg_3 = arg_0._data[arg_2]
            if SparseParameter._is_supported_matrix(arg_3):

                arg_4, arg_5, arg_6 = SparseParameter._serialize_matrix(arg_3)
                arg_7 = ['%s%s%s' % (arg_2, SparseParameter.IDENTIFIER, arg_12)
                               for arg_12 in arg_5]

                arg_8 = int(len(arg_7) == 4)
                arg_1[arg_2 + arg_9.IDENTIFIER + 'is_dia'] = arg_8

                for arg_11, arg_12 in enumerate(arg_7):
                    arg_1[arg_12] = arg_4[arg_11]

            else:
                arg_1[arg_2] = arg_3

        return arg_1


def Func(arg_0, arg_1):
        """Loads data from `load_dict`

        Reconstruction of sparse matrices similar to the :class:`~pypet.parameter.SparseParameter`.

        """
        for arg_2 in list(arg_1.keys()):
            # We delete keys over time:
            if arg_2 in arg_1:
                if SparseResult.IDENTIFIER in arg_2:
                    arg_3 = arg_2.split(SparseResult.IDENTIFIER)[0]

                    arg_4 = arg_1.pop(arg_3 + SparseResult.IDENTIFIER + 'is_dia')

                    arg_5 = SparseParameter._get_name_list(arg_4)
                    arg_6 = ['%s%s%s' % (arg_3, SparseResult.IDENTIFIER, name)
                                   for name in arg_5]

                    arg_7 = [arg_1.pop(name) for name in arg_6]
                    arg_8 = SparseParameter._reconstruct_matrix(arg_7)
                    arg_0._data[arg_3] = arg_8
                else:
                    arg_0._data[arg_2] = arg_1[arg_2]


def Func():
    """Simply merge all trajectories in the working directory"""
    arg_0 = os.getcwd()
    print('Merging all files')
    merge_all_in_folder(arg_0,
                        delete_other_files=True,  # We will only keep one trajectory
                        dynamic_imports=FunctionParameter,
                        backup=False)
    print('Done')


def Func():
    """ Creates and returns a new SAGA session """
    arg_0 = saga.Context("UserPass")
    arg_0.user_id = USER
    arg_0.user_pass = PASSWORD

    arg_3 = saga.Session()
    arg_3.add_context(arg_0)

    return arg_3


def Func(arg_0):
    """ Starts all jobs and runs `the_task.py` in batches. """

    arg_1 = saga.job.Service('ssh://' + ADDRESS, arg_0=arg_0)

    arg_2 = range(3)
    arg_3 = []

    for arg_4 in arg_2:
        print('Starting batch %d' % arg_4)

        arg_5 = saga.job.Description()

        arg_5.executable      = 'python'
        arg_5.arguments       = ['the_task.py --batch=' + str(arg_4)]
        arg_5.output          = "mysagajob.stdout" + str(arg_4)
        arg_5.error           = "mysagajob.stderr" + str(arg_4)
        arg_5.working_directory = WORKING_DIR

        arg_11 = arg_1.create_job(arg_5)

        print("Job ID    : %s" % (arg_11.id))
        print("Job State : %s" % (arg_11.state))

        print("\n...starting job...\n")

        arg_11.run()
        arg_3.append(arg_11)

    for arg_11 in arg_3:
        print("Job ID    : %s" % (arg_11.id))
        print("Job State : %s" % (arg_11.state))

        print("\n...waiting for job...\n")
        # wait for the job to either finish or fail
        arg_11.wait()

        print("Job State : %s" % (arg_11.state))
        print("Exitcode  : %s" % (arg_11.exit_code))


def Func(arg_0):
    """Sophisticated simulation of multiplication"""
    arg_1=arg_0.x*arg_0.y
    arg_0.f_add_result('z',arg_1=arg_1, comment='I am the product of two reals!')


def Func(arg_0):
    """Runs a simulation of a model neuron.

    :param traj:

        Container with all parameters.

    :return:

        An estimate of the firing rate of the neuron

    """

    # Extract all parameters from `traj`
    arg_1 = arg_0.par.neuron.V_init
    arg_2 = arg_0.par.neuron.I
    arg_3 = arg_0.par.neuron.tau_V
    arg_4 = arg_0.par.neuron.tau_ref
    arg_5 = arg_0.par.simulation.dt
    arg_6 = arg_0.par.simulation.duration

    arg_7 = int(arg_6 / float(arg_5))
    # Create some containers for the Euler integration
    arg_8 = np.zeros(arg_7)
    arg_8[0] = arg_1
    arg_9 = []  # List to collect all times of action potentials

    # Do the Euler integration:
    print('Starting Euler Integration')
    for arg_10 in range(1, arg_7):
        if arg_8[arg_10-1] >= 1:
            # The membrane potential crossed the threshold and we mark this as
            # an action potential
            arg_8[arg_10] = 0
            arg_9.append((arg_10-1)*arg_5)
        elif arg_9 and arg_10 * arg_5 - arg_9[-1] <= arg_4:
            # We are in the refractory period, so we simply clamp the voltage
            # to 0
            arg_8[arg_10] = 0
        else:
            # Euler Integration step:
            arg_11 = -1/arg_3 * arg_8[arg_10-1] + arg_2
            arg_8[arg_10] = arg_8[arg_10-1] + arg_11*arg_5

    print('Finished Euler Integration')

    # Add the voltage trace and spike times
    arg_0.f_add_result('neuron.$', V=arg_8, nspikes=len(arg_9),
                      comment='Contains the development of the membrane potential over time '
                              'as well as the number of spikes.')
    # This result will be renamed to `traj.results.neuron.run_XXXXXXXX`.

    # And finally we return the estimate of the firing rate
    return len(arg_9) / float(arg_0.par.simulation.duration) *1000


def Func(arg_0, arg_1):
    """Postprocessing, sorts computed firing rates into a table

    :param traj:

        Container for results and parameters

    :param result_list:

        List of tuples, where first entry is the run index and second is the actual
        result of the corresponding run.

    :return:
    """

    # Let's create a pandas DataFrame to sort the computed firing rate according to the
    # parameters. We could have also used a 2D numpy array.
    # But a pandas DataFrame has the advantage that we can index into directly with
    # the parameter values without translating these into integer indices.
    arg_2 = arg_0.par.neuron.f_get('I').f_get_range()
    arg_3 = arg_0.par.neuron.f_get('tau_ref').f_get_range()

    arg_4 = sorted(set(arg_2))
    arg_5 = sorted(set(arg_3))
    arg_6 = pd.DataFrame(columns=arg_5, index=arg_4)
    # This frame is basically a two dimensional table that we can index with our
    # parameters

    # Now iterate over the results. The result list is a list of tuples, with the
    # run index at first position and our result at the second
    for arg_7 in arg_1:
        arg_8 = arg_7[0]
        arg_9 = arg_7[1]
        arg_10 = arg_2[arg_8]
        arg_11 = arg_3[arg_8]
        arg_6.loc[arg_10, arg_11] = arg_9 # Put the firing rate into the
        # data frame

    # Finally we going to store our new firing rate table into the trajectory
    arg_0.f_add_result('summary.firing_rates', arg_6=arg_6,
                      comment='Contains a pandas data frame with all firing rates.')


def Func(arg_0, arg_1, arg_2=False):
        """Extracts subruns from the trajectory.

        :param traj: Trajectory container

        :param pre_run: Boolean whether current run is regular or a pre-run

        :raises: RuntimeError if orders are duplicates or even missing

        """
        if arg_2:
            arg_3 = arg_1.f_get_all(arg_0._pre_durations_group_name)
        else:
            arg_3 = arg_1.f_get_all(arg_0._durations_group_name)

        arg_4 = {}
        arg_5 = []

        for arg_6 in arg_3:
            for arg_7 in arg_6.f_iter_leaves(with_links=False):

                if 'order' in arg_7.v_annotations:
                    arg_8 = arg_7.v_annotations.order
                else:
                    raise RuntimeError('Your duration parameter %s has no order. Please add '
                                       'an order in `v_annotations.order`.' %
                                       arg_7.v_full_name)

                if arg_8 in arg_4:
                    raise RuntimeError('Your durations must differ in their order, there are two '
                                       'with order %d.' % arg_8)
                else:
                    arg_4[arg_8] = arg_7
                    arg_5.append(arg_8)

        return [arg_4[arg_8] for arg_8 in sorted(arg_5)]


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                             arg_5, arg_6=False):
        """Generic `execute_network_run` function, handles experimental runs as well as pre-runs.

        See also :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` and
         :func:`~pypet.brian2.network.NetworkRunner.execute_network_pre_run`.

        """

        # Initially extract the `subrun_list`
        arg_7 = arg_0._extract_subruns(arg_1, arg_6=arg_6)

        # counter for subruns
        arg_8 = 0

        # Execute all subruns in order
        while len(arg_7) > 0:

            # Get the next subrun
            arg_9 = arg_7.pop(0)

            # 1. Call `add` of all normal components
            for arg_10 in arg_4:
                arg_10.add_to_network(arg_1, arg_2, arg_9, arg_7,
                                         arg_3)

            # 2. Call `add` of all analyser components
            for arg_11 in arg_5:
                arg_11.add_to_network(arg_1, arg_2, arg_9, arg_7,
                                        arg_3)

            # 3. Call `add` of the network runner itself
            arg_0.add_to_network(arg_1, arg_2, arg_9, arg_7,
                                arg_3)

            # 4. Run the network
            arg_0._logger.info('STARTING subrun `%s` (#%d) lasting %s.' %
                             (arg_9.v_name, arg_8, str(arg_9.f_get())))
            arg_2.run(duration=arg_9.f_get(), report=arg_0._report,
                              report_period=arg_0._report_period)

            # 5. Call `analyse` of all analyser components
            for arg_11 in arg_5:
                arg_11.analyse(arg_1, arg_2, arg_9, arg_7,
                                 arg_3)

            # 6. Call `remove` of the network runner itself
            arg_0.remove_from_network(arg_1, arg_2, arg_9, arg_7,
                                     arg_3)

            # 7. Call `remove` for all analyser components
            for arg_11 in arg_5:
                arg_11.remove_from_network(arg_1, arg_2, arg_9, arg_7,
                                             arg_3)

            # 8. Call `remove` for all normal components
            for arg_10 in arg_4:
                arg_10.remove_from_network(arg_1, arg_2, arg_9, arg_7,
                                              arg_3)

            arg_8 += 1


def Func(arg_0, arg_1):
        """Top-level simulation function, pass this to the environment

        Performs an individual network run during parameter exploration.

        `Func` does not need to be called by the user. If this
        method (not this one of the NetworkManager)
        is passed to an :class:`~pypet.environment.Environment` with this NetworkManager,
        `Func` and :func:`~pypet.brian2.network.NetworkManager.build`
        are automatically called for each individual experimental run.

        This function will create a new BRIAN2 network in case one was not pre-run.
        The execution of the network run is carried out by
        the :class:`~pypet.brian2.network.NetworkRunner` and it's
        :func:`~pypet.brian2.network.NetworkRunner.execute_network_run` (also take
        a look at this function's documentation to see the structure of a network run).

        :param traj: Trajectory container

        """

        # Check if the network was pre-built
        if arg_0._pre_built:
            if arg_0._pre_run and hasattr(arg_0._network, 'restore'):
                arg_0._network.restore('pre_run')
                # Temprorary fix for https://github.com/brian-team/brian2/issues/681
                arg_0._network.store('pre_run')
            arg_0._Func(arg_1)
        else:
            arg_0._Func(arg_1)


def Func(arg_0, arg_1):
        """Starts a single run carried out by a NetworkRunner.

        Called from the public function :func:`~pypet.brian2.network.NetworkManger.run_network`.

        :param traj: Trajectory container

        """
        arg_0.build(arg_1)

        arg_0._pretty_print_explored_parameters(arg_1)

        # We need to construct a network object in case one was not pre-run
        if not arg_0._pre_run:

            arg_0._network = arg_0._network_constructor(*arg_0._brian_list)

        # Start the experimental run
        arg_0.network_runner.execute_network_run(arg_1, arg_0._network, arg_0._network_dict,
                                                arg_0.components, arg_0.analysers)

        arg_0._logger.info('\n-----------------------------\n'
                          'Network Simulation successful\n'
                          '-----------------------------')


def Func(arg_0):
    """ Function to create generic filenames based on what has been explored """
    arg_1 = arg_0.f_get_explored_parameters()
    arg_2 = ''
    for arg_3 in arg_1.values():
        arg_4 = arg_3.v_name
        arg_5 = arg_3.f_get()
        arg_2 += '%s_%s__' % (arg_4, str(arg_5))

    return arg_2[:-2] + '.png'


def Func(arg_0, arg_1='.hdf5',
                        arg_2=None,
                        arg_3=None,
                        arg_4=False,
                        arg_5=(),
                        arg_6=False,
                        arg_7=False,
                        arg_8=True,
                        arg_9=True,
                        arg_10=True,
                        arg_11=True):
    """Merges all files in a given folder.

    IMPORTANT: Does not check if there are more than 1 trajectory in a file. Always
    uses the last trajectory in file and ignores the other ones.

    Trajectories are merged according to the alphabetical order of the files,
    i.e. the resulting merged trajectory is found in the first file
    (according to lexicographic ordering).

    :param folder: folder (not recursive) where to look for files
    :param ext: only files with the given extension are used
    :param dynamic_imports: Dynamic imports for loading
    :param storage_service: storage service to use, leave `None` to use the default one
    :param force: If loading should be forced.
    :param delete_other_files: Deletes files of merged trajectories

    All other parameters as in `f_merge_many` of the trajectory.

    :return: The merged traj

    """
    arg_12 = os.listdir(arg_0)
    arg_13 = []
    # Find all files with matching extension
    for arg_14 in arg_12:
        arg_15 = os.path.join(arg_0, arg_14)
        if os.path.isfile(arg_15):
            arg_16, arg_17 = os.path.splitext(arg_15)
            if arg_17 == arg_1:
                arg_13.append(arg_15)
    arg_13 = sorted(arg_13)

    # Open all trajectories
    arg_18 = []
    for arg_15 in arg_13:
        arg_19 = load_trajectory(index=-1,
                               arg_3=arg_3,
                               filename=arg_15,
                               load_data=0,
                               arg_4=arg_4,
                               arg_2=arg_2)
        arg_18.append(arg_19)

    # Merge all trajectories
    arg_20 = arg_18.pop(0)
    arg_20.f_merge_many(arg_18,
                arg_5=arg_5,
                arg_6=arg_6,
                delete_other_trajectory=False,
                arg_8=arg_8,
                arg_9=arg_9,
                arg_10=arg_10,
                arg_11=arg_11)

    if arg_7:
        # Delete all but the first file
        for arg_14 in arg_13[1:]:
            os.remove(arg_14)

    return arg_20


def Func(arg_0, arg_1, arg_2):
        """Handler of SIGINT

        Does nothing if SIGINT is encountered once but raises a KeyboardInterrupt in case it
        is encountered twice.
        immediatly.

        """
        if arg_0.hit:
            arg_3 = 'Exiting immediately!'
            raise KeyboardInterrupt(arg_3)
        else:
            arg_0.hit = True
            arg_3 = ('\nYou killed the process(es) via `SIGINT` (`CTRL+C`). '
                      'I am trying to exit '
                      'gracefully. Using `SIGINT` (`CTRL+C`) '
                      'again will cause an immediate exit.\n')
            sys.stderr.write(arg_3)


def Func(arg_0, arg_1=None):
    ''' Small configuration file management function'''
    if arg_1:
        # We're writing configuration
        try:
            with open(arg_0, 'w') as fdesc:
                fdesc.write(json.dumps(arg_1))
        except IOError as error:
            logger.exception(error)
            return False
        return True
    else:
        # We're reading config
        if os.path.isfile(arg_0):
            try:
                with open(arg_0, 'r') as fdesc:
                    return json.loads(fdesc.read())
            except IOError as error:
                return False
        else:
            return {}


def Func(arg_0):
        ''' Method to request API tokens from ecobee '''
        arg_1 = 'https://api.ecobee.com/token'
        arg_2 = {'grant_type': 'ecobeePin', 'code': arg_0.authorization_code,
                  'client_id': arg_0.api_key}
        try:
            arg_3 = requests.post(arg_1, arg_2=arg_2)
        except RequestException:
            logger.warn("Error connecting to Ecobee.  Possible connectivity outage."
                        "Could not request token.")
            return
        if arg_3.status_code == requests.codes.ok:
            arg_0.access_token = arg_3.json()['access_token']
            arg_0.refresh_token = arg_3.json()['refresh_token']
            arg_0.write_tokens_to_file()
            arg_0.pin = None
        else:
            logger.warn('Error while requesting tokens from ecobee.com.'
                  ' Status code: ' + str(arg_3.status_code))
            return


def Func(arg_0):
        ''' Write api tokens to a file '''
        arg_1 = dict()
        arg_1['API_KEY'] = arg_0.api_key
        arg_1['ACCESS_TOKEN'] = arg_0.access_token
        arg_1['REFRESH_TOKEN'] = arg_0.refresh_token
        arg_1['AUTHORIZATION_CODE'] = arg_0.authorization_code
        if arg_0.file_based_config:
            config_from_file(arg_0.config_filename, arg_1)
        else:
            arg_0.config = arg_1


def Func(arg_0, arg_1, arg_2):
        ''' The minimum time, in minutes, to run the fan each hour. Value from 1 to 60 '''
        arg_3 = {"selection": {"selectionType": "thermostats",
                        "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                        "thermostat": {
                            "settings": {
                                "fanMinOnTime": arg_2
                            }
                        }}
        arg_4 = "set fan minimum on time."
        return arg_0.make_request(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3="nextTransition"):
        ''' Set a climate hold - ie away, home, sleep '''
        arg_4 = {"selection": {
                    "selectionType": "thermostats",
                    "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                "functions": [{"type": "setHold", "params": {
                    "holdType": arg_3,
                    "holdClimateRef": arg_2
                }}]}
        arg_5 = "set climate hold"
        return arg_0.make_request(arg_4, arg_5)


def Func(arg_0, arg_1, arg_2):
        ''' Delete the vacation with name vacation '''
        arg_3 = {"selection": {
                    "selectionType": "thermostats",
                    "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                "functions": [{"type": "deleteVacation", "params": {
                    "name": arg_2
                }}]}

        arg_4 = "delete a vacation"
        return arg_0.make_request(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2=False):
        ''' Resume currently scheduled program '''
        arg_3 = {"selection": {
                    "selectionType": "thermostats",
                    "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                "functions": [{"type": "resumeProgram", "params": {
                    "resumeAll": arg_2
                }}]}

        arg_4 = "resume program"
        return arg_0.make_request(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2):
        ''' Set humidity level'''
        arg_3 = {"selection": {"selectionType": "thermostats",
                              "selectionMatch": arg_0.thermostats[arg_1]['identifier']},
                              "thermostat": {
                                  "settings": {
                                      "humidity": int(arg_2)
                                  }
                              }}

        arg_4 = "set humidity level"
        return arg_0.make_request(arg_3, arg_4)


def Func(arg_0):
    """Generate the time in seconds in which DHCPDISCOVER wil be retransmited.

    [:rfc:`2131#section-3.1`]::

        might retransmit the
        DHCPREQUEST message four times, for a total delay of 60 seconds

    [:rfc:`2131#section-4.1`]::

        For example, in a 10Mb/sec Ethernet
        internetwork, the delay before the first retransmission SHOULD be 4
        seconds randomized by the value of a uniform random number chosen
        from the range -1 to +1.  Clients with clocks that provide resolution
        granularity of less than one second may choose a non-integer
        randomization value.  The delay before the next retransmission SHOULD
        be 8 seconds randomized by the value of a uniform number chosen from
        the range -1 to +1.  The retransmission delay SHOULD be doubled with
        subsequent retransmissions up to a maximum of 64 seconds.

    """
    arg_1 = 2 ** (arg_0 + 1) + random.uniform(-1, +1)
    logger.debug('next timeout resending will happen on %s',
                 future_dt_str(nowutc(), arg_1))
    return arg_1


def Func(arg_0):
    """Generate time in seconds to retransmit DHCPREQUEST.

    [:rfc:`2131#section-4..4.5`]::

        In both RENEWING and REBINDING states,
        if the client receives no response to its DHCPREQUEST
        message, the client SHOULD wait one-half of the remaining
        time until T2 (in RENEWING state) and one-half of the
        remaining lease time (in REBINDING state), down to a
        minimum of 60 seconds, before retransmitting the
        DHCPREQUEST message.

    """
    arg_1 = (arg_0.rebinding_time - arg_0.renewing_time) * RENEW_PERC
    if arg_1 < 60:
        arg_1 = 60
    logger.debug('Next request in renew will happen on %s',
                 future_dt_str(nowutc(), arg_1))
    return arg_1


def Func(arg_0):
        """Return the self object attributes not inherited as dict."""
        return {arg_1: arg_2 for arg_1, arg_2 in arg_0.__dict__.items() if arg_1 in FSM_ATTRS}


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None):
        """Reset object attributes when state is INIT."""
        logger.debug('Reseting attributes.')
        if arg_1 is None:
            arg_1 = conf.iface
        if arg_2 is None:
            # scapy for python 3 returns byte, not tuple
            arg_5 = get_if_raw_hwaddr(arg_1)
            if isinstance(arg_5, tuple) and len(arg_5) == 2:
                arg_6 = arg_5[1]
            else:
                arg_6 = arg_5
            arg_2 = str2mac(arg_6)
        arg_0.client = DHCPCAP(arg_1=arg_1, arg_2=arg_2, arg_3=arg_3)
        if arg_4 is not None:
            arg_0.script = ClientScript(arg_4)
        else:
            arg_0.script = None
        arg_0.time_sent_request = None
        arg_0.discover_attempts = 0
        arg_0.request_attempts = 0
        arg_0.current_state = STATE_PREINIT
        arg_0.offers = list()


def Func(arg_0, arg_1, arg_2):
        """Workaround to get timeout in the ATMT.timeout class method."""
        arg_1 = STATES2NAMES[arg_1]
        for arg_3 in arg_0.timeout[arg_1]:
            # access the function name
            if arg_3[1] is not None and \
               arg_3[1].atmt_condname == arg_2.atmt_condname:
                logger.debug('Timeout for state %s, function %s, is %s',
                             arg_1, arg_2.atmt_condname, arg_3[0])
                return arg_3[0]
        return None


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Workaround to change timeout values in the ATMT.timeout class method.

        self.timeout format is::

            {'STATE': [
                (TIMEOUT0, <function foo>),
                (TIMEOUT1, <function bar>)),
                (None, None)
                ],
            }

        """
        arg_1 = STATES2NAMES[arg_1]
        for arg_4 in arg_0.timeout[arg_1]:
            # access the function name
            if arg_4[1] is not None and \
               arg_4[1].atmt_condname == arg_2.atmt_condname:
                # convert list to tuple to make it mutable
                arg_5 = list(arg_4)
                # modify the timeout
                arg_5[0] = arg_3
                # set the new timeoute to self.timeout
                arg_6 = arg_0.timeout[arg_1].index(arg_4)
                arg_0.timeout[arg_1][arg_6] = tuple(arg_5)
                logger.debug('Set state %s, function %s, to timeout %s',
                             arg_1, arg_2.atmt_condname, arg_3)


def Func(arg_0):
        """Select an offer from the offers received.

        [:rfc:`2131#section-4.2`]::

            DHCP clients are free to use any strategy in selecting a DHCP
            server among those from which the client receives a DHCPOFFER.

        [:rfc:`2131#section-4.4.1`]::

            The time
            over which the client collects messages and the mechanism used to
            select one DHCPOFFER are implementation dependent.

        Nor [:rfc:`7844`] nor [:rfc:`2131`] specify the algorithm.
        Here, currently the first offer is selected.

        .. todo::

           - Check other implementations algorithm to select offer.

        """
        logger.debug('Selecting offer.')
        arg_1 = arg_0.offers[0]
        arg_0.client.handle_offer(arg_1)


def Func(arg_0):
        """Send request.

        [:rfc:`2131#section-3.1`]::

        a client retransmitting as described in section 4.1 might retransmit
        the DHCPREQUEST message four times, for a total delay of 60 seconds

        .. todo::

           - The maximum number of retransmitted REQUESTs is per state or in
             total?
           - Are the retransmitted REQUESTs independent to the retransmitted
             DISCOVERs?

        """
        assert arg_0.client
        if arg_0.current_state == STATE_BOUND:
            arg_1 = arg_0.client.gen_request_unicast()
        else:
            arg_1 = arg_0.client.gen_request()
        sendp(arg_1)
        logger.debug('Modifying FSM obj, setting time_sent_request.')
        arg_0.time_sent_request = nowutc()
        logger.info('DHCPREQUEST of %s on %s to %s port %s',
                    arg_0.client.iface, arg_0.client.client_ip,
                    arg_0.client.server_ip, arg_0.client.server_port)

        # NOTE: see previous TODO, maybe the MAX_ATTEMPTS_REQUEST needs to be
        # calculated per state.
        if arg_0.request_attempts < MAX_ATTEMPTS_REQUEST:
            arg_0.request_attempts *= 2
            logger.debug('Increased request attempts to %s',
                         arg_0.request_attempts)
        if arg_0.current_state == STATE_RENEWING:
            arg_3 = gen_timeout_request_renew(arg_0.client.lease)
            arg_0.set_timeout(arg_0.current_state,
                             arg_0.timeout_request_renewing,
                             arg_3)
        elif arg_0.current_state == STATE_REBINDING:
            arg_4 = gen_timeout_request_rebind(arg_0.client.lease)
            arg_0.set_timeout(arg_0.current_state,
                             arg_0.timeout_request_rebinding,
                             arg_4)
        else:
            arg_5 = \
                gen_timeout_resend(arg_0.request_attempts)
            arg_0.set_timeout(arg_0.current_state,
                             arg_0.timeout_requesting,
                             arg_5)


def Func(arg_0):
        """Func state.

        [:rfc:`2131#section-4.4.1`]::

            The client SHOULD wait a random time between one and ten
            seconds to desynchronize the use of DHCP at startup

        .. todo::
           - The initial delay is implemented, but probably is not in other
             implementations. Check what other implementations do.
        """
        # NOTE: in case Func is reached from other state, initialize attributes
        # reset all variables.
        logger.debug('In state: Func')
        if arg_0.current_state is not STATE_PREFunc:
            arg_0.reset()
        arg_0.current_state = STATE_Func
        # NOTE: see previous TODO, maybe this is not needed.
        if arg_0.delay_selecting:
            if arg_0.delay_before_selecting is None:
                arg_2 = gen_delay_selecting()
            else:
                arg_2 = arg_0.delay_before_selecting
        else:
            arg_2 = 0
        arg_0.set_timeout(arg_0.current_state,
                         arg_0.timeout_delay_before_selecting,
                         arg_2)
        if arg_0.timeout_select is not None:
            arg_0.set_timeout(STATE_SELECTING,
                             arg_0.timeout_selecting,
                             arg_0.timeout_select)


def Func(arg_0):
        """Func state."""
        logger.debug('In state: Func')
        arg_0.current_state = STATE_Func
        if arg_0.script is not None:
            arg_0.script.script_init(arg_0.client.lease, arg_0.current_state)
            arg_0.script.script_go()
        else:
            set_net(arg_0.client.lease)
        return


def Func(arg_0):
        """Func state."""
        logger.debug('In state: Func')
        arg_0.current_state = STATE_Func
        if arg_0.script is not None:
            arg_0.script.script_init(arg_0.client.lease, arg_0.current_state)
            arg_0.script.script_go()
        set_net(arg_0.client.lease)
        raise arg_0.INIT()


def Func(arg_0):
        """Timeout of selecting on SELECTING state.

        Not specifiyed in [:rfc:`7844`].
        See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.

        """
        logger.debug('C2.1: T In %s, timeout receiving response to select.',
                     arg_0.current_state)

        if len(arg_0.offers) >= MAX_OFFERS_COLLECTED:
            logger.debug('C2.2: T Maximum number of offers reached, '
                         'raise REQUESTING.')
            raise arg_0.REQUESTING()

        if arg_0.discover_attempts >= MAX_ATTEMPTS_DISCOVER:
            logger.debug('C2.3: T Maximum number of discover retries is %s'
                         ' and already sent %s.',
                         MAX_ATTEMPTS_DISCOVER, arg_0.discover_attempts)
            if len(arg_0.offers) <= 0:
                logger.debug('C2.4: T. But no OFFERS where received, '
                             'raise ERROR.')
                raise arg_0.ERROR()
            logger.debug('C2.4: F. But there is some OFFERS, '
                         'raise REQUESTING.')
            raise arg_0.REQUESTING()

        logger.debug('C2.2: F. Still not received all OFFERS, but not '
                     'max # attemps reached, raise SELECTING.')
        raise arg_0.SELECTING()


def Func(arg_0):
        """Timeout requesting in REQUESTING state.

        Not specifiyed in [:rfc:`7844`]

        [:rfc:`2131#section-3.1`]::

            might retransmit the
            DHCPREQUEST message four times, for a total delay of 60 seconds

        """
        logger.debug("C3.2: T. In %s, timeout receiving response to request, ",
                     arg_0.current_state)
        if arg_0.discover_requests >= MAX_ATTEMPTS_REQUEST:
            logger.debug('C2.3: T. Maximum number %s of REQUESTs '
                         'reached, already sent %s, raise ERROR.',
                         MAX_ATTEMPTS_REQUEST, arg_0.disover_requests)
            raise arg_0.ERROR()
        logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached,"
                     "raise REQUESTING.")
        raise arg_0.REQUESTING()


def Func(arg_0):
        """Timeout of renewing on RENEWING state.

        Same comments as in
        :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.

        """
        logger.debug("C5.2:T In %s, timeout receiving response to request.",
                     arg_0.current_state)
        if arg_0.request_attempts >= MAX_ATTEMPTS_REQUEST:
            logger.debug('C2.3: T Maximum number %s of REQUESTs '
                         'reached, already sent %s, wait to rebinding time.',
                         MAX_ATTEMPTS_REQUEST, arg_0.disover_requests)
            # raise self.ERROR()
        logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached,"
                     "raise RENEWING.")
        raise arg_0.RENEWING()


def Func(arg_0):
        """Timeout of request rebinding on REBINDING state.

        Same comments as in
        :func:`dhcpcapfsm.DHCPCAPFSM.timeout_requesting`.

        """
        logger.debug("C6.2:T In %s, timeout receiving response to request.",
                     arg_0.current_state)
        if arg_0.request_attempts >= MAX_ATTEMPTS_REQUEST:
            logger.debug('C.2.3: T. Maximum number %s of REQUESTs '
                         'reached, already sent %s, wait lease time expires.',
                         MAX_ATTEMPTS_REQUEST, arg_0.disover_requests)
            # raise self.ERROR()
        logger.debug("C2.3: F. Maximum number of REQUESTs retries not reached,"
                     "raise REBINDING.")
        raise arg_0.REBINDING()


def Func(arg_0, arg_1):
        """Receive offer on SELECTING state."""
        logger.debug("C2. Received OFFER?, in SELECTING state.")
        if isoffer(arg_1):
            logger.debug("C2: T, OFFER received")
            arg_0.offers.append(arg_1)
            if len(arg_0.offers) >= MAX_OFFERS_COLLECTED:
                logger.debug("C2.5: T, raise REQUESTING.")
                arg_0.select_offer()
                raise arg_0.REQUESTING()
            logger.debug("C2.5: F, raise SELECTING.")
            raise arg_0.SELECTING()


def Func(arg_0, arg_1):
        """Receive ACK in REQUESTING state."""
        logger.debug("C3. Received ACK?, in REQUESTING state.")
        if arg_0.process_received_ack(arg_1):
            logger.debug("C3: T. Received ACK, in REQUESTING state, "
                         "raise BOUND.")
            raise arg_0.BOUND()


def Func(arg_0, arg_1):
        """Receive ACK in RENEWING state."""
        logger.debug("C3. Received ACK?, in RENEWING state.")
        if arg_0.process_received_ack(arg_1):
            logger.debug("C3: T. Received ACK, in RENEWING state, "
                         "raise BOUND.")
            raise arg_0.BOUND()


def Func(arg_0, arg_1):
        """Receive NAK in RENEWING state."""
        logger.debug("C3.1. Received NAK?, in RENEWING state.")
        if arg_0.process_received_nak(arg_1):
            logger.debug("C3.1: T. Received NAK, in RENEWING state, "
                         " raise INIT.")
            raise arg_0.INIT()


def Func(arg_0, arg_1, arg_2):
        """ Assign a value, remove if it's None """
        arg_3 = arg_0._clone()
        if django.VERSION[0] <= 1 and django.VERSION[1] <= 4:
            arg_2 = arg_2 or None
        arg_3._qsl = [(q, v) for (q, v) in arg_0._qsl if q != arg_1]
        if arg_2 is not None:
            arg_3._qsl.append((arg_1, arg_2))
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """ Append a value to multiple value parameter. """
        arg_3 = arg_0._clone()
        arg_3._qsl = [p for p in arg_0._qsl
                      if not(p[0] == arg_1 and p[1] == arg_2)]
        arg_3._qsl.append((arg_1, arg_2,))
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """ Remove a value from multiple value parameter. """
        arg_3 = arg_0._clone()
        arg_3._qsl = [qb for qb in arg_0._qsl if qb != (arg_1, str(arg_2))]
        return arg_3


def Func(arg_0, arg_1, arg_2="geojson", arg_3="body", arg_4=True):
        """Pass in an Overpass query in Overpass QL."""
        # Construct full Overpass query
        if arg_4:
            arg_5 = arg_0._construct_ql_query(
                arg_1, arg_2=arg_2, arg_3=arg_3
            )
        else:
            arg_5 = arg_1

        if arg_0.debug:
            logging.FuncLogger().info(arg_1)

        # Get the response from Overpass
        arg_6 = arg_0._Func_from_overpass(arg_5)
        arg_7 = arg_6.headers.Func("content-type")

        if arg_0.debug:
            print(arg_7)
        if arg_7 == "text/csv":
            arg_8 = []
            arg_9 = csv.reader(StringIO(arg_6.text), delimiter="\t")
            for arg_10 in arg_9:
                arg_8.append(arg_10)
            return arg_8
        elif arg_7 in ("text/xml", "application/xml", "application/osm3s+xml"):
            return arg_6.text
        elif arg_7 == "application/json":
            arg_11 = json.loads(arg_6.text)

        if not arg_4:
            return arg_11

        # Check for valid answer from Overpass.
        # A valid answer contains an 'elements' key at the root level.
        if "elements" not in arg_11:
            raise UnknownOverpassError("Received an invalid answer from Overpass.")

        # If there is a 'remark' key, it spells trouble.
        arg_12 = arg_11.Func("remark", None)
        if arg_12 and arg_12.startswith("runtime error"):
            raise ServerRuntimeError(arg_12)

        if arg_2 is not "geojson":
            return arg_11

        # construct geojson
        return arg_0._as_geojson(arg_11["elements"])


def Func(arg_0, arg_1, arg_2, arg_3,
                                 arg_4, arg_5, arg_6=None,
                                 **arg_7):
        """This attempts to allocate v6 addresses as per RFC2462 and RFC3041.

        To accomodate this, we effectively treat all v6 assignment as a
        first time allocation utilizing the MAC address of the VIF. Because
        we recycle MACs, we will eventually attempt to recreate a previously
        generated v6 address. Instead of failing, we've opted to handle
        reallocating that address in this method.

        This should provide a performance boost over attempting to check
        each and every subnet in the existing reallocate logic, as we'd
        have to iterate over each and every subnet returned
        """

        LOG.info("Attempting to allocate a v6 address - [{0}]".format(
            utils.pretty_kwargs(network_id=arg_2, arg_3=arg_3,
                                arg_4=arg_4, arg_6=arg_6)))

        if arg_6:
            LOG.info("IP %s explicitly requested, deferring to standard "
                     "allocation" % arg_6)
            return arg_0._allocate_from_subnet(arg_1, arg_2=arg_2,
                                              arg_3=arg_3, arg_4=arg_4,
                                              arg_5=arg_5,
                                              arg_6=arg_6, **arg_7)
        else:
            arg_8 = arg_7.get("mac_address")
            if arg_8:
                arg_8 = arg_7["mac_address"].get("address")

            if arg_3 and arg_3["ip_policy"]:
                arg_9 = arg_3["ip_policy"].get_cidrs_ip_set()
            else:
                arg_9 = netaddr.IPSet([])

            for arg_10, arg_6 in enumerate(
                    generate_v6(arg_8, arg_4, arg_3["cidr"])):

                LOG.info("Attempt {0} of {1}".format(
                    arg_10 + 1, CONF.QUARK.v6_allocation_attempts))

                if arg_10 > CONF.QUARK.v6_allocation_attempts - 1:
                    LOG.info("Exceeded v6 allocation attempts, bailing")
                    raise ip_address_failure(arg_2)

                arg_6 = netaddr.IPAddress(arg_6).ipv6()
                LOG.info("Generated a new v6 address {0}".format(
                    str(arg_6)))

                if (arg_9 is not None and
                        arg_6 in arg_9):
                    LOG.info("Address {0} excluded by policy".format(
                        str(arg_6)))
                    continue

                try:
                    with arg_1.session.begin():
                        arg_11 = db_api.ip_address_create(
                            arg_1, arg_11=arg_6,
                            subnet_id=arg_3["id"],
                            version=arg_3["ip_version"], network_id=arg_2,
                            address_type=arg_7.get('address_type',
                                                    ip_types.FIXED))
                        return arg_11
                except db_exception.DBDuplicateEntry:
                    # This shouldn't ever happen, since we hold a unique MAC
                    # address from the previous IPAM step.
                    LOG.info("{0} exists but was already "
                             "allocated".format(str(arg_6)))
                    LOG.debug("Duplicate entry found when inserting subnet_id"
                              " %s ip_address %s", arg_3["id"], arg_6)


def Func(arg_0, arg_1, arg_2):
    """Associates the flip with ports and creates it with the flip driver

    :param context: neutron api request context.
    :param flip: quark.db.models.IPAddress object representing a floating IP
    :param port_fixed_ips: dictionary of the structure:
    {"<id of port>": {"port": <quark.db.models.Port>,
     "fixed_ip": "<fixed ip address>"}}
    :return: None
    """
    if arg_2:
        arg_0.session.begin()
        try:
            arg_3 = [val['port'] for val in arg_2.values()]
            arg_1 = db_api.port_associate_ip(arg_0, arg_3, arg_1,
                                            arg_2.keys())

            for arg_4 in arg_2:
                arg_5 = arg_2[arg_4]['fixed_ip']
                arg_1 = db_api.floating_ip_associate_fixed_ip(arg_0, arg_1,
                                                             arg_5)

            arg_6 = registry.DRIVER_REGISTRY.get_driver()

            arg_6.register_floating_ip(arg_1, arg_2)
            arg_0.session.commit()
        except Exception:
            arg_0.session.rollback()
            raise

    # alexm: Notify from this method for consistency with _delete_flip
    billing.notify(arg_0, billing.IP_ASSOC, arg_1)


def Func(arg_0, arg_1, arg_2):
    """Update an existing floating IP.

    :param context: neutron api request context.
    :param id: id of the floating ip
    :param content: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.

    :returns: Dictionary containing details for the new floating IP.  If values
        are declared in the fields parameter, then only those keys will be
        present.
    """

    LOG.info('Func %s for tenant %s and body %s' %
             (arg_1, arg_0.tenant_id, arg_2))

    if 'port_id' not in arg_2:
        raise n_exc.BadRequest(resource='floating_ip',
                               msg='port_id is required.')

    arg_3 = []
    if arg_2.get('port_id'):
        arg_3 = [{'port_id': arg_2.get('port_id')}]
    arg_4 = _update_flip(arg_0, arg_1, ip_types.FLOATING, arg_3)
    return v._make_floating_ip_dict(arg_4)


def Func(arg_0, arg_1):
    """deallocate a floating IP.

    :param context: neutron api request context.
    :param id: id of the floating ip
    """

    LOG.info('Func %s for tenant %s' % (arg_1, arg_0.tenant_id))

    _delete_flip(arg_0, arg_1, ip_types.FLOATING)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=['id'],
                    arg_4=None, arg_5=None, arg_6=False):
    """Retrieve a list of floating ips.

    :param context: neutron api request context.
    :param filters: a dictionary with keys that are valid keys for
        a floating ip as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.
    :param fields: a list of strings that are valid keys in a
        floating IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.

    :returns: List of floating IPs that are accessible to the tenant who
        submits the request (as indicated by the tenant id of the context)
        as well as any filters.
    """
    LOG.info('Func for tenant %s filters %s fields %s' %
             (arg_0.tenant_id, arg_1, arg_2))

    arg_7 = _get_ips_by_type(arg_0, ip_types.FLOATING,
                                    arg_1=arg_1, arg_2=arg_2)

    return [v._make_floating_ip_dict(arg_8) for arg_8 in arg_7]


def Func(arg_0, arg_1=None):
    """Return the number of floating IPs.

    :param context: neutron api request context
    :param filters: a dictionary with keys that are valid keys for
        a floating IP as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictionary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    :returns: The number of floating IPs that are accessible to the tenant who
        submits the request (as indicated by the tenant id of the context)
        as well as any filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.
    """
    LOG.info('Func for tenant %s filters %s' %
             (arg_0.tenant_id, arg_1))

    if arg_1 is None:
        arg_1 = {}

    arg_1['_deallocated'] = False
    arg_1['address_type'] = ip_types.FLOATING
    arg_2 = db_api.ip_address_count_all(arg_0, arg_1)

    LOG.info('Found %s floating ips for tenant %s' % (arg_2,
                                                      arg_0.tenant_id))
    return arg_2


def Func(arg_0, arg_1, arg_2):
    """Update an existing scaling IP.

    :param context: neutron api request context.
    :param id: id of the scaling ip
    :param content: dictionary with keys indicating fields to update.
        valid keys are those that have a value of True for 'allow_put'
        as listed in the RESOURCE_ATTRIBUTE_MAP object in
        neutron/api/v2/attributes.py.

    :returns: Dictionary containing details for the new scaling IP.  If values
        are declared in the fields parameter, then only those keys will be
        present.
    """
    LOG.info('Func %s for tenant %s and body %s' %
             (arg_1, arg_0.tenant_id, arg_2))
    arg_3 = arg_2.get('ports', [])
    arg_4 = _update_flip(arg_0, arg_1, ip_types.SCALING, arg_3)
    return v._make_scaling_ip_dict(arg_4)


def Func(arg_0, arg_1, arg_2):
    """Splits VIFs into three explicit categories and one implicit

    Added - Groups exist in Redis that have not been ack'd and the VIF
            is not tagged.
            Action: Tag the VIF and apply flows
    Updated - Groups exist in Redis that have not been ack'd and the VIF
              is already tagged
              Action: Do not tag the VIF, do apply flows
    Removed - Groups do NOT exist in Redis but the VIF is tagged
              Action: Untag the VIF, apply default flows
    Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat
                this case as if it were an "added" group.
                Action: Tag the VIF and apply flows
    NOOP - The VIF is not tagged and there are no matching groups in Redis.
           This is our implicit category
           Action: Do nothing
    """
    arg_3 = []
    arg_4 = []
    arg_5 = []

    for arg_6 in arg_1:
        # Quark should not action on isonet vifs in regions that use FLIP
        if ('floating_ip' in CONF.QUARK.environment_capabilities and
                is_isonet_vif(arg_6)):
            continue

        arg_7 = arg_6 in arg_2
        if arg_6.tagged and arg_7 and\
                arg_2[arg_6][sg_cli.SECURITY_GROUP_ACK]:
            # Already ack'd these groups and VIF is tagged, reapply.
            # If it's not tagged, fall through and have it self-heal
            continue

        if arg_6.tagged:
            if arg_7:
                arg_4.append(arg_6)
            else:
                arg_5.append(arg_6)
        else:
            if arg_7:
                arg_3.append(arg_6)
            # if not tagged and no groups, skip

    return arg_3, arg_4, arg_5


def Func():
    """Fetches changes and applies them to VIFs periodically

    Process as of RM11449:
    * Get all groups from redis
    * Fetch ALL VIFs from Xen
    * Walk ALL VIFs and partition them into added, updated and removed
    * Walk the final "modified" VIFs list and apply flows to each
    """
    arg_0 = sg_cli.SecurityGroupsClient()
    arg_1 = xapi.XapiClient()

    arg_2 = set()
    while True:
        try:
            arg_2 = arg_1.get_interfaces()
        except Exception:
            LOG.exception("Unable to get instances/interfaces from xapi")
            _sleep()
            continue

        try:
            arg_3 = arg_0.get_security_group_states(arg_2)
            arg_4, arg_5, arg_6 = partition_vifs(arg_1,
                                                            arg_2,
                                                            arg_3)
            arg_1.update_interfaces(arg_4, arg_5, arg_6)
            arg_7 = [v for v in arg_4 + arg_5 if v.success]
            # NOTE(quade): This solves a race condition where a security group
            # rule may have changed between the time the sg_states were called
            # and when they were officially ack'd. It functions as a compare
            # and set. This is a fix until we get onto a proper messaging
            # queue. NCP-2287
            arg_8 = arg_0.get_security_group_states(arg_2)
            arg_7 = get_groups_to_ack(arg_7, arg_3,
                                              arg_8)
            # This list will contain all the security group rules that do not
            # match
            ack_groups(arg_0, arg_7)

        except Exception:
            LOG.exception("Unable to get security groups from registry and "
                          "apply them to xapi")
            _sleep()
            continue

        _sleep()


def Func(arg_0, arg_1):
        """Delete the quota entries for a given tenant_id.

        Atfer deletion, this tenant will use default quota values in conf.
        """

        arg_2 = arg_0.session.query(Quota)
        arg_2 = arg_2.filter_by(arg_1=arg_1)
        arg_2.delete()


def Func(arg_0, arg_1, arg_2):
    """Validate the CIDR for a subnet.

    Verifies the specified CIDR does not overlap with the ones defined
    for the other subnets specified for this network, or with any other
    CIDR if overlapping IPs are disabled.

    """
    if neutron_cfg.cfg.CONF.allow_overlapping_ips:
        return

    try:
        arg_3 = netaddr.IPSet([arg_2])
    except TypeError:
        LOG.exception("Invalid or missing cidr: %s" % arg_2)
        raise n_exc.BadRequest(resource="subnet",
                               msg="Invalid or missing cidr")

    arg_4 = {
        'network_id': arg_1,
        'shared': [False]
    }
    # Using admin context here, in case we actually share networks later
    arg_5 = db_api.subnet_find(arg_0=arg_0.elevated(), **arg_4)

    for arg_6 in arg_5:
        if (netaddr.IPSet([arg_6.cidr]) & arg_3):
            # don't give out details of the overlapping subnet
            arg_7 = (_("Requested subnet with cidr: %(cidr)s for "
                         "network: %(network_id)s overlaps with another "
                         "subnet") %
                       {'cidr': arg_2,
                        'network_id': arg_1})
            LOG.error(_("Validation for CIDR: %(new_cidr)s failed - "
                        "overlaps with subnet %(subnet_id)s "
                        "(CIDR: %(cidr)s)"),
                      {'new_cidr': arg_2,
                       'subnet_id': arg_6.id,
                       'cidr': arg_6.cidr})
            raise n_exc.InvalidInput(error_message=arg_7)


def Func(arg_0, arg_1, arg_2=None):
    """Retrieve a subnet.

    : param context: neutron api request context
    : param id: UUID representing the subnet to fetch.
    : param fields: a list of strings that are valid keys in a
        subnet dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
        object in neutron/api/v2/attributes.py. Only these fields
        will be returned.
    """
    LOG.info("Func %s for tenant %s with fields %s" %
             (arg_1, arg_0.tenant_id, arg_2))
    arg_3 = db_api.subnet_find(arg_0=arg_0, limit=None,
                                page_reverse=False, sorts=['id'],
                                marker_obj=None, arg_2=None, arg_1=arg_1,
                                join_dns=True, join_routes=True,
                                scope=db_api.ONE)
    if not arg_3:
        raise n_exc.SubnetNotFound(subnet_id=arg_1)

    arg_4 = arg_3.get("_allocation_pool_cache")
    if not arg_4:
        arg_5 = arg_3.allocation_pools
        db_api.subnet_update_set_alloc_pool_cache(arg_0, arg_3, arg_5)
    return v._make_subnet_dict(arg_3)


def Func(arg_0, arg_1=None):
    """Return the number of subnets.

    The result depends on the identity of the user making the request
    (as indicated by the context) as well as any filters.
    : param context: neutron api request context
    : param filters: a dictionary with keys that are valid keys for
        a network as listed in the RESOURCE_ATTRIBUTE_MAP object
        in neutron/api/v2/attributes.py.  Values in this dictiontary
        are an iterable containing values that will be used for an exact
        match comparison for that value.  Each result returned by this
        function will have matched one of the values for each key in
        filters.

    NOTE: this method is optional, as it was not part of the originally
          defined plugin API.
    """
    LOG.info("Func for tenant %s with filters %s" %
             (arg_0.tenant_id, arg_1))
    return db_api.subnet_count_all(arg_0, **arg_1)