code: def add_rule_to_best_shard(
      rule_to_add: BazelRule,
      shards: List[List[BazelRule]],
      optimum: float,
  ):
      """Adds a rule to the best shard.
  
      The best shard is determined in the following fashion:
      1. Pick first shard which is below optimum,
      2. If no shard is below optimum, pick the shard closest
          to optimum.
      """
      first_shard_index_below_optimum = None
      shard_index_right_above_optimum = None
      shard_index_right_above_optimum_time = None
      for i, shard in enumerate(shards):
          # Total time the shard needs to run so far
          shard_time = sum(rule.actual_timeout_s for rule in shard)
          # Total time the shard would need to run with the rule_to_add
          shard_time_with_item = (
              shard_time + rule_to_add.actual_timeout_s
          )
  
          if shard_time_with_item < optimum:
              # If there's a shard below optimum, just use that
              first_shard_index_below_optimum = i
              break
          elif (
              shard_index_right_above_optimum is None
              or shard_index_right_above_optimum_time
              > shard_time_with_item
          ):
              # Otherwise, pick the shard closest to optimum
              shard_index_right_above_optimum = i
              shard_index_right_above_optimum_time = (
                  shard_time_with_item
              )
      if first_shard_index_below_optimum is not None:
          best_shard_index = first_shard_index_below_optimum
      else:
          best_shard_index = shard_index_right_above_optimum
  
      shards[best_shard_index].append(rule_to_add)
  
imports: from collections import defaultdict
  from dataclasses import dataclass
  from typing import Iterable, List, Optional, Set, Tuple
  import argparse
  import os
  import re
  import shlex
  import subprocess
  import sys
  import xml.etree.ElementTree
label_desc: Use image node_id 10 for calling a global function with example usage: add_rule_to_best_shard(rule_to_add, shards, optimum) without return types