code: def _indexes_grouped_by_classes(
      targets: Sequence[int],
      patterns_indexes: Union[None, Sequence[int]],
      sort_indexes: bool = True,
      sort_classes: bool = True,
  ) -> Union[List[int], None]:
      result_per_class: Dict[int, List[int]] = OrderedDict()
      result: List[int] = []
  
      indexes_was_none = patterns_indexes is None
  
      if patterns_indexes is not None:
          patterns_indexes = tensor_as_list(patterns_indexes)
      else:
          patterns_indexes = list(range(len(targets)))
  
      targets = tensor_as_list(targets)
  
      # Consider that result_per_class is an OrderedDict
      # This means that, if sort_classes is True, the next for statement
      # will initialize "result_per_class" in sorted order which in turn means
      # that patterns will be ordered by ascending class ID.
      classes = torch.unique(
          torch.as_tensor(targets), sorted=sort_classes
      ).tolist()
  
      for class_id in classes:
          result_per_class[class_id] = []
  
      # Stores each pattern index in the appropriate class list
      for idx in patterns_indexes:
          result_per_class[targets[idx]].append(idx)
  
      # Concatenate all the pattern indexes
      for class_id in classes:
          if sort_indexes:
              result_per_class[class_id].sort()
          result.extend(result_per_class[class_id])
  
      if result == patterns_indexes and indexes_was_none:
          # Result is [0, 1, 2, ..., N] and patterns_indexes was originally None
          # This means that the user tried to obtain a full Dataset
          # (indexes_was_none) only ordered according to the sort_indexes and
          # sort_classes parameters. However, sort_indexes+sort_classes returned
          # the plain pattern sequence as it already is. So the original Dataset
          # already satisfies the sort_indexes+sort_classes constraints.
          # By returning None, we communicate that the Dataset can be taken as-is.
          return None
  
      return result
  
imports: from collections import OrderedDict, defaultdict, deque
  from typing import TYPE_CHECKING, Any, Callable, Generic, Iterator, List, Iterable, Mapping, Optional, Sequence, TypeVar, Union, Dict, SupportsInt
  import warnings
  import torch
  from torch import Tensor
  from torch.utils.data import Subset, ConcatDataset
  from .data import AvalancheDataset
  from .data_attribute import DataAttribute
  from .dataset_definitions import ISupportedClassificationDataset
  from .dataset_utils import SubSequence, find_list_from_index
  from .flat_data import ConstantSequence
  from .transform_groups import TransformGroupDef, TransformGroups, XTransform, YTransform
label_desc: Use image node_id 2 for calling a global function with example usage: _indexes_grouped_by_classes(targets, patterns_indexes, sort_indexes, sort_classes) and returns: result, None