code: def _get_flexible_source_candidates_for_submodule(ds, sm):
      """Assemble candidate locations from where to clone a submodule
  
      The following location candidates are considered. For each candidate a
      cost is given in parenthesis, higher values indicate higher cost, and
      thus lower priority:
  
      - A datalad URL recorded in `.gitmodules` (cost 590). This allows for
        datalad URLs that require additional handling/resolution by datalad, like
        ria-schemes (ria+http, ria+ssh, etc.)
  
      - A URL or absolute path recorded for git in `.gitmodules` (cost 600).
  
      - URL of any configured superdataset remote that is known to have the
        desired submodule commit, with the submodule path appended to it.
        There can be more than one candidate (cost 650).
  
      - In case `.gitmodules` contains a relative path instead of a URL,
        the URL of any configured superdataset remote that is known to have the
        desired submodule commit, with this relative path appended to it.
        There can be more than one candidate (cost 650).
  
      - In case `.gitmodules` contains a relative path as a URL, the absolute
        path of the superdataset, appended with this relative path (cost 900).
  
      Additional candidate URLs can be generated based on templates specified as
      configuration variables with the pattern
  
        `datalad.get.subdataset-source-candidate-<name>`
  
      where `name` is an arbitrary identifier. If name starts with three digits
      (e.g. '400myserver') these will be interpreted as a cost, and the
      respective candidate will be sorted into the generated candidate list
      according to this cost. If no cost is given, a default of 700
      is used.
  
      A template string assigned to such a variable can utilize the Python format
      mini language and may reference a number of properties that are inferred
      from the parent dataset's knowledge about the target subdataset. Properties
      include any submodule property specified in the respective `.gitmodules`
      record. For convenience, an existing `datalad-id` record is made available
      under the shortened name `id`.
  
      Additionally, the URL of any configured remote that contains the respective
      submodule commit is available as `remoteurl-<name>` property, where `name`
      is the configured remote name.
  
      Lastly, all candidates are sorted according to their cost (lower values
      first), and duplicate URLs are stripped, while preserving the first item in the
      candidate list.
  
      More information on this feature can be found at
      http://handbook.datalad.org/r.html?clone-priority
  
      Parameters
      ----------
      ds : Dataset
        Parent dataset of to-be-installed subdataset.
      sm : dict
        Submodule record as produced by `subdatasets()`.
  
      Returns
      -------
      list of dict
        Where each dict has keys 'cost' (int), 'name' (str), 'url' (str).
        Names are not unique and either derived from the name of the respective
        remote, template configuration variable, or 'local'.
      """
  
      # short cuts
      ds_repo = ds.repo
      sm_url = sm.get("gitmodule_url", None)
      sm_datalad_url = sm.get("gitmodule_datalad-url", None)
      sm_path = op.relpath(sm["path"], start=sm["parentds"])
  
      clone_urls = []
  
      # CANDIDATE: tracking remote of the current branch
      tracking_remote, tracking_branch = ds_repo.get_tracking_branch()
      candidate_remotes = [tracking_remote] if tracking_remote else []
  
      # if we have a remote, let's check the location of that remote
      # for the presence of the desired submodule
      last_commit = ds_repo.get_last_commit_hexsha(sm_path)
      if last_commit:
          # CANDIDATE: any remote that has the commit when the submodule was
          # last modified
  
          # ideally should also give preference to the remotes which have
          # the same branch checked out I guess
          candidate_remotes += list(
              _get_remotes_having_commit(ds_repo, last_commit)
          )
  
      # prepare a dict to generate URL candidates from templates
      sm_candidate_props = {
          k[10:].replace("datalad-id", "id"): v
          for k, v in sm.items()
          if k.startswith("gitmodule_")
      }
  
      for remote in unique(candidate_remotes):
          remote_url = ds_repo.get_remote_url(remote, push=False)
  
          # Directly on parent's ds url
          if remote_url:
              # make remotes and their URLs available to template rendering
              sm_candidate_props[
                  "remoteurl-{}".format(remote)
              ] = remote_url
              # attempt: submodule checkout at parent remote URL
              # We might need to quote sm_path portion, e.g. for spaces etc
              if isinstance(RI(remote_url), URL):
                  sm_path_url = urlquote(sm_path)
              else:
                  sm_path_url = sm_path
  
              clone_urls.extend(
                  dict(cost=650, name=remote, url=url)
                  for url in _get_flexible_source_candidates(
                      # alternate suffixes are tested by `clone` anyways
                      sm_path_url,
                      remote_url,
                      alternate_suffix=False,
                  )
              )
  
              # attempt: provided (configured?) submodule URL
              # TODO: consider supporting DataLadRI here?  or would confuse
              #  git and we wouldn't want that (i.e. not allow pure git clone
              #  --recursive)
              if sm_url:
                  clone_urls.extend(
                      dict(cost=600, name=remote, url=url)
                      for url in _get_flexible_source_candidates(
                          sm_url, remote_url, alternate_suffix=False
                      )
                  )
  
      cost_candidate_expr = re.compile("[0-9][0-9][0-9].*")
      candcfg_prefix = "datalad.get.subdataset-source-candidate-"
      for name, tmpl in [
          (c[len(candcfg_prefix) :], ds_repo.config[c])
          for c in ds_repo.config.keys()
          if c.startswith(candcfg_prefix)
      ]:
          # ensure that there is only one template of the same name
          if type(tmpl) == tuple and len(tmpl) > 1:
              raise ValueError(
                  f"There are multiple URL templates for submodule clone "
                  f"candidate '{name}', but only one is allowed. "
                  f"Check datalad.get.subdataset-source-candidate-* configuration!"
              )
          try:
              url = tmpl.format(**sm_candidate_props)
          except KeyError as e:
              ce = CapturedException(e)
              lgr.warning(
                  "Failed to format template %r for a submodule clone. "
                  "Error: %s",
                  tmpl,
                  ce,
              )
              continue
          # we don't want "flexible_source_candidates" here, this is
          # configuration that can be made arbitrarily precise from the
          # outside. Additional guesswork can only make it slower
          has_cost = cost_candidate_expr.match(name) is not None
          clone_urls.append(
              # assign a default cost, if a config doesn't have one
              dict(
                  cost=int(name[:3]) if has_cost else 700,
                  name=name[3:] if has_cost else name,
                  url=url,
                  from_config=True,
              )
          )
  
      # CANDIDATE: the actual configured gitmodule URL
      if sm_url:
          clone_urls.extend(
              dict(cost=900, name="local", url=url)
              for url in _get_flexible_source_candidates(
                  sm_url, ds.path, alternate_suffix=False
              )
              # avoid inclusion of submodule location itself
              if url != sm["path"]
          )
  
      # Consider original datalad URL in .gitmodules before any URL that is meant
      # to be consumed by git:
      if sm_datalad_url:
          clone_urls.append(
              dict(cost=590, name="dl-url", url=sm_datalad_url)
          )
  
      # sort all candidates by their label, thereby allowing a
      # candidate provided by configuration to purposefully
      # sort before or after automatically generated configuration
      clone_urls = sorted(clone_urls, key=lambda x: x["cost"])
      # take out any duplicate source candidates
      # unique() takes out the duplicated at the tail end
      clone_urls = unique(clone_urls, lambda x: x["url"])
      lgr.debug(
          "Assembled %i clone candidates for %s: %s",
          len(clone_urls),
          sm_path,
          [cand["url"] for cand in clone_urls],
      )
  
      return clone_urls
  
imports: import logging
  import re
  import os.path
  from datalad.config import ConfigManager
  from datalad.interface.base import Interface, eval_results
  from datalad.interface.base import build_doc
  from datalad.interface.results import get_status_dict, results_from_paths, annexjson2result, success_status_map, results_from_annex_noinfo
  from datalad.interface.common_opts import recursion_flag, location_description, jobs_opt, reckless_opt
  from datalad.interface.results import is_ok_dataset
  from datalad.support.constraints import EnsureInt, EnsureChoice, EnsureStr, EnsureNone
  from datalad.support.collections import ReadOnlyDict
  from datalad.support.param import Parameter
  from datalad.support.annexrepo import AnnexRepo
  from datalad.support.gitrepo import GitRepo, _fixup_submodule_dotgit_setup
  from datalad.support.exceptions import CapturedException, CommandError, InsufficientArgumentsError
  from datalad.support.network import URL, RI, urlquote
  from datalad.support.parallel import ProducerConsumerProgressLog
  from datalad.utils import unique, Path, get_dataset_root, shortened_repr
  from datalad.local.subdatasets import Subdatasets
  from datalad.distribution.dataset import Dataset, EnsureDataset, datasetmethod, require_dataset
  from datalad.core.distributed.clone import clone_dataset
  from datalad.distribution.utils import _get_flexible_source_candidates
label_desc: Use image node_id 2 for calling a global function with example usage: _get_flexible_source_candidates_for_submodule(ds, sm) and returns: clone_urls