import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
import javax.swing.border.TitledBorder;
import java.text.*;
import javax.swing.border.*;
import java.util.jar.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.util.TimeZone;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.nio.charset.Charset;
import java.awt.geom.Path2D;
import java.awt.image.DataBufferByte;
import java.nio.file.Files;
import java.nio.file.Path;

class main {

  static public String windowTitle = "Gazelle V 2020-10-28 .09";

  static public String downloadURL = "https://botcompany.de/jar/1033411?withLibs=1&noCompiler=1";

  static public String trayIconImageID = "#1103047";

  static public int borderSize = 5;

  static public Color color1 = awtColor("ADD8E6");

  static public Color color2 = awtColor("EEEEEE");

  static public Color color3 = awtColor("A3C0AA");

  static public IF0<PingSource> ping_v3_pingSourceMaker() {
    return () -> new PingSource();
  }

  static public class Stem {

    public JFrame window;

    public Rect getFrameRect() {
      return toRect(getBounds(window));
    }
  }

  static public Stem stem;

  static public GazelleV gazelle;

  static public TrayIcon trayIcon;

  static public JFrame mainWindow;

  static public Set<String> argsSet;

  static public void trayIconLeftClick() {
    activateFrame_v3(mainWindow);
  }

  static public void makeTrayIcon() {
    try {
      trayIcon_imageAutoSize = false;
      trayIcon = installTrayIcon(trayIconImageID, windowTitle, new Runnable() {

        public void run() {
          try {
            trayIconLeftClick();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "trayIconLeftClick();";
        }
      }, "Show Gazelle", new Runnable() {

        public void run() {
          try {
            activateFrame(mainWindow);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "activateFrame(mainWindow)";
        }
      }, "Exit Gazelle", new Runnable() {

        public void run() {
          try {
            cleanExit();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cleanExit();";
        }
      });
    } catch (Throwable __e) {
      print(exceptionToStringShort(__e));
    }
  }

  public static void main(final String[] args) throws Exception {
    __javax = x30.class;
    loadableUtils.utils.__setJavaX(x30.class);
    vm_generalMap_put("stefansOS", mc());
    __javax = x30.class;
    x30.__javax = x30.class;
    x30_pkg.x30_util.__setJavaX(x30.class);
    x30.cleanKillMsg = "";
    callOnLoadMethods(mc());
    argsSet = asSet(args);
    if (!argsSet.contains("noflatlaf"))
      com.formdev.flatlaf.FlatLightLaf.setup();
    if (contains(args, "profile"))
      profileToConsole(() -> actualMain(args));
    else
      actualMain(args);
    if (argsSet.contains("brexit"))
      System.exit(0);
    AutoCloseable __11 = gazelle.enter();
    try {
      gazelle.start();
    } finally {
      _close(__11);
    }
  }

  static public void actualMain(String... args) {
    System.out.println(hmsWithColonsAndMS() + ": Init");
    if (containsOneOf(argsSet, "upgrade", "update")) {
      upgradeGazelle();
      return;
    }
    makeTrayIcon();
    printWithMS("new GazelleV");
    gazelle = new GazelleV();
    stem = new Stem();
    gazelle._host = stem;
    copyLocalLog(gazelle, mc());
    AutoCloseable __12 = gazelle.enter();
    try {
      printWithMS("Visualize");
      var vis = swing(() -> gazelle.visualize());
      vis = makeWindowBorderAndTitle(vis, windowTitle);
      printWithMS("Show frame");
      JFrame frame = makeUndecoratedFrame(windowTitle, vis);
      setFrameIcon(frame, trayIconImageID);
      stem.window = mainWindow = frame;
      onWindowClosing(stem.window, new Runnable() {

        public void run() {
          try {
            cleanExit();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cleanExit();";
        }
      });
      showWindow(stem.window);
      printWithMS("Dudadoneski");
    } finally {
      _close(__12);
    }
  }

  static public void minimize() {
    if (trayIcon == null)
      minimizeWindow(mainWindow);
    else
      hideWindow(mainWindow);
  }

  static public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
    var icons = jline();
    icons.add(jbutton("Minimize", new Runnable() {

      public void run() {
        try {
          minimize();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "minimize();";
      }
    }));
    icons.add(jbutton("Close", new Runnable() {

      public void run() {
        try {
          disposeWindow(icons);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "disposeWindow(icons)";
      }
    }));
    icons.add(jPopDownButton_noText("Update Gazelle", runnableThread(new Runnable() {

      public void run() {
        try {
          upgradeGazelle();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "upgradeGazelle();";
      }
    }), "Dump threads", runnableThread(new Runnable() {

      public void run() {
        try {
          showText("User threads", renderUserThreadsWithStackTraces());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "showText(\"User threads\", renderUserThreadsWithStackTraces());";
      }
    })));
    var actualTitle = fontSizePlus(7, jCenteredLabel(title));
    var spacer = gazelle_wavySpacer();
    var titleBarMain = setOpaqueBackground(color1, westCenterAndEastWithMargin(jImage_scaledToHeight(24, trayIconImageID), actualTitle, setOpaqueBackground(color2, spacer)));
    installWindowDragger(actualTitle);
    installWindowDragger(spacer);
    var titleBar = setBackground(color2, centerAndEast(titleBarMain, icons));
    var border = BorderFactory.createLineBorder(color1, borderSize);
    var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
    installWindowResizeDraggerOnBorder(outerPanel);
    return outerPanel;
  }

  static public Object dm_getStem(Object moduleOrID) {
    return stem;
  }

  static public Object resolveModule(Object moduleOrID) {
    return moduleOrID == stem ? gazelle : moduleOrID;
  }

  static public void cleanExit() {
    System.exit(0);
  }

  static public void upgradeGazelle() {
    File myJar = getBytecodePathForClass(mc());
    print("myJar", myJar);
    String javaCmd = or2(currentProcessCommand(), "java");
    String date = ymdMinusHMS();
    File f = javaxCodeDir("Downloaded Updates/" + "gazelle-" + date + ".jar");
    infoBox("Downloading Update...");
    loadBinaryPageToFile(downloadURL, f);
    printFileInfo(f);
    if (!isNonEmptySingleZip_byMagicHeader(f)) {
      infoBox("Bad file downloaded... :(");
      return;
    }
    boolean replaced = false;
    if (isFile(myJar)) {
      print("Loaded " + nClasses(loadAllClassesInByteCodePath(myJar)));
      print("Replacing with new version: " + myJar);
      renameFile(myJar, appendToBaseName(myJar, ".bak." + date));
      copyFile(f, myJar);
      printFileInfo(myJar);
      replaced = true;
    }
    infoBox(replaced ? "Installed update, replaced " + f2s(myJar) + " - now starting" : "Starting update, but could not replace originally downloaded jar");
    String cmd = pqO(javaCmd) + " -jar " + pqO(replaced ? myJar : f);
    print(cmd);
    nohup(cmd);
    cleanExit();
  }

  static public class GazelleV extends DynPrintLogAndEnabled {

    static public boolean _switchableField_x1 = true;

    public int x1;

    static public boolean _switchableField_y1 = true;

    public int y1;

    static public boolean _switchableField_w = true;

    public int w = screenWidth();

    static public boolean _switchableField_h = true;

    public int h = screenHeight();

    static public boolean _switchableField_maxFPS = true;

    public double maxFPS = 10;

    static public boolean _switchableField_previewWidth = true;

    public int previewWidth = 200;

    static public boolean _switchableField_statsEvery = true;

    public double statsEvery = 5;

    static public boolean _switchableField_brokenMethod = true;

    volatile public boolean brokenMethod = false;

    public PersistableThrowable lastProcessingError;

    transient public WithTimestamp<OKOrError<BufferedImage>> lastScreen;

    transient public Average screenShotTime = new Average();

    transient public Average iiTime = new Average();

    transient public Timestamp loopStarted;

    transient public RestartableCountdown screenShotCountdown = new RestartableCountdown();

    transient public ImageSurface imageSurface;

    transient public Throwable currentProcessingError;

    transient public BufferedImage previewImage;

    transient public JButton popDownButton;

    transient public JComponent topControls;

    transient public long screenShotsTaken;

    transient public double fps;

    transient public Compression longTermCompression;

    transient public String longTermCompressionProbability;

    transient public String longTermCompressionScore;

    public Rect area() {
      return rect(x1, y1, w, h);
    }

    public class Compression {

      final public Compression setImage(BufferedImage image) {
        return image(image);
      }

      public Compression image(BufferedImage image) {
        this.image = image;
        return this;
      }

      final public BufferedImage getImage() {
        return image();
      }

      public BufferedImage image() {
        return image;
      }

      public BufferedImage image;

      final public Compression setIi(BWIntegralImage ii) {
        return ii(ii);
      }

      public Compression ii(BWIntegralImage ii) {
        this.ii = ii;
        return this;
      }

      final public BWIntegralImage getIi() {
        return ii();
      }

      public BWIntegralImage ii() {
        return ii;
      }

      public BWIntegralImage ii;

      public CompressionSearch_AnyType search;

      public int baseLineLength;

      public GridCodec1 codec;

      public double compressionPercentage;

      public String score() {
        var submission = search == null ? null : search.bestSubmission();
        Integer compressedSize = or(submission.compressedSize(), baseLineLength);
        compressionPercentage = doubleRatio(compressedSize, baseLineLength) * 100;
        return formatDouble(compressionPercentage, 3) + "%";
      }

      public IProbabilisticScheduler scheduler() {
        return search == null ? null : search.scheduler();
      }

      public String probability() {
        var scheduler = scheduler();
        if (scheduler == null)
          return "-";
        var prob = scheduler.lastExecutedProbability();
        return formatDouble(prob, 3);
      }

      public void run() {
        try {
          int lHex = pixelCount(image) * 8;
          baseLineLength = calculateLengthOfFunctionCall("imageFromHex", lHex + 2);
          print("baseLineLength", baseLineLength);
          codec = new GridCodec1(image);
          search = codec.forward();
          startThread("Gazelle Visual", new Runnable() {

            public void run() {
              try {
                for (int _repeat_9 = 0; _repeat_9 < 60; _repeat_9++) {
                  stepForNSeconds(1, search);
                  print("stepCount", search.scheduler().stepCount());
                  setFields("longTermCompressionProbability", probability(), "longTermCompressionScore", score());
                }
                try {
                  List<ICachedJavaXExpr> cellCompressions = codec.strat.codeForElements();
                  String code = str(codec.winnerCode());
                  String name = "Screenshot " + ymdMinusHMS();
                  File f = makeFileNameUnique_beforeExtension(javaxDataDir("Compressed Screenshots/" + name + ".javax"));
                  saveTextFile(f, code);
                  printFileInfo(f);
                  saveGZTextFile(f = replaceExtension(f, ".jgz"), code);
                  printFileInfo(f);
                } catch (Throwable e) {
                  printStackTrace(e);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "for (int _repeat_9 = 0; _repeat_9 < 60; _repeat_9++)  {\r\n          stepForNSe...";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }
    }

    public void start() {
      try {
        super.start();
        startThread("Start", new Runnable() {

          public void run() {
            try {
              AutoCloseable __13 = enter();
              try {
                try {
                  dm_registerAs_direct("gazelleV");
                  dm_watchField("enabled", new Runnable() {

                    public void run() {
                      try {
                        if (enabled)
                          dm_reload();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (enabled) dm_reload();";
                    }
                  });
                  dm_doEvery(1.0, new Runnable() {

                    public void run() {
                      try {
                        if (dm_moduleIsPoppedOut())
                          adjustUIForPoppedOutWindow();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (dm_moduleIsPoppedOut()) adjustUIForPoppedOutWindow();";
                    }
                  });
                  print("Screen bounds: " + allScreenBounds());
                  dm_doEvery(min(statsEvery, 10.0), statsEvery, new Runnable() {

                    public void run() {
                      try {
                        if (enabled)
                          printStats();
                      } catch (Exception __e) {
                        throw rethrow(__e);
                      }
                    }

                    public String toString() {
                      return "if (enabled) printStats();";
                    }
                  });
                  loopStarted = tsNow();
                  shoot();
                } catch (Throwable __e) {
                  printStackTrace(__e);
                }
              } finally {
                _close(__13);
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "AutoCloseable __13 = enter(); try { try {\r\n    dm_registerAs_direct gazelleV(...";
          }
        });
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void shoot() {
      AutoCloseable __14 = enter();
      try {
        if (!enabled)
          return;
        long targetTime = sysNow() + iround(1000 / maxFPS);
        long time = nanoTime();
        try {
          lastScreen = withTimestamp(okOrError(() -> screenshot(area())));
          ++screenShotsTaken;
          setField("fps", doubleRatio(screenShotsTaken, elapsedSeconds(loopStarted)));
          screenShotTime.add(nanosToSeconds(nanoTime() - time));
          if (lastScreen.get().isOK()) {
            time = nanoTime();
            var ii = new BWIntegralImage(lastScreen.get().get());
            iiTime.add(nanosToSeconds(nanoTime() - time));
            if (longTermCompression == null) {
              longTermCompression = new Compression().image(lastScreen.get().get()).ii(ii);
              longTermCompression.run();
            }
            previewImage = brokenMethod ? scaledBufferedImageFromBWIntegralImage(ii, previewWidth) : scaleDownUsingIntegralImageBW(ii, previewWidth).getBufferedImage();
            {
              if (imageSurface != null)
                imageSurface.setImage(previewImage);
            }
            cpuTotal();
          }
          currentProcessingError = null;
        } catch (Throwable e) {
          printStackTrace(e);
          setField("lastProcessingError", currentProcessingError = e);
          sleepSeconds(60);
        }
        screenShotCountdown.setTargetTime(targetTime, new Runnable() {

          public void run() {
            try {
              shoot();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "shoot();";
          }
        });
      } finally {
        _close(__14);
      }
    }

    public void printStats() {
      print(stats());
    }

    public String stats() {
      var screen = lastScreen == null ? null : lastScreen.get();
      return formatColonProperties_noNulls("Monitored area", area(), "Error", screen == null ? null : screen.getError(), "Last screenshot taken", lastScreen == null ? null : lastScreen.timeStamp(), "Average time to take a screenshot", screenShotTime, "Average time to make integral image", iiTime, "Capacity left in first core", percentRatioStrOneDigit(freeInCore()), "Total CPU used", cpuTotal());
    }

    public String cpuTotal() {
      return setFieldAndReturn("cpuTotal", percentRatioStrOneDigit((1 - freeInCore()) / numberOfCores()));
    }

    public double freeInCore() {
      return ratio(toSeconds(screenShotCountdown.totalSleepTime), elapsedSeconds(loopStarted));
    }

    {
    }

    public JComponent visualize() {
      return hsplit(northAndCenterWithMargin(topControls = hgrid(jCenteredSection("FPS", dm_calculatedCenteredLabel(() -> iround(fps))), jCenteredSection("Compression", dm_centeredFieldLabel("longTermCompressionScore")), jCenteredSection("Probability", dm_centeredFieldLabel("longTermCompressionProbability")), jCenteredSection("CPU (" + numberOfCores() + ")", dm_centeredFieldLabel("cpuTotal"))), super.visualize()), jscroll_center(imageSurface = doubleBufferedImageSurface_noAlpha()));
    }

    public BufferedImage lastScreenImage() {
      return getVar(getVar(lastScreen));
    }

    public void adjustUIForPoppedOutWindow() {
      swing(new Runnable() {

        public void run() {
          try {
            if (popDownButton == null) {
              Window window = (Window) (getWindow(dm_vis()));
              var popBackInButton = findButton(window, "Pop Back In");
              var parent = getParent(popBackInButton);
              print("parent", parent);
              removeFromParent(parent);
              popDownButton = jPopDownButton_noText("Pop Back In", new Runnable() {

                public void run() {
                  try {
                    dm_popInModule(me());
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "dm_popInModule(me())";
                }
              }, jCheckBoxMenuItem("Always On Top", isAlwaysOnTop(window), new Runnable() {

                public void run() {
                  try {
                    AutoCloseable __16 = enter();
                    try {
                      dm_toggleAlwaysOnTop();
                    } finally {
                      _close(__16);
                    }
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "temp enter();  dm_toggleAlwaysOnTop();";
                }
              }));
              addControl(popDownButton);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (popDownButton == null) {\r\n      Window window =  (Window) (getWindow(dm_v...";
        }
      });
    }
  }

  static public boolean _moduleClass_GazelleV = true;

  static public String programID;

  static public void _onLoad_initUtils() {
    utils.__javax = javax();
  }

  static public void _onLoad_defaultClassFinder() {
    setDefaultClassFinder(new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("main$"))
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
        return null;
      }
    });
  }

  static public ThreadLocal<Boolean> dynamicObjectIsLoading_threadLocal() {
    return DynamicObject_loading;
  }

  static volatile public Concepts mainConcepts;

  static public Concepts db_mainConcepts() {
    if (mainConcepts == null)
      mainConcepts = newConceptsWithClassFinder(getDBProgramID());
    return mainConcepts;
  }

  static public void cleanMeUp_concepts() {
    if (db_mainConcepts() != null)
      db_mainConcepts().cleanMeUp();
  }

  static public java.awt.Color awtColor(String hex) {
    byte[] b = bytesFromHex(dropPrefix("#", hex));
    return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
  }

  static public Rect toRect(Rectangle r) {
    return r == null ? null : new Rect(r);
  }

  static public Rect toRect(RectangularShape r) {
    return r == null ? null : toRect(r.getBounds());
  }

  static public Rect toRect(DoubleRect r) {
    if (r == null)
      return null;
    int x = iround(r.x), y = iround(r.y);
    return new Rect(x, y, iround(r.x2()) - x, iround(r.y2()) - y);
  }

  static public Rect toRect(Rect r) {
    return r;
  }

  static public Rectangle getBounds(final Component c) {
    return c == null ? null : swing(new F0<Rectangle>() {

      public Rectangle get() {
        try {
          return c.getBounds();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getBounds();";
      }
    });
  }

  static public int activateFrame_v3_delay = 100;

  static public boolean activateFrame_v3(Component c, Object... __) {
    return swing(() -> {
      Frame f = getAWTFrame(c);
      if (f == null)
        return false;
      if (!f.isVisible())
        f.setVisible(true);
      int state = f.getState();
      boolean iconified = state == Frame.ICONIFIED;
      boolean maximize = boolPar("maximize", __);
      if (iconified)
        f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);
      else {
        f.setState(Frame.ICONIFIED);
        print("Restoring frame in " + activateFrame_v3_delay + " ms");
        doLater(activateFrame_v3_delay, new Runnable() {

          public void run() {
            try {
              f.setState(state);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "f.setState(state)";
          }
        });
      }
      f.toFront();
      return true;
    });
  }

  static public boolean trayIcon_imageAutoSize = true;

  static public TrayIcon installTrayIcon(String imageID, String tooltip) {
    return installTrayIcon(imageID, tooltip, null);
  }

  static public TrayIcon installTrayIcon(String imageID, String tooltip, Object... menuItems) {
    try {
      if (!isSnippetID(imageID) && isSnippetID(tooltip)) {
        String s = tooltip;
        tooltip = imageID;
        imageID = s;
      }
      Image image = loadImage2(imageID);
      return installTrayIcon(image, tooltip, menuItems);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public TrayIcon installTrayIcon(final Image image, final String tooltip, final Object... _menuItems) {
    try {
      return swing(new F0<TrayIcon>() {

        public TrayIcon get() {
          try {
            Runnable leftClick = null;
            Object[] menuItems = params_unpackList(_menuItems);
            if (l(menuItems) > 0 && menuItems[0] instanceof Runnable) {
              leftClick = (Runnable) menuItems[0];
              menuItems = dropFirst(menuItems);
            }
            PopupMenu menu = makePopupMenu(menuItems);
            TrayIcon trayIcon = new TrayIcon(image, tooltip, menu);
            trayIcon.setImageAutoSize(trayIcon_imageAutoSize);
            if (leftClick != null) {
              final Runnable _leftClick = leftClick;
              onLeftClick(trayIcon, _leftClick);
            }
            SystemTray.getSystemTray().add(trayIcon);
            return trayIcon;
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Runnable leftClick = null;\r\n    O[] menuItems = params_unpackList(_menuItems)...";
        }
      });
    } catch (Throwable __e) {
      return null;
    }
  }

  static public boolean activateFrame(final Component c, Object... __) {
    return swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          Frame f = getAWTFrame(c);
          if (f == null)
            return false;
          if (!f.isVisible())
            f.setVisible(true);
          boolean windowsHack = optPar("windowsHack", __, true);
          boolean iconified = f.getState() == Frame.ICONIFIED;
          boolean maximize = boolPar("maximize", __);
          if (iconified)
            f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);
          if (windowsHack && !iconified && isWindows()) {
            boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
            f.setExtendedState(JFrame.ICONIFIED);
            f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
          }
          f.toFront();
          return true;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Frame f = getAWTFrame(c);\r\n    if (f == null) false;\r\n    if (!f.isVisible())...";
      }
    });
  }

  static volatile public NotifyingStringBuffer local_log = new NotifyingStringBuffer();

  static public void _onLoad_print() {
    print_autoRotate();
  }

  static volatile public Appendable print_log = local_log;

  static volatile public int print_log_max = 1024 * 1024;

  static volatile public int local_log_max = 100 * 1024;

  static public boolean print_silent = false;

  static public Object print_byThread_lock = new Object();

  static volatile public ThreadLocal<Object> print_byThread;

  static volatile public Object print_allThreads;

  static volatile public Object print_preprocess;

  static public void print() {
    print("");
  }

  static public <A> A print(String s, A o) {
    print(combinePrintParameters(s, o));
    return o;
  }

  static public <A> A print(A o) {
    ping_okInCleanUp();
    if (print_silent)
      return o;
    String s = o + "\n";
    print_noNewLine(s);
    return o;
  }

  static public void print_noNewLine(String s) {
    try {
      Object f = getThreadLocal(print_byThread_dontCreate());
      if (f == null)
        f = print_allThreads;
      if (f != null)
        if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
          return;
    } catch (Throwable e) {
      System.out.println(getStackTrace(e));
    }
    print_raw(s);
  }

  static public void print_raw(String s) {
    if (print_preprocess != null)
      s = (String) callF(print_preprocess, s);
    s = fixNewLines(s);
    Appendable loc = local_log;
    Appendable buf = print_log;
    int loc_max = print_log_max;
    if (buf != loc && buf != null) {
      print_append(buf, s, print_log_max);
      loc_max = local_log_max;
    }
    if (loc != null)
      print_append(loc, s, loc_max);
    System.out.print(s);
    vmBus_send("printed", mc(), s);
  }

  static public void print_autoRotate() {
    makeNotifyingStringBufferRotate(local_log, () -> local_log_max);
  }

  static public String exceptionToStringShort(Throwable e) {
    lastException(e);
    e = getInnerException(e);
    String msg = hideCredentials(unnull(e.getMessage()));
    if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
      return baseClassName(e) + prependIfNempty(": ", msg);
    else
      return msg;
  }

  static public Object vm_generalMap_put(Object key, Object value) {
    return mapPutOrRemove(vm_generalMap(), key, value);
  }

  static public Class mc() {
    return main.class;
  }

  static public void callOnLoadMethods(Class c) {
    for (String name : methodsStartingWith(c, "_onLoad_")) pcallOpt(c, name);
    pcallOpt(c, "_onLoad");
  }

  static public Set asSet(Object[] array) {
    HashSet set = new HashSet();
    for (Object o : array) if (o != null)
      set.add(o);
    return set;
  }

  static public Set<String> asSet(String[] array) {
    TreeSet<String> set = new TreeSet();
    for (String o : array) if (o != null)
      set.add(o);
    return set;
  }

  static public <A> Set<A> asSet(Iterable<A> l) {
    if (l instanceof Set)
      return (Set) l;
    HashSet<A> set = new HashSet();
    for (A o : unnull(l)) if (o != null)
      set.add(o);
    return set;
  }

  static public <A> Set<A> asSet(MultiSet<A> ms) {
    return ms == null ? null : ms.asSet();
  }

  static public boolean contains(Collection c, Object o) {
    return c != null && c.contains(o);
  }

  static public boolean contains(Iterable it, Object a) {
    if (it != null)
      for (Object o : it) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(Object[] x, Object o) {
    if (x != null)
      for (Object a : x) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(String s, char c) {
    return s != null && s.indexOf(c) >= 0;
  }

  static public boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static public boolean contains(BitSet bs, int i) {
    return bs != null && bs.get(i);
  }

  static public <A> boolean contains(Producer<A> p, A a) {
    if (p != null && a != null)
      while (true) {
        A x = p.next();
        if (x == null)
          break;
        if (eq(x, a))
          return true;
      }
    return false;
  }

  static public void profileToConsole(Runnable r) {
    poorMansProfileToConsole(r);
  }

  static public <A> A profileToConsole(IF0<A> r) {
    if (r == null)
      return null;
    Var<A> var = new Var();
    poorMansProfileToConsole(new Runnable() {

      public void run() {
        try {
          var.set(r.get());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "var.set(r!)";
      }
    });
    return var.get();
  }

  static public void _close(AutoCloseable c) {
    if (c != null)
      try {
        c.close();
      } catch (Throwable e) {
        if (c instanceof javax.imageio.stream.ImageOutputStream)
          return;
        else
          throw rethrow(e);
      }
  }

  static public String hmsWithColonsAndMS() {
    return hmsWithColonsAndMS(now());
  }

  static public String hmsWithColonsAndMS(long time) {
    return simpleDateFormat_local("HH:mm:ss:SSSS").format(time);
  }

  static public <A> boolean containsOneOf(Collection<A> l, A... x) {
    if (l instanceof Set) {
      if (x != null)
        for (A a : x) if (l.contains(a))
          return true;
    } else {
      for (A a : unnull(l)) if (eqOneOf(a, x))
        return true;
    }
    return false;
  }

  static public <A> boolean containsOneOf(Collection<A> l, Set<A> set) {
    if (set == null)
      return false;
    for (A a : unnull(l)) if (set.contains(a))
      return true;
    return false;
  }

  static public boolean containsOneOf(String s, String... x) {
    for (String o : x) if (contains(s, o))
      return true;
    return false;
  }

  static public void printWithMS(String s) {
    printWithMSTime(s);
  }

  static public void copyLocalLog(Object src, Object dest) {
    Object log = getOpt(src, "local_log");
    if (log != null)
      setOpt(dest, "local_log", local_log);
  }

  static public Object swing(Object f) {
    return swingAndWait(f);
  }

  static public <A> A swing(F0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A> A swing(IF0<A> f) {
    return (A) swingAndWait(f);
  }

  static public JFrame makeUndecoratedFrame(String title, Object content) {
    return swing(() -> {
      JFrame frame = new JFrame(title);
      frame.setUndecorated(true);
      Component wrapped = wrap(content);
      if (wrapped != null)
        frame.getContentPane().add(wrapped);
      frame.setBounds(defaultNewFrameBounds());
      return frame;
    });
  }

  static public <A extends Component> A setFrameIcon(A c, String imageID) {
    setFrameIconLater(c, imageID);
    return c;
  }

  static public <A extends Component> A setFrameIcon(String imageID, A c) {
    return setFrameIcon(c, imageID);
  }

  static public <A extends Window> A onWindowClosing(final A w, final Object r) {
    if (w != null) {
      swing(new Runnable() {

        public void run() {
          try {
            w.addWindowListener(new WindowAdapter() {

              public void windowClosing(WindowEvent e) {
                AutoCloseable __1 = tempRememberListener(w, "removeWindowListener", this);
                try {
                  pcallF(r);
                } finally {
                  _close(__1);
                }
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "w.addWindowListener(new WindowAdapter {\r\n      public void windowClosing(Wind...";
        }
      });
    }
    return w;
  }

  static public <A extends Window> A showWindow(A w) {
    if (w != null) {
      swing(new Runnable() {

        public void run() {
          try {
            w.setVisible(true);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "w.setVisible(true);";
        }
      });
    }
    return w;
  }

  static public void minimizeWindow(JFrame f) {
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            f.setState(JFrame.ICONIFIED);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "f.setState(JFrame.ICONIFIED);";
        }
      });
    }
  }

  static public void hideWindow(final Component c) {
    final Window w = getWindow(c);
    if (w != null) {
      swing(new Runnable() {

        public void run() {
          try {
            w.setVisible(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "w.setVisible(false);";
        }
      });
    }
  }

  static public JPanel jline(final Component... components) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          return new LeftAlignedLine(components);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new LeftAlignedLine(components);";
      }
    });
  }

  static public <A extends Component> JPanel jline(List<A> components) {
    return jline(asArray(Component.class, components));
  }

  static public JButton jbutton(String text, Object action) {
    return newButton(text, action);
  }

  static public JButton jbutton(String text) {
    return newButton(text, null);
  }

  static public JButton jbutton(Action action) {
    return swingNu(JButton.class, action);
  }

  static public void disposeWindow(final Window window) {
    if (window != null) {
      swing(new Runnable() {

        public void run() {
          try {
            window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
            myFrames_list.remove(window);
            window.dispose();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //...";
        }
      });
    }
  }

  static public void disposeWindow(final Component c) {
    disposeWindow(getWindow(c));
  }

  static public void disposeWindow(Object o) {
    if (o != null)
      disposeWindow(((Component) o));
  }

  static public void disposeWindow() {
    disposeWindow(heldInstance(Component.class));
  }

  static public JButton jPopDownButton_noText(final Object... menuParams) {
    return toolTip("Additional commands", jPopDownButton("", menuParams));
  }

  static public Runnable runnableThread(final Runnable r) {
    return new Runnable() {

      public void run() {
        try {
          startThread(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "startThread(r)";
      }
    };
  }

  static public JTextArea showText(final String title, Object text) {
    return showText(null, title, text);
  }

  static public JTextArea showText(JTextArea ta, final String title, Object text) {
    final String _text = str(text);
    if (ta != null)
      return activateFrameAndReturnComponent(setFrameTitle(title, setText(ta, _text)));
    return swing(new F0<JTextArea>() {

      public JTextArea get() {
        try {
          JTextArea textArea = newTypeWriterTextArea(_text);
          makeFrame(title, new JScrollPane(textArea));
          return textArea;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JTextArea textArea = newTypeWriterTextArea(_text);\r\n    makeFrame(title, new ...";
      }
    });
  }

  static public JTextArea showText(Object text) {
    return showText(str(text));
  }

  static public JTextArea showText(String text) {
    return showText(autoFrameTitle(), text);
  }

  static public JTextArea showText() {
    return showText("");
  }

  static public String renderUserThreadsWithStackTraces() {
    return renderUserThreadsWithStackTraces(Thread.getAllStackTraces());
  }

  static public String renderUserThreadsWithStackTraces(Map<Thread, StackTraceElement[]> threadMap) {
    return renderUserThreadsWithStackTraces(threadMap, "user thread");
  }

  static public String renderUserThreadsWithStackTraces(Map<Thread, StackTraceElement[]> threadMap, String threadDescription) {
    StringBuilder buf = new StringBuilder();
    int n = 0;
    for (Thread t : threadMap.keySet()) {
      ThreadGroup g = t.getThreadGroup();
      if (g != null && g.getName().equals("system"))
        continue;
      ++n;
      printTo(buf, t);
      for (StackTraceElement e : threadMap.get(t)) {
        printTo(buf, "  " + e);
      }
      printTo(buf);
    }
    printTo(buf, n(n, threadDescription) + ".");
    return asciiHeading2(n(n, threadDescription) + " (+" + (l(threadMap) - n) + ")") + "\n" + buf;
  }

  static public <A extends JComponent> A fontSizePlus(final int delta, final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            Font font = c.getFont();
            c.setFont(font.deriveFont(font.getSize2D() + delta));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Font font = c.getFont();\r\n    c.setFont(font.deriveFont(font.getSize2D()+delt...";
        }
      });
    }
    return c;
  }

  static public JLabel jCenteredLabel(String text) {
    return jcenteredLabel(text);
  }

  static public JLabel jCenteredLabel() {
    return jcenteredLabel();
  }

  static public JComponent gazelle_wavySpacer() {
    return jMinWidth(30, swing(() -> new JComponent() {

      public void paintComponent(Graphics g) {
        int w = getWidth(), h = getHeight();
        var points = graphAsPolygon(x -> 1 - sineSigmoid(x), w, h);
        fillRect(((Graphics2D) g), 0, 0, w, h, gazelle_color2());
        fillPrecisePolygon(((Graphics2D) g), points, gazelle_color1());
      }
    }));
  }

  static public <A extends JComponent> A setOpaqueBackground(final Color color, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setBackground(color);
            a.setOpaque(true);
            a.putClientProperty("substancelaf.colorizationFactor", 1.0);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setBackground(color);\r\n    a.setOpaque(true);\r\n    a.putClientProperty(\"sub...";
        }
      });
    }
    return a;
  }

  static public JPanel westCenterAndEastWithMargin(Component w, Component c, Component e) {
    return westCenterAndEast(w, withLeftAndRightMargin(c), e);
  }

  static public JLabel jImage_scaledToHeight(String imageID, int height) {
    return jImage(resizeImageToHeight_bilinear(loadImage2(imageID), height));
  }

  static public JLabel jImage_scaledToHeight(int height, String imageID) {
    return jImage_scaledToHeight(imageID, height);
  }

  static public void installWindowDragger(JComponent c) {
    onMouseDown(c, event -> new WindowDragger(event));
  }

  static public <A extends JComponent> A setBackground(final Color color, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setBackground(color);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setBackground(color);";
        }
      });
    }
    return a;
  }

  static public <A extends JComponent> A setBackground(A a, Color color) {
    return setBackground(color, a);
  }

  static public JPanel centerAndEast(final Component c, final Component e) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          panel.add(BorderLayout.EAST, wrap(e));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public JPanel withBorder(final Border border, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(border);
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(border);\r\n    p.add...";
      }
    });
  }

  static public JPanel northAndCenter(Component n, Component c) {
    return centerAndNorth(c, n);
  }

  static public void installWindowResizeDraggerOnBorder(JComponent c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            new WindowResizeDragger(c);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "new WindowResizeDragger(c);";
        }
      });
    }
  }

  static public File getBytecodePathForClass(Class c) {
    try {
      return c == null ? null : new File(c.getProtectionDomain().getCodeSource().getLocation().toURI());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String or2(String a, String b) {
    return nempty(a) ? a : b;
  }

  static public String or2(String a, String b, String c) {
    return or2(or2(a, b), c);
  }

  static public String currentProcessCommand() {
    ProcessHandle processHandle = ProcessHandle.current();
    return getVar(processHandle.info().command());
  }

  static public String ymdMinusHMS() {
    return ymd_minus_hms();
  }

  static public File javaxCodeDir_dir;

  static public File javaxCodeDir() {
    return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code");
  }

  static public File javaxCodeDir(String sub) {
    return newFile(javaxCodeDir(), sub);
  }

  static public JWindow infoBox(String text) {
    return infoMessage(text);
  }

  static public JWindow infoBox(String text, double seconds) {
    return infoMessage(text, seconds);
  }

  static public JWindow infoBox(Throwable e) {
    return infoMessage(e);
  }

  static public void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile(URLConnection con, File file) {
    try {
      setHeaders(con);
      loadBinaryPageToFile_noHeaders(con, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
    try {
      File ftemp = new File(f2s(file) + "_temp");
      FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
      try {
        InputStream inputStream = con.getInputStream();
        long len = 0;
        try {
          len = con.getContentLength();
        } catch (Throwable e) {
          printStackTrace(e);
        }
        String pat = "  {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
        copyStreamWithPrints(inputStream, buf, pat);
        inputStream.close();
        buf.close();
        file.delete();
        renameFile_assertTrue(ftemp, file);
      } finally {
        if (buf != null)
          buf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File printFileInfo(File f) {
    return printFileInfo("", f);
  }

  static public File printFileInfo(String s, File f) {
    print(s, renderFileInfo(f));
    return f;
  }

  static public byte[] header = bytesFromHex("504B0304");

  static public boolean isNonEmptySingleZip_byMagicHeader(byte[] data) {
    return byteArrayStartsWith(data, header);
  }

  static public boolean isNonEmptySingleZip_byMagicHeader(File f) {
    return isNonEmptySingleZip_byMagicHeader(loadBeginningOfBinaryFile(f, l(header)));
  }

  static public boolean isFile(File f) {
    return f != null && f.isFile();
  }

  static public boolean isFile(String path) {
    return isFile(newFile(path));
  }

  static public String nClasses(long n) {
    return n2(n, "class", "classes");
  }

  static public String nClasses(Collection l) {
    return nClasses(l(l));
  }

  static public String nClasses(Map map) {
    return nClasses(l(map));
  }

  static public int loadAllClassesInByteCodePath(File path) {
    int n = 0;
    for (String name : allClassNamesOnPath(ll(path))) try {
      Class.forName(name);
      ++n;
    } catch (Throwable __e) {
      print(exceptionToStringShort(__e));
    }
    return n;
  }

  static public boolean renameFile(File a, File b) {
    mkdirsForFile(b);
    return a.renameTo(b);
  }

  static public boolean renameFile(File a, String newName) {
    return renameFile(a, fileInSameDir(a, newName));
  }

  static public File appendToBaseName(File f, String s) {
    return appendToFileNameBeforeExtension(f, s);
  }

  static public File copyFile(File src, File dest) {
    try {
      FileInputStream inputStream = new FileInputStream(src.getPath());
      FileOutputStream outputStream = newFileOutputStream(dest.getPath());
      try {
        copyStream(inputStream, outputStream);
        inputStream.close();
      } finally {
        outputStream.close();
      }
      return dest;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String f2s(File f) {
    return f == null ? null : f.getAbsolutePath();
  }

  static public String f2s(String s) {
    return f2s(newFile(s));
  }

  static public String f2s(java.nio.file.Path p) {
    return p == null ? null : f2s(p.toFile());
  }

  static public String pqO(String s) {
    return platformQuoteOpt(s);
  }

  static public String pqO(File f) {
    return platformQuoteOpt(f);
  }

  static public boolean nohup_debug = false;

  static public boolean nohup_noSlashB = false;

  static public ThreadLocal<Integer> nohup_exitValue = new ThreadLocal();

  public static File nohup(String cmd) {
    try {
      File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd) + "_", ".out");
      nohup(cmd, outFile, false);
      return outFile;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static void nohup(String cmd, File outFile, boolean append) {
    try {
      String command = nohup_makeNohupCommand(cmd, outFile, append);
      File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : "");
      System.out.println("[Nohup] " + command);
      try {
        if (nohup_debug)
          print("[nohup] Script file: " + scriptFile.getPath());
        saveTextFile(scriptFile.getPath(), command);
        String[] command2;
        if (isWindows())
          if (nohup_noSlashB)
            command2 = new String[] { "cmd", "/c", "start", scriptFile.getPath() };
          else
            command2 = new String[] { "cmd", "/c", "start", "/b", scriptFile.getPath() };
        else
          command2 = new String[] { "/bin/bash", scriptFile.getPath() };
        printStruct("[nohup] ", command2);
        Process process = Runtime.getRuntime().exec(command2);
        try {
          process.waitFor();
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
        int value = process.exitValue();
        nohup_exitValue.set(value);
        if (value != 0)
          warn("nohup exit value != 0: " + value);
      } finally {
        if (!isWindows())
          scriptFile.delete();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) {
    mkdirsForFile(outFile);
    String command;
    if (isWindows())
      command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1";
    else
      command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &";
    return command;
  }

  static public int screenWidth() {
    return getScreenWidth();
  }

  static public int screenHeight() {
    return getScreenHeight();
  }

  static public int area(Rect r) {
    return rectArea(r);
  }

  static public double area(DoubleRect r) {
    return r == null ? 0 : r.w * r.h;
  }

  static public Rect rect(int x, int y, int w, int h) {
    return new Rect(x, y, w, h);
  }

  static public Rect rect(Pt p, int w, int h) {
    return new Rect(p.x, p.y, w, h);
  }

  static public Rect rect(int w, int h) {
    return new Rect(0, 0, w, h);
  }

  static public JLabel setImage(final BufferedImage img, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(img));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(img));";
        }
      });
    }
    return lbl;
  }

  static public JLabel setImage(JLabel lbl, BufferedImage img) {
    return setImage(img, lbl);
  }

  static public JLabel setImage(final String imageID, final JLabel lbl) {
    if (lbl != null) {
      swing(new Runnable() {

        public void run() {
          try {
            lbl.setIcon(imageIcon(imageID));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lbl.setIcon(imageIcon(imageID));";
        }
      });
    }
    return lbl;
  }

  static public JLabel setImage(JLabel lbl, String imageID) {
    return setImage(imageID, lbl);
  }

  static public <A> A or(A a, A b) {
    return a != null ? a : b;
  }

  static public double doubleRatio(double x, double y) {
    return y == 0 ? 0 : x / y;
  }

  static public double doubleRatio(Seconds x, Seconds y) {
    return doubleRatio(x.get(), y.get());
  }

  static public String formatDouble(double d, int digits) {
    String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
    return decimalFormatEnglish(format, d);
  }

  static public String formatDouble(double d) {
    return str(d);
  }

  static public String formatDouble(DoubleRange r, int digits) {
    return r == null ? "null" : "[" + formatDouble(r.start, digits) + ";" + formatDouble(r.end, digits) + "]";
  }

  static public int pixelCount(BufferedImage img) {
    return img == null ? 0 : img.getWidth() * img.getHeight();
  }

  static public int calculateLengthOfFunctionCall(String fname, int... argLengths) {
    return l(fname) + 2 + intSum(argLengths);
  }

  static public BufferedImage imageFromHex(int w, int h, String pixelsAsHex) {
    return intArrayToBufferedImage(hexToInts_dropSpaces(pixelsAsHex), w, h);
  }

  static public Thread startThread(Object runnable) {
    return startThread(defaultThreadName(), runnable);
  }

  static public Thread startThread(String name, Runnable runnable) {
    runnable = wrapAsActivity(runnable);
    return startThread(newThread(runnable, name));
  }

  static public Thread startThread(String name, Object runnable) {
    runnable = wrapAsActivity(runnable);
    return startThread(newThread(toRunnable(runnable), name));
  }

  static public Thread startThread(Thread t) {
    _registerThread(t);
    t.start();
    return t;
  }

  static public void stepForNSeconds(double timeout, Steppable s) {
    stepAllWithTimeout(timeout, s);
  }

  static public float score(Scored s) {
    return s == null ? 0 : s.score();
  }

  static public String str(Object o) {
    return o == null ? "null" : o.toString();
  }

  static public String str(char[] c) {
    return new String(c);
  }

  static public File makeFileNameUnique_beforeExtension(File f) {
    File orig = f;
    int n = 0;
    while (f.exists()) f = appendToFileBaseName(orig, "." + ++n);
    return f;
  }

  static public File javaxDataDir_dir;

  static public File javaxDataDir() {
    return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
  }

  static public File javaxDataDir(String... subs) {
    return newFile(javaxDataDir(), subs);
  }

  static public File saveTextFile(String fileName, String contents) throws IOException {
    CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
    try {
      File file = new File(fileName);
      mkdirsForFile(file);
      String tempFileName = fileName + "_temp";
      File tempFile = new File(tempFileName);
      if (contents != null) {
        if (tempFile.exists())
          try {
            String saveName = tempFileName + ".saved." + now();
            copyFile(tempFile, new File(saveName));
          } catch (Throwable e) {
            printStackTrace(e);
          }
        FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
      }
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (contents != null)
        if (!tempFile.renameTo(file))
          throw new IOException("Can't rename " + tempFile + " to " + file);
      vmBus_send("wroteFile", file);
      return file;
    } finally {
      action.done();
    }
  }

  static public File saveTextFile(File fileName, String contents) {
    try {
      saveTextFile(fileName.getPath(), contents);
      return fileName;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void saveGZTextFile(File file, String contents) {
    saveGZTextFile(file, contents, "UTF-8");
  }

  static public void saveGZTextFile(File file, String contents, String encoding) {
    try {
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = file.getPath() + "_temp";
      File tempFile = new File(tempFileName);
      if (contents != null) {
        if (tempFile.exists())
          try {
            String saveName = tempFileName + ".saved." + now();
            copyFile(tempFile, new File(saveName));
          } catch (Throwable e) {
            printStackTrace(e);
          }
        FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
        GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, encoding);
        PrintWriter printWriter = new PrintWriter(outputStreamWriter);
        printWriter.print(contents);
        printWriter.close();
        gos.close();
        fileOutputStream.close();
      }
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + file.getPath());
      if (contents != null)
        if (!tempFile.renameTo(file))
          throw new IOException("Can't rename " + tempFile + " to " + file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File replaceExtension(File f, String extOld, String extNew) {
    return newFile(replaceExtension(f2s(f), extOld, extNew));
  }

  static public File replaceExtension(File f, String extNew) {
    return replaceExtension(f, fileExtension(f), extNew);
  }

  static public String replaceExtension(String s, String extOld, String extNew) {
    s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
    return s + addPrefixOptIfNempty(".", extNew);
  }

  static public String replaceExtension(String name, String extNew) {
    return replaceExtension(name, fileExtension(name), extNew);
  }

  static public <A extends Throwable> A printStackTrace(A e) {
    if (e != null)
      print(getStackTrace(e));
    return e;
  }

  static public void printStackTrace() {
    printStackTrace(new Throwable());
  }

  static public void printStackTrace(String msg) {
    printStackTrace(new Throwable(msg));
  }

  static public void printStackTrace(String msg, Throwable e) {
    printStackTrace(new Throwable(msg, e));
  }

  static public AutoCloseable dm_registerAs_direct(String... msgs) {
    return dm_registerAs_directLink(msgs);
  }

  static public void dm_watchField(String field, Runnable onChange) {
    new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
  }

  static public void dm_reload() {
    dm_reloadMe();
  }

  static public FixedRateTimer dm_doEvery(long delay, Runnable r) {
    return dm_ownTimer(doEvery(delay, delay, dm_rEnter(r)));
  }

  static public FixedRateTimer dm_doEvery(long delay, long firstDelay, Runnable r) {
    return dm_ownTimer(doEvery(delay, firstDelay, dm_rEnter(r)));
  }

  static public FixedRateTimer dm_doEvery(double initialSeconds, double delaySeconds, Runnable r) {
    return dm_ownTimer(doEvery(initialSeconds, delaySeconds, dm_rEnter(r)));
  }

  static public FixedRateTimer dm_doEvery(double delaySeconds, Runnable r) {
    return dm_ownTimer(doEvery(delaySeconds, dm_rEnter(r)));
  }

  static public boolean dm_moduleIsPoppedOut() {
    return dm_moduleIsPoppedOut(dm_current_mandatory_generic());
  }

  static public boolean dm_moduleIsPoppedOut(Object mod) {
    return isTrue(dm_callOSOpt("stefansOS_moduleIsPoppedOut", dm_getStem(mod)));
  }

  static public List<Rect> allScreenBounds() {
    return map(__37 -> screenBounds(__37), screenDevices());
  }

  static public int min(int a, int b) {
    return Math.min(a, b);
  }

  static public long min(long a, long b) {
    return Math.min(a, b);
  }

  static public float min(float a, float b) {
    return Math.min(a, b);
  }

  static public float min(float a, float b, float c) {
    return min(min(a, b), c);
  }

  static public double min(double a, double b) {
    return Math.min(a, b);
  }

  static public double min(double[] c) {
    double x = Double.MAX_VALUE;
    for (double d : c) x = Math.min(x, d);
    return x;
  }

  static public float min(float[] c) {
    float x = Float.MAX_VALUE;
    for (float d : c) x = Math.min(x, d);
    return x;
  }

  static public byte min(byte[] c) {
    byte x = 127;
    for (byte d : c) if (d < x)
      x = d;
    return x;
  }

  static public short min(short[] c) {
    short x = 0x7FFF;
    for (short d : c) if (d < x)
      x = d;
    return x;
  }

  static public int min(int[] c) {
    int x = Integer.MAX_VALUE;
    for (int d : c) if (d < x)
      x = d;
    return x;
  }

  static public Timestamp tsNow() {
    return new Timestamp();
  }

  static public long sysNow() {
    ping();
    return System.nanoTime() / 1000000;
  }

  static public int iround(double d) {
    return (int) Math.round(d);
  }

  static public int iround(Number n) {
    return iround(toDouble(n));
  }

  static public long nanoTime() {
    return System.nanoTime();
  }

  static public <A> WithTimestamp<A> withTimestamp(A value) {
    return withTimestamp(now(), value);
  }

  static public <A> WithTimestamp<A> withTimestamp(long timestamp, A value) {
    return new WithTimestamp(timestamp, value);
  }

  static public <A> OKOrError<A> okOrError(IF0<A> f) {
    try {
      return OKOrError_ok(f.get());
    } catch (Throwable e) {
      printStackTrace(e);
      return OKOrError_error(e);
    }
  }

  static public <A> OKOrError<A> okOrError(Runnable r) {
    return okOrError(runnableToIF0(r));
  }

  static public BufferedImage screenshot() {
    return shootScreen2();
  }

  static public BufferedImage screenshot(Rectangle area) {
    try {
      return shootScreen2(area);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage screenshot(Rect area) {
    return shootScreen2(area);
  }

  static public BufferedImage screenshot(int x, int y, int w, int h) {
    return shootScreen2(x, y, w, h);
  }

  static public double elapsedSeconds(long time) {
    return toSeconds(sysNow() - time);
  }

  static public double elapsedSeconds(Timestamp ts) {
    return ts == null ? Double.NaN : toSeconds(now() - ts.date);
  }

  static public double nanosToSeconds(double nanos) {
    return nanoSecondsToSeconds(nanos);
  }

  static public BufferedImage scaledBufferedImageFromBWIntegralImage(int w, BWIntegralImage img) {
    return scaledBufferedImageFromBWIntegralImage(img, w);
  }

  static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w) {
    return scaledBufferedImageFromBWIntegralImage(img, w, heightForWidth(img.w, img.h, w));
  }

  static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w, int h) {
    int w1 = img.w, h1 = img.h;
    int[] pixels = new int[w * h];
    int i = 0;
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
      int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w);
      int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h);
      int pixel = iround(img.getPixelAverage(x1, y1, x2, y2));
      pixels[i++] = brightnessToRGBA(pixel);
    }
    return bufferedImage(w, h, pixels);
  }

  static public BWImage scaleDownUsingIntegralImageBW(int w, BWIntegralImage img) {
    return scaleDownUsingIntegralImageBW(img, w);
  }

  static public BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w) {
    return scaleDownUsingIntegralImageBW(img, w, iround(w * img.h / (double) img.w));
  }

  static public BWImage scaleDownUsingIntegralImageBW(BWIntegralImage img, int w, int h) {
    int w1 = img.w, h1 = img.h;
    BWImage out = new BWImage(w, h);
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
      int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w);
      int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h);
      int area = (x2 - x1) * (y2 - y1);
      int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2) / area;
      out.setByte(x, y, (byte) pixel);
    }
    return out;
  }

  static public BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w) {
    return scaleDownUsingIntegralImageBW(img, w, iround(w * img.getHeight() / (double) img.getWidth()));
  }

  static public BWImage scaleDownUsingIntegralImageBW(IBWIntegralImage img, int w, int h) {
    int w1 = img.getWidth(), h1 = img.getHeight();
    BWImage out = new BWImage(w, h);
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
      int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w);
      int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h);
      int area = (x2 - x1) * (y2 - y1);
      int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2) / area;
      out.setByte(x, y, (byte) pixel);
    }
    return out;
  }

  static public void sleepSeconds(double s) {
    if (s > 0)
      sleep(round(s * 1000));
  }

  static public <A, B> String formatColonProperties_noNulls(Object... params) {
    return formatColonProperties(nonNullPairs(paramsToPairs(params)));
  }

  static public String percentRatioStrOneDigit(double x) {
    return percentRatioStrOneDigit(x, 1);
  }

  static public String percentRatioStrOneDigit(double x, double y) {
    return formatDouble1(doublePercentRatio(x, y)) + " %";
  }

  static volatile public int numberOfCores_value;

  static public int numberOfCores() {
    if (numberOfCores_value == 0)
      numberOfCores_value = Runtime.getRuntime().availableProcessors();
    return numberOfCores_value;
  }

  static public long ratio(long x, long y) {
    return y == 0 ? 0 : x / y;
  }

  static public double ratio(double x, double y) {
    return y == 0 ? 0 : x / y;
  }

  static public double toSeconds(long ms) {
    return ms / 1000.0;
  }

  static public String toSeconds(long ms, int digits) {
    return formatDouble(toSeconds(ms), digits);
  }

  static public double toSeconds(double ms) {
    return ms / 1000.0;
  }

  static public String toSeconds(double ms, int digits) {
    return formatDouble(toSeconds(ms), digits);
  }

  static public JSplitPane hsplit(Component l, Component r) {
    return jhsplit(l, r);
  }

  static public JSplitPane hsplit(Component l, Component r, double splitPoint, int delay) {
    return jhsplit(l, r, splitPoint, delay);
  }

  static public JSplitPane hsplit(Component l, Component r, double splitPoint) {
    return jhsplit(l, r, splitPoint);
  }

  static public JSplitPane hsplit(double splitPoint, Component l, Component r) {
    return jhsplit(splitPoint, l, r);
  }

  static public JPanel northAndCenterWithMargin(int margin, Component n, Component c) {
    return northAndCenter(withBottomMargin(margin, n), c);
  }

  static public JPanel northAndCenterWithMargin(Component n, Component c) {
    return northAndCenter(withBottomMargin(n), c);
  }

  static public JPanel hgrid(final Object... parts) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel();
          Object[] _parts = flattenArray2(parts);
          panel.setLayout(new GridLayout(1, _parts.length));
          smartAdd(panel, _parts);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JPanel panel;\r\n    O[] _parts = flattenArray2(parts);\r\n    panel.setLayou...";
      }
    });
  }

  static public JPanel jCenteredSection(Component c) {
    return jCenteredSection("", c);
  }

  static public JPanel jCenteredSection(String title, Swingable c) {
    return jCenteredSection(title, wrap(c));
  }

  static public JPanel jCenteredSection(String title, Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = jSection(title, c);
          ((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = jSection(title, c);\r\n    ((TitledBorder) p.getBorder()).setTitleJu...";
      }
    });
  }

  static public JPanel jCenteredSection(String title) {
    return jCenteredSection(title, jpanel());
  }

  static public JLabel dm_calculatedCenteredLabel(IF0<Object> calc) {
    return dm_centeredCalculatedLabel(calc);
  }

  static public JLabel dm_centeredFieldLabel(String fieldName) {
    return centerLabel(dm_fieldLabel(fieldName));
  }

  static public JScrollPane jscroll_center(Component c) {
    return jscroll_centered(c);
  }

  static public ImageSurface doubleBufferedImageSurface_noAlpha() {
    ImageSurface is = doubleBufferedImageSurface();
    is.noAlpha = true;
    return is;
  }

  static public <A> A getVar(IF0<A> v) {
    return v == null ? null : v.get();
  }

  static public <A> A getVar(Optional<A> v) {
    return v == null ? null : v.orElse(null);
  }

  static public Window getWindow(Object o) {
    if (!(o instanceof Component))
      return null;
    return swing(() -> {
      Component c = (Component) o;
      while (c != null) {
        if (c instanceof Window)
          return ((Window) c);
        c = c.getParent();
      }
      return null;
    });
  }

  static public JComponent dm_vis(Object module) {
    return dm_getVisualization(module);
  }

  static public JComponent dm_vis() {
    return dm_getVisualization();
  }

  static public JButton findButton(Component c, String name) {
    for (JButton b : childrenOfType(c, JButton.class)) if (eq(b.getText(), name))
      return b;
    for (JButton b : childrenOfType(getFrame(c), JButton.class)) if (eq(b.getText(), name))
      return b;
    return null;
  }

  static public JButton findButton(Component c) {
    return childOfType(c, JButton.class);
  }

  static public Container getParent(final Component c) {
    return c == null ? null : swing(new F0<Container>() {

      public Container get() {
        try {
          return c.getParent();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getParent();";
      }
    });
  }

  static public void removeFromParent(final Component c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            Container cc = c.getParent();
            if (cc != null) {
              cc.remove(c);
              revalidate(cc);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Container cc = c.getParent();\r\n    if (cc != null) {\r\n      cc.remove(c);\r\n  ...";
        }
      });
    }
  }

  static public void dm_popInModule(Object module) {
    dm_callOS("stefansOS_popInModule", dm_getStem(module));
  }

  static public void dm_popInModule() {
    dm_popInModule(dm_current_generic_mandatory());
  }

  static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
    final JCheckBoxMenuItem mi = swing(() -> new JCheckBoxMenuItem(text, checked));
    addActionListener(mi, new Runnable() {

      public void run() {
        try {
          callF(r, isChecked(mi));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(r, isChecked(mi))";
      }
    });
    return mi;
  }

  static public JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, IVF1<Boolean> r) {
    return jCheckBoxMenuItem(text, checked, (Object) r);
  }

  static public boolean isAlwaysOnTop(JFrame f) {
    return f != null && swing(() -> f.isAlwaysOnTop());
  }

  static public boolean isAlwaysOnTop(Window w) {
    return w != null && swing(() -> w.isAlwaysOnTop());
  }

  static public void dm_toggleAlwaysOnTop() {
    if (dm_moduleIsPoppedOut()) {
      boolean aot = !isTrue(dm_getFlag("ALWAYSONTOPWHENPOPPEDOUT"));
      dm_setFlag("ALWAYSONTOPWHENPOPPEDOUT", aot);
      alwaysOnTop(dm_windowIfSingleModule(dm_current_generic()), aot);
    }
  }

  static public Class javax() {
    return getJavaX();
  }

  static public void setDefaultClassFinder(Object cf) {
    _defaultClassFinder_value = cf;
  }

  static public HashMap<String, Class> findClass_fullName_cache = new HashMap();

  static public Class findClass_fullName(String name) {
    synchronized (findClass_fullName_cache) {
      if (findClass_fullName_cache.containsKey(name))
        return findClass_fullName_cache.get(name);
      Class c;
      try {
        c = Class.forName(name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_fullName_cache.put(name, c);
      return c;
    }
  }

  static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1<String, Boolean> f) {
    return print_byThread().get() == null ? tempInterceptPrint(f) : null;
  }

  static public Map<JFrame, Boolean> myFrames_list = weakHashMap();

  static public List<JFrame> myFrames() {
    return swing(new F0<List<JFrame>>() {

      public List<JFrame> get() {
        try {
          return keysList(myFrames_list);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret keysList(myFrames_list);";
      }
    });
  }

  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public Concepts newConceptsWithClassFinder(String progID) {
    Concepts cc = new Concepts(progID);
    cc.classFinder = _defaultClassFinder();
    return cc;
  }

  static public String getDBProgramID_id;

  static public String getDBProgramID() {
    return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
  }

  static public byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

  static public String dropPrefix(String prefix, String s) {
    return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
  }

  static public int ubyteToInt(byte b) {
    return b & 0x0FF;
  }

  static public int ubyteToInt(char c) {
    return c & 0x0FF;
  }

  static public Frame getAWTFrame(final Object _o) {
    return swing(new F0<Frame>() {

      public Frame get() {
        try {
          Object o = _o;
          if (o instanceof ButtonGroup)
            o = first(buttonsInGroup((ButtonGroup) o));
          if (!(o instanceof Component))
            return null;
          Component c = (Component) o;
          while (c != null) {
            if (c instanceof Frame)
              return (Frame) c;
            c = c.getParent();
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "O o = _o;\r\n    /*\r\n    ifdef HaveProcessing\r\n      if (o instanceof PApplet) ...";
      }
    });
  }

  static public boolean boolPar(ThreadLocal<Boolean> tl) {
    return boolOptParam(tl);
  }

  static public boolean boolPar(Object[] __, String name) {
    return boolOptParam(__, name);
  }

  static public boolean boolPar(String name, Object[] __) {
    return boolOptParam(__, name);
  }

  static public boolean boolPar(String name, Map __) {
    return boolOptParam(name, __);
  }

  static public boolean boolPar(String name, Object[] params, boolean defaultValue) {
    return optParam(params, name, defaultValue);
  }

  static public java.util.Timer doLater(long delay, final Object r) {
    ping();
    final java.util.Timer timer = new java.util.Timer();
    timer.schedule(timerTask(r, timer), delay);
    return vmBus_timerStarted(timer);
  }

  static public java.util.Timer doLater(double delaySeconds, final Object r) {
    return doLater(toMS(delaySeconds), r);
  }

  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }

  static public BufferedImage loadImage2(String snippetIDOrURL) {
    return loadBufferedImage(snippetIDOrURL);
  }

  static public BufferedImage loadImage2(File file) {
    return loadBufferedImage(file);
  }

  static public Object[] params_unpackList(Object[] params) {
    if (l(params) == 1 && params[0] instanceof List)
      return toObjectArray((List) params[0]);
    return params;
  }

  static public String[] dropFirst(int n, String[] a) {
    return drop(n, a);
  }

  static public String[] dropFirst(String[] a) {
    return drop(1, a);
  }

  static public Object[] dropFirst(Object[] a) {
    return drop(1, a);
  }

  static public <A> List<A> dropFirst(List<A> l) {
    return dropFirst(1, l);
  }

  static public <A> List<A> dropFirst(int n, Iterable<A> i) {
    return dropFirst(n, toList(i));
  }

  static public <A> List<A> dropFirst(Iterable<A> i) {
    return dropFirst(toList(i));
  }

  static public <A> List<A> dropFirst(int n, List<A> l) {
    return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
  }

  static public <A> List<A> dropFirst(List<A> l, int n) {
    return dropFirst(n, l);
  }

  static public String dropFirst(int n, String s) {
    return substring(s, n);
  }

  static public String dropFirst(String s, int n) {
    return substring(s, n);
  }

  static public String dropFirst(String s) {
    return substring(s, 1);
  }

  static public PopupMenu makePopupMenu(Object... x) {
    if (x == null)
      return null;
    if (l(x) == 1 && x[0] instanceof PopupMenu)
      return (PopupMenu) x[0];
    PopupMenu m = new PopupMenu();
    for (int i = 0; i < l(x); i++) {
      Object o = x[i];
      if (eqOneOf(o, "***", "---", "===", ""))
        m.addSeparator();
      else if (o instanceof String && get(x, i + 1) instanceof Runnable)
        m.add(menuItem((String) o, get(x, ++i)));
      else if (o instanceof String || o instanceof Menu || o instanceof MenuItem)
        call(m, "add", o);
      else
        print("Unknown menu item: " + o);
    }
    return m;
  }

  static public <A extends JComponent> A onLeftClick(final A c, final Object runnable) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(leftClickMouseAdapter(runnable));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(leftClickMouseAdapter(runnable));";
        }
      });
    }
    return c;
  }

  static public TrayIcon onLeftClick(final TrayIcon c, final Object runnable) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(leftClickMouseAdapter_noPt(runnable));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(leftClickMouseAdapter_noPt(runnable));";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A onLeftClick(final Object runnable, A c) {
    return onLeftClick(c, runnable);
  }

  static public <A> A optPar(ThreadLocal<A> tl, A defaultValue) {
    A a = tl.get();
    if (a != null) {
      tl.set(null);
      return a;
    }
    return defaultValue;
  }

  static public <A> A optPar(ThreadLocal<A> tl) {
    return optPar(tl, null);
  }

  static public Object optPar(Object[] params, String name) {
    return optParam(params, name);
  }

  static public Object optPar(String name, Object[] params) {
    return optParam(params, name);
  }

  static public Object optPar(String name, Map params) {
    return optParam(name, params);
  }

  static public <A> A optPar(Object[] params, String name, A defaultValue) {
    return optParam(params, name, defaultValue);
  }

  static public <A> A optPar(String name, Object[] params, A defaultValue) {
    return optParam(params, name, defaultValue);
  }

  public static boolean isWindows() {
    return System.getProperty("os.name").contains("Windows");
  }

  static public String combinePrintParameters(String s, Object o) {
    return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
  }

  static public void ping_okInCleanUp() {
  }

  static public Object getThreadLocal(Object o, String name) {
    ThreadLocal t = (ThreadLocal) (getOpt(o, name));
    return t != null ? t.get() : null;
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl) {
    return tl == null ? null : tl.get();
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl, A defaultValue) {
    return or(getThreadLocal(tl), defaultValue);
  }

  static public ThreadLocal<Object> print_byThread_dontCreate() {
    return print_byThread;
  }

  static public boolean isFalse(Object o) {
    return eq(false, o);
  }

  static public Object callF(Object f, Object... args) {
    try {
      if (f instanceof String)
        return callMC((String) f, args);
      return x30_util.callF(f, args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A callF(F0<A> f) {
    return f == null ? null : f.get();
  }

  static public <A> A callF(IF0<A> f) {
    return f == null ? null : f.get();
  }

  static public <A, B> B callF(F1<A, B> f, A a) {
    return f == null ? null : f.get(a);
  }

  static public <A, B> B callF(IF1<A, B> f, A a) {
    return f == null ? null : f.get(a);
  }

  static public <A, B, C> C callF(F2<A, B, C> f, A a, B b) {
    return f == null ? null : f.get(a, b);
  }

  static public <A> void callF(VF1<A> f, A a) {
    if (f != null)
      f.get(a);
  }

  static public Object callMC(String method, Object... args) {
    return call(mc(), method, args);
  }

  static public Object call(Object o) {
    return callF(o);
  }

  static public Object call(Object o, String method, Object... args) {
    return call_withVarargs(o, method, args);
  }

  static public String getStackTrace(Throwable throwable) {
    lastException(throwable);
    return getStackTrace_noRecord(throwable);
  }

  static public String getStackTrace_noRecord(Throwable throwable) {
    StringWriter writer = new StringWriter();
    throwable.printStackTrace(new PrintWriter(writer));
    return hideCredentials(writer.toString());
  }

  static public String getStackTrace() {
    return getStackTrace_noRecord(new Throwable());
  }

  static public String getStackTrace(String msg) {
    return getStackTrace_noRecord(new Throwable(msg));
  }

  static public String fixNewLines(String s) {
    int i = indexOf(s, '\r');
    if (i < 0)
      return s;
    int l = s.length();
    StringBuilder out = new StringBuilder(l);
    out.append(s, 0, i);
    for (; i < l; i++) {
      char c = s.charAt(i);
      if (c != '\r')
        out.append(c);
      else {
        out.append('\n');
        if (i + 1 < l && s.charAt(i + 1) == '\n')
          ++i;
      }
    }
    return out.toString();
  }

  static public void print_append(Appendable buf, String s, int max) {
    try {
      synchronized (buf) {
        buf.append(s);
        if (buf instanceof StringBuffer)
          rotateStringBuffer(((StringBuffer) buf), max);
        else if (buf instanceof StringBuilder)
          rotateStringBuilder(((StringBuilder) buf), max);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void vmBus_send(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
    pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

  static public void vmBus_send(String msg) {
    vmBus_send(msg, (Object) null);
  }

  static public boolean makeNotifyingStringBufferRotate_verbose = false;

  static public class NotifyingStringBufferRotator implements Runnable {

    public NotifyingStringBuffer buf;

    public IF0<Integer> getMaxChars;

    public boolean processing = false;

    public NotifyingStringBufferRotator(NotifyingStringBuffer buf, IF0<Integer> getMaxChars) {
      this.getMaxChars = getMaxChars;
      this.buf = buf;
    }

    public void run() {
      try {
        if (processing)
          return;
        AutoCloseable __1 = tempSet(this, "processing", true);
        try {
          Integer max = callF(getMaxChars);
          if (max == null || buf.length() <= max)
            return;
          if (makeNotifyingStringBufferRotate_verbose)
            print("Rotating NotifyingStringBuffer (" + buf.length() + "/" + max + ")");
          try {
            int newLength = max / 2;
            int ofs = buf.length() - newLength;
            String newString = buf.substring(ofs);
            buf.setLength(0);
            buf.append("[...] ").append(newString);
          } catch (Exception e) {
            buf.setLength(0);
          }
          buf.trimToSize();
        } finally {
          _close(__1);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  static public void makeNotifyingStringBufferRotate(NotifyingStringBuffer buf, IF0<Integer> getMaxChars) {
    if (hasElementWithClassShortNamed("NotifyingStringBufferRotator", buf.onChange))
      return;
    buf.onChange(new NotifyingStringBufferRotator(buf, getMaxChars));
  }

  static volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

  static public void lastException(Throwable e) {
    lastException_lastException = persistableThrowable(e);
  }

  static public Throwable getInnerException(Throwable e) {
    if (e == null)
      return null;
    while (e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Throwable getInnerException(Runnable r) {
    return getInnerException(getException(r));
  }

  static public String hideCredentials(URL url) {
    return url == null ? null : hideCredentials(str(url));
  }

  static public String hideCredentials(String url) {
    try {
      if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
        return url;
    } catch (Throwable e) {
      print("HideCredentials", e);
    }
    return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=<hidden>");
  }

  static public String hideCredentials(Object o) {
    return hideCredentials(str(o));
  }

  static public String unnull(String s) {
    return s == null ? "" : s;
  }

  static public <A> Collection<A> unnull(Collection<A> l) {
    return l == null ? emptyList() : l;
  }

  static public <A> List<A> unnull(List<A> l) {
    return l == null ? emptyList() : l;
  }

  static public int[] unnull(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnull(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnull(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

  static public <A, B> Map<A, B> unnull(Map<A, B> l) {
    return l == null ? emptyMap() : l;
  }

  static public <A> Iterable<A> unnull(Iterable<A> i) {
    return i == null ? emptyList() : i;
  }

  static public <A> A[] unnull(A[] a) {
    return a == null ? (A[]) emptyObjectArray() : a;
  }

  static public BitSet unnull(BitSet b) {
    return b == null ? new BitSet() : b;
  }

  static public Pt unnull(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public Symbol unnull(Symbol s) {
    return s == null ? emptySymbol() : s;
  }

  static public <A, B> Pair<A, B> unnull(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public int unnull(Integer i) {
    return i == null ? 0 : i;
  }

  static public long unnull(Long l) {
    return l == null ? 0L : l;
  }

  static public double unnull(Double l) {
    return l == null ? 0.0 : l;
  }

  static public String baseClassName(String className) {
    return substring(className, className.lastIndexOf('.') + 1);
  }

  static public String baseClassName(Object o) {
    return baseClassName(getClassName(o));
  }

  static public String prependIfNempty(String prefix, String s) {
    return empty(s) ? unnull(s) : prefix + s;
  }

  static public <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        return map.put(key, value);
      else
        return map.remove(key);
    return null;
  }

  static public Map vm_generalMap_map;

  static public Map vm_generalMap() {
    if (vm_generalMap_map == null)
      vm_generalMap_map = (Map) get(javax(), "generalMap");
    return vm_generalMap_map;
  }

  static public List<String> methodsStartingWith(Object o, final String prefix) {
    return filter(allMethodNames(o), new F1<String, Object>() {

      public Object get(String s) {
        try {
          return startsWith(s, prefix);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "startsWith(s, prefix)";
      }
    });
  }

  static public Object pcallOpt(Object o, String method, Object... args) {
    try {
      return callOpt(o, method, args);
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
    return null;
  }

  static public boolean eq(Object a, Object b) {
    return a == b || a != null && b != null && a.equals(b);
  }

  static public boolean eq(Symbol a, String b) {
    return eq(str(a), b);
  }

  static public void poorMansProfileToConsole(Runnable r) {
    poorMansProfiling();
    try {
      r.run();
    } finally {
      poorMansProfiling_stopAndPrintResults();
    }
  }

  static public long now_virtualTime;

  static public long now() {
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
  }

  static public SimpleDateFormat simpleDateFormat_local(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    sdf.setTimeZone(localTimeZone());
    return sdf;
  }

  static public boolean eqOneOf(Object o, Object... l) {
    for (Object x : l) if (eq(o, x))
      return true;
    return false;
  }

  static public void printWithMSTime(String s) {
    print(hmsWithColonsAndMS() + ": " + s);
  }

  static public void swingAndWait(Runnable r) {
    try {
      if (isAWTThread())
        r.run();
      else
        EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object swingAndWait(final Object f) {
    if (isAWTThread())
      return callF(f);
    else {
      final Var result = new Var();
      swingAndWait(new Runnable() {

        public void run() {
          try {
            result.set(callF(f));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "result.set(callF(f));";
        }
      });
      return result.get();
    }
  }

  static public JComponent wrap(Object swingable) {
    return _recordNewSwingComponent(wrap_2(swingable));
  }

  static public JComponent wrap_2(Object swingable) {
    if (swingable == null)
      return null;
    JComponent c;
    if (swingable instanceof Component)
      c = componentToJComponent((Component) swingable);
    else if (swingable instanceof Swingable)
      c = componentToJComponent(((Swingable) swingable).visualize());
    else
      c = componentToJComponent((Component) callOpt(swingable, "swing"));
    if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
      return jscroll(c);
    return c == null ? jlabel(str(swingable)) : c;
  }

  static public Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);

  static public Rectangle defaultNewFrameBounds() {
    return swing(new F0<Rectangle>() {

      public Rectangle get() {
        try {
          defaultNewFrameBounds_r.translate(60, 20);
          if (!screenRectangle().contains(defaultNewFrameBounds_r))
            defaultNewFrameBounds_r.setLocation(30 + random(30), 20 + random(20));
          return new Rectangle(defaultNewFrameBounds_r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "defaultNewFrameBounds_r.translate(60, 20);\r\n    if (!screenRectangle().contai...";
      }
    });
  }

  static public JFrame setFrameIconLater(Component c, final String imageID) {
    final JFrame frame = getFrame(c);
    if (frame != null)
      startThread("Loading Icon", new Runnable() {

        public void run() {
          try {
            final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
            swingLater(new Runnable() {

              public void run() {
                try {
                  frame.setIconImage(i);
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "frame.setIconImage(i);";
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n      swingL...";
        }
      });
    return frame;
  }

  static public class tempRememberListener_c implements IFieldsToList {

    static final public String _fieldOrder = "mainObject removeMethod listener";

    public Object mainObject;

    public String removeMethod;

    public Object listener;

    public tempRememberListener_c() {
    }

    public tempRememberListener_c(Object mainObject, String removeMethod, Object listener) {
      this.listener = listener;
      this.removeMethod = removeMethod;
      this.mainObject = mainObject;
    }

    public String toString() {
      return shortClassName_dropNumberPrefix(this) + "(" + mainObject + ", " + removeMethod + ", " + listener + ")";
    }

    public boolean equals(Object o) {
      if (!(o instanceof tempRememberListener_c))
        return false;
      tempRememberListener_c __1 = (tempRememberListener_c) o;
      return eq(mainObject, __1.mainObject) && eq(removeMethod, __1.removeMethod) && eq(listener, __1.listener);
    }

    public int hashCode() {
      int h = 1262836985;
      h = boostHashCombine(h, _hashCode(mainObject));
      h = boostHashCombine(h, _hashCode(removeMethod));
      h = boostHashCombine(h, _hashCode(listener));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { mainObject, removeMethod, listener };
    }
  }

  static public AutoCloseable tempRememberListener(Object mainObject, String removeMethod, Object listener) {
    return tempHoldInstance(new tempRememberListener_c(mainObject, removeMethod, listener));
  }

  static public Object pcallF(Object f, Object... args) {
    return pcallFunction(f, args);
  }

  static public <A> A pcallF(F0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A, B> B pcallF(F1<A, B> f, A a) {
    try {
      return f == null ? null : f.get(a);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A> void pcallF(VF1<A> f, A a) {
    try {
      {
        if (f != null)
          f.get(a);
      }
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
  }

  static public Object pcallF(Runnable r) {
    try {
      {
        if (r != null)
          r.run();
      }
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A> A pcallF(IF0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A, B> B pcallF(IF1<A, B> f, A a) {
    try {
      return f == null ? null : f.get(a);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public Object[] asArray(List l) {
    return toObjectArray(l);
  }

  static public <A> A[] asArray(Class<A> type, List l) {
    return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
  }

  static public boolean newButton_autoToolTip = true;

  static public JButton newButton(final String text, final Object action) {
    return swing(new F0<JButton>() {

      public JButton get() {
        try {
          String text2 = dropPrefix("[disabled] ", text);
          final JButton btn = new JButton(text2);
          if (l(text2) < l(text))
            btn.setEnabled(false);
          if (newButton_autoToolTip) {
            btn.setToolTipText(btn.getText());
          }
          if (action != null)
            btn.addActionListener(actionListener(action, btn));
          return btn;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "S text2 = dropPrefix(\"[disabled] \", text);\r\n    final JButton btn = new JButt...";
      }
    });
  }

  static public <A> A swingNu(final Class<A> c, final Object... args) {
    return swingConstruct(c, args);
  }

  static public <A> A heldInstance(Class<A> c) {
    List<Object> l = holdInstance_l.get();
    for (int i = l(l) - 1; i >= 0; i--) {
      Object o = l.get(i);
      if (isInstanceOf(o, c))
        return (A) o;
    }
    throw fail("No instance of " + className(c) + " held");
  }

  static public <A extends JComponent> A toolTip(A c, final Object toolTip) {
    return setToolTipText(c, toolTip);
  }

  static public <A extends JComponent> A toolTip(Object toolTip, A c) {
    return setToolTipText(toolTip, c);
  }

  static public JButton jPopDownButton(String text, final Object... menuParams) {
    return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() {

      public void run() {
        try {
          JPopupMenu menu = new JPopupMenu();
          int emptyCount = menu.getComponentCount();
          String position = (String) (optPar_ignoreOddLength("position", menuParams));
          fillJPopupMenu(menu, paramsWithout(menuParams, "position"));
          if (menu.getComponentCount() != emptyCount) {
            JButton btn = heldInstance(JButton.class);
            int x = 0;
            if (eq(position, "center"))
              x = (btn.getWidth() - getPreferredWidth(menu)) / 2;
            else if (eq(position, "right"))
              x = btn.getWidth() - getPreferredWidth(menu);
            menu.show(btn, x, btn.getHeight());
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JPopupMenu menu;\r\n    int emptyCount = menu.getComponentCount();\r\n    Str...";
      }
    });
  }

  static public <A extends Component> A activateFrameAndReturnComponent(A c) {
    activateFrame(c);
    return c;
  }

  static public <A> A setFrameTitle(A c, final String title) {
    final Frame f = getAWTFrame(c);
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            f.setTitle(title);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "f.setTitle(title);";
        }
      });
    }
    return c;
  }

  static public <A extends Component> A setFrameTitle(String title, A c) {
    return setFrameTitle(c, title);
  }

  static public JFrame setFrameTitle(String title) {
    Object f = getOpt(mc(), "frame");
    if (f instanceof JFrame)
      return setFrameTitle((JFrame) f, title);
    return null;
  }

  static public boolean setText_opt = true;

  static public <A extends JTextComponent> A setText(A c, Object text) {
    setText((JComponent) c, text);
    return c;
  }

  static public <A extends JComboBox> A setText(final A c, Object text) {
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.getEditor().setItem(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.getEditor().setItem(s);";
        }
      });
    }
    return c;
  }

  static public void setText(JLabel c, Object text) {
    setText((JComponent) c, text);
  }

  static public JButton setText(JButton c, Object text) {
    setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
    return c;
  }

  static public <A extends JComponent> A setText(final A c, Object text) {
    if (c == null)
      return null;
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (!setText_opt || neq(callOpt(c, "getText"), s))
              call(c, "setText", s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n      call(c, \"setText\", s);";
        }
      });
    }
    return c;
  }

  static public JTextArea newTypeWriterTextArea() {
    return newTypeWriterTextArea("");
  }

  static public JTextArea newTypeWriterTextArea(String text) {
    return withTypeWriterFont(jTextArea(text));
  }

  static public String makeFrame_defaultIcon;

  static public boolean makeFrame_hideConsole = false;

  static public ThreadLocal<VF1<JFrame>> makeFrame_post = new ThreadLocal();

  static public JFrame makeFrame() {
    return makeFrame((Component) null);
  }

  static public JFrame makeFrame(Object content) {
    return makeFrame(programTitle(), content);
  }

  static public JFrame makeFrame(String title) {
    return makeFrame(title, null);
  }

  static public JFrame makeFrame(String title, Object content) {
    return makeFrame(title, content, true);
  }

  static public JFrame makeFrame(final String title, final Object content, final boolean showIt) {
    final VF1<JFrame> post = optParam(makeFrame_post);
    return swing(new F0<JFrame>() {

      public JFrame get() {
        try {
          if (getFrame(content) != null)
            return getFrame(setFrameTitle((Component) content, title));
          final JFrame frame = new JFrame(title);
          if (makeFrame_defaultIcon != null)
            setFrameIconLater(frame, makeFrame_defaultIcon);
          _initFrame(frame);
          Component wrapped = wrap(content);
          if (wrapped != null)
            frame.getContentPane().add(wrapped);
          frame.setBounds(defaultNewFrameBounds());
          callF(post, frame);
          if (showIt)
            frame.setVisible(true);
          if (showIt && makeFrame_hideConsole) {
            hideConsole();
            makeFrame_hideConsole = false;
          }
          return frame;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "if (getFrame(content) != null)\r\n      ret getFrame(setFrameTitle((Component) ...";
      }
    });
  }

  static public String autoFrameTitle_value;

  static public String autoFrameTitle() {
    return autoFrameTitle_value != null ? autoFrameTitle_value : getProgramTitle();
  }

  static public void autoFrameTitle(Component c) {
    setFrameTitle(getFrame(c), autoFrameTitle());
  }

  static public void printTo(StringBuilder buf, Object o) {
    buf.append(str(o)).append("\n");
  }

  static public void printTo(StringBuilder buf) {
    printTo(buf, "");
  }

  static public String n(long l, String name) {
    return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
  }

  static public String n(Collection l, String name) {
    return n(l(l), name);
  }

  static public String n(Map m, String name) {
    return n(l(m), name);
  }

  static public String n(Object[] a, String name) {
    return n(l(a), name);
  }

  static public String n(MultiSet ms, String name) {
    return n(l(ms), name);
  }

  static public String asciiHeading2(String title) {
    return asciiHeading(title) + "\n";
  }

  static public JLabel jcenteredLabel(String text) {
    return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
  }

  static public JLabel jcenteredLabel() {
    return jcenteredLabel(" ");
  }

  static public <A extends Component> A jMinWidth(final int w, final A c) {
    if (c == null)
      return null;
    return swing(new F0<A>() {

      public A get() {
        try {
          Dimension size = c.getMinimumSize();
          c.setMinimumSize(new Dimension(w, size.height));
          return jPreferWidth(w, c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Dimension size = c.getMinimumSize();\r\n    c.setMinimumSize(new Dimension(/*ma...";
      }
    });
  }

  static public int getWidth(Component c) {
    return c == null ? 0 : (int) swingCall(c, "getWidth");
  }

  static public int getHeight(Component c) {
    return c == null ? 0 : (int) swingCall(c, "getHeight");
  }

  static public List<DoublePt> graphAsPolygon(IF1<Double, Double> formula, int w, int h) {
    List<DoublePt> points = new ArrayList();
    points.add(new DoublePt(0, 0));
    for (int x = 0; x < w; x++) {
      double y = formula.get(doubleRatio(x, w)) * h;
      points.add(new DoublePt(x, y));
    }
    points.add(new DoublePt(w - 1, 0));
    return points;
  }

  static public double sineSigmoid(double x) {
    return 0.5 * (1 + sin(pi() * (x - .5)));
  }

  static public void fillRect(BufferedImage image, int x, int y, int w, int h, Color color) {
    Graphics2D g = imageGraphics(image);
    fillRect(g, x, y, w, h, color);
    g.dispose();
  }

  static public void fillRect(Graphics g, int x, int y, int w, int h, Color color) {
    g.setColor(color);
    g.fillRect(x, y, w, h);
  }

  static public void fillRect(int x, int y, int w, int h, Color color) {
    fillRect(currentImage(), x, y, w, h, color);
  }

  static public void fillRect(Rect r, Color color) {
    fillRect(r.x, r.y, r.w, r.h, color);
  }

  static public void fillRect(BufferedImage image, Rect r, Color c) {
    if (r != null)
      fillRect(image, r.x, r.y, r.w, r.h, c);
  }

  static public void fillRect(Graphics g, Rect r, Color c) {
    if (r != null)
      fillRect(g, r.x, r.y, r.w, r.h, c);
  }

  static public Color gazelle_color2() {
    return awtColor("EEEEEE");
  }

  static public void fillPrecisePolygon(BufferedImage g, List<DoublePt> points, Color color) {
    fillPrecisePolygon(graphics(g), points, color);
  }

  static public void fillPrecisePolygon(Graphics2D g, List<DoublePt> points, Color color) {
    g.setColor(color);
    g.fill(new PrecisePolygon(points));
  }

  static public void fillPrecisePolygon(BufferedImage g, List<DoublePt> points) {
    fillPrecisePolygon(graphics(g), points);
  }

  static public void fillPrecisePolygon(Graphics2D g, List<DoublePt> points) {
    g.fill(new PrecisePolygon(points));
  }

  static public Color gazelle_color1() {
    return awtColor("ADD8E6");
  }

  static public JPanel westCenterAndEast(Component w, Component c, Component e) {
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(BorderLayout.WEST, wrap(w));
    panel.add(BorderLayout.CENTER, wrap(c));
    panel.add(BorderLayout.EAST, wrap(e));
    return panel;
  }

  static public int withLeftAndRightMargin_defaultWidth = 6;

  static public JPanel withLeftAndRightMargin(Component c) {
    return withLeftAndRightMargin(withLeftAndRightMargin_defaultWidth, c);
  }

  static public JPanel withLeftAndRightMargin(int w, Component c) {
    return withLeftAndRightMargin(w, w, c);
  }

  static public JPanel withLeftAndRightMargin(final int w1, final int w2, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = marginPanel();
          p.setBorder(BorderFactory.createEmptyBorder(0, w1, 0, w2));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = marginPanel();\r\n    p.setBorder(BorderFactory.createEmptyBorder(0,...";
      }
    });
  }

  static public JLabel jImage(Image img) {
    return jimage(img);
  }

  static public JLabel jImage(String imageID) {
    return jimage(imageID);
  }

  static public BufferedImage resizeImageToHeight_bilinear(BufferedImage img, int newH) {
    return scaleImage_bilinear(doubleRatio(newH, img.getHeight()), img);
  }

  static public void onMouseDown(Component c, Object r) {
    if (c != null && r != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(new MouseAdapter() {

              public void mousePressed(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1)
                  pcallF(r);
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(new MouseAdapter {\r\n      public void mousePressed(MouseEv...";
        }
      });
    }
  }

  static public MouseAdapter onMouseDown(Component c, IVF1<MouseEvent> f) {
    return c == null || f == null ? null : swing(() -> {
      MouseAdapter ma = new MouseAdapter() {

        public void mousePressed(MouseEvent e) {
          if (e.getButton() == MouseEvent.BUTTON1)
            f.get(e);
        }
      };
      c.addMouseListener(ma);
      return ma;
    });
  }

  static public JPanel centerAndNorth(final Component c, final Component n) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          panel.add(BorderLayout.NORTH, wrap(n));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public boolean nempty(Collection c) {
    return !empty(c);
  }

  static public boolean nempty(CharSequence s) {
    return !empty(s);
  }

  static public boolean nempty(Object[] o) {
    return !empty(o);
  }

  static public boolean nempty(byte[] o) {
    return !empty(o);
  }

  static public boolean nempty(int[] o) {
    return !empty(o);
  }

  static public boolean nempty(BitSet bs) {
    return !empty(bs);
  }

  static public boolean nempty(Map m) {
    return !empty(m);
  }

  static public boolean nempty(Iterator i) {
    return i != null && i.hasNext();
  }

  static public boolean nempty(MultiMap mm) {
    return mm != null && !mm.isEmpty();
  }

  static public boolean nempty(Object o) {
    return !empty(o);
  }

  static public boolean nempty(IntRange r) {
    return !empty(r);
  }

  static public boolean nempty(IntBuffer b) {
    return b != null && !b.isEmpty();
  }

  static public boolean nempty(Rect r) {
    return r != null && r.w != 0 && r.h != 0;
  }

  static public String ymd_minus_hms() {
    return ymd() + "-" + hms();
  }

  static public String _userHome;

  static public String userHome() {
    if (_userHome == null)
      return actualUserHome();
    return _userHome;
  }

  static public File userHome(String path) {
    return new File(userDir(), path);
  }

  static public File newFile(File base, String... names) {
    for (String name : names) base = new File(base, name);
    return base;
  }

  static public File newFile(String name) {
    return name == null ? null : new File(name);
  }

  static public File newFile(String base, String... names) {
    return newFile(newFile(base), names);
  }

  static public boolean infoMessage_alwaysOnTop = true;

  static public double infoMessage_defaultTime = 5.0;

  static public JWindow infoMessage(String text) {
    return infoMessage(text, infoMessage_defaultTime);
  }

  static public JWindow infoMessage(final String text, final double seconds) {
    printHidingCredentials(text);
    return infoMessage_noprint(text, seconds);
  }

  static public JWindow infoMessage_noprint(String text) {
    return infoMessage_noprint(text, infoMessage_defaultTime);
  }

  static public JWindow infoMessage_noprint(final String _text, final double seconds) {
    final String text = hideCredentials(_text);
    if (empty(text))
      return null;
    logQuotedWithDate(infoBoxesLogFile(), text);
    if (isHeadless())
      return null;
    return (JWindow) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          JWindow window = makeWindow(infoMessage_makePanel(text));
          window.setSize(300, 150);
          moveToTopRightCorner(window);
          if (infoMessage_alwaysOnTop)
            window.setAlwaysOnTop(true);
          if (vmBus_noObjections("shouldShowInfoBox", window, text))
            window.setVisible(true);
          if (seconds != 0)
            disposeWindowAfter(iround(seconds * 1000), window);
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n    window.setSize...";
      }
    });
  }

  static public JWindow infoMessage(Throwable e) {
    printStackTrace(e);
    return infoMessage(exceptionToStringShort(e));
  }

  static public URLConnection openConnection(String url) {
    try {
      return openConnection(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void setHeaders(URLConnection con) throws IOException {
    String computerID = getComputerID_quick();
    if (computerID != null)
      try {
        con.setRequestProperty("X-ComputerID", computerID);
        con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
      } catch (Throwable e) {
      }
  }

  static public FileOutputStream newFileOutputStream(File path) throws IOException {
    return newFileOutputStream(path.getPath());
  }

  static public FileOutputStream newFileOutputStream(String path) throws IOException {
    return newFileOutputStream(path, false);
  }

  static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
    return newFileOutputStream(path.getPath(), append);
  }

  static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
    mkdirsForFile(path);
    FileOutputStream f = new FileOutputStream(path, append);
    _registerIO(f, path, true);
    return f;
  }

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

  static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
    try {
      byte[] buf = new byte[65536];
      int total = 0;
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
        if ((total + n) / 100000 > total / 100000)
          print(pat.replace("{*}", str(roundDownTo(100000, total))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File renameFile_assertTrue(File a, File b) {
    try {
      if (a.equals(b))
        return b;
      if (!a.exists())
        throw fail("Source file not found: " + f2s(a));
      if (b.exists())
        throw fail("Target file exists: " + f2s(b));
      mkdirsForFile(b);
      if (!a.renameTo(b))
        throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
      return b;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String renderFileInfo(File f) {
    return f == null ? "-" : f2s(f) + " " + (f.isFile() ? "(file, " + n2(fileSize(f)) + " bytes)" : f.isDirectory() ? "(dir)" : "(not found)");
  }

  static public boolean byteArrayStartsWith(byte[] a, byte[] b) {
    if (a == null || b == null)
      return false;
    if (a.length < b.length)
      return false;
    for (int i = 0; i < b.length; i++) if (a[i] != b[i])
      return false;
    return true;
  }

  static public byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
    return loadBinaryFilePart(file, 0, maxBytes);
  }

  static public String n2(long l) {
    return formatWithThousands(l);
  }

  static public String n2(AtomicLong l) {
    return n2(l.get());
  }

  static public String n2(Collection l) {
    return n2(l(l));
  }

  static public String n2(Map map) {
    return n2(l(map));
  }

  static public String n2(double l, String singular) {
    return empty(singular) ? str(l) : n2(l, singular, singular + "s");
  }

  static public String n2(double l, String singular, String plural) {
    if (fraction(l) == 0)
      return n2((long) l, singular, plural);
    else
      return l + " " + plural;
  }

  static public String n2(long l, String singular, String plural) {
    return n_fancy2(l, singular, plural);
  }

  static public String n2(long l, String singular) {
    return empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s");
  }

  static public String n2(Collection l, String singular) {
    return n2(l(l), singular);
  }

  static public String n2(Collection l, String singular, String plural) {
    return n_fancy2(l, singular, plural);
  }

  static public String n2(Map m, String singular, String plural) {
    return n_fancy2(m, singular, plural);
  }

  static public String n2(Map m, String singular) {
    return n2(l(m), singular);
  }

  static public String n2(long[] a, String singular) {
    return n2(l(a), singular);
  }

  static public String n2(Object[] a, String singular) {
    return n2(l(a), singular);
  }

  static public String n2(Object[] a, String singular, String plural) {
    return n_fancy2(a, singular, plural);
  }

  static public String n2(MultiSet ms, String singular, String plural) {
    return n_fancy2(ms, singular, plural);
  }

  static public List<String> allClassNamesOnPath(Collection<File> files) {
    List<String> classes = new ArrayList();
    for (File dir : files) classes.addAll(classNamesInJarOrDir(dir));
    return classes;
  }

  static public <A> List<A> ll(A... a) {
    ArrayList l = new ArrayList(a.length);
    if (a != null)
      for (A x : a) l.add(x);
    return l;
  }

  public static File mkdirsForFile(File file) {
    File dir = file.getParentFile();
    if (dir != null) {
      dir.mkdirs();
      if (!dir.isDirectory())
        if (dir.isFile())
          throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
        else
          throw fail("Unknown IO exception during mkdirs of " + f2s(file));
    }
    return file;
  }

  public static String mkdirsForFile(String path) {
    mkdirsForFile(new File(path));
    return path;
  }

  static public File fileInSameDir(File f, String newName) {
    return newFile(parentFile(f), newName);
  }

  static public File appendToFileNameBeforeExtension(File f, String s) {
    String ext = fileExtension(f);
    String name = dropSuffixIC(ext, f.getName());
    name += s;
    return newFile(parentFile(f), name + ext);
  }

  static public void copyStream(InputStream in, OutputStream out) {
    try {
      byte[] buf = new byte[65536];
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String platformQuoteOpt(String s) {
    return containsUnsafePlatformCmdLineChar(s) ? platformQuote(s) : s;
  }

  static public String platformQuoteOpt(File f) {
    return platformQuoteOpt(f2s(f));
  }

  static public String nohup_sanitize(String s) {
    return empty(s) ? s : takeFirst(50, s.replaceAll("[^.a-zA-Z0-9\\-_]", ""));
  }

  static public <A> A printStruct(String prefix, A a) {
    printStructure(prefix, a);
    return a;
  }

  static public <A> A printStruct(A a) {
    printStructure(a);
    return a;
  }

  static public boolean warn_on = true;

  static public ThreadLocal<List<String>> warn_warnings = new ThreadLocal();

  static public void warn(String s) {
    if (warn_on)
      print("Warning: " + s);
  }

  static public void warn(String s, List<String> warnings) {
    warn(s);
    if (warnings != null)
      warnings.add(s);
    addToCollection(warn_warnings.get(), s);
  }

  public static String winQuote(String text) {
    if (text == null)
      return null;
    return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") + "\"";
  }

  static public String winQuote(File f) {
    return winQuote(f.getAbsolutePath());
  }

  static public String bashQuote(String text) {
    if (text == null)
      return null;
    return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") + "\"";
  }

  static public String bashQuote(File f) {
    return bashQuote(f.getAbsolutePath());
  }

  static public int getScreenWidth() {
    return getScreenSize().width;
  }

  static public int getScreenHeight() {
    return getScreenSize().height;
  }

  static public int rectArea(Rect r) {
    return r == null ? 0 : r.w * r.h;
  }

  static public int imageIcon_cacheSize = 10;

  static public boolean imageIcon_verbose = false;

  static public Map<String, ImageIcon> imageIcon_cache;

  static public Lock imageIcon_lock = lock();

  static public ThreadLocal<Boolean> imageIcon_fixGIF = new ThreadLocal();

  static public ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __0 = imageIcon_lock;
      lock(__0);
      try {
        if (imageIcon_cache == null)
          imageIcon_cache = new MRUCache(imageIcon_cacheSize);
        imageID = fsI(imageID);
        ImageIcon ii = imageIcon_cache.get(imageID);
        if (ii == null) {
          if (imageIcon_verbose)
            print("Loading image icon: " + imageID);
          File f = loadBinarySnippet(imageID);
          Boolean b = imageIcon_fixGIF.get();
          if (!isFalse(b))
            ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
          else
            ii = new ImageIcon(f.toURI().toURL());
        } else
          imageIcon_cache.remove(imageID);
        imageIcon_cache.put(imageID, ii);
        return ii;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(File f) {
    try {
      return new ImageIcon(f.toURI().toURL());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(Image img) {
    return new ImageIcon(img);
  }

  static public ImageIcon imageIcon(RGBImage img) {
    return imageIcon(img.getBufferedImage());
  }

  static public String rep(int n, char c) {
    return repeat(c, n);
  }

  static public String rep(char c, int n) {
    return repeat(c, n);
  }

  static public <A> List<A> rep(A a, int n) {
    return repeat(a, n);
  }

  static public <A> List<A> rep(int n, A a) {
    return repeat(n, a);
  }

  static public String decimalFormatEnglish(String format, double d) {
    return decimalFormatEnglish(format).format(d);
  }

  static public java.text.DecimalFormat decimalFormatEnglish(String format) {
    return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH));
  }

  static public int intSum(Collection c, String field) {
    int sum = 0;
    for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
    return sum;
  }

  static public int intSum(Iterable<Integer> l) {
    int sum = 0;
    for (Integer i : unnull(l)) if (i != null)
      sum += i;
    return sum;
  }

  static public int intSum(int[] l) {
    int sum = 0;
    for (int i : unnull(l)) sum += i;
    return sum;
  }

  static public BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) {
    int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };
    SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
    DataBufferInt db = new DataBufferInt(pixels, pixels.length);
    WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
    return new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);
  }

  static public int[] hexToInts_dropSpaces(String s) {
    return hexToInts(dropSpaceEtc(s));
  }

  static public String defaultThreadName_name;

  static public String defaultThreadName() {
    if (defaultThreadName_name == null)
      defaultThreadName_name = "A thread by " + programID();
    return defaultThreadName_name;
  }

  static public Runnable wrapAsActivity(Object r) {
    if (r == null)
      return null;
    Runnable r2 = toRunnable(r);
    Object mod = dm_current_generic();
    if (mod == null)
      return r2;
    return new Runnable() {

      public void run() {
        try {
          AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
          AutoCloseable __1 = c;
          try {
            r2.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "AutoCloseable c =  (AutoCloseable) (rcall enter(mod));\r\n    temp c;\r\n    r2.r...";
      }
    };
  }

  static public Thread newThread(Object runnable) {
    return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
  }

  static public Thread newThread(Object runnable, String name) {
    if (name == null)
      name = defaultThreadName();
    return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name);
  }

  static public Thread newThread(String name, Object runnable) {
    return newThread(runnable, name);
  }

  static public Runnable toRunnable(final Object o) {
    if (o instanceof Runnable)
      return (Runnable) o;
    return new Runnable() {

      public void run() {
        try {
          callF(o);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(o)";
      }
    };
  }

  static public Map<Thread, Boolean> _registerThread_threads;

  static public Object _onRegisterThread;

  static public Thread _registerThread(Thread t) {
    if (_registerThread_threads == null)
      _registerThread_threads = newWeakHashMap();
    _registerThread_threads.put(t, true);
    vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
    callF(_onRegisterThread, t);
    return t;
  }

  static public void _registerThread() {
    _registerThread(Thread.currentThread());
  }

  static public void stepAllWithTimeout(double timeout, Steppable s) {
    if (s == null)
      return;
    long endTime = sysNow() + toMS(timeout);
    do {
      ping();
    } while (s.step() && sysNow() < endTime);
  }

  static public File appendToFileBaseName(File f, String s) {
    return appendToFileNameBeforeExtension(f, s);
  }

  static public List<CriticalAction> beginCriticalAction_inFlight = synchroList();

  static public class CriticalAction {

    public String description;

    public CriticalAction() {
    }

    public CriticalAction(String description) {
      this.description = description;
    }

    public void done() {
      beginCriticalAction_inFlight.remove(this);
    }
  }

  static public CriticalAction beginCriticalAction(String description) {
    ping();
    CriticalAction c = new CriticalAction(description);
    beginCriticalAction_inFlight.add(c);
    return c;
  }

  static public void cleanMeUp_beginCriticalAction() {
    int n = 0;
    while (nempty(beginCriticalAction_inFlight)) {
      int m = l(beginCriticalAction_inFlight);
      if (m != n) {
        n = m;
        try {
          print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
        } catch (Throwable __e) {
          printStackTrace(__e);
        }
      }
      sleepInCleanUp(10);
    }
  }

  static public String fileExtension(File f) {
    if (f == null)
      return null;
    return fileExtension(f.getName());
  }

  static public String fileExtension(String s) {
    return substring(s, smartLastIndexOf(s, '.'));
  }

  static public String dropSuffixIC(String suffix, String s) {
    return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  static public String addPrefixOptIfNempty(String prefix, String s) {
    return addPrefixIfNotEmpty2(prefix, s);
  }

  static public AutoCloseable dm_registerAs_directLink(String... msgs) {
    Object mod = dm_current_mandatory_generic();
    return combineAutoCloseables(map(msgs, msg -> dm_vmBus_answerToMessage(msg, fConst(mod))));
  }

  static public void dm_reloadMe() {
    dm_reloadModule(dm_currentModule());
  }

  static public void dm_ownTimer(Object resource, Object closerHelper) {
    call(dm_current_generic(), "ownTimer", resource, closerHelper);
  }

  static public <A> A dm_ownTimer(A resource) {
    call(dm_current_generic(), "ownTimer", resource);
    return resource;
  }

  static public <A> void dm_ownTimer(IVF1<A> closerHelper, A resource) {
    dm_ownTimer(resource, closerHelper);
  }

  static public FixedRateTimer doEvery(long delay, final Object r) {
    return doEvery(delay, delay, r);
  }

  static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
    return vmBus_timerStarted(timer);
  }

  static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
  }

  static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), r);
  }

  static public F0<AutoCloseable> dm_rEnter() {
    return dm_rEnter(dm_current());
  }

  static public F0<AutoCloseable> dm_rEnter(DynModule mod) {
    return mod == null ? null : new F0<AutoCloseable>() {

      public AutoCloseable get() {
        try {
          return mod.enter();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret mod.enter();";
      }
    };
  }

  static public Runnable dm_rEnter(Runnable r) {
    return dm_rEnter(dm_current(), r);
  }

  static public Runnable dm_rEnter(DynModule mod, Runnable r) {
    return mod == null || r == null ? r : new Runnable() {

      public void run() {
        try {
          AutoCloseable __1 = mod.enter();
          try {
            r.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp mod.enter(); r.run();";
      }
    };
  }

  static public <A> A dm_callOSOpt(String functionName, Object... args) {
    return (A) callOpt(dm_os(), functionName, args);
  }

  static public List map(Iterable l, Object f) {
    return map(f, l);
  }

  static public List map(Object f, Iterable l) {
    List x = emptyList(l);
    if (l != null)
      for (Object o : l) {
        ping();
        x.add(callF(f, o));
      }
    return x;
  }

  static public <A, B> List<B> map(Iterable<A> l, F1<A, B> f) {
    return map(f, l);
  }

  static public <A, B> List<B> map(F1<A, B> f, Iterable<A> l) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(callF(f, o));
      }
    return x;
  }

  static public <A, B> List<B> map(IF1<A, B> f, Iterable<A> l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(Iterable<A> l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public <A, B> List<B> map(IF1<A, B> f, A[] l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(A[] l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public List map(Object f, Object[] l) {
    return map(f, asList(l));
  }

  static public List map(Object[] l, Object f) {
    return map(f, l);
  }

  static public List map(Object f, Map map) {
    return map(map, f);
  }

  static public List map(Map map, Object f) {
    List x = new ArrayList();
    if (map != null)
      for (Object _e : map.entrySet()) {
        ping();
        Map.Entry e = (Map.Entry) _e;
        x.add(callF(f, e.getKey(), e.getValue()));
      }
    return x;
  }

  static public <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
    return map(map, (Object) f);
  }

  static public <A, B> List<A> map(IF1<A, B> f, A data1, A... moreData) {
    List x = emptyList(l(moreData) + 1);
    x.add(f.get(data1));
    if (moreData != null)
      for (A o : moreData) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public Rect screenBounds(GraphicsDevice screen) {
    return screen == null ? null : toRect(screen.getDefaultConfiguration().getBounds());
  }

  static public Rect screenBounds(int iScreen) {
    return screenBounds(get(screenDevices(), iScreen));
  }

  static public List<GraphicsDevice> screenDevices() {
    return asList(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
  }

  static public boolean ping() {
    return ping(pingSource());
  }

  static public boolean ping(PingSource source) {
    ping_v3(source);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    return ping();
  }

  static volatile public boolean ping_pauseAll = false;

  static public double toDouble(Object o) {
    if (o instanceof Number)
      return ((Number) o).doubleValue();
    if (o instanceof BigInteger)
      return ((BigInteger) o).doubleValue();
    if (o instanceof String)
      return parseDouble((String) o);
    if (o == null)
      return 0.0;
    throw fail(o);
  }

  static public <A> OKOrError<A> OKOrError_ok(A a) {
    return new OKOrError(a);
  }

  static public OKOrError OKOrError_error(Throwable e) {
    return new OKOrError(false, e);
  }

  static public IF0 runnableToIF0(Runnable r) {
    return r == null ? null : () -> {
      r.run();
      return null;
    };
  }

  static public boolean shootScreen_useScrot = false;

  static public BufferedImage shootScreen2() {
    return shootScreen2(screenRectangle());
  }

  static public BufferedImage shootScreen2(Rectangle area) {
    try {
      ping();
      if (shootScreen_useScrot && eq(area, screenRectangle())) {
        if (!isOnPATH("scrot"))
          shootScreen2_fallback();
        if (shootScreen_useScrot) {
          String filename = "screenshot-" + randomID(12) + ".png";
          File f = linux_fileInRamDisk(filename);
          if (f == null)
            f = prepareProgramFile(filename);
          try {
            String cmd = "scrot " + bashQuote(f);
            String out = backtick(cmd);
            if (f.exists())
              return loadPNG(f);
            shootScreen2_fallback();
          } catch (Throwable e) {
            print(e);
            shootScreen2_fallback();
          } finally {
            f.delete();
          }
        }
      }
      return new Robot().createScreenCapture(area);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage shootScreen2(Rect area) {
    return shootScreen2(area.getRectangle());
  }

  static public BufferedImage shootScreen2(int x, int y, int w, int h) {
    return shootScreen2(new Rectangle(x, y, w, h));
  }

  static public void shootScreen2_fallback() {
    if (shootScreen_useScrot) {
      if (isLinux())
        print("Scrot failed. Reverting to internal screenshots.");
      shootScreen_useScrot = false;
    }
  }

  static public double nanoSecondsToSeconds(double nanos) {
    return nanos * 1e-9;
  }

  static public int heightForWidth(int w, int h, int newWidth) {
    return iround(newWidth * doubleRatio(h, w));
  }

  static public int heightForWidth(BufferedImage img, int newWidth) {
    return heightForWidth(img.getWidth(), img.getHeight(), newWidth);
  }

  static public int heightForWidth(int newWidth, BufferedImage img) {
    return heightForWidth(img, newWidth);
  }

  static public int max(int a, int b) {
    return Math.max(a, b);
  }

  static public int max(int a, int b, int c) {
    return max(max(a, b), c);
  }

  static public long max(int a, long b) {
    return Math.max((long) a, b);
  }

  static public long max(long a, long b) {
    return Math.max(a, b);
  }

  static public double max(int a, double b) {
    return Math.max((double) a, b);
  }

  static public float max(float a, float b) {
    return Math.max(a, b);
  }

  static public double max(double a, double b) {
    return Math.max(a, b);
  }

  static public int max(Collection<Integer> c) {
    int x = Integer.MIN_VALUE;
    for (int i : c) x = max(x, i);
    return x;
  }

  static public double max(double[] c) {
    if (c.length == 0)
      return Double.MIN_VALUE;
    double x = c[0];
    for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
    return x;
  }

  static public float max(float[] c) {
    if (c.length == 0)
      return Float.MAX_VALUE;
    float x = c[0];
    for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
    return x;
  }

  static public byte max(byte[] c) {
    byte x = -128;
    for (byte d : c) if (d > x)
      x = d;
    return x;
  }

  static public short max(short[] c) {
    short x = -0x8000;
    for (short d : c) if (d > x)
      x = d;
    return x;
  }

  static public int max(int[] c) {
    int x = Integer.MIN_VALUE;
    for (int d : c) if (d > x)
      x = d;
    return x;
  }

  static public int brightnessToRGBA(int brightness) {
    return 0xFF000000 | clamp(brightness, 0, 255) * 0x010101;
  }

  static public BufferedImage bufferedImage(int w, int h) {
    return newBufferedImage(w, h);
  }

  static public BufferedImage bufferedImage(int w, int h, RGB rgb) {
    return newBufferedImage(w, h, rgb);
  }

  static public BufferedImage bufferedImage(int w, int h, Color color) {
    return newBufferedImage(w, h, color);
  }

  static public BufferedImage bufferedImage(Pt p, Color color) {
    return newBufferedImage(p, color);
  }

  static public BufferedImage bufferedImage(int w, int h, int[] pixels) {
    return intArrayToBufferedImage(pixels, w, h);
  }

  static public int bwIntegralImage_sumRect(BWIntegralImage img, int x1, int y1, int x2, int y2) {
    int bottomLeft = img.getIIValue(x1 - 1, y2 - 1);
    int bottomRight = img.getIIValue(x2 - 1, y2 - 1);
    int topLeft = img.getIIValue(x1 - 1, y1 - 1);
    int topRight = img.getIIValue(x2 - 1, y1 - 1);
    return bottomRight + topLeft - topRight - bottomLeft;
  }

  static public int bwIntegralImage_sumRect(IBWIntegralImage img, int x1, int y1, int x2, int y2) {
    int bottomLeft = img.getIIValue(x1 - 1, y2 - 1);
    int bottomRight = img.getIIValue(x2 - 1, y2 - 1);
    int topLeft = img.getIIValue(x1 - 1, y1 - 1);
    int topRight = img.getIIValue(x2 - 1, y1 - 1);
    return bottomRight + topLeft - topRight - bottomLeft;
  }

  static volatile public boolean sleep_noSleep = false;

  static public void sleep(long ms) {
    ping();
    if (ms < 0)
      return;
    if (isAWTThread() && ms > 100)
      throw fail("Should not sleep on AWT thread");
    try {
      Thread.sleep(ms);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static public void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public long round(double d) {
    return Math.round(d);
  }

  static public String round(String s) {
    return roundBracket(s);
  }

  static public Complex round(Complex c) {
    return new Complex(round(c.re), round(c.im));
  }

  static public <A, B> String formatColonProperties(Map<A, B> map) {
    return mapToLines(__38 -> joinPairWithColon(__38), mapToPairs(map));
  }

  static public <A, B> String formatColonProperties(List<Pair<A, B>> l) {
    return mapToLines(__39 -> joinPairWithColon(__39), l);
  }

  static public <A, B> String formatColonProperties(Object... params) {
    return formatColonProperties(paramsToPairs(params));
  }

  static public <A, B> List<Pair<A, B>> nonNullPairs(Iterable<Pair<A, B>> l) {
    return filter(l, p -> p != null && p.a != null && p.b != null);
  }

  static public <A> List<Pair<A, A>> paramsToPairs(A... params) {
    if (l(params) == 1 && params[0] instanceof Map)
      return mapToPairs((Map) params[0]);
    List<Pair<A, A>> l = emptyList(l(params) / 2);
    for (int i = 0; i + 1 < l(params); i += 2) l.add(pair(params[i], params[i + 1]));
    return l;
  }

  static public String formatDouble1(double d) {
    return formatDouble(d, 1);
  }

  static public double doublePercentRatio(double x, double y) {
    return doubleRatio(x, y) * 100;
  }

  static public double doublePercentRatio(Seconds x, Seconds y) {
    return doublePercentRatio(x.get(), y.get());
  }

  static public JSplitPane jhsplit(Component l, Component r) {
    return jhsplit(l, r, 0.5);
  }

  static public JSplitPane jhsplit(Component l, Component r, double splitPoint, int delay) {
    return jhsplit(l, r, splitPoint);
  }

  static public JSplitPane jhsplit(Component l, Component r, double splitPoint) {
    return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.HORIZONTAL_SPLIT, wrap(l), wrap(r)), splitPoint);
  }

  static public JSplitPane jhsplit(double splitPoint, Component l, Component r) {
    return jhsplit(l, r, splitPoint);
  }

  static public int withBottomMargin_defaultWidth = 6;

  static public JPanel withBottomMargin(Component c) {
    return withBottomMargin(withBottomMargin_defaultWidth, c);
  }

  static public JPanel withBottomMargin(final int w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public Object[] flattenArray2(Object... a) {
    List l = new ArrayList();
    if (a != null)
      for (Object x : a) if (x instanceof Object[])
        l.addAll(asList((Object[]) x));
      else if (x instanceof Collection)
        l.addAll((Collection) x);
      else
        l.add(x);
    return asObjectArray(l);
  }

  static public JPanel smartAdd(JPanel panel, List parts) {
    for (Object o : parts) addToContainer(panel, wrapForSmartAdd(o));
    return panel;
  }

  static public JPanel smartAdd(JPanel panel, Object... parts) {
    return smartAdd(panel, asList(parts));
  }

  static public JPanel jSection(Component c) {
    return jSection("", c);
  }

  static public JPanel jSection(final String title, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
          border = BorderFactory.createTitledBorder(border, title);
          JSection panel = new JSection(c);
          panel.setBorder(border);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n    bo...";
      }
    });
  }

  static public JPanel jSection(String title) {
    return jSection(title, jpanel());
  }

  static public JPanel jSection(LiveValue<?> lv, Component c) {
    return jLiveValueSection(lv, c);
  }

  static public JPanel jpanel(LayoutManager layout) {
    return swingNu(JPanel.class, layout);
  }

  static public JPanel jpanel() {
    return swingNu(JPanel.class);
  }

  static public JLabel dm_centeredCalculatedLabel(IF0<Object> calc) {
    return centerLabel(dm_calculatedLabel(calc));
  }

  static public <A extends JLabel> A centerLabel(A l) {
    if (l != null)
      l.setHorizontalAlignment(SwingConstants.CENTER);
    return l;
  }

  static public JLabel dm_fieldLabel(String fieldName) {
    return jLiveValueLabel(dm_fieldLiveValue(fieldName));
  }

  static public JScrollPane jscroll_centered(Component c) {
    return jscroll(jFullCenter(c));
  }

  static public ImageSurface doubleBufferedImageSurface() {
    ImageSurface is = imageSurface();
    setDoubleBuffered(is, true);
    return is;
  }

  static public JComponent dm_getVisualization(Object module) {
    return (JComponent) callOpt(dm_getStem(module), "vis");
  }

  static public JComponent dm_getVisualization() {
    return dm_getVisualization(dm_current_mandatory_generic());
  }

  static public <A> List<A> childrenOfType(Component c, Class<A> theClass) {
    List<A> l = new ArrayList();
    scanForComponents(c, theClass, l);
    return l;
  }

  static public <A> List<A> childrenOfType(Class<A> theClass, Component c) {
    return childrenOfType(c, theClass);
  }

  static public JFrame getFrame(final Object _o) {
    return swing(new F0<JFrame>() {

      public JFrame get() {
        try {
          Object o = _o;
          if (o instanceof ButtonGroup)
            o = first(buttonsInGroup((ButtonGroup) o));
          if (!(o instanceof Component))
            return null;
          Component c = (Component) o;
          while (c != null) {
            if (c instanceof JFrame)
              return (JFrame) c;
            c = c.getParent();
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
      }
    });
  }

  static public <A> A childOfType(Component c, Class<A> theClass) {
    return first(childrenOfType(c, theClass));
  }

  static public <A> A childOfType(Class<A> theClass, Component c) {
    return childOfType(c, theClass);
  }

  static public <A extends Component> A revalidate(final A c) {
    if (c == null || !c.isShowing())
      return c;
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.revalidate();
            c.repaint();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "// magic combo to actually relayout and repaint\r\n    c.revalidate();\r\n    c.r...";
        }
      });
    }
    return c;
  }

  static public void revalidate(JFrame f) {
    revalidate((Component) f);
  }

  static public void revalidate(JInternalFrame f) {
    revalidate((Component) f);
  }

  static public Object dm_callOS(String functionName, Object... args) {
    return call(dm_os(), functionName, args);
  }

  static public Object dm_current_generic_mandatory() {
    return dm_current_mandatory_generic();
  }

  static public void addActionListener(JTextField tf, final Runnable action) {
    onEnter(tf, action);
  }

  static public void addActionListener(final JComboBox cb, final Runnable action) {
    if (cb != null) {
      swing(new Runnable() {

        public void run() {
          try {
            cb.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "cb.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public void addActionListener(final AbstractButton b, final Runnable action) {
    if (b != null) {
      swing(new Runnable() {

        public void run() {
          try {
            b.addActionListener(actionListener(action));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addActionListener(actionListener(action));";
        }
      });
    }
  }

  static public boolean isChecked(JCheckBox checkBox) {
    return checkBox != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return checkBox.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret checkBox.isSelected();";
      }
    });
  }

  static public boolean isChecked(JCheckBoxMenuItem mi) {
    return mi != null && (boolean) swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return mi.isSelected();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret mi.isSelected();";
      }
    });
  }

  static public boolean isChecked(JRadioButton rb) {
    return rb != null && (boolean) swing(() -> rb.isSelected());
  }

  static public Boolean dm_getFlag(String flagName) {
    Object mod = dm_current_generic();
    Object stem = dm_stem(mod);
    Integer flagCode = (Integer) (getOpt(flagName, stem));
    return flagCode == null ? null : (Boolean) call(stem, "hasFlag", flagCode);
  }

  static public boolean dm_setFlag(String flagName) {
    return dm_setFlag(flagName, true);
  }

  static public boolean dm_setFlag(String flagName, boolean value) {
    Object mod = dm_current_generic();
    Object stem = dm_stem(mod);
    Integer flagCode = (Integer) (getOpt("flagName", stem));
    if (flagCode == null)
      return false;
    call(stem, value ? "setFlag" : "clearFlag", flagCode);
    return true;
  }

  static public <A extends Component> A alwaysOnTop(A c) {
    return alwaysOnTop(c, true);
  }

  static public <A extends Component> A alwaysOnTop(A c, boolean on) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            Window w = getWindow(c);
            if (w != null && w.isAlwaysOnTop() != on)
              w.setAlwaysOnTop(on);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Window w = getWindow(c);\r\n    if (w != null && w.isAlwaysOnTop() != on)\r\n    ...";
        }
      });
    }
    return c;
  }

  static public Window dm_windowIfSingleModule(Object module) {
    Window w = dm_window(module);
    return w == null || w != getWindow(dm_desktopPane()) ? w : null;
  }

  static public Class __javax;

  static public Class getJavaX() {
    try {
      return __javax;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void __setJavaX(Class j) {
    __javax = j;
    _onJavaXSet();
  }

  static public ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

  static public AutoCloseable holdInstance(Object o) {
    if (o == null)
      return null;
    listThreadLocalAdd(holdInstance_l, o);
    return new AutoCloseable() {

      public void close() {
        listThreadLocalPopLast(holdInstance_l);
      }
    };
  }

  static public ThreadLocal<Object> print_byThread() {
    synchronized (print_byThread_lock) {
      if (print_byThread == null)
        print_byThread = new ThreadLocal();
    }
    return print_byThread;
  }

  static public AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
    return tempSetThreadLocal(print_byThread(), f);
  }

  static public <A, B> Map<A, B> weakHashMap() {
    return newWeakHashMap();
  }

  static public <A, B> List<A> keysList(Map<A, B> map) {
    return cloneListSynchronizingOn(keys(map), map);
  }

  static public <A> List<A> keysList(MultiSet<A> ms) {
    return ms == null ? null : keysList(ms.map);
  }

  static public Object defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        Class c = get2(name);
        return c;
      }

      public Class get2(String name) {
        if (eq(name, "<main>"))
          return mc();
        {
          Class c = findClass_fullName(name);
          if (c != null)
            return c;
        }
        if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
          for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
            String newName = pkg + afterDollar(name);
            {
              Class c = findClass_fullName(newName);
              if (c != null)
                return c;
            }
          }
        return null;
      }
    };
  }

  static public String programIDWithCase() {
    return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
  }

  static public byte[] hexToBytes(String s) {
    if (odd(l(s)))
      throw fail("Hex string has odd length: " + quote(shorten(10, s)));
    int n = l(s) / 2;
    byte[] bytes = new byte[n];
    for (int i = 0; i < n; i++) {
      int a = parseHexChar(s.charAt(i * 2));
      int b = parseHexChar(s.charAt(i * 2 + 1));
      if (a < 0 || b < 0)
        throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
      bytes[i] = (byte) ((a << 4) | b);
    }
    return bytes;
  }

  static public Object first(Object list) {
    return first((Iterable) list);
  }

  static public <A> A first(List<A> list) {
    return empty(list) ? null : list.get(0);
  }

  static public <A> A first(A[] bla) {
    return bla == null || bla.length == 0 ? null : bla[0];
  }

  static public <A, B> Pair<A, B> first(Map<A, B> map) {
    return mapEntryToPair(first(entrySet(map)));
  }

  static public <A, B> Pair<A, B> first(MultiMap<A, B> mm) {
    if (mm == null)
      return null;
    var e = first(mm.data.entrySet());
    if (e == null)
      return null;
    return pair(e.getKey(), first(e.getValue()));
  }

  static public <A> A first(IterableIterator<A> i) {
    return first((Iterator<A>) i);
  }

  static public <A> A first(Iterator<A> i) {
    return i == null || !i.hasNext() ? null : i.next();
  }

  static public <A> A first(Iterable<A> i) {
    if (i == null)
      return null;
    Iterator<A> it = i.iterator();
    return it.hasNext() ? it.next() : null;
  }

  static public Character first(String s) {
    return empty(s) ? null : s.charAt(0);
  }

  static public Character first(CharSequence s) {
    return empty(s) ? null : s.charAt(0);
  }

  static public <A, B> A first(Pair<A, B> p) {
    return p == null ? null : p.a;
  }

  static public <A, B, C> A first(T3<A, B, C> t) {
    return t == null ? null : t.a;
  }

  static public Byte first(byte[] l) {
    return empty(l) ? null : l[0];
  }

  static public int first(IntBuffer buf) {
    return buf.get(0);
  }

  static public <A> A first(A[] l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(Iterable<A> l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(pred, l);
  }

  static public List<AbstractButton> buttonsInGroup(ButtonGroup g) {
    if (g == null)
      return ll();
    return asList(g.getElements());
  }

  static public boolean boolOptParam(ThreadLocal<Boolean> tl) {
    return isTrue(optPar(tl));
  }

  static public boolean boolOptParam(Object[] __, String name) {
    return isTrue(optParam(__, name));
  }

  static public boolean boolOptParam(String name, Object[] __) {
    return boolOptParam(__, name);
  }

  static public boolean boolOptParam(String name, Map __) {
    return isTrue(optPar(name, __));
  }

  static public <A> A optParam(ThreadLocal<A> tl, A defaultValue) {
    return optPar(tl, defaultValue);
  }

  static public <A> A optParam(ThreadLocal<A> tl) {
    return optPar(tl);
  }

  static public Object optParam(String name, Map params) {
    return mapGet(params, name);
  }

  static public <A> A optParam(Object[] opt, String name, A defaultValue) {
    int n = l(opt);
    if (n == 1 && opt[0] instanceof Map) {
      Map map = (Map) (opt[0]);
      return map.containsKey(name) ? (A) map.get(name) : defaultValue;
    }
    if (!even(l(opt)))
      throw fail("Odd parameter length");
    for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
      return (A) opt[i + 1];
    return defaultValue;
  }

  static public Object optParam(Object[] opt, String name) {
    return optParam(opt, name, null);
  }

  static public Object optParam(String name, Object[] params) {
    return optParam(params, name);
  }

  static public TimerTask timerTask(final Object r, final java.util.Timer timer) {
    return new TimerTask() {

      public void run() {
        if (!licensed())
          timer.cancel();
        else
          pcallF(r);
      }
    };
  }

  static public <A> A vmBus_timerStarted(A timer) {
    vmBus_send("timerStarted", timer, costCenter());
    return timer;
  }

  static public long toMS(double seconds) {
    return (long) (seconds * 1000);
  }

  public static long parseSnippetID(String snippetID) {
    long id = Long.parseLong(shortenSnippetID(snippetID));
    if (id == 0)
      throw fail("0 is not a snippet ID");
    return id;
  }

  static public boolean loadBufferedImage_useImageCache = true;

  static public BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
    try {
      ping();
      if (snippetIDOrURLOrFile == null)
        return null;
      if (isURL(snippetIDOrURLOrFile))
        return imageIO_readURL(snippetIDOrURLOrFile);
      if (isAbsolutePath(snippetIDOrURLOrFile))
        return loadBufferedImage(new File(snippetIDOrURLOrFile));
      if (!isSnippetID(snippetIDOrURLOrFile))
        throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
      String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return loadBufferedImage(rl.loadLibrary(snippetID));
      File dir = imageSnippetsCacheDir();
      if (loadBufferedImage_useImageCache) {
        dir.mkdirs();
        File file = new File(dir, snippetID + ".png");
        if (file.exists() && file.length() != 0)
          try {
            return ImageIO.read(file);
          } catch (Throwable e) {
            e.printStackTrace();
          }
      }
      String imageURL = snippetImageURL_http(snippetID);
      print("Loading image: " + imageURL);
      BufferedImage image = imageIO_readURL(imageURL);
      if (loadBufferedImage_useImageCache) {
        File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
        ImageIO.write(image, "png", tempFile);
        tempFile.renameTo(new File(dir, snippetID + ".png"));
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage loadBufferedImage(File file) {
    return loadBufferedImageFile(file);
  }

  static public Object[] toObjectArray(Collection c) {
    return toObjectArray((Iterable) c);
  }

  static public Object[] toObjectArray(Iterable c) {
    List l = asList(c);
    return l.toArray(new Object[l.size()]);
  }

  static public String[] drop(int n, String[] a) {
    n = Math.min(n, a.length);
    String[] b = new String[a.length - n];
    System.arraycopy(a, n, b, 0, b.length);
    return b;
  }

  static public Object[] drop(int n, Object[] a) {
    n = Math.min(n, a.length);
    Object[] b = new Object[a.length - n];
    System.arraycopy(a, n, b, 0, b.length);
    return b;
  }

  static public <A> ArrayList<A> toList(A[] a) {
    return asList(a);
  }

  static public ArrayList<Integer> toList(int[] a) {
    return asList(a);
  }

  static public <A> ArrayList<A> toList(Set<A> s) {
    return asList(s);
  }

  static public <A> ArrayList<A> toList(Iterable<A> s) {
    return asList(s);
  }

  static public String substring(String s, int x) {
    return substring(s, x, strL(s));
  }

  static public String substring(String s, int x, int y) {
    if (s == null)
      return null;
    if (x < 0)
      x = 0;
    int n = s.length();
    if (y < x)
      y = x;
    if (y > n)
      y = n;
    if (x >= y)
      return "";
    return s.substring(x, y);
  }

  static public String substring(String s, IntRange r) {
    return r == null ? null : substring(s, r.start, r.end);
  }

  static public String substring(String s, CharSequence l) {
    return substring(s, lCharSequence(l));
  }

  static public MenuItem menuItem(String text, final Object r) {
    MenuItem mi = new MenuItem(text);
    mi.addActionListener(actionListener(r));
    return mi;
  }

  static public MouseAdapter leftClickMouseAdapter(final Object r) {
    return new MouseAdapter() {

      public void mouseClicked(MouseEvent e) {
        if (e.getButton() == 1)
          callF(r, new Pt(e.getPoint()));
      }
    };
  }

  static public MouseAdapter leftClickMouseAdapter_noPt(final Object r) {
    return new MouseAdapter() {

      public void mouseClicked(MouseEvent e) {
        if (e.getButton() == 1)
          pcallF(r);
      }
    };
  }

  static public boolean endsWithLetterOrDigit(String s) {
    return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
  }

  static public Object call_withVarargs(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findStaticMethod(method, args);
        if (me != null)
          return invokeMethod(me, null, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            {
              if (!(isStaticMethod(m)))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, null, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me != null)
          return invokeMethod(me, o, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, o, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void rotateStringBuffer(StringBuffer buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void rotateStringBuilder(StringBuilder buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

  static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) {
        ping();
        pcallF_minimalExceptionHandling(f, args);
      }
  }

  static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
    while (it.hasNext()) {
      ping();
      pcallF_minimalExceptionHandling(it.next(), args);
    }
  }

  static public Set vm_busListeners_live_cache;

  static public Set vm_busListeners_live() {
    if (vm_busListeners_live_cache == null)
      vm_busListeners_live_cache = vm_busListeners_live_load();
    return vm_busListeners_live_cache;
  }

  static public Set vm_busListeners_live_load() {
    return vm_generalIdentityHashSet("busListeners");
  }

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

  static public Map<String, Set> vm_busListenersByMessage_live() {
    if (vm_busListenersByMessage_live_cache == null)
      vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
    return vm_busListenersByMessage_live_cache;
  }

  static public Map<String, Set> vm_busListenersByMessage_live_load() {
    return vm_generalHashMap("busListenersByMessage");
  }

  static public AutoCloseable tempSet(Object o, final String field, Object value) {
    return tempSetField(o, field, value);
  }

  static public <A> boolean hasElementWithClassShortNamed(String shortName, Iterable<A> l) {
    return firstWithClassShortNamed(shortName, l) != null;
  }

  static public <A> boolean hasElementWithClassShortNamed(String shortName, A[] l) {
    return firstWithClassShortNamed(shortName, l) != null;
  }

  static public PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

  static public Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  static public boolean startsWithOneOf(String s, String... l) {
    for (String x : l) if (startsWith(s, x))
      return true;
    return false;
  }

  static public boolean startsWithOneOf(String s, Matches m, String... l) {
    for (String x : l) if (startsWith(s, x, m))
      return true;
    return false;
  }

  static public boolean isAGIBlueDomain(String domain) {
    return domainIsUnder(domain, theAGIBlueDomain());
  }

  static public String hostNameFromURL(String url) {
    try {
      return new URL(url).getHost();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ArrayList emptyList() {
    return new ArrayList();
  }

  static public ArrayList emptyList(int capacity) {
    return new ArrayList(max(0, capacity));
  }

  static public ArrayList emptyList(Iterable l) {
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
  }

  static public ArrayList emptyList(Object[] l) {
    return emptyList(l(l));
  }

  static public <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

  static public int[] emptyIntArray_a = new int[0];

  static public int[] emptyIntArray() {
    return emptyIntArray_a;
  }

  static public char[] emptyCharArray = new char[0];

  static public char[] emptyCharArray() {
    return emptyCharArray;
  }

  static public double[] emptyDoubleArray = new double[0];

  static public double[] emptyDoubleArray() {
    return emptyDoubleArray;
  }

  static public Map emptyMap() {
    return new HashMap();
  }

  static public Object[] emptyObjectArray_a = new Object[0];

  static public Object[] emptyObjectArray() {
    return emptyObjectArray_a;
  }

  static public Symbol emptySymbol_value;

  static public Symbol emptySymbol() {
    if (emptySymbol_value == null)
      emptySymbol_value = symbol("");
    return emptySymbol_value;
  }

  static public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  static public boolean empty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean empty(Iterable c) {
    return c == null || !c.iterator().hasNext();
  }

  static public boolean empty(CharSequence s) {
    return s == null || s.length() == 0;
  }

  static public boolean empty(Map map) {
    return map == null || map.isEmpty();
  }

  static public boolean empty(Object[] o) {
    return o == null || o.length == 0;
  }

  static public boolean empty(BitSet bs) {
    return bs == null || bs.isEmpty();
  }

  static public boolean empty(Object o) {
    if (o instanceof Collection)
      return empty((Collection) o);
    if (o instanceof String)
      return empty((String) o);
    if (o instanceof Map)
      return empty((Map) o);
    if (o instanceof Object[])
      return empty((Object[]) o);
    if (o instanceof byte[])
      return empty((byte[]) o);
    if (o == null)
      return true;
    throw fail("unknown type for 'empty': " + getType(o));
  }

  static public boolean empty(Iterator i) {
    return i == null || !i.hasNext();
  }

  static public boolean empty(double[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(float[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(int[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(long[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(short[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(MultiSet ms) {
    return ms == null || ms.isEmpty();
  }

  static public boolean empty(MultiMap mm) {
    return mm == null || mm.isEmpty();
  }

  static public boolean empty(File f) {
    return getFileSize(f) == 0;
  }

  static public boolean empty(IntRange r) {
    return r == null || r.empty();
  }

  static public boolean empty(DoubleRange r) {
    return r == null || r.isEmpty();
  }

  static public boolean empty(IntBuffer b) {
    return b == null || b.isEmpty();
  }

  static public boolean empty(Rect r) {
    return !(r != null && r.w != 0 && r.h != 0);
  }

  static public <A> List<A> filter(Iterable<A> c, Object pred) {
    if (pred instanceof F1)
      return filter(c, (F1<A, Boolean>) pred);
    List x = new ArrayList();
    if (c != null)
      for (Object o : c) if (isTrue(callF(pred, o)))
        x.add(o);
    return x;
  }

  static public List filter(Object pred, Iterable c) {
    return filter(c, pred);
  }

  static public <A, B extends A> List<B> filter(Iterable<B> c, F1<A, Boolean> pred) {
    List x = new ArrayList();
    if (c != null)
      for (B o : c) if (pred.get(o))
        x.add(o);
    return x;
  }

  static public <A, B extends A> List<B> filter(F1<A, Boolean> pred, Iterable<B> c) {
    return filter(c, pred);
  }

  static public <A, B extends A> List<B> filter(Iterable<B> c, IF1<A, Boolean> pred) {
    List x = new ArrayList();
    if (c != null)
      for (B o : c) if (pred.get(o))
        x.add(o);
    return x;
  }

  static public <A, B extends A> List<B> filter(B[] c, IF1<A, Boolean> pred) {
    List x = new ArrayList();
    if (c != null)
      for (B o : c) if (pred.get(o))
        x.add(o);
    return x;
  }

  static public <A, B extends A> List<B> filter(IF1<A, Boolean> pred, Iterable<B> c) {
    return filter(c, pred);
  }

  static public List<String> allMethodNames(Object o) {
    Class c = _getClass(o);
    TreeSet<String> names = new TreeSet();
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) names.add(m.getName());
      c = c.getSuperclass();
    }
    return asList(names);
  }

  static public boolean startsWith(String a, String b) {
    return a != null && a.startsWith(unnull(b));
  }

  static public boolean startsWith(String a, char c) {
    return nemptyString(a) && a.charAt(0) == c;
  }

  static public boolean startsWith(String a, String b, Matches m) {
    if (!startsWith(a, b))
      return false;
    if (m != null)
      m.m = new String[] { substring(a, strL(b)) };
    return true;
  }

  static public boolean startsWith(List a, List b) {
    if (a == null || listL(b) > listL(a))
      return false;
    for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
      return false;
    return true;
  }

  static public MultiSet<String> poorMansProfiling_results = new MultiSet();

  static public int poorMansProfiling_samples;

  static public java.util.Timer poorMansProfiling_timer;

  static public Lock poorMansProfiling_lock = lock();

  static public Thread poorMansProfiling_threadToSample;

  static public void poorMansProfiling() {
    poorMansProfiling(poorMansProfiling_defaultInterval());
  }

  static public void poorMansProfiling(Thread thread) {
    poorMansProfiling(poorMansProfiling_defaultInterval(), thread);
  }

  static public void poorMansProfiling(int interval) {
    poorMansProfiling(interval, null);
  }

  static public void poorMansProfiling(int interval, Thread thread) {
    Lock __0 = poorMansProfiling_lock;
    lock(__0);
    try {
      poorMansProfiling_threadToSample = thread;
      poorMansProfiling_stop();
      poorMansProfiling_clear();
      poorMansProfiling_timer = doEvery_daemon(interval, new Runnable() {

        public void run() {
          try {
            Map<Thread, StackTraceElement[]> map = poorMansProfiling_threadToSample != null ? litmap(poorMansProfiling_threadToSample, poorMansProfiling_threadToSample.getStackTrace()) : runnableThreadsWithStackTraces();
            Lock __1 = poorMansProfiling_lock;
            lock(__1);
            try {
              poorMansProfiling_samples++;
              for (Thread t : keys(map)) {
                {
                  if (isSystemThread(t))
                    continue;
                }
                StringBuilder buf = new StringBuilder();
                for (StackTraceElement e : map.get(t)) buf.append(e).append("\n");
                poorMansProfiling_results.add(str(buf));
              }
            } finally {
              unlock(__1);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Map<Thread, StackTraceElement[]> map =\r\n      poorMansProfiling_threadToSampl...";
        }
      });
    } finally {
      unlock(__0);
    }
  }

  static public void poorMansProfiling_stop() {
    Lock __2 = poorMansProfiling_lock;
    lock(__2);
    try {
      if (poorMansProfiling_timer != null) {
        stopTimer(poorMansProfiling_timer);
        poorMansProfiling_timer = null;
      }
    } finally {
      unlock(__2);
    }
  }

  static public void poorMansProfiling_clear() {
    Lock __3 = poorMansProfiling_lock;
    lock(__3);
    try {
      poorMansProfiling_results.clear();
      poorMansProfiling_samples = 0;
    } finally {
      unlock(__3);
    }
  }

  static public MultiSet<String> poorMansProfiling_results() {
    return new MultiSet(poorMansProfiling_results);
  }

  static public MultiSet<String> poorMansProfiling_stopAndGetResults() {
    Lock __4 = poorMansProfiling_lock;
    lock(__4);
    try {
      poorMansProfiling_stop();
      return poorMansProfiling_results();
    } finally {
      unlock(__4);
    }
  }

  static public void poorMansProfiling_stopAndPrintResults() {
    poorMansProfiling_renderFullResults_backwards.set(true);
    print(poorMansProfiling_stopAndRenderResults());
  }

  static public TimeZone localTimeZone() {
    return getTimeZone(standardTimeZone());
  }

  static public boolean isAWTThread() {
    if (isAndroid())
      return false;
    if (isHeadless())
      return false;
    return isAWTThread_awt();
  }

  static public boolean isAWTThread_awt() {
    return SwingUtilities.isEventDispatchThread();
  }

  static public Runnable addThreadInfoToRunnable(final Object r) {
    final Object info = _threadInfo();
    return info == null ? asRunnable(r) : new Runnable() {

      public void run() {
        try {
          _inheritThreadInfo(info);
          callF(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "_inheritThreadInfo(info); callF(r);";
      }
    };
  }

  static public <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
    return c;
  }

  static public JComponent componentToJComponent(Component c) {
    if (c instanceof JComponent)
      return (JComponent) c;
    if (c instanceof JFrame)
      return ((JFrame) c).getRootPane();
    if (c == null)
      return null;
    throw fail("boohoo " + getClassName(c));
  }

  static public JScrollPane jscroll(final Component c) {
    return swing(new F0<JScrollPane>() {

      public JScrollPane get() {
        try {
          return new JScrollPane(c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JScrollPane(c);";
      }
    });
  }

  static public JLabel jlabel(final String text) {
    return swingConstruct(BetterLabel.class, text);
  }

  static public JLabel jlabel() {
    return jlabel(" ");
  }

  static public Rectangle screenRectangle() {
    return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
  }

  static public Rectangle screenRectangle(GraphicsDevice device) {
    if (device == null)
      return null;
    DisplayMode mode = device.getDisplayMode();
    return new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
  }

  static public Random random_random = new Random();

  static public int random(int n) {
    return random(random_random, n);
  }

  static public int random(int n, Random r) {
    return random(r, n);
  }

  static public int random(Random r, int n) {
    return n <= 0 ? 0 : r.nextInt(n);
  }

  static public double random(double max) {
    return random() * max;
  }

  static public double random() {
    return random_random.nextInt(100001) / 100000.0;
  }

  static public double random(double min, double max) {
    return min + random() * (max - min);
  }

  static public int random(int min, int max) {
    return min + random(max - min);
  }

  static public int random(int min, int max, Random r) {
    return random(r, min, max);
  }

  static public int random(Random r, int min, int max) {
    return min + random(r, max - min);
  }

  static public <A> A random(List<A> l) {
    return oneOf(l);
  }

  static public <A> A random(Collection<A> c) {
    if (c instanceof List)
      return random((List<A>) c);
    int i = random(l(c));
    return collectionGet(c, i);
  }

  static public int random(IntRange r) {
    return random(r.start, r.end);
  }

  static public <A, B> Pair<A, B> random(Map<A, B> map) {
    return entryToPair(random(entries(map)));
  }

  static public void swingLater(long delay, final Object r) {
    javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
    timer.setRepeats(false);
    timer.start();
  }

  static public void swingLater(Object r) {
    SwingUtilities.invokeLater(toRunnable(r));
  }

  static public String shortClassName_dropNumberPrefix(Object o) {
    return dropNumberPrefix(shortClassName(o));
  }

  static public int boostHashCombine(int a, int b) {
    return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
  }

  static public int _hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public AutoCloseable tempHoldInstance(Object o) {
    return holdInstance(o);
  }

  static public Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
    return null;
  }

  static public ActionListener actionListener(final Object runnable) {
    return actionListener(runnable, null);
  }

  static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    final Object info = _threadInfo();
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          _threadInheritInfo(info);
          AutoCloseable __1 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__1);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public <A> A swingConstruct(final Class<A> c, final Object... args) {
    return swing(new F0<A>() {

      public A get() {
        try {
          return nuObject(c, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret nuObject(c, args);";
      }
    });
  }

  static public boolean isInstanceOf(Object o, Class type) {
    return type.isInstance(o);
  }

  static public RuntimeException fail() {
    throw new RuntimeException("fail");
  }

  static public RuntimeException fail(Throwable e) {
    throw asRuntimeException(e);
  }

  static public RuntimeException fail(Object msg) {
    throw new RuntimeException(String.valueOf(msg));
  }

  static public RuntimeException fail(Object... objects) {
    throw new Fail(objects);
  }

  static public RuntimeException fail(String msg) {
    throw new RuntimeException(msg == null ? "" : msg);
  }

  static public RuntimeException fail(String msg, Throwable innerException) {
    throw new RuntimeException(msg, innerException);
  }

  static public String className(Object o) {
    return getClassName(o);
  }

  static public <A extends JComponent> A setToolTipText(final A c, final Object toolTip) {
    if (c == null)
      return null;
    {
      swing(new Runnable() {

        public void run() {
          try {
            String s = nullIfEmpty(str(toolTip));
            if (neq(s, c.getToolTipText()))
              c.setToolTipText(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "String s = nullIfEmpty(str(toolTip));\r\n    if (neq(s, c.getToolTipText()))\r\n ...";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A setToolTipText(Object toolTip, A c) {
    return setToolTipText(c, toolTip);
  }

  static public String unicode_downPointingTriangle() {
    return charToString(0x25BC);
  }

  static public <A> A optPar_ignoreOddLength(Object[] opt, String name, A defaultValue) {
    int n = l(opt);
    if (n == 1 && opt[0] instanceof Map) {
      Map map = (Map) (opt[0]);
      return map.containsKey(name) ? (A) map.get(name) : defaultValue;
    }
    for (int i = 0; i + 1 < l(opt); i += 2) if (eq(opt[i], name))
      return (A) opt[i + 1];
    return defaultValue;
  }

  static public Object optPar_ignoreOddLength(Object[] opt, String name) {
    return optPar_ignoreOddLength(opt, name, null);
  }

  static public Object optPar_ignoreOddLength(String name, Object[] params) {
    return optPar_ignoreOddLength(params, name);
  }

  static public void fillJPopupMenu(JPopupMenu m, Object... x) {
    if (x == null)
      return;
    for (int i = 0; i < l(x); i++) {
      Object o = x[i], y = get(x, i + 1);
      if (o instanceof IVF1)
        callF(o, m);
      else if (o instanceof List)
        fillJPopupMenu(m, asArray((List) o));
      else if (isMenuSeparatorIndicator(o))
        m.addSeparator();
      else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
        final LiveValue<String> lv = (LiveValue<String>) o;
        final JMenuItem mi = jmenuItem("", y);
        bindLiveValueListenerToComponent(mi, lv, new Runnable() {

          public void run() {
            try {
              String s = lv.get();
              if (isCurlyBracketed(s)) {
                setEnabled(mi, false);
                s = unCurlyBracket(s);
              } else
                setEnabled(mi, true);
              setText(mi, s);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "String s = lv!;\r\n        if (isCurlyBracketed(s)) {\r\n          setEnabled(mi,...";
          }
        });
        m.add(mi);
      } else if (o instanceof String && isRunnableX(y)) {
        m.add(jmenuItem((String) o, y));
        ++i;
      } else if (o instanceof JMenuItem)
        m.add((JMenuItem) o);
      else if (o instanceof String || o instanceof Action || o instanceof Component)
        call(m, "add", o);
      else if (o != null)
        print("Unknown menu item: " + o);
    }
  }

  static public Object[] paramsWithout(Object[] a1, Object... keys) {
    if (l(a1) == 1 && a1[0] instanceof Map)
      return new Object[] { mapMinus((Map) a1[0], keys) };
    Set set = lithashset(keys);
    List l = new ArrayList();
    int n = l(a1);
    for (int i = 0; i < n; i += 2) if (i == n - 1)
      l.add(a1[i]);
    else if (!set.contains(a1[i])) {
      l.add(a1[i]);
      l.add(a1[i + 1]);
    }
    return toObjectArray(l);
  }

  static public int getPreferredWidth(Component c) {
    return preferredWidth(c);
  }

  static public String strUnnull(Object o) {
    return o == null ? "" : str(o);
  }

  static public String jlabel_textAsHTML_center_ifNeeded(String text) {
    if (swic(text, "<html>") && ewic(text, "</html>"))
      return text;
    if (!containsNewLines(text))
      return text;
    return jlabel_textAsHTML_center(text);
  }

  static public boolean neq(Object a, Object b) {
    return !eq(a, b);
  }

  static public <A extends JComponent> A withTypeWriterFont(A c) {
    return setFont(c, typeWriterFont());
  }

  static public JTextArea jTextArea() {
    return jTextArea("");
  }

  static public JTextArea jTextArea(final String text) {
    return jTextAreaWithUndo(text);
  }

  static public String programTitle() {
    return getProgramName();
  }

  static public void _initFrame(JFrame f) {
    myFrames_list.put(f, Boolean.TRUE);
    standardTitlePopupMenu(f);
  }

  static public void hideConsole() {
    final JFrame frame = consoleFrame();
    if (frame != null) {
      autoVMExit();
      swingLater(new Runnable() {

        public void run() {
          try {
            frame.setVisible(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "frame.setVisible(false);";
        }
      });
    }
  }

  static public String getProgramTitle() {
    return getProgramName();
  }

  static public String trim(String s) {
    return s == null ? null : s.trim();
  }

  static public String trim(StringBuilder buf) {
    return buf.toString().trim();
  }

  static public String trim(StringBuffer buf) {
    return buf.toString().trim();
  }

  static public Map<String, String> singular_specials = litmap("children", "child", "images", "image", "chess", "chess");

  static public Set<String> singular_specials2 = litciset("time", "machine", "line", "rule");

  static public String singular(String s) {
    if (s == null)
      return null;
    {
      String __1 = singular_specials.get(s);
      if (!empty(__1))
        return __1;
    }
    if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s))))
      return dropSuffix("s", s);
    if (s.endsWith("ness"))
      return s;
    if (s.endsWith("ges"))
      return dropSuffix("s", s);
    if (endsWith(s, "bases"))
      return dropLast(s);
    s = dropSuffix("es", s);
    s = dropSuffix("s", s);
    return s;
  }

  static public Set<String> getPlural_specials = litciset("sheep", "fish");

  static public String getPlural(String s) {
    if (contains(getPlural_specials, s))
      return s;
    if (ewic(s, "y"))
      return dropSuffixIgnoreCase("y", s) + "ies";
    if (ewicOneOf(s, "ss", "ch"))
      return s + "es";
    if (ewic(s, "s"))
      return s;
    return s + "s";
  }

  static public String asciiHeading(String title) {
    return "\n" + title + "\n" + rep(l(title), '-');
  }

  static public <A extends JLabel> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends AbstractButton> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends JTextField> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public JLabel jLabel(String text) {
    return jlabel(text);
  }

  static public JLabel jLabel() {
    return jlabel();
  }

  static public <A extends Component> A jPreferWidth(int w, A c) {
    Dimension size = c.getPreferredSize();
    c.setPreferredSize(new Dimension(w, size.height));
    return c;
  }

  static public Object swingCall(final Object o, final String method, final Object... args) {
    return swing(new F0<Object>() {

      public Object get() {
        try {
          return call(o, method, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret call(o, method, args);";
      }
    });
  }

  static public double sin(double x) {
    return Math.sin(x);
  }

  static public double pi() {
    return Math.PI;
  }

  static public ThreadLocal<Boolean> imageGraphics_antiAlias = new ThreadLocal();

  static public Graphics2D imageGraphics(BufferedImage img) {
    return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : createGraphics(img);
  }

  static public ThreadLocal<BufferedImage> currentImage_var = new ThreadLocal();

  static public BufferedImage currentImage() {
    return currentImage_var.get();
  }

  static public void currentImage(BufferedImage img) {
    currentImage_var.set(img);
  }

  static public JPanel marginPanel() {
    return jtransparent(borderLayoutPanel());
  }

  static public JLabel jimage(Image img) {
    return jImageLabel(img);
  }

  static public JLabel jimage(String imageID) {
    return jImageLabel(imageID);
  }

  static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX) {
    return scaleImage_bilinear(before, scaleX, scaleX);
  }

  static public BufferedImage scaleImage_bilinear(BufferedImage before, double scaleX, double scaleY) {
    return scaleImageWithOp(before, scaleX, scaleY, AffineTransformOp.TYPE_BILINEAR);
  }

  static public BufferedImage scaleImage_bilinear(double scale, BufferedImage before) {
    return scaleImage_bilinear(before, scale);
  }

  static public String ymd() {
    return ymd(now());
  }

  static public String ymd(long now) {
    return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2);
  }

  static public String ymd(long now, TimeZone tz) {
    return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2);
  }

  static public String hms() {
    return hms(now());
  }

  static public String hms(long time) {
    return new SimpleDateFormat("HHmmss").format(time);
  }

  static public String actualUserHome_value;

  static public String actualUserHome() {
    if (actualUserHome_value == null) {
      if (isAndroid())
        actualUserHome_value = "/storage/emulated/0/";
      else
        actualUserHome_value = System.getProperty("user.home");
    }
    return actualUserHome_value;
  }

  static public File actualUserHome(String sub) {
    return newFile(new File(actualUserHome()), sub);
  }

  static public File userDir() {
    return new File(userHome());
  }

  static public File userDir(String path) {
    return new File(userHome(), path);
  }

  static public <A> A printHidingCredentials(A o) {
    print(hideCredentials(str(o)));
    return o;
  }

  static public void logQuotedWithDate(String s) {
    logQuotedWithTime(s);
  }

  static public void logQuotedWithDate(String logFile, String s) {
    logQuotedWithTime(logFile, s);
  }

  static public void logQuotedWithDate(File logFile, String s) {
    logQuotedWithTime(logFile, s);
  }

  static public File infoBoxesLogFile() {
    return new File(javaxDataDir(), "Logs/infoBoxes.txt");
  }

  static public JWindow makeWindow(final Component c) {
    return swing(new F0<JWindow>() {

      public JWindow get() {
        try {
          JWindow w = new JWindow();
          w.add(wrap(c));
          return w;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JWindow w;\r\n    w.add(wrap(c));\r\n    ret w;";
      }
    });
  }

  static public JPanel infoMessage_makePanel(String text) {
    final JTextArea ta = wrappedTextArea(text);
    onClick(ta, new Runnable() {

      public void run() {
        try {
          disposeWindow(ta);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "disposeWindow(ta)";
      }
    });
    int size = 14;
    if (l(text) <= 50)
      size *= 2;
    else if (l(text) < 100)
      size = iround(size * 1.5);
    ta.setFont(typeWriterFont(size));
    JScrollPane sp = jscroll(ta);
    return withMargin(sp);
  }

  static public int moveToTopRightCorner_inset = 20;

  static public <A extends Component> A moveToTopRightCorner(A a) {
    return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
  }

  static public <A extends Component> A moveToTopRightCorner(int insetX, int insetY, A a) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            Window w = getWindow(a);
            if (w != null)
              w.setLocation(getScreenSize().width - w.getWidth() - insetX, insetY);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Window w = getWindow(a);\r\n    if (w != null)\r\n      w.setLocation(getScreenSi...";
        }
      });
    }
    return a;
  }

  static public boolean vmBus_noObjections(String msg, Object... args) {
    return !vmBus_anyFalse(msg, args);
  }

  static public <A extends Window> A disposeWindowAfter(int delay, final A w) {
    if (w != null)
      swingLater(delay, new Runnable() {

        public void run() {
          try {
            w.dispose();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "w.dispose();";
        }
      });
    return w;
  }

  static public <A extends Window> A disposeWindowAfter(A w, double seconds) {
    return disposeWindowAfter(toMS_int(seconds), w);
  }

  static public <A extends Window> A disposeWindowAfter(double seconds, A w) {
    return disposeWindowAfter(w, seconds);
  }

  static public String getComputerID_quick() {
    return computerID();
  }

  static public void _registerIO(Object object, String path, boolean opened) {
  }

  static public int roundDownTo(int n, int x) {
    return x / n * n;
  }

  static public long roundDownTo(long n, long x) {
    return x / n * n;
  }

  static public long fileSize(String path) {
    return getFileSize(path);
  }

  static public long fileSize(File f) {
    return getFileSize(f);
  }

  static public byte[] loadBinaryFilePart(File file, long start, long end) {
    try {
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      int n = toInt(min(raf.length(), end - start));
      byte[] buffer = new byte[n];
      try {
        raf.seek(start);
        raf.readFully(buffer, 0, n);
        return buffer;
      } finally {
        raf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String formatWithThousands(long l) {
    return formatWithThousandsSeparator(l);
  }

  static public double fraction(double d) {
    return d % 1;
  }

  static public String n_fancy2(long l, String singular, String plural) {
    return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
  }

  static public String n_fancy2(Collection l, String singular, String plural) {
    return n_fancy2(l(l), singular, plural);
  }

  static public String n_fancy2(Map m, String singular, String plural) {
    return n_fancy2(l(m), singular, plural);
  }

  static public String n_fancy2(Object[] a, String singular, String plural) {
    return n_fancy2(l(a), singular, plural);
  }

  static public String n_fancy2(MultiSet ms, String singular, String plural) {
    return n_fancy2(l(ms), singular, plural);
  }

  static public List<String> classNamesInJarOrDir(File dir) {
    List<String> classes = new ArrayList();
    if (dir.isDirectory()) {
      for (File f : listFiles(dir)) {
        String s = f.getName();
        if (s.endsWith(".class"))
          classes.add(dropSuffix(".class", s));
      }
    } else if (dir.isFile()) {
      try {
        JarFile jarFile = new JarFile(dir);
        try {
          Enumeration<JarEntry> e = jarFile.entries();
          while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            if (je.isDirectory() || !je.getName().endsWith(".class"))
              continue;
            String className = dropSuffix(".class", je.getName());
            className = className.replace('/', '.');
            classes.add(className);
          }
        } finally {
          jarFile.close();
        }
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
    return classes;
  }

  static public File parentFile(File f) {
    return dirOfFile(f);
  }

  static public boolean containsUnsafePlatformCmdLineChar(String s) {
    return containsRegexp(s, "[\\|&;<>()\\$`\\\\\"' \t\r\n\\*\\?\\[#~=%]");
  }

  static public String platformQuote(String s) {
    return isWindows() ? winQuote(s) : bashQuote(s);
  }

  static public String platformQuote(File f) {
    return platformQuote(f2s(f));
  }

  static public <A> List<A> takeFirst(List<A> l, int n) {
    return l(l) <= n ? l : newSubListOrSame(l, 0, n);
  }

  static public <A> List<A> takeFirst(int n, List<A> l) {
    return takeFirst(l, n);
  }

  static public String takeFirst(int n, String s) {
    return substring(s, 0, n);
  }

  static public String takeFirst(String s, int n) {
    return substring(s, 0, n);
  }

  static public CharSequence takeFirst(int n, CharSequence s) {
    return subCharSequence(s, 0, n);
  }

  static public <A> List<A> takeFirst(int n, Iterator<A> it) {
    if (it == null)
      return null;
    List l = new ArrayList();
    for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
      if (it.hasNext())
        l.add(it.next());
      else
        break;
    }
    return l;
  }

  static public <A> List<A> takeFirst(int n, Iterable<A> i) {
    if (i == null)
      return null;
    return i == null ? null : takeFirst(n, i.iterator());
  }

  static public <A> List<A> takeFirst(int n, IterableIterator<A> i) {
    return takeFirst(n, (Iterator<A>) i);
  }

  static public int[] takeFirst(int n, int[] a) {
    return takeFirstOfIntArray(n, a);
  }

  static public short[] takeFirst(int n, short[] a) {
    return takeFirstOfShortArray(n, a);
  }

  static public byte[] takeFirst(int n, byte[] a) {
    return takeFirstOfByteArray(n, a);
  }

  static public byte[] takeFirst(byte[] a, int n) {
    return takeFirstOfByteArray(n, a);
  }

  static public double[] takeFirst(int n, double[] a) {
    return takeFirstOfDoubleArray(n, a);
  }

  static public double[] takeFirst(double[] a, int n) {
    return takeFirstOfDoubleArray(n, a);
  }

  static public <A> A printStructure(String prefix, A o) {
    if (endsWithLetter(prefix))
      prefix += ": ";
    print(prefix + structureForUser(o));
    return o;
  }

  static public <A> A printStructure(A o) {
    print(structureForUser(o));
    return o;
  }

  static public <A> boolean addToCollection(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  static public Dimension getScreenSize() {
    return Toolkit.getDefaultToolkit().getScreenSize();
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        vmBus_send("locking", lock, "thread", currentThread());
        lock.lockInterruptibly();
        vmBus_send("locked", lock, "thread", currentThread());
      } catch (InterruptedException e) {
        Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
        print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
        printStackTrace(e);
        rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void lock(Lock lock, String msg) {
    print("Locking: " + msg);
    lock(lock);
  }

  static public void lock(Lock lock, String msg, long timeout) {
    print("Locking: " + msg);
    lockOrFail(lock, timeout);
  }

  static public ReentrantLock lock() {
    return fairLock();
  }

  static public String fsI(String id) {
    return formatSnippetID(id);
  }

  static public String fsI(long id) {
    return formatSnippetID(id);
  }

  static public File loadBinarySnippet(String snippetID) {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.loadLibrary(snippetID);
    return loadBinarySnippet_noResourceLoader(snippetID);
  }

  static public File loadBinarySnippet_noResourceLoader(String snippetID) {
    try {
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile_noResourceLoader(snippetID);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean loadBufferedImageFixingGIFs_debug = false;

  static public ThreadLocal<Var<byte[]>> loadBufferedImageFixingGIFs_output = new ThreadLocal();

  static public Image loadBufferedImageFixingGIFs(File file) {
    try {
      if (!file.exists())
        return null;
      if (!isGIF(file))
        return ImageIO.read(file);
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": checking gif");
      ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
      reader.setInput(ImageIO.createImageInputStream(file));
      int numImages = reader.getNumImages(true);
      IIOMetadata imageMetaData = reader.getImageMetadata(0);
      String metaFormatName = imageMetaData.getNativeMetadataFormatName();
      boolean foundBug = false;
      for (int i = 0; i < numImages && !foundBug; i++) {
        IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
        int nNodes = root.getLength();
        for (int j = 0; j < nNodes; j++) {
          org.w3c.dom.Node node = root.item(j);
          if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
            String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
            if (Integer.parseInt(delay) == 0) {
              foundBug = true;
            }
            break;
          }
        }
      }
      if (loadBufferedImageFixingGIFs_debug)
        print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
      Image image;
      if (!foundBug) {
        image = Toolkit.getDefaultToolkit().createImage(f2s(file));
      } else {
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        {
          ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
          try {
            ImageWriter writer = ImageIO.getImageWriter(reader);
            writer.setOutput(ios);
            writer.prepareWriteSequence(null);
            for (int i = 0; i < numImages; i++) {
              BufferedImage frameIn = reader.read(i);
              IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
              int nNodes = root.getLength();
              for (int j = 0; j < nNodes; j++) {
                org.w3c.dom.Node node = root.item(j);
                if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
                  String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
                  if (Integer.parseInt(delay) == 0) {
                    ((IIOMetadataNode) node).setAttribute("delayTime", "10");
                  }
                  break;
                }
              }
              IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
              metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
              IIOImage frameOut = new IIOImage(frameIn, null, metadata);
              writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
            }
            writer.endWriteSequence();
          } finally {
            _close(ios);
          }
        }
        byte[] data = baoStream.toByteArray();
        setVar(loadBufferedImageFixingGIFs_output.get(), data);
        if (loadBufferedImageFixingGIFs_debug)
          print("Data size: " + l(data));
        image = Toolkit.getDefaultToolkit().createImage(data);
      }
      return image;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
    print("Unlocked: " + msg);
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
  }

  static public String repeat(char c, int n) {
    n = Math.max(n, 0);
    char[] chars = new char[n];
    for (int i = 0; i < n; i++) chars[i] = c;
    return new String(chars);
  }

  static public <A> List<A> repeat(A a, int n) {
    n = Math.max(n, 0);
    List<A> l = new ArrayList(n);
    for (int i = 0; i < n; i++) l.add(a);
    return l;
  }

  static public <A> List<A> repeat(int n, A a) {
    return repeat(a, n);
  }

  static public int toInt(Object o) {
    if (o == null)
      return 0;
    if (o instanceof Number)
      return ((Number) o).intValue();
    if (o instanceof String)
      return parseInt((String) o);
    if (o instanceof Boolean)
      return boolToInt((Boolean) o);
    throw fail("woot not int: " + getClassName(o));
  }

  static public int toInt(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public int[] hexToInts(String s) {
    if (odd(l(s)))
      throw fail("Hex string has odd length: " + quote(shorten(10, s)));
    int n = l(s) / 8;
    int[] ints = new int[n];
    for (int i = 0; i < n; i++) {
      int value = 0;
      for (int j = 0; j < 4; j++) {
        int idx = i * 8 + j * 2;
        int a = parseHexChar(s.charAt(idx));
        int b = parseHexChar(s.charAt(idx + 1));
        if (a < 0 || b < 0)
          throw fail("Bad hex byte: " + quote(substring(s, idx, idx + 2)) + " at " + idx + "/" + l(s));
        value |= ((a << 4) | b) << (j * 8);
      }
      ints[i] = value;
    }
    return ints;
  }

  static public String dropSpaceEtc(String s) {
    if (empty(s))
      return null;
    int n = l(s), i = 0;
    char c = s.charAt(i);
    boolean totality = !isSpaceEtc(c);
    for (++i; i < n; i++) {
      c = s.charAt(i);
      boolean b = !isSpaceEtc(c);
      if (b != totality) {
        StringBuilder buf = new StringBuilder();
        if (totality)
          buf.append(substring(s, 0, i));
        while (true) {
          ping();
          if (b)
            buf.append(c);
          if (++i >= n)
            break;
          c = s.charAt(i);
          b = !isSpaceEtc(c);
        }
        return buf.toString();
      }
    }
    return totality ? s : "";
  }

  static public String programID() {
    return getProgramID();
  }

  static public String programID(Object o) {
    return getProgramID(o);
  }

  static public Object rcall(String method, Object o, Object... args) {
    return call_withVarargs(o, method, args);
  }

  static public Runnable _topLevelErrorHandling(Runnable r) {
    if (r == null)
      return null;
    Object info = _threadInfo();
    Object mod = dm_current_generic();
    if (info == null && mod == null)
      return r;
    return new Runnable() {

      public void run() {
        try {
          AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod));
          try {
            _threadInheritInfo(info);
            r.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp (AutoCloseable) rcall enter(mod);\r\n    _threadInheritInfo(info);\r\n    r....";
      }
    };
  }

  static public <A> WeakReference<A> weakRef(A a) {
    return newWeakReference(a);
  }

  static public <A> List<A> synchroList() {
    return synchroList(new ArrayList<A>());
  }

  static public <A> List<A> synchroList(List<A> l) {
    return Collections.synchronizedList(l);
  }

  public static <A> String join(String glue, Iterable<A> strings) {
    if (strings == null)
      return "";
    if (strings instanceof Collection) {
      if (((Collection) strings).size() == 1)
        return str(first((Collection) strings));
    }
    StringBuilder buf = new StringBuilder();
    Iterator<A> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext()) buf.append(glue).append(i.next());
    }
    return buf.toString();
  }

  public static String join(String glue, String... strings) {
    return join(glue, Arrays.asList(strings));
  }

  public static String join(String glue, Object... strings) {
    return join(glue, Arrays.asList(strings));
  }

  static public <A> String join(Iterable<A> strings) {
    return join("", strings);
  }

  static public <A> String join(Iterable<A> strings, String glue) {
    return join(glue, strings);
  }

  public static String join(String[] strings) {
    return join("", strings);
  }

  static public String join(String glue, Pair p) {
    return p == null ? "" : str(p.a) + glue + str(p.b);
  }

  static public List collect(Iterable c, String field) {
    return collectField(c, field);
  }

  static public List collect(String field, Iterable c) {
    return collectField(c, field);
  }

  static public void sleepInCleanUp(long ms) {
    try {
      if (ms < 0)
        return;
      Thread.sleep(ms);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int smartLastIndexOf(String s, char c) {
    if (s == null)
      return 0;
    int i = s.lastIndexOf(c);
    return i >= 0 ? i : l(s);
  }

  static public <A> int smartLastIndexOf(List<A> l, A sub) {
    int i = lastIndexOf(l, sub);
    return i < 0 ? l(l) : i;
  }

  static public boolean ewic(String a, String b) {
    return endsWithIgnoreCase(a, b);
  }

  static public boolean ewic(String a, String b, Matches m) {
    return endsWithIgnoreCase(a, b, m);
  }

  static public String addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
    return a == null ? b : b == null ? a : new AutoCloseable() {

      public String toString() {
        return "pClose(a); pClose(b);";
      }

      public void close() throws Exception {
        pClose(a);
        pClose(b);
      }
    };
  }

  static public AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) {
    return combineAutoCloseables(concatLists(ll(a, b, c), asList(more)));
  }

  static public AutoCloseable combineAutoCloseables(Iterable<AutoCloseable> l) {
    return foldl(new F2<AutoCloseable, AutoCloseable, AutoCloseable>() {

      public AutoCloseable get(AutoCloseable a, AutoCloseable b) {
        try {
          return combineAutoCloseables(a, b);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "combineAutoCloseables(a,b)";
      }
    }, null, l);
  }

  static public AutoCloseable dm_vmBus_answerToMessage(String msg, final IF0 f) {
    final DynModule m = dm_current_mandatory();
    return dm_ownResource(vmBus_addListener_basic(msg, new F2<String, Object, Object>() {

      public Object get(String _msg, Object arg) {
        try {
          AutoCloseable __1 = m.enter();
          try {
            return callF(f);
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp m.enter();\r\n    ret callF(f);";
      }
    }));
  }

  static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) {
    final DynModule m = dm_current_mandatory();
    return dm_ownResource(vmBus_addListener_basic(msg, new F2<String, Object, Object>() {

      public Object get(String _msg, Object arg) {
        try {
          AutoCloseable __2 = m.enter();
          try {
            return callF(f);
          } finally {
            _close(__2);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp m.enter();\r\n    ret callF(f);";
      }
    }));
  }

  static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F1 f) {
    final DynModule m = dm_current_mandatory();
    return dm_ownResource(vmBus_addListener_basic(msg, new F2<String, Object, Object>() {

      public Object get(String _msg, Object arg) {
        try {
          AutoCloseable __3 = m.enter();
          try {
            return callF(f, arg);
          } finally {
            _close(__3);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp m.enter();\r\n    ret callF(f, arg);";
      }
    }));
  }

  static public AutoCloseable dm_vmBus_answerToMessage(String msg, F2 f) {
    final DynModule m = dm_current_mandatory();
    return dm_ownResource(vmBus_addListener_basic(msg, new F2<String, Object, Object>() {

      public Object get(String _msg, Object arg) {
        try {
          if (arg instanceof Object[]) {
            if (((Object[]) arg).length != 2)
              return null;
            AutoCloseable __4 = m.enter();
            try {
              return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1]);
            } finally {
              _close(__4);
            }
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "if (arg cast O[]) {\r\n      if (arg.length != 2) null;\r\n      temp m.enter();\r...";
      }
    }));
  }

  static public AutoCloseable dm_vmBus_answerToMessage(String msg, F3 f) {
    final DynModule m = dm_current_mandatory();
    return dm_ownResource(vmBus_addListener_basic(msg, new F2<String, Object, Object>() {

      public Object get(String _msg, Object arg) {
        try {
          if (arg instanceof Object[]) {
            if (((Object[]) arg).length != 3)
              return null;
            AutoCloseable __5 = m.enter();
            try {
              return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1], ((Object[]) arg)[2]);
            } finally {
              _close(__5);
            }
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "if (arg cast O[]) {\r\n      if (arg.length != 3) null;\r\n      temp m.enter();\r...";
      }
    }));
  }

  static public <A> F0<A> fConst(A a) {
    return f0_const(a);
  }

  static public void dm_reloadModule(Object module) {
    dm_reloadModuleInBackground(module);
  }

  static public void dm_reloadModule() {
    dm_reloadModuleInBackground();
  }

  static public int shorten_default = 100;

  static public String shorten(CharSequence s) {
    return shorten(s, shorten_default);
  }

  static public String shorten(CharSequence s, int max) {
    return shorten(s, max, "...");
  }

  static public String shorten(CharSequence s, int max, String shortener) {
    if (s == null)
      return "";
    if (max < 0)
      return str(s);
    return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max - l(shortener))) + shortener;
  }

  static public String shorten(int max, CharSequence s) {
    return shorten(s, max);
  }

  static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
    return new SmartTimerTask(r, timer, delay, _threadInfo());
  }

  static public class SmartTimerTask extends TimerTask implements IFieldsToList {

    public Object r;

    public java.util.Timer timer;

    public long delay;

    public Object threadInfo;

    public SmartTimerTask() {
    }

    public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
      this.threadInfo = threadInfo;
      this.delay = delay;
      this.timer = timer;
      this.r = r;
    }

    public String toString() {
      return shortClassName_dropNumberPrefix(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
    }

    public Object[] _fieldsToList() {
      return new Object[] { r, timer, delay, threadInfo };
    }

    public long lastRun;

    public void run() {
      if (!licensed())
        timer.cancel();
      else {
        _threadInheritInfo(threadInfo);
        AutoCloseable __1 = tempActivity(r);
        try {
          lastRun = fixTimestamp(lastRun);
          long now = now();
          if (now >= lastRun + delay * 0.9) {
            lastRun = now;
            if (eq(false, pcallF(r)))
              timer.cancel();
          }
        } finally {
          _close(__1);
        }
      }
    }
  }

  static public DynModule dm_current() {
    return dm_currentModule();
  }

  static public Object dm_os() {
    {
      Object __1 = vm_generalMap_get("stefansOS");
      if (__1 != null)
        return __1;
    }
    return creator();
  }

  static public <A> ArrayList<A> asList(A[] a) {
    return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
  }

  static public ArrayList<Integer> asList(int[] a) {
    if (a == null)
      return null;
    ArrayList<Integer> l = emptyList(a.length);
    for (int i : a) l.add(i);
    return l;
  }

  static public ArrayList<Long> asList(long[] a) {
    if (a == null)
      return null;
    ArrayList<Long> l = emptyList(a.length);
    for (long i : a) l.add(i);
    return l;
  }

  static public ArrayList<Float> asList(float[] a) {
    if (a == null)
      return null;
    ArrayList<Float> l = emptyList(a.length);
    for (float i : a) l.add(i);
    return l;
  }

  static public ArrayList<Double> asList(double[] a) {
    if (a == null)
      return null;
    ArrayList<Double> l = emptyList(a.length);
    for (double i : a) l.add(i);
    return l;
  }

  static public ArrayList<Short> asList(short[] a) {
    if (a == null)
      return null;
    ArrayList<Short> l = emptyList(a.length);
    for (short i : a) l.add(i);
    return l;
  }

  static public <A> ArrayList<A> asList(Iterator<A> it) {
    ArrayList l = new ArrayList();
    if (it != null)
      while (it.hasNext()) l.add(it.next());
    return l;
  }

  static public <A> ArrayList<A> asList(IterableIterator<A> s) {
    return asList((Iterator) s);
  }

  static public <A> ArrayList<A> asList(Iterable<A> s) {
    if (s instanceof ArrayList)
      return (ArrayList) s;
    ArrayList l = new ArrayList();
    if (s != null)
      for (A a : s) l.add(a);
    return l;
  }

  static public <A> ArrayList<A> asList(Producer<A> p) {
    ArrayList l = new ArrayList();
    A a;
    if (p != null)
      while ((a = p.next()) != null) l.add(a);
    return l;
  }

  static public <A> ArrayList<A> asList(Enumeration<A> e) {
    ArrayList l = new ArrayList();
    if (e != null)
      while (e.hasMoreElements()) l.add(e.nextElement());
    return l;
  }

  static public <A> List<A> asList(Pair<A, A> p) {
    return p == null ? null : ll(p.a, p.b);
  }

  static public PingSource pingSource() {
    return pingSource_tl().get();
  }

  static public boolean ping_v3() {
    return ping_v3(pingSource());
  }

  static public boolean ping_v3(PingSource source) {
    {
      if (source != null)
        source.get();
    }
    return true;
  }

  static public double parseDouble(String s) {
    return empty(s) ? 0.0 : Double.parseDouble(s);
  }

  static public boolean isOnPATH(String cmd) {
    return findCmdOnPATH(cmd) != null;
  }

  static public int randomID_defaultLength = 12;

  static public String randomID(int length) {
    return makeRandomID(length);
  }

  static public String randomID(Random r, int length) {
    return makeRandomID(r, length);
  }

  static public String randomID() {
    return randomID(randomID_defaultLength);
  }

  static public String randomID(Random r) {
    return randomID(r, randomID_defaultLength);
  }

  static public File linux_fileInRamDisk(String name) {
    if (!isLinux())
      return null;
    File dir = newFile("/dev/shm");
    if (dir.isDirectory())
      return newFile(dir, name);
    return null;
  }

  static public File prepareProgramFile(String name) {
    return mkdirsForFile(getProgramFile(name));
  }

  static public File prepareProgramFile(String progID, String name) {
    return mkdirsForFile(getProgramFile(progID, name));
  }

  static public int backtick_exitValue;

  static public boolean backtick_verbose, backtick_keepScript;

  static public ThreadLocal<File> backtick_scriptFile = new ThreadLocal();

  static public ThreadLocal<Boolean> backtick_uninterruptable = new ThreadLocal();

  static public boolean backtick_win_cmd = false;

  static public String backtick(String cmd) {
    try {
      ping();
      File outFile = File.createTempFile("_backtick", "");
      backtickToFile(cmd, outFile);
      String result = loadTextFile(outFile.getPath(), "");
      if (backtick_verbose) {
        print("[[\n" + result + "]]");
      }
      outFile.delete();
      return result;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public java.lang.Process backtickToFile(String cmd, File outFile) {
    try {
      try {
        java.lang.Process process = backtickToFile_noWait(cmd, outFile);
        process.waitFor();
        backtick_exitValue = process.exitValue();
        if (backtick_verbose)
          System.out.println("Process return code: " + backtick_exitValue);
        return process;
      } finally {
        if (!backtick_keepScript)
          deleteFile(backtick_scriptFile.get());
        backtick_scriptFile.set(null);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public java.lang.Process backtickToFile_noWait(String cmd, File outFile) {
    try {
      ping();
      File scriptFile;
      String ext = isWindows() ? ".bat" : "";
      if (backtick_keepScript)
        scriptFile = makeFileNameUnique_withExtension(javaxCachesDir("Cmd Scripts/backtick"), ".bat");
      else
        scriptFile = File.createTempFile("_backtick", ext);
      backtick_scriptFile.set(scriptFile);
      if (backtick_verbose)
        print("backtick: scriptFile " + f2s(scriptFile));
      boolean makeInterruptable = !isTrue(backtick_uninterruptable.get()) && !isWindows();
      cmd = trim(cmd);
      if (makeInterruptable && numLines(cmd) > 1)
        throw fail("No multi-line commands allowed when making interruptable");
      String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
      if (makeInterruptable)
        command = fixNewLines("\r\ninterruptable() {\r\n\r\n    # handle options\r\n    local setsid=\"\"\r\n    local debug=false\r\n    while true; do\r\n        case \"${1:-}\" in\r\n            --killall)      setsid=setsid; shift ;;\r\n            --debug)        debug=true; shift ;;\r\n            --*)            echo \"Invalid option: $1\" 1>&2; exit 1;;\r\n            *)              break;; # no more options\r\n        esac\r\n    done\r\n\r\n    # start the specified command\r\n    $setsid \"$@\" &\r\n    local child_pid=$!\r\n\r\n    # arrange to propagate a signal to the child process\r\n    trap '\r\n        exec 1>&2\r\n        set +e\r\n        trap \"\" SIGPIPE # ensure a possible sigpipe from the echo does not prevent the kill\r\n        echo \"${BASH_SOURCE[0]} caught SIGTERM while executing $* (pid $child_pid), sending SIGTERM to it\"\r\n        # (race) child may have exited in which case kill will report an error\r\n        # if setsid is used then prefix the pid with a \"-\" to indicate that the signal\r\n        # should be sent to the entire process group\r\n        kill ${setsid:+-}$child_pid\r\n        exit 143\r\n    ' SIGTERM\r\n    # ensure that the trap doesn't persist after we return\r\n    trap 'trap - SIGTERM' RETURN\r\n\r\n    $debug && echo \"interruptable wait (child $child_pid, self $$) for: $*\"\r\n\r\n    # An error status from the child process will trigger an exception (via set -e)\r\n    # here unless the caller is checking the return status\r\n    wait $child_pid # last command, so status of waited for command is returned\r\n}\r\n\r\ninterruptable ") + command;
      if (backtick_verbose) {
        print("backtick: command " + command);
        print("backtick: saving to " + scriptFile.getPath());
      }
      saveTextFile(scriptFile.getPath(), command);
      if (backtick_verbose)
        print("backtick: command length=" + l(command) + ", file length=" + scriptFile.length());
      String[] command2;
      if (isWindows())
        if (backtick_win_cmd)
          command2 = new String[] { "cmd", "/c", scriptFile.getPath() };
        else
          command2 = new String[] { scriptFile.getPath() };
      else
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
      if (backtick_verbose)
        print("backtick: command2 " + structure(command2));
      return Runtime.getRuntime().exec(command2);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedImage loadPNG(File file) {
    return loadBufferedImage(file);
  }

  static public Cache<Boolean> isLinux_cache = new Cache<>(() -> isLinux_load());

  static public boolean isLinux() {
    return isLinux_cache.get();
  }

  static public Boolean isLinux_load() {
    return !isWindows() && !isMac() && !isAndroid();
  }

  static public float clamp(float x, float a, float b) {
    return x < a ? a : x > b ? b : x;
  }

  static public double clamp(double x, double a, double b) {
    return x < a ? a : x > b ? b : x;
  }

  static public int clamp(int x, int a, int b) {
    return x < a ? a : x > b ? b : x;
  }

  static public long clamp(long x, long a, long b) {
    return x < a ? a : x > b ? b : x;
  }

  static public BufferedImage newBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
    return newBufferedImage(w, h, rgb.getColor());
  }

  static public BufferedImage newBufferedImage(int w, int h, Color color) {
    BufferedImage img = newBufferedImage(w, h);
    Graphics2D g = img.createGraphics();
    g.setColor(or(color, Color.white));
    g.fillRect(0, 0, w, h);
    return img;
  }

  static public BufferedImage newBufferedImage(Pt p, Color color) {
    return newBufferedImage(p.x, p.y, color);
  }

  static public BufferedImage newBufferedImage(int w, int h, int[] pixels) {
    return intArrayToBufferedImage(pixels, w, h);
  }

  static public Object sleepQuietly_monitor = new Object();

  static public void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String roundBracket(String s) {
    return "(" + s + ")";
  }

  static public String roundBracket(Object s) {
    return roundBracket(str(s));
  }

  static public List<String> mapToLines(Map map) {
    List<String> l = new ArrayList();
    for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
    return l;
  }

  static public String mapToLines(Map map, Object f) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Map map) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Iterable l) {
    return lines(map(f, l));
  }

  static public <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
    return mapToLines((Object) f, l);
  }

  static public <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
    return mapToLines((Object) f, l);
  }

  static public <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
    return lines(map(map, f));
  }

  static public <A> String mapToLines(IF1<A, String> f, A data1, A... moreData) {
    return lines(map(f, data1, moreData));
  }

  static public String joinPairWithColon(Pair p) {
    return p == null ? "" : str(p.a) + ": " + str(p.b);
  }

  static public <A, B> List<Pair<A, B>> mapToPairs(Map<A, B> map) {
    List<Pair<A, B>> l = emptyList(l(map));
    if (map != null)
      for (Map.Entry<A, B> e : map.entrySet()) l.add(pair(e.getKey(), e.getValue()));
    return l;
  }

  static public <A, B> Pair<A, B> pair(A a, B b) {
    return new Pair(a, b);
  }

  static public <A> Pair<A, A> pair(A a) {
    return new Pair(a, a);
  }

  static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value) {
    return setSplitPaneOnFirstShowing(c, value, 0);
  }

  static public JSplitPane setSplitPaneOnFirstShowing(Component c, double value, int delay) {
    final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
    if (sp != null)
      onFirstResize(sp, new Runnable() {

        public void run() {
          try {
            if (delay == 0)
              sp.setDividerLocation(value);
            else
              awtLater(delay, new Runnable() {

                public void run() {
                  try {
                    sp.setDividerLocation(value);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "sp.setDividerLocation(value);";
                }
              });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef setSplitPaneOnFirstShowing_debug\r\n        printVars setSplitPaneOnFirst...";
        }
      });
    return sp;
  }

  static public Object[] asObjectArray(Collection l) {
    return toObjectArray(l);
  }

  static public void addToContainer(Container a, Component... b) {
    if (a == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            for (Component c : unnullForIteration(b)) if (c != null)
              a.add(c);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (Component c : unnullForIteration(b))\r\n      if (c != null) \r\n        a.a...";
        }
      });
    }
  }

  static public Component wrapForSmartAdd(Object o) {
    if (o == null)
      return jpanel();
    if (o instanceof String)
      return jlabel((String) o);
    return wrap(o);
  }

  static public class jLiveValueSection_class extends SingleComponentPanel {

    public LiveValue<?> liveValue;

    public String getTitle() {
      return strOrEmpty(liveValue.get());
    }

    public jLiveValueSection_class(LiveValue<?> lv, Component c) {
      super(c);
      bindLiveValueListenerToComponent(this, liveValue = lv, new Runnable() {

        public void run() {
          try {
            swingLater(new Runnable() {

              public void run() {
                try {
                  setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), getTitle()));
                  revalidate();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "setBorder(BorderFactory.createTitledBorder(\r\n        BorderFactory.createBeve...";
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "swingLater(r {\r\n      setBorder(BorderFactory.createTitledBorder(\r\n        Bo...";
        }
      });
    }
  }

  static public JPanel jLiveValueSection(LiveValue<?> lv, Component c) {
    return swingNu(jLiveValueSection_class.class, lv, c);
  }

  static public JLabel dm_calculatedLabel(IF0<Object> calc) {
    return jLiveValueLabel(dm_calculatedLiveValue(Object.class, calc));
  }

  static public JLabel jLiveValueLabel(final LiveValue lv) {
    return bindJLabelToLiveValue(jlabel(), lv);
  }

  static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
    return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
  }

  static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
    Lock __0 = module.lock;
    lock(__0);
    try {
      AutoCloseable __2 = module.enter();
      try {
        Class type = getFieldType(module, fieldName);
        final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
        dm_watchField(fieldName, new Runnable() {

          public void run() {
            try {
              Object o = get(module, fieldName);
              value.set(o);
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting \" + fi...";
          }
        });
        value.onChange(new Runnable() {

          public void run() {
            try {
              module.setField(fieldName, value.get());
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting 2 \" + ...";
          }
        });
        return value;
      } finally {
        _close(__2);
      }
    } finally {
      unlock(__0);
    }
  }

  static public JPanel jFullCenter(final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          panel.add(c);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    panel.add(c);\r\n    ret panel;";
      }
    });
  }

  static public ImageSurface imageSurface(BufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface(MakesBufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface() {
    return swingNu(ImageSurface.class);
  }

  static public <A extends JComponent> A setDoubleBuffered(A c, boolean b) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            {
              if (c != null)
                c.setDoubleBuffered(b);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c?.setDoubleBuffered(b);";
        }
      });
    }
    return c;
  }

  static public <A> void scanForComponents(final Component c, final Class<A> theClass, final List<A> l) {
    if (theClass.isInstance(c))
      l.add((A) c);
    if (c instanceof Container) {
      swing(new Runnable() {

        public void run() {
          try {
            for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (Component comp : ((Container) c).getComponents())\r\n      scanForComponen...";
        }
      });
    }
  }

  static public JTextField onEnter(final JTextField tf, final Object action) {
    if (action == null || tf == null)
      return tf;
    tf.addActionListener(new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          tf.selectAll();
          callF(action);
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    });
    return tf;
  }

  static public JButton onEnter(JButton btn, final Object action) {
    if (action == null || btn == null)
      return btn;
    btn.addActionListener(actionListener(action));
    return btn;
  }

  static public JList onEnter(JList list, Object action) {
    list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
    return list;
  }

  static public JComboBox onEnter(final JComboBox cb, final Object action) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (cb.isEditable()) {
              JTextField text = (JTextField) cb.getEditor().getEditorComponent();
              onEnter(text, action);
            } else {
              cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
              cb.getActionMap().put("enter", abstractAction("", new Runnable() {

                public void run() {
                  try {
                    cb.hidePopup();
                    callF(action);
                  } catch (Exception __e) {
                    throw rethrow(__e);
                  }
                }

                public String toString() {
                  return "cb.hidePopup(); callF(action);";
                }
              }));
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (cb.isEditable()) {\r\n      JTextField text = (JTextField) cb.getEditor().g...";
        }
      });
    }
    return cb;
  }

  static public JTable onEnter(final JTable table, final Object action) {
    table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {

      public void actionPerformed(ActionEvent e) {
        callF(action, table.getSelectedRow());
      }
    });
    return table;
  }

  static public JTextField onEnter(Object action, JTextField tf) {
    return onEnter(tf, action);
  }

  static public Object dm_stem() {
    return dm_stem(dm_current_generic());
  }

  static public Object dm_stem(Object moduleOrID) {
    return dm_getStem(moduleOrID);
  }

  static public Window dm_window(Object module) {
    return getWindow(dm_vis(module));
  }

  static public JDesktopPane dm_desktopPane() {
    return dm_getOSOpt("desktop");
  }

  static public void _onJavaXSet() {
  }

  static public <A> void listThreadLocalAdd(ThreadLocal<List<A>> tl, A a) {
    List<A> l = tl.get();
    if (l == null)
      tl.set(l = new ArrayList());
    l.add(a);
  }

  static public <A> A listThreadLocalPopLast(ThreadLocal<List<A>> tl) {
    List<A> l = tl.get();
    if (l == null)
      return null;
    A a = popLast(l);
    if (empty(l))
      tl.set(null);
    return a;
  }

  static public <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
    if (tl == null)
      return null;
    final A prev = setThreadLocal(tl, a);
    return new AutoCloseable() {

      public String toString() {
        return "tl.set(prev);";
      }

      public void close() throws Exception {
        tl.set(prev);
      }
    };
  }

  static public <A> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
    if (l == null)
      return new ArrayList();
    synchronized (mutex) {
      return new ArrayList<A>(l);
    }
  }

  static public <A, B> Set<A> keys(Map<A, B> map) {
    return map == null ? new HashSet() : map.keySet();
  }

  static public Set keys(Object map) {
    return keys((Map) map);
  }

  static public <A> Set<A> keys(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public <A, B> Set<A> keys(MultiMap<A, B> mm) {
    return mm.keySet();
  }

  static public Object get2(Object o, String field1, String field2) {
    return get(get(o, field1), field2);
  }

  static public boolean startsWithAny(String a, Collection<String> b) {
    for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
      return true;
    return false;
  }

  static public boolean startsWithAny(String a, String... b) {
    if (b != null)
      for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
        return true;
    return false;
  }

  static public boolean startsWithAny(String a, Collection<String> b, Matches m) {
    for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m))
      return true;
    return false;
  }

  static public String mcDollar() {
    return mcName() + "$";
  }

  static public String afterDollar(String s) {
    return substring(s, smartIndexOf(s, '$') + 1);
  }

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

  static public void caseID(String id) {
    caseID_caseID = id;
  }

  static public String quoteUnlessIdentifierOrInteger(String s) {
    return quoteIfNotIdentifierOrInteger(s);
  }

  static public boolean odd(int i) {
    return (i & 1) != 0;
  }

  static public boolean odd(long i) {
    return (i & 1) != 0;
  }

  static public boolean odd(BigInteger i) {
    return odd(toInt(i));
  }

  static public String quote(Object o) {
    if (o == null)
      return "null";
    return quote(str(o));
  }

  static public String quote(String s) {
    if (s == null)
      return "null";
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
    quote_impl(s, out);
    return out.toString();
  }

  static public void quote_impl(String s, StringBuilder out) {
    out.append('"');
    int l = s.length();
    for (int i = 0; i < l; i++) {
      char c = s.charAt(i);
      if (c == '\\' || c == '"')
        out.append('\\').append(c);
      else if (c == '\r')
        out.append("\\r");
      else if (c == '\n')
        out.append("\\n");
      else if (c == '\t')
        out.append("\\t");
      else if (c == '\0')
        out.append("\\0");
      else
        out.append(c);
    }
    out.append('"');
  }

  static public int parseHexChar(char c) {
    if (c >= '0' && c <= '9')
      return charDiff(c, '0');
    if (c >= 'a' && c <= 'f')
      return charDiff(c, 'a') + 10;
    if (c >= 'A' && c <= 'F')
      return charDiff(c, 'A') + 10;
    return -1;
  }

  static public <A, B> Pair<A, B> mapEntryToPair(Map.Entry<A, B> e) {
    return e == null ? null : pair(e.getKey(), e.getValue());
  }

  static public <A, B> Set<Map.Entry<A, B>> entrySet(Map<A, B> map) {
    return _entrySet(map);
  }

  static public <A> A firstThat(Iterable<A> l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(A[] l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(l, pred);
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, A[] l) {
    return firstThat(l, pred);
  }

  static public <A, B> B mapGet(Map<A, B> map, A a) {
    return map == null || a == null ? null : map.get(a);
  }

  static public <A, B> B mapGet(A a, Map<A, B> map) {
    return map == null || a == null ? null : map.get(a);
  }

  static public boolean even(int i) {
    return (i & 1) == 0;
  }

  static public boolean even(long i) {
    return (i & 1) == 0;
  }

  static public boolean even(BigInteger n) {
    return even(n.intValue());
  }

  static volatile public boolean licensed_yes = true;

  static public boolean licensed() {
    if (!licensed_yes)
      return false;
    ping_okInCleanUp();
    return true;
  }

  static public void licensed_off() {
    licensed_yes = false;
  }

  static public Object costCenter() {
    return mc();
  }

  static public String shortenSnippetID(String snippetID) {
    if (snippetID.startsWith("#"))
      snippetID = snippetID.substring(1);
    String httpBlaBla = "http://tinybrain.de/";
    if (snippetID.startsWith(httpBlaBla))
      snippetID = snippetID.substring(httpBlaBla.length());
    return "" + parseLong(snippetID);
  }

  static public boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

  static public BufferedImage imageIO_readURL(String url) {
    try {
      return ImageIO.read(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isAbsolutePath(String s) {
    return s != null && new File(s).isAbsolute();
  }

  static public boolean isAbsolutePath(File f) {
    return f != null && f.isAbsolute();
  }

  static public IResourceLoader vm_getResourceLoader() {
    return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
  }

  static public File imageSnippetsCacheDir() {
    return javaxCachesDir("Image-Snippets");
  }

  static public String snippetImageURL_http(String snippetID) {
    return snippetImageURL_http(snippetID, "png");
  }

  static public String snippetImageURL_http(String snippetID, String contentType) {
    return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
  }

  static public BufferedImage loadBufferedImageFile(File file) {
    try {
      return isFile(file) ? ImageIO.read(file) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int strL(String s) {
    return s == null ? 0 : s.length();
  }

  static public int lCharSequence(CharSequence s) {
    return s == null ? 0 : s.length();
  }

  static final public Map<Class, _MethodCache> callOpt_cache = newDangerousWeakHashMap();

  static public Object callOpt_cached(Object o, String methodName, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null)
          return null;
        return invokeMethod(me, o, args);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public _MethodCache callOpt_getCache(Class c) {
    _MethodCache cache = callOpt_cache.get(c);
    if (cache == null)
      callOpt_cache.put(c, cache = new _MethodCache(c));
    return cache;
  }

  static public Object invokeMethod(Method m, Object o, Object... args) {
    try {
      try {
        return m.invoke(o, args);
      } catch (InvocationTargetException e) {
        throw rethrow(getExceptionCause(e));
      } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isStaticMethod(Method m) {
    return methodIsStatic(m);
  }

  static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    int n = types.length - 1, nArgs = args.length;
    if (nArgs < n)
      return null;
    for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
      return null;
    Class varArgType = types[n].getComponentType();
    for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
      return null;
    Object[] newArgs = new Object[n + 1];
    arraycopy(args, 0, newArgs, 0, n);
    Object[] varArgs = arrayOfType(varArgType, nArgs - n);
    arraycopy(args, n, varArgs, 0, nArgs - n);
    newArgs[n] = varArgs;
    return newArgs;
  }

  static public <A> String joinWithComma(Collection<A> c) {
    return join(", ", c);
  }

  static public String joinWithComma(Object... c) {
    return join(", ", c);
  }

  static public String joinWithComma(String... c) {
    return join(", ", c);
  }

  static public String joinWithComma(Pair p) {
    return p == null ? "" : joinWithComma(str(p.a), str(p.b));
  }

  static public List<String> classNames(Collection l) {
    return getClassNames(l);
  }

  static public List<String> classNames(Object[] l) {
    return getClassNames(Arrays.asList(l));
  }

  static public <A> ArrayList<A> cloneList(Iterable<A> l) {
    return l instanceof Collection ? cloneList((Collection) l) : asList(l);
  }

  static public <A> ArrayList<A> cloneList(Collection<A> l) {
    if (l == null)
      return new ArrayList();
    synchronized (collectionMutex(l)) {
      return new ArrayList<A>(l);
    }
  }

  static public Object pcallF_minimalExceptionHandling(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable e) {
      System.out.println(getStackTrace(e));
      _storeException(e);
    }
    return null;
  }

  static public AutoCloseable tempSetField(Object o, String field, Object value) {
    final Object oldValue = get(o, field);
    set(o, field, value);
    return () -> set(o, field, oldValue);
  }

  static public <A> AutoCloseable tempSetField(ISetAndGet<A> gs, A value) {
    if (gs == null)
      return null;
    A oldValue = gs.get();
    gs.set(value);
    return () -> gs.set(oldValue);
  }

  static public <A> AutoCloseable tempSetField(A value, ISetAndGet<A> gs) {
    return tempSetField(gs, value);
  }

  static public <A> A firstWithClassShortNamed(String shortName, Iterable<A> l) {
    if (l != null)
      for (A o : l) if (eq(shortClassName(o), shortName))
        return o;
    return null;
  }

  static public <A> A firstWithClassShortNamed(String shortName, A[] l) {
    if (l != null)
      for (A o : l) if (eq(shortClassName(o), shortName))
        return o;
    return null;
  }

  static public boolean domainIsUnder(String domain, String mainDomain) {
    return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
  }

  static public String theAGIBlueDomain() {
    return "agi.blue";
  }

  static public WeakHasherMap<Symbol, Boolean> symbol_map = new WeakHasherMap(new Hasher<Symbol>() {

    public int hashCode(Symbol symbol) {
      return symbol.text.hashCode();
    }

    public boolean equals(Symbol a, Symbol b) {
      if (a == null)
        return b == null;
      return b != null && eq(a.text, b.text);
    }
  });

  static public Symbol symbol(String s) {
    if (s == null)
      return null;
    synchronized (symbol_map) {
      Symbol symbol = new Symbol(s, true);
      Symbol existingSymbol = symbol_map.findKey(symbol);
      if (existingSymbol == null)
        symbol_map.put(existingSymbol = symbol, true);
      return existingSymbol;
    }
  }

  static public Symbol symbol(CharSequence s) {
    if (s == null)
      return null;
    if (s instanceof Symbol)
      return (Symbol) s;
    if (s instanceof String)
      return symbol((String) s);
    return symbol(str(s));
  }

  static public Symbol symbol(Object o) {
    return symbol((CharSequence) o);
  }

  static public String getType(Object o) {
    return getClassName(o);
  }

  static public long getFileSize(String path) {
    return path == null ? 0 : new File(path).length();
  }

  static public long getFileSize(File f) {
    return f == null ? 0 : f.length();
  }

  static public Class<?> _getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class _getClass(Object o) {
    return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
  }

  static public Class _getClass(Object realm, String name) {
    try {
      return classLoaderForObject(realm).loadClass(classNameToVM(name));
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public boolean nemptyString(String s) {
    return s != null && s.length() > 0;
  }

  static public int listL(Collection l) {
    return l == null ? 0 : l.size();
  }

  static public int poorMansProfiling_defaultInterval() {
    return 25;
  }

  static public FixedRateTimer doEvery_daemon(long delay, final Object r) {
    return doEvery_daemon(defaultTimerName(), delay, r);
  }

  static public FixedRateTimer doEvery_daemon(String timerName, long delay, final Object r) {
    return doEvery_daemon(timerName, delay, delay, r);
  }

  static public FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) {
    return doEvery_daemon(defaultTimerName(), delay, firstDelay, r);
  }

  static public FixedRateTimer doEvery_daemon(String timerName, long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(true);
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay);
    return timer;
  }

  static public FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) {
    return doEvery_daemon(toMS(delaySeconds), r);
  }

  static public HashMap litmap(Object... x) {
    HashMap map = new HashMap();
    litmap_impl(map, x);
    return map;
  }

  static public void litmap_impl(Map map, Object... x) {
    if (x != null)
      for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
        map.put(x[i], x[i + 1]);
  }

  static public Map<Thread, StackTraceElement[]> runnableThreadsWithStackTraces() {
    Map<Thread, StackTraceElement[]> map = filterMap((__42, __43) -> isThreadRunnable_x(__42, __43), Thread.getAllStackTraces());
    map.remove(currentThread());
    return map;
  }

  static public boolean isSystemThread(Thread t) {
    ThreadGroup g = t.getThreadGroup();
    return g != null && g.getName().equals("system");
  }

  static public void stopTimer(java.util.Timer timer) {
    if (timer != null)
      timer.cancel();
  }

  static public String poorMansProfiling_stopAndRenderResults() {
    return poorMansProfiling_renderFullResults(poorMansProfiling_stopAndGetResults());
  }

  static public TimeZone getTimeZone(String name) {
    return TimeZone.getTimeZone(name);
  }

  static public String standardTimeZone_name = "Europe/Berlin";

  static public String standardTimeZone() {
    return standardTimeZone_name;
  }

  static public Runnable asRunnable(Object o) {
    return toRunnable(o);
  }

  static public void _inheritThreadInfo(Object info) {
    _threadInheritInfo(info);
  }

  static public Object vm_generalMap_get(Object key) {
    return vm_generalMap().get(key);
  }

  static public <A> A oneOf(List<A> l) {
    return empty(l) ? null : l.get(new Random().nextInt(l.size()));
  }

  static public char oneOf(String s) {
    return empty(s) ? '?' : s.charAt(random(l(s)));
  }

  static public String oneOf(String... l) {
    return oneOf(asList(l));
  }

  static public <A> A collectionGet(Collection<A> c, int idx) {
    if (c == null || idx < 0 || idx >= l(c))
      return null;
    if (c instanceof List)
      return listGet((List<A>) c, idx);
    Iterator<A> it = c.iterator();
    for (int i = 0; i < idx; i++) if (it.hasNext())
      it.next();
    else
      return null;
    return it.hasNext() ? it.next() : null;
  }

  static public <A, B> Pair<A, B> entryToPair(Map.Entry<A, B> e) {
    return mapEntryToPair(e);
  }

  static public <A, B> Set<Map.Entry<A, B>> entries(Map<A, B> map) {
    return _entrySet(map);
  }

  static public String dropNumberPrefix(String s) {
    return dropFirst(s, indexOfNonDigit(s));
  }

  static public String shortClassName(Object o) {
    if (o == null)
      return null;
    Class c = o instanceof Class ? (Class) o : o.getClass();
    String name = c.getName();
    return shortenClassName(name);
  }

  static public Object callFunction(Object f, Object... args) {
    return callF(f, args);
  }

  static public void messageBox(final String msg) {
    if (headless())
      print(msg);
    else {
      swing(new Runnable() {

        public void run() {
          try {
            JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
        }
      });
    }
  }

  static public void messageBox(Throwable e) {
    printStackTrace(e);
    messageBox(hideCredentials(innerException2(e)));
  }

  static public Object nuObject(String className, Object... args) {
    try {
      return nuObject(classForName(className), args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObject(Class<A> c, Object... args) {
    try {
      if (args.length == 0)
        return nuObjectWithoutArguments(c);
      Constructor m = nuObject_findConstructor(c, args);
      makeAccessible(m);
      return (A) m.newInstance(args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuObject_findConstructor(Class c, Object... args) {
    for (Constructor m : c.getDeclaredConstructors()) {
      if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
        continue;
      return m;
    }
    throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
  }

  static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
    return true;
  }

  static public RuntimeException asRuntimeException(Throwable t) {
    if (t instanceof Error)
      _handleError((Error) t);
    return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
  }

  static public String nullIfEmpty(String s) {
    return isEmpty(s) ? null : s;
  }

  static public <A, B> Map<A, B> nullIfEmpty(Map<A, B> map) {
    return isEmpty(map) ? null : map;
  }

  static public <A> List<A> nullIfEmpty(List<A> l) {
    return isEmpty(l) ? null : l;
  }

  static public String charToString(char c) {
    return String.valueOf(c);
  }

  static public String charToString(int c) {
    return String.valueOf((char) c);
  }

  static public boolean isMenuSeparatorIndicator(Object o) {
    return eqOneOf(o, "***", "---", "===", "");
  }

  static public boolean isRunnableX(Object o) {
    if (o == null)
      return false;
    if (o instanceof String)
      return hasMethod(mc(), (String) o);
    return o instanceof Runnable || hasMethod(o, "get");
  }

  static public boolean jmenuItem_newThreads = false;

  static public JMenuItem jmenuItem(final String text) {
    return jMenuItem(text, null);
  }

  static public JMenuItem jmenuItem(final String text, final Object r) {
    return swing(new F0<JMenuItem>() {

      public JMenuItem get() {
        try {
          Pair<String, Integer> p = jmenu_autoMnemonic(dropPrefix("[disabled] ", text));
          JMenuItem mi = new JMenuItem(p.a);
          if (startsWith(text, "[disabled] "))
            disableMenuItem(mi);
          if (p.b != 0)
            mi.setMnemonic(p.b);
          mi.addActionListener(jmenuItem_newThreads ? actionListenerInNewThread(r) : actionListener(r));
          return mi;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Pair<S, Int> p = jmenu_autoMnemonic(dropPrefix(\"[disabled] \", text));\r\n    JM...";
      }
    });
  }

  static public <A extends JComponent> A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
    if (lv != null)
      bindToComponent(component, new Runnable() {

        public void run() {
          try {
            lv.onChangeAndNow(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef bindLiveValueListenerToComponent_debug\r\n          print(\"bindLiveValueL...";
        }
      }, new Runnable() {

        public void run() {
          try {
            lv.removeOnChangeListener(listener);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "lv.removeOnChangeListener(listener)";
        }
      });
    return component;
  }

  static public boolean isCurlyBracketed(String s) {
    return isCurlyBraced(s);
  }

  static public <A extends JComponent> A setEnabled(A c, boolean enable) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.setEnabled(enable);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.setEnabled(enable);";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A setEnabled(boolean enable, A c) {
    return setEnabled(c, enable);
  }

  static public String unCurlyBracket(String s) {
    return tok_unCurlyBracket(s);
  }

  static public <A, B> Map<A, B> mapMinus(Map<A, B> map, Object... keys) {
    if (empty(keys))
      return map;
    Map<A, B> m2 = cloneMap(map);
    for (Object key : keys) m2.remove(key);
    return m2;
  }

  static public <A> HashSet<A> lithashset(A... items) {
    HashSet<A> set = new HashSet();
    for (A a : items) set.add(a);
    return set;
  }

  static public int preferredWidth(Component c) {
    return c == null ? 0 : getPreferredSize(c).width;
  }

  static public boolean swic(String a, String b) {
    return startsWithIgnoreCase(a, b);
  }

  static public boolean swic(String a, String b, Matches m) {
    if (!swic(a, b))
      return false;
    m.m = new String[] { substring(a, l(b)) };
    return true;
  }

  static public boolean containsNewLines(String s) {
    return containsNewLine(s);
  }

  static public String jlabel_textAsHTML_center(String text) {
    return "<html><div style=\"text-align: center;\">" + replace(htmlencode2(text), "\n", "<br>") + "</div></html>";
  }

  static public <A extends JComponent> A setFont(final Font font, final A a) {
    if (a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            a.setFont(font);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setFont(font);";
        }
      });
    }
    return a;
  }

  static public <A extends JComponent> A setFont(A a, Font font) {
    return setFont(font, a);
  }

  static public <A extends JComponent> A setFont(final String fontID, float fontSize, final A a) {
    return setFont(loadFont_cached(fontID, fontSize), a);
  }

  static public Font typeWriterFont() {
    return typeWriterFont(iround(14 * getSwingFontScale()));
  }

  static public Font typeWriterFont(int size) {
    return new Font("Courier", Font.PLAIN, size);
  }

  static public JTextArea jTextAreaWithUndo() {
    return jTextAreaWithUndo("");
  }

  static public JTextArea jTextAreaWithUndo(final String text) {
    return jenableUndoRedo(swingNu(JTextArea.class, text));
  }

  static public String getProgramName_cache;

  static public String getProgramName() {
    Lock __0 = downloadLock();
    lock(__0);
    try {
      if (getProgramName_cache == null)
        getProgramName_cache = getSnippetTitleOpt(programID());
      return getProgramName_cache;
    } finally {
      unlock(__0);
    }
  }

  static public void _onLoad_getProgramName() {
    {
      startThread(new Runnable() {

        public void run() {
          try {
            getProgramName();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "getProgramName();";
        }
      });
    }
  }

  static public void standardTitlePopupMenu(final JFrame frame) {
    if (!isSubstanceLAF())
      return;
    titlePopupMenu(frame, new VF1<JPopupMenu>() {

      public void get(JPopupMenu menu) {
        try {
          boolean alwaysOnTop = frame.isAlwaysOnTop();
          menu.add(jmenuItem("Restart Program", "restart"));
          menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
          menu.add(jmenuItem("Show Console", "showConsole"));
          menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() {

            public void run() {
              try {
                toggleAlwaysOnTop(frame);
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "toggleAlwaysOnTop(frame)";
            }
          }));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n    ifndef standardTitlePopupMenu_...";
      }
    });
  }

  static public JFrame consoleFrame() {
    return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
  }

  static public void autoVMExit() {
    call(getJavaX(), "autoVMExit");
  }

  static public TreeSet<String> litciset(String... items) {
    TreeSet<String> set = caseInsensitiveSet();
    for (String a : items) set.add(a);
    return set;
  }

  static public TreeSet<Symbol> litciset(Symbol... items) {
    TreeSet<Symbol> set = treeSet();
    for (Symbol a : items) set.add(a);
    return set;
  }

  static public String dropSuffix(String suffix, String s) {
    return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  static public String afterLastSpace(String s) {
    return s == null ? null : substring(s, s.lastIndexOf(' ') + 1);
  }

  static public boolean endsWith(String a, String b) {
    return a != null && a.endsWith(b);
  }

  static public boolean endsWith(String a, char c) {
    return nempty(a) && lastChar(a) == c;
  }

  static public boolean endsWith(String a, String b, Matches m) {
    if (!endsWith(a, b))
      return false;
    m.m = new String[] { dropLast(l(b), a) };
    return true;
  }

  static public <A> A[] dropLast(A[] a) {
    return dropLast(a, 1);
  }

  static public <A> A[] dropLast(A[] a, int n) {
    if (a == null)
      return null;
    n = Math.min(n, a.length);
    A[] b = arrayOfSameType(a, a.length - n);
    System.arraycopy(a, 0, b, 0, b.length);
    return b;
  }

  static public <A> List<A> dropLast(List<A> l) {
    return subList(l, 0, l(l) - 1);
  }

  static public <A> List<A> dropLast(int n, List<A> l) {
    return subList(l, 0, l(l) - n);
  }

  static public <A> List<A> dropLast(Iterable<A> l) {
    return dropLast(asList(l));
  }

  static public String dropLast(String s) {
    return substring(s, 0, l(s) - 1);
  }

  static public String dropLast(String s, int n) {
    return substring(s, 0, l(s) - n);
  }

  static public String dropLast(int n, String s) {
    return dropLast(s, n);
  }

  static public String dropSuffixIgnoreCase(String suffix, String s) {
    return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  static public boolean ewicOneOf(String s, String... l) {
    if (s != null)
      for (String x : l) if (ewic(s, x))
        return true;
    return false;
  }

  static public Graphics2D antiAliasGraphics(BufferedImage img) {
    return antiAliasOn(createGraphics(img));
  }

  static public Map<BufferedImage, Object> createGraphics_modulators = synchroIdentityHashMap();

  static public Graphics2D createGraphics(BufferedImage img) {
    Graphics2D g = img.createGraphics();
    Object mod = createGraphics_modulators.get(img);
    if (mod != null)
      callF(mod, g);
    return g;
  }

  static public void createGraphics_modulate(BufferedImage img, Object mod) {
    mapPut2(createGraphics_modulators, img, mod);
  }

  static public <A extends JComponent> A jtransparent(final A a) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            a.setOpaque(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "a.setOpaque(false);";
        }
      });
    }
    return a;
  }

  static public JPanel borderLayoutPanel() {
    return jpanel(new BorderLayout());
  }

  static public JLabel jImageLabel(Image img) {
    return swingNu(JLabel.class, imageIcon(img));
  }

  static public JLabel jImageLabel(javax.swing.Icon icon) {
    return swingNu(JLabel.class, icon);
  }

  static public JLabel jImageLabel(String imageID) {
    return jImageLabel(imageIcon(imageID));
  }

  static public JLabel jImageLabel(String text, String imageID) {
    final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER);
    {
      swing(new Runnable() {

        public void run() {
          try {
            l.setVerticalTextPosition(SwingConstants.BOTTOM);
            l.setHorizontalTextPosition(SwingConstants.CENTER);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n    l.setHorizontalTextPos...";
        }
      });
    }
    return l;
  }

  static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, int affineTransformOpType) {
    return scaleImageWithOp(before, scaleX, scaleX, affineTransformOpType);
  }

  static public BufferedImage scaleImageWithOp(BufferedImage before, double scaleX, double scaleY, int affineTransformOpType) {
    if (scaleX == 1 && scaleY == 1)
      return before;
    int w = before.getWidth();
    int h = before.getHeight();
    int neww = max(1, iround(w * scaleX)), newh = max(1, iround(h * scaleY));
    BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
    AffineTransform at = new AffineTransform();
    at.scale(scaleX, scaleY);
    AffineTransformOp scaleOp = new AffineTransformOp(at, affineTransformOpType);
    return scaleOp.filter(before, after);
  }

  static public int year() {
    return localYear();
  }

  static public int year(long now) {
    return localYear(now);
  }

  static public int year(long now, TimeZone tz) {
    return parseInt(simpleDateFormat("y", tz).format(now));
  }

  static public String formatInt(int i, int digits) {
    return padLeft(str(i), '0', digits);
  }

  static public String formatInt(long l, int digits) {
    return padLeft(str(l), '0', digits);
  }

  static public int month() {
    return localMonth();
  }

  static public int month(long now) {
    return localMonth(now);
  }

  static public int month(long now, TimeZone tz) {
    return parseInt(simpleDateFormat("M", tz).format(now));
  }

  static public int dayOfMonth() {
    return localDayOfMonth();
  }

  static public int dayOfMonth(long now) {
    return localDayOfMonth(now);
  }

  static public int dayOfMonth(long now, TimeZone tz) {
    return parseInt(simpleDateFormat("d", tz).format(now));
  }

  static public void logQuotedWithTime(String s) {
    logQuotedWithTime(standardLogFile(), s);
  }

  static public void logQuotedWithTime(File logFile, String s) {
    logQuoted(logFile, logQuotedWithTime_format(s));
  }

  static public void logQuotedWithTime(String logFile, String s) {
    logQuoted(logFile, logQuotedWithTime_format(s));
  }

  static public String logQuotedWithTime_format(String s) {
    return (now()) + " " + s;
  }

  static public JTextArea wrappedTextArea(final JTextArea ta) {
    enableWordWrapForTextArea(ta);
    return ta;
  }

  static public JTextArea wrappedTextArea() {
    return wrappedTextArea(jtextarea());
  }

  static public JTextArea wrappedTextArea(String text) {
    JTextArea ta = wrappedTextArea();
    setText(ta, text);
    return ta;
  }

  static public <A extends JComponent> A onClick(final A c, final Object runnable) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(new MouseAdapter() {

              public void mouseClicked(MouseEvent e) {
                callF(runnable, e);
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(new MouseAdapter {\r\n      public void mouseClicked(MouseEv...";
        }
      });
    }
    return c;
  }

  static public void onClick(JButton btn, final Object runnable) {
    onEnter(btn, runnable);
  }

  static public int withMargin_defaultWidth = 6;

  static public JPanel withMargin(Component c) {
    return withMargin(withMargin_defaultWidth, c);
  }

  static public JPanel withMargin(int w, Component c) {
    return withMargin(w, w, c);
  }

  static public JPanel withMargin(int w, int h, Component c) {
    return withMargin(w, h, w, h, c);
  }

  static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = marginPanel();
          p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = marginPanel();\r\n    p.setBorder(BorderFactory.createEmptyBorder(to...";
      }
    });
  }

  static public boolean vmBus_anyFalse(String msg, Object... args) {
    return contains(vmBus_queryAll(msg, args), false);
  }

  static public int toMS_int(double seconds) {
    return toInt_checked((long) (seconds * 1000));
  }

  static public String _computerID;

  static public Lock computerID_lock = lock();

  public static String computerID() {
    if (_computerID == null) {
      Lock __0 = computerID_lock;
      lock(__0);
      try {
        if (_computerID != null)
          return _computerID;
        File file = computerIDFile();
        _computerID = loadTextFile(file.getPath());
        if (_computerID == null) {
          _computerID = loadTextFile(userDir(".tinybrain/computer-id"));
          if (_computerID == null)
            _computerID = makeRandomID(12, new SecureRandom());
          saveTextFile(file, _computerID);
        }
      } finally {
        unlock(__0);
      }
    }
    return _computerID;
  }

  static public String formatWithThousandsSeparator(long l) {
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
  }

  static public File[] listFiles(File dir) {
    File[] files = dir.listFiles();
    return files == null ? new File[0] : files;
  }

  static public File[] listFiles(String dir) {
    return listFiles(new File(dir));
  }

  static public File dirOfFile(File f) {
    return f == null ? null : f.getParentFile();
  }

  static public boolean containsRegexp(String s, String pat) {
    return regexpFinds(pat, s);
  }

  static public <A> List<A> newSubListOrSame(List<A> l, int startIndex) {
    return newSubListOrSame(l, startIndex, l(l));
  }

  static public <A> List<A> newSubListOrSame(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = max(0, startIndex);
    endIndex = min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return cloneList(l.subList(startIndex, endIndex));
  }

  static public <A> List<A> newSubListOrSame(List<A> l, IntRange r) {
    return newSubListOrSame(l, r.start, r.end);
  }

  static public CharSequence subCharSequence(CharSequence s, int x) {
    return subCharSequence(s, x, s == null ? 0 : s.length());
  }

  static public CharSequence subCharSequence(CharSequence s, int x, int y) {
    if (s == null)
      return null;
    if (x < 0)
      x = 0;
    if (x >= s.length())
      return "";
    if (y < x)
      y = x;
    if (y > s.length())
      y = s.length();
    return s.subSequence(x, y);
  }

  static public int[] takeFirstOfIntArray(int[] b, int n) {
    return subIntArray(b, 0, n);
  }

  static public int[] takeFirstOfIntArray(int n, int[] b) {
    return takeFirstOfIntArray(b, n);
  }

  static public short[] takeFirstOfShortArray(short[] b, int n) {
    return subShortArray(b, 0, n);
  }

  static public short[] takeFirstOfShortArray(int n, short[] b) {
    return takeFirstOfShortArray(b, n);
  }

  static public byte[] takeFirstOfByteArray(byte[] b, int n) {
    return subByteArray(b, 0, n);
  }

  static public byte[] takeFirstOfByteArray(int n, byte[] b) {
    return takeFirstOfByteArray(b, n);
  }

  static public double[] takeFirstOfDoubleArray(double[] b, int n) {
    return subDoubleArray(b, 0, n);
  }

  static public double[] takeFirstOfDoubleArray(int n, double[] b) {
    return takeFirstOfDoubleArray(b, n);
  }

  static public boolean endsWithLetter(String s) {
    return nempty(s) && isLetter(last(s));
  }

  static public String structureForUser(Object o) {
    return beautifyStructure(struct_noStringSharing(o));
  }

  static public Thread currentThread() {
    return Thread.currentThread();
  }

  static public Map<Thread, Object> vm_threadInterruptionReasonsMap() {
    return vm_generalWeakSubMap("Thread interruption reasons");
  }

  static public String strOr(Object o, String ifNull) {
    return o == null ? ifNull : str(o);
  }

  static public void lockOrFail(Lock lock, long timeout) {
    try {
      ping();
      vmBus_send("locking", lock, "thread", currentThread());
      if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
        String s = "Couldn't acquire lock after " + timeout + " ms.";
        if (lock instanceof ReentrantLock) {
          ReentrantLock l = (ReentrantLock) lock;
          s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
        }
        throw fail(s);
      }
      vmBus_send("locked", lock, "thread", currentThread());
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  static public String formatSnippetID(String id) {
    return "#" + parseSnippetID(id);
  }

  static public String formatSnippetID(long id) {
    return "#" + id;
  }

  static public boolean isImageServerSnippet(long id) {
    return id >= 1100000 && id < 1200000;
  }

  static public File loadImageAsFile(String snippetIDOrURL) {
    try {
      if (isURL(snippetIDOrURL))
        throw fail("not implemented");
      if (!isSnippetID(snippetIDOrURL))
        throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
      String snippetID = "" + parseSnippetID(snippetIDOrURL);
      File file = imageSnippetCacheFile(snippetID);
      if (fileSize(file) > 0)
        return file;
      String imageURL = snippetImageURL_noHttps(snippetID);
      System.err.println("Loading image: " + imageURL);
      byte[] data = loadBinaryPage(imageURL);
      saveBinaryFile(file, data);
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File DiskSnippetCache_file(long snippetID) {
    return new File(getGlobalCache(), "data_" + snippetID + ".jar");
  }

  public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
    File file = DiskSnippetCache_file(snippetID);
    return file.exists() ? file : null;
  }

  public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
    saveBinaryFile(DiskSnippetCache_file(snippetID), data);
  }

  static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
    byte[] data;
    try {
      URL url = new URL(dataSnippetLink(snippetID));
      print("Loading library: " + hideCredentials(url));
      try {
        data = loadBinaryPage(url.openConnection());
      } catch (RuntimeException e) {
        data = null;
      }
      if (data == null || data.length == 0) {
        url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
        print("Loading library: " + hideCredentials(url));
        data = loadBinaryPage(url.openConnection());
      }
      print("Bytes loaded: " + data.length);
    } catch (FileNotFoundException e) {
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
    }
    return data;
  }

  static public File loadDataSnippetToFile(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      return loadDataSnippetToFile_noResourceLoader(snippetID);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File loadDataSnippetToFile_noResourceLoader(String snippetID) {
    try {
      snippetID = fsI(snippetID);
      File f = DiskSnippetCache_file(parseSnippetID(snippetID));
      List<URL> urlsTried = new ArrayList();
      List<Throwable> errors = new ArrayList();
      try {
        URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
        print("Loading library: " + hideCredentials(url));
        try {
          loadBinaryPageToFile(openConnection(url), f);
          if (fileSize(f) == 0)
            throw fail();
        } catch (Throwable e) {
          errors.add(e);
          url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
          print(e);
          print("Trying other server: " + hideCredentials(url));
          loadBinaryPageToFile(openConnection(url), f);
          print("Got bytes: " + fileSize(f));
        }
        if (fileSize(f) == 0)
          throw fail();
        System.err.println("Bytes loaded: " + fileSize(f));
      } catch (Throwable e) {
        errors.add(e);
        throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
      }
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] isGIF_magic = bytesFromHex("47494638");

  static public boolean isGIF(byte[] data) {
    return byteArrayStartsWith(data, isGIF_magic);
  }

  static public boolean isGIF(File f) {
    return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
  }

  static public <A> void setVar(IVar<A> v, A value) {
    if (v != null)
      v.set(value);
  }

  static public <A> IVF1<A> setVar(IVar<A> v) {
    return a -> {
      if (v != null)
        v.set(a);
    };
  }

  static public int parseInt(String s) {
    return emptyString(s) ? 0 : Integer.parseInt(s);
  }

  static public int parseInt(char c) {
    return Integer.parseInt(str(c));
  }

  static public int boolToInt(boolean b) {
    return b ? 1 : 0;
  }

  static public String filterChars(IF1<Character, Boolean> pred, String s) {
    if (empty(s))
      return null;
    int n = l(s), i = 0;
    char c = s.charAt(i);
    boolean totality = pred.get(c);
    for (++i; i < n; i++) {
      c = s.charAt(i);
      boolean b = pred.get(c);
      if (b != totality) {
        StringBuilder buf = new StringBuilder();
        if (totality)
          buf.append(substring(s, 0, i));
        while (true) {
          ping();
          if (b)
            buf.append(c);
          if (++i >= n)
            break;
          c = s.charAt(i);
          b = pred.get(c);
        }
        return buf.toString();
      }
    }
    return totality ? s : "";
  }

  static public boolean isSpaceEtc(char c) {
    return c == ' ' || c == '\t' || c == '\r' || c == '\n';
  }

  static public String getProgramID() {
    return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
  }

  static public String getProgramID(Class c) {
    String id = (String) getOpt(c, "programID");
    if (nempty(id))
      return formatSnippetID(id);
    return "?";
  }

  static public String getProgramID(Object o) {
    return getProgramID(getMainClass(o));
  }

  static public <A> WeakReference<A> newWeakReference(A a) {
    return a == null ? null : new WeakReference(a);
  }

  static public List collectField(Iterable c, String field) {
    List l = new ArrayList();
    if (c != null)
      for (Object a : c) l.add(getOpt(a, field));
    return l;
  }

  static public List collectField(String field, Iterable c) {
    return collectField(c, field);
  }

  static public int lastIndexOf(String a, String b) {
    return a == null || b == null ? -1 : a.lastIndexOf(b);
  }

  static public int lastIndexOf(String a, char b) {
    return a == null ? -1 : a.lastIndexOf(b);
  }

  static public <A> int lastIndexOf(List<A> l, int i, A a) {
    if (l == null)
      return -1;
    for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
      return i;
    return -1;
  }

  static public <A> int lastIndexOf(List<A> l, A a) {
    if (l == null)
      return -1;
    for (int i = l(l) - 1; i >= 0; i--) if (eq(l.get(i), a))
      return i;
    return -1;
  }

  static public boolean endsWithIgnoreCase(String a, String b) {
    int la = l(a), lb = l(b);
    return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
  }

  static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
    if (!endsWithIgnoreCase(a, b))
      return false;
    if (m != null)
      m.m = new String[] { substring(a, 0, l(a) - l(b)) };
    return true;
  }

  static public String addPrefix(String prefix, String s) {
    return s.startsWith(prefix) ? s : prefix + s;
  }

  static public void pClose(AutoCloseable c) {
    close_pcall(c);
  }

  static public <A> List<A> concatLists(Iterable<A>... lists) {
    List<A> l = new ArrayList();
    if (lists != null)
      for (Iterable<A> list : lists) addAll(l, list);
    return l;
  }

  static public <A> List<A> concatLists(Collection<? extends Iterable<A>> lists) {
    List<A> l = new ArrayList();
    if (lists != null)
      for (Iterable<A> list : lists) addAll(l, list);
    return l;
  }

  static public <A, B> A foldl(F2<A, B, A> f, A seed, Iterable<B> l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = callF(f, a, b);
    return a;
  }

  static public <A, B> A foldl(F2<A, B, A> f, A seed, B[] l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = callF(f, a, b);
    return a;
  }

  static public <A, B> A foldl(Object f, A seed, B[] l) {
    A a = seed;
    if (l != null)
      for (B b : l) a = (A) callF(f, a, b);
    return a;
  }

  static public <A extends AutoCloseable> A dm_ownResource(A resource) {
    dm_currentModuleMandatory().ownResource(resource);
    return resource;
  }

  static public <A> AutoCloseable vmBus_addListener_basic(String msg, Object listener) {
    Map<String, Set> map = vm_busListenersByMessage_live();
    synchronized (map) {
      Set listeners = map.get(msg);
      if (listeners == null)
        map.put(msg, listeners = syncIdentityHashSet());
      return tempAdd(listeners, listener);
    }
  }

  static public <A> F0<A> f0_const(final A a) {
    return new F0<A>() {

      public A get() {
        try {
          return a;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret a;";
      }
    };
  }

  static public void dm_reloadModuleInBackground(Object module) {
    dm_callOS("reloadModuleInBackground", dm_getStem(module));
  }

  static public void dm_reloadModuleInBackground() {
    dm_reloadModuleInBackground(dm_current_mandatory_generic());
  }

  static public AutoCloseable tempActivity(Object r) {
    return null;
  }

  static public long fixTimestamp(long timestamp) {
    return timestamp > now() ? 0 : timestamp;
  }

  static public WeakReference<Object> creator_class;

  static public Object creator() {
    return creator_class == null ? null : creator_class.get();
  }

  static public ThreadLocal<PingSource> pingSource_tl_var = new ThreadLocal<PingSource>() {

    public PingSource initialValue() {
      return ping_v3_pingSourceMaker().get();
    }
  };

  static public ThreadLocal<PingSource> pingSource_tl() {
    return pingSource_tl_var;
  }

  static public File findCmdOnPATH(String cmd) {
    String path = System.getenv("PATH");
    List<String> dirs = splitAt(path, File.pathSeparator);
    String c = isWindows() ? addSuffix(cmd, ".exe") : cmd;
    for (String dir : dirs) {
      File f = new File(dir, c);
      if (f.isFile())
        return f;
    }
    return null;
  }

  static public String makeRandomID(int length) {
    return makeRandomID(length, defaultRandomGenerator());
  }

  static public String makeRandomID(int length, Random random) {
    char[] id = new char[length];
    for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
    return new String(id);
  }

  static public String makeRandomID(Random r, int length) {
    return makeRandomID(length, r);
  }

  static public File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

  static public File getProgramFile(String fileName) {
    return getProgramFile(getProgramID(), fileName);
  }

  static public String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(File f, String defaultContents) {
    return loadTextFile(f, defaultContents, "UTF-8");
  }

  static public String loadTextFile(File f, String defaultContents, String encoding) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
      return loadTextFile(inputStreamReader);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadTextFile(File fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(String fileName, String defaultContents) {
    return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
  }

  static public String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
    } finally {
      reader.close();
    }
    return str(builder);
  }

  static public boolean deleteFile(File file) {
    return file != null && file.delete();
  }

  static public File makeFileNameUnique_withExtension(File f, String ext) {
    File orig = f;
    int n = 0;
    ext = addPrefixIfNempty(".", dropPrefix(".", ext));
    String name = dropSuffixIC(ext, orig.getName());
    f = new File(dirOfFile(orig), name + ext);
    while (f.exists()) f = new File(dirOfFile(orig), name + "." + (++n) + ext);
    return f;
  }

  static public File javaxCachesDir_dir;

  static public File javaxCachesDir() {
    return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
  }

  static public File javaxCachesDir(String sub) {
    return newFile(javaxCachesDir(), sub);
  }

  static public int numLines(String s) {
    return countLines(s);
  }

  static public boolean isMac() {
    return System.getProperty("os.name").toLowerCase().contains("mac");
  }

  static public void assertFalse(Object o) {
    if (!(eq(o, false)))
      throw fail(str(o));
  }

  static public boolean assertFalse(boolean b) {
    if (b)
      throw fail("oops");
    return b;
  }

  static public boolean assertFalse(String msg, boolean b) {
    if (b)
      throw fail(msg);
    return b;
  }

  static public String lines(Iterable lines) {
    return fromLines(lines);
  }

  static public String lines(Object[] lines) {
    return fromLines(asList(lines));
  }

  static public List<String> lines(String s) {
    return toLines(s);
  }

  static public <A> String lines(Iterable<A> l, IF1<A, String> f) {
    return mapToLines(l, f);
  }

  static public void onFirstResize(final Component c, final Object r) {
    if (c != null && r != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addComponentListener(new ComponentAdapter() {

              public void componentResized(ComponentEvent e) {
                c.removeComponentListener(this);
                pcallF(r);
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addComponentListener(new ComponentAdapter {\r\n      public void componentRes...";
        }
      });
    }
  }

  static public void awtLater(int delay, final Object r) {
    swingLater(delay, r);
  }

  static public void awtLater(Object r) {
    swingLater(r);
  }

  static public void awtLater(JComponent component, int delay, Object r) {
    installTimer(component, r, delay, delay, false);
  }

  static public void awtLater(JFrame frame, int delay, Object r) {
    awtLater(frame.getRootPane(), delay, r);
  }

  static public String unnullForIteration(String s) {
    return s == null ? "" : s;
  }

  static public <A> Collection<A> unnullForIteration(Collection<A> l) {
    return l == null ? immutableEmptyList() : l;
  }

  static public <A> List<A> unnullForIteration(List<A> l) {
    return l == null ? immutableEmptyList() : l;
  }

  static public int[] unnullForIteration(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnullForIteration(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnullForIteration(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

  static public short[] unnullForIteration(short[] l) {
    return l == null ? emptyShortArray() : l;
  }

  static public <A, B> Map<A, B> unnullForIteration(Map<A, B> l) {
    return l == null ? immutableEmptyMap() : l;
  }

  static public <A> Iterable<A> unnullForIteration(Iterable<A> i) {
    return i == null ? immutableEmptyList() : i;
  }

  static public <A> A[] unnullForIteration(A[] a) {
    return a == null ? (A[]) emptyObjectArray() : a;
  }

  static public BitSet unnullForIteration(BitSet b) {
    return b == null ? new BitSet() : b;
  }

  static public Pt unnullForIteration(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public Symbol unnullForIteration(Symbol s) {
    return s == null ? emptySymbol() : s;
  }

  static public <A, B> Pair<A, B> unnullForIteration(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public long unnullForIteration(Long l) {
    return l == null ? 0L : l;
  }

  static public String strOrEmpty(Object o) {
    return o == null ? "" : str(o);
  }

  static public <A> LiveValue<A> dm_calculatedLiveValue(final DynModule module, final Class type, final F0<A> calc) {
    Lock __0 = module.lock;
    lock(__0);
    try {
      final SimpleLiveValue value = new SimpleLiveValue(type, callF(calc));
      module.onChange(new Runnable() {

        public void run() {
          try {
            value.set(callF(calc));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "value.set(callF(calc))";
        }
      });
      return value;
    } finally {
      unlock(__0);
    }
  }

  static public <A> LiveValue<A> dm_calculatedLiveValue(Class type, F0<A> calc) {
    return dm_calculatedLiveValue(dm_current_mandatory(), type, calc);
  }

  static public <A> LiveValue<A> dm_calculatedLiveValue(Class<A> type, IF0<A> calc) {
    return dm_calculatedLiveValue(type, if0ToF0(calc));
  }

  static public LiveValue<Object> dm_calculatedLiveValue(IF0<?> calc) {
    return dm_calculatedLiveValue(Object.class, (F0) if0ToF0(calc));
  }

  static public <A extends JLabel> A bindJLabelToLiveValue(final A label, final LiveValue lv) {
    bindLiveValueListenerToComponent(label, lv, new Runnable() {

      public void run() {
        try {
          setText(label, strOrNull(lv.get()));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setText(label, strOrNull(lv!))";
      }
    });
    return label;
  }

  static public Class getFieldType(Object o, String field) {
    return fieldType(o, field);
  }

  static public KeyListener enterKeyListener(final Object action) {
    return new KeyAdapter() {

      public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER)
          pcallF(action);
      }
    };
  }

  static public Runnable rCallOnSelectedListItem(final JList list, final Object action) {
    return new Runnable() {

      public void run() {
        try {
          pcallF(action, getSelectedItem(list));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(action, getSelectedItem(list))";
      }
    };
  }

  static public AbstractAction abstractAction(String name, final Object runnable) {
    return new AbstractAction(name) {

      public void actionPerformed(ActionEvent evt) {
        pcallF(runnable);
      }
    };
  }

  static public <A> A dm_getOSOpt(String field) {
    return (A) getOpt(dm_os(), field);
  }

  static public void restart() {
    Object j = getJavaX();
    call(j, "cleanRestart", get(j, "fullArgs"));
  }

  static public void duplicateThisProgram() {
    nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
  }

  static public void showConsole() {
    callOpt(get(javax(), "console"), "showConsole");
  }

  static public <A> A popLast(List<A> l) {
    return liftLast(l);
  }

  static public <A> List<A> popLast(int n, List<A> l) {
    return liftLast(n, l);
  }

  static public <A> A setThreadLocal(ThreadLocal<A> tl, A value) {
    if (tl == null)
      return null;
    A old = tl.get();
    tl.set(value);
    return old;
  }

  static public String mcName() {
    return mc().getName();
  }

  static public int smartIndexOf(String s, String sub, int i) {
    if (s == null)
      return 0;
    i = s.indexOf(sub, min(i, l(s)));
    return i >= 0 ? i : l(s);
  }

  static public int smartIndexOf(String s, int i, char c) {
    return smartIndexOf(s, c, i);
  }

  static public int smartIndexOf(String s, char c, int i) {
    if (s == null)
      return 0;
    i = s.indexOf(c, min(i, l(s)));
    return i >= 0 ? i : l(s);
  }

  static public int smartIndexOf(String s, String sub) {
    return smartIndexOf(s, sub, 0);
  }

  static public int smartIndexOf(String s, char c) {
    return smartIndexOf(s, c, 0);
  }

  static public <A> int smartIndexOf(List<A> l, A sub) {
    return smartIndexOf(l, sub, 0);
  }

  static public <A> int smartIndexOf(List<A> l, int start, A sub) {
    return smartIndexOf(l, sub, start);
  }

  static public <A> int smartIndexOf(List<A> l, A sub, int start) {
    int i = indexOf(l, sub, start);
    return i < 0 ? l(l) : i;
  }

  static public String quoteIfNotIdentifierOrInteger(String s) {
    if (s == null)
      return null;
    return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
  }

  static public int charDiff(char a, char b) {
    return (int) a - (int) b;
  }

  static public int charDiff(String a, char b) {
    return charDiff(stringToChar(a), b);
  }

  static public <A, B> Set<Map.Entry<A, B>> _entrySet(Map<A, B> map) {
    return map == null ? Collections.EMPTY_SET : map.entrySet();
  }

  static public long parseLong(String s) {
    if (empty(s))
      return 0;
    return Long.parseLong(dropSuffix("L", s));
  }

  static public long parseLong(Object s) {
    return Long.parseLong((String) s);
  }

  static public <A> A proxy(Class<A> intrface, final Object target) {
    if (target == null)
      return null;
    if (isInstance(intrface, target))
      return (A) target;
    return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target));
  }

  static public <A> A proxy(Object target, Class<A> intrface) {
    return proxy(intrface, target);
  }

  static public String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

  static public String snippetImageURL(long snippetID) {
    return snippetImageURL(fsI(snippetID));
  }

  static public String snippetImageURL(String snippetID) {
    return snippetImageURL(snippetID, "png");
  }

  static public String snippetImageURL(String snippetID, String contentType) {
    if (snippetID == null || isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://botcompany.de/img/" + id;
    return url;
  }

  static public Throwable getExceptionCause(Throwable e) {
    Throwable c = e.getCause();
    return c != null ? c : e;
  }

  static public String joinWithSpace(Iterable c) {
    return join(" ", c);
  }

  static public String joinWithSpace(String... c) {
    return join(" ", c);
  }

  static public boolean methodIsStatic(Method m) {
    return (m.getModifiers() & Modifier.STATIC) != 0;
  }

  static public boolean argumentCompatibleWithType(Object arg, Class type) {
    return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
  }

  static public void arraycopy(Object[] a, Object[] b) {
    if (a != null && b != null)
      arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
  }

  static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
    if (n != 0)
      System.arraycopy(src, srcPos, dest, destPos, n);
  }

  static public <A> A[] arrayOfType(Class<A> type, int n) {
    return makeArray(type, n);
  }

  static public <A> A[] arrayOfType(int n, Class<A> type) {
    return arrayOfType(type, n);
  }

  static public List<String> getClassNames(Collection l) {
    List<String> out = new ArrayList();
    if (l != null)
      for (Object o : l) out.add(o == null ? null : getClassName(o));
    return out;
  }

  static public Object collectionMutex(List l) {
    return l;
  }

  static public Object collectionMutex(Object o) {
    if (o instanceof List)
      return o;
    String c = className(o);
    if (eq(c, "java.util.TreeMap$KeySet"))
      c = className(o = getOpt(o, "m"));
    else if (eq(c, "java.util.HashMap$KeySet"))
      c = className(o = get_raw(o, "this$0"));
    if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
      c = className(o = get_raw(o, "m"));
    return o;
  }

  static public Throwable _storeException_value;

  static public void _storeException(Throwable e) {
    _storeException_value = e;
  }

  static public <A> A set(A o, String field, Object value) {
    if (o == null)
      return null;
    if (o instanceof Class)
      set((Class) o, field, value);
    else
      try {
        Field f = set_findField(o.getClass(), field);
        makeAccessible(f);
        smartSet(f, o, value);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    return o;
  }

  static public void set(Class c, String field, Object value) {
    if (c == null)
      return;
    try {
      Field f = set_findStaticField(c, field);
      makeAccessible(f);
      smartSet(f, null, value);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static public Field set_findStaticField(Class<?> c, String field) {
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
      _c = _c.getSuperclass();
    } while (_c != null);
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
  }

  static public Field set_findField(Class<?> c, String field) {
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
        return f;
      _c = _c.getSuperclass();
    } while (_c != null);
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
  }

  static public void set(BitSet bs, int idx) {
    {
      if (bs != null)
        bs.set(idx);
    }
  }

  static public boolean eqic(String a, String b) {
    if ((a == null) != (b == null))
      return false;
    if (a == null)
      return true;
    return a.equalsIgnoreCase(b);
  }

  static public boolean eqic(Symbol a, Symbol b) {
    return eq(a, b);
  }

  static public boolean eqic(Symbol a, String b) {
    return eqic(asString(a), b);
  }

  static public boolean eqic(char a, char b) {
    if (a == b)
      return true;
    char u1 = Character.toUpperCase(a);
    char u2 = Character.toUpperCase(b);
    if (u1 == u2)
      return true;
    return Character.toLowerCase(u1) == Character.toLowerCase(u2);
  }

  static public ClassLoader classLoaderForObject(Object o) {
    if (o instanceof ClassLoader)
      return ((ClassLoader) o);
    if (o == null)
      return null;
    return _getClass(o).getClassLoader();
  }

  static public String classNameToVM(String name) {
    return name.replace(".", "$");
  }

  static public String defaultTimerName_name;

  static public String defaultTimerName() {
    if (defaultTimerName_name == null)
      defaultTimerName_name = "A timer by " + programID();
    return defaultTimerName_name;
  }

  static public <A, B> Map<A, B> filterMap(Map<A, B> map, IF2<A, B, Boolean> f) {
    if (map == null)
      return null;
    Map<A, B> m2 = similarEmptyMap(map);
    for (Map.Entry<? extends A, ? extends B> __0 : _entrySet(map)) {
      A a = __0.getKey();
      B b = __0.getValue();
      if (f.get(a, b))
        m2.put(a, b);
    }
    return m2;
  }

  static public <A, B> Map<A, B> filterMap(IF2<A, B, Boolean> f, Map<A, B> map) {
    return filterMap(map, f);
  }

  static public <A, B> Map<A, B> filterMap(Map<A, B> map, A... keys) {
    return getMultipleKeys(map, keys);
  }

  static public <A, B> Map<A, B> filterMap(Map<A, B> map, Iterable<A> keys) {
    return getMultipleKeys(map, keys);
  }

  static public Set<String> isThreadRunnable_x_exclude = lithashset("Java.lang.Thread.start0", "java.lang.Object.wait", "java.net.Inet6AddressImpl.lookupAllHostAddr", "java.io.FileInputStream.readBytes", "jdk.internal.misc.Unsafe.park", "sun.misc.Unsafe.park", "java.net.SocketInputStream.socketRead0", "java.net.PlainSocketImpl.socketConnect", "java.net.PlainSocketImpl.socketAccept", "sun.awt.X11.XToolkit.waitForEvents", "java.net.DualStackPlainSocketImpl.accept0", "org.jnativehook.GlobalScreen$NativeHookThread.enable", "java.lang.Thread.sleep", "sun.nio.ch.EPollArrayWrapper.epollWait", "com.ibm.lang.management.internal.MemoryNotificationThread.processNotificationLoop", "com.ibm.tools.attach.target.IPC.waitSemaphore", "sun.nio.ch.Net.poll", "sun.nio.ch.Net.accept", "sun.nio.ch.Net.connect0", "sun.nio.ch.EPoll.wait", "sun.nio.ch.SocketDispatcher.read0", "sun.nio.fs.LinuxWatchService.poll", "java.lang.ref.Reference.waitForReferencePendingList", "com.sun.java.accessibility.internal.AccessBridge.runDLL", "java.lang.ProcessHandleImpl.waitForProcessExit0");

  static public boolean isThreadRunnable_x(Thread t, StackTraceElement[] trace) {
    {
      Boolean __1 = (Boolean) vmBus_query("isThreadRunnable_x", t, trace);
      if (__1 != null)
        return __1;
    }
    if (t.getState() != Thread.State.RUNNABLE)
      return false;
    StackTraceElement e = first(trace);
    if (e == null)
      return false;
    String s = e.getClassName() + "." + e.getMethodName();
    return !isThreadRunnable_x_exclude.contains(s);
  }

  static public ThreadLocal<Boolean> poorMansProfiling_renderFullResults_backwards = new ThreadLocal();

  static public String poorMansProfiling_renderFullResults(final MultiSet<String> traces) {
    int samples = poorMansProfiling_samples;
    boolean backwards = isTrue(getAndClearThreadLocal(poorMansProfiling_renderFullResults_backwards));
    final int n = traces.size();
    int percent = ratioToIntPercent(l(traces), samples);
    return (samples == 0 ? "Nothing sampled" : percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n" + joinMap(backwards ? traces.lowestFirst() : traces.highestFirst(), new F1<String, Object>() {

      public Object get(String trace) {
        try {
          return traces.get(trace) + "/" + n + "\n" + trace + "\n\n";
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "traces.get(trace) + \"/\" + n + \"\\n\" + trace + \"\\n\\n\"";
      }
    });
  }

  static public <A> A listGet(List<A> l, int idx) {
    return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
  }

  static public int indexOfNonDigit(String s) {
    int n = l(s);
    for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i)))
      return i;
    return -1;
  }

  static public String shortenClassName(String name) {
    if (name == null)
      return null;
    int i = lastIndexOf(name, "$");
    if (i < 0)
      i = lastIndexOf(name, ".");
    return i < 0 ? name : substring(name, i + 1);
  }

  static public boolean headless() {
    return isHeadless();
  }

  static public Throwable innerException2(Throwable e) {
    if (e == null)
      return null;
    while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Map<String, Class> classForName_cache = synchroHashMap();

  static public Class classForName(String name) {
    return classForName(name, null);
  }

  static public Class classForName(String name, Object classFinder) {
    if (classForName_cache == null || classFinder != null)
      return classForName_uncached(name, classFinder);
    Class c = classForName_cache.get(name);
    if (c == null)
      classForName_cache.put(name, c = classForName_uncached(name, null));
    return c;
  }

  static public Class classForName_uncached(String name, Object classFinder) {
    try {
      if (classFinder != null)
        return (Class) callF(classFinder, name);
      return Class.forName(name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, Constructor> nuObjectWithoutArguments_cache = newDangerousWeakHashMap();

  static public Object nuObjectWithoutArguments(String className) {
    try {
      return nuObjectWithoutArguments(classForName(className));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObjectWithoutArguments(Class<A> c) {
    try {
      if (nuObjectWithoutArguments_cache == null)
        return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
      Constructor m = nuObjectWithoutArguments_cache.get(c);
      if (m == null)
        nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
      return (A) m.newInstance();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
    for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
      makeAccessible(m);
      return m;
    }
    throw fail("No default constructor found in " + c.getName());
  }

  static public Field makeAccessible(Field f) {
    try {
      f.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, f);
    }
    return f;
  }

  static public Method makeAccessible(Method m) {
    try {
      m.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, m);
    }
    return m;
  }

  static public Constructor makeAccessible(Constructor c) {
    try {
      c.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, c);
    }
    return c;
  }

  static public List<Class> getClasses(Object[] array) {
    List<Class> l = emptyList(l(array));
    for (Object o : array) l.add(_getClass(o));
    return l;
  }

  static public boolean isInstanceX(Class type, Object arg) {
    if (type == boolean.class)
      return arg instanceof Boolean;
    if (type == int.class)
      return arg instanceof Integer;
    if (type == long.class)
      return arg instanceof Long;
    if (type == float.class)
      return arg instanceof Float;
    if (type == short.class)
      return arg instanceof Short;
    if (type == char.class)
      return arg instanceof Character;
    if (type == byte.class)
      return arg instanceof Byte;
    if (type == double.class)
      return arg instanceof Double;
    return type.isInstance(arg);
  }

  static public void _handleError(Error e) {
    call(javax(), "_handleError", e);
  }

  static public boolean isEmpty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean isEmpty(CharSequence s) {
    return s == null || s.length() == 0;
  }

  static public boolean isEmpty(Object[] a) {
    return a == null || a.length == 0;
  }

  static public boolean isEmpty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean isEmpty(Map map) {
    return map == null || map.isEmpty();
  }

  static public boolean isEmpty(DoubleRange r) {
    return r == null || r.isEmpty();
  }

  static public boolean hasMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args) != null;
  }

  static public JMenuItem jMenuItem(final String text) {
    return jmenuItem(text);
  }

  static public JMenuItem jMenuItem(String text, Object r) {
    return jmenuItem(text, r);
  }

  static public Pair<String, Integer> jmenu_autoMnemonic(String s) {
    int i = indexOf(s, '&');
    if (i >= 0 && i < l(s) && isLetterOrDigit(s.charAt(i + 1)))
      return pair(substring(s, 0, i) + substring(s, i + 1), (int) s.charAt(i + 1));
    return pair(s, 0);
  }

  static public JMenuItem disableMenuItem(final JMenuItem mi) {
    if (mi != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mi.setEnabled(false);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mi.setEnabled(false);";
        }
      });
    }
    return mi;
  }

  static public ActionListener actionListenerInNewThread(final Object runnable) {
    return actionListenerInNewThread(runnable, null);
  }

  static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
    if (runnable instanceof ActionListener)
      return (ActionListener) runnable;
    return new java.awt.event.ActionListener() {

      public void actionPerformed(java.awt.event.ActionEvent _evt) {
        try {
          startThread("Action Listener", new Runnable() {

            public void run() {
              try {
                AutoCloseable __1 = holdInstance(instanceToHold);
                try {
                  callF(runnable);
                } finally {
                  _close(__1);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n      callF(runnable...";
            }
          });
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public boolean isCurlyBraced(String s) {
    List<String> tok = tok_combineCurlyBrackets_keep(javaTok(s));
    return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
  }

  static public String tok_unCurlyBracket(String s) {
    return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
  }

  static public <A, B> Map<A, B> cloneMap(Map<A, B> map) {
    if (map == null)
      return new HashMap();
    synchronized (map) {
      return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
    }
  }

  static public <A, B> List<B> cloneMap(Iterable<A> l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : cloneList(l)) x.add(f.get(o));
    return x;
  }

  static public Dimension getPreferredSize(final Component c) {
    return c == null ? null : swing(new F0<Dimension>() {

      public Dimension get() {
        try {
          return c.getPreferredSize();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getPreferredSize();";
      }
    });
  }

  static public boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  static public boolean containsNewLine(String s) {
    return contains(s, '\n');
  }

  static public <A> List<A> replace(List<A> l, A a, A b) {
    for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
      l.set(i, b);
    return l;
  }

  static public <A> List<A> replace(A a, A b, List<A> l) {
    return replace(l, a, b);
  }

  static public String replace(String s, String a, String b) {
    return s == null ? null : a == null || b == null ? s : s.replace(a, b);
  }

  static public String replace(String s, char a, char b) {
    return s == null ? null : s.replace(a, b);
  }

  static public String htmlencode2(String s) {
    return htmlencode_noQuotes(s);
  }

  static public Map<String, Font> loadFont_cached_cache = new HashMap();

  static synchronized public Font loadFont_cached(String snippetID) {
    try {
      snippetID = formatSnippetID(snippetID);
      Font f = loadFont_cached_cache.get(snippetID);
      if (f == null)
        loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static synchronized public Font loadFont_cached(String snippetID, float size) {
    try {
      return loadFont_cached(snippetID).deriveFont(size);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public float getSwingFontScale() {
    return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
  }

  static public <A extends JTextComponent> A jenableUndoRedo(final A textcomp) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            final UndoManager undo = new UndoManager();
            vm_generalWeakSet("Undo Managers").add(undo);
            textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {

              public void undoableEditHappened(UndoableEditEvent evt) {
                undo.addEdit(evt.getEdit());
              }
            });
            textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {

              public void run() {
                try {
                  if (undo.canUndo())
                    undo.undo();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "if (undo.canUndo()) undo.undo()";
              }
            }));
            textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {

              public void run() {
                try {
                  if (undo.canRedo())
                    undo.redo();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "if (undo.canRedo()) undo.redo()";
              }
            }));
            textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
            textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "final new UndoManager undo;\r\n    vm_generalWeakSet(\"Undo Managers\").add(undo)...";
        }
      });
    }
    return textcomp;
  }

  static public Lock downloadLock_lock = fairLock();

  static public Lock downloadLock() {
    return downloadLock_lock;
  }

  static public String getSnippetTitleOpt(String s) {
    try {
      return isSnippetID(s) ? getSnippetTitle(s) : s;
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
    return s;
  }

  static public boolean isSubstanceLAF() {
    return substanceLookAndFeelEnabled();
  }

  static public boolean titlePopupMenu(final Component c, final Object menuMaker) {
    JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
    if (titleBar == null) {
      print("Can't add title right click!");
      return false;
    } else {
      componentPopupMenu(titleBar, menuMaker);
      return true;
    }
  }

  static public void toggleAlwaysOnTop(Window frame) {
    if (frame == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "frame.setAlwaysOnTop(!frame.isAlwaysOnTop());";
        }
      });
    }
  }

  static public TreeSet<String> caseInsensitiveSet() {
    return caseInsensitiveSet_treeSet();
  }

  static public TreeSet<String> caseInsensitiveSet(Collection<String> c) {
    return caseInsensitiveSet_treeSet(c);
  }

  static public <A> TreeSet<A> treeSet() {
    return new TreeSet();
  }

  static public char lastChar(String s) {
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
  }

  static public <A> A[] arrayOfSameType(A[] a, int n) {
    return newObjectArrayOfSameType(a, n);
  }

  static public <A> List<A> subList(List<A> l, int startIndex) {
    return subList(l, startIndex, l(l));
  }

  static public <A> List<A> subList(int startIndex, List<A> l) {
    return subList(l, startIndex);
  }

  static public <A> List<A> subList(int startIndex, int endIndex, List<A> l) {
    return subList(l, startIndex, endIndex);
  }

  static public <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = Math.max(0, startIndex);
    endIndex = Math.min(n, endIndex);
    if (startIndex > endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return l.subList(startIndex, endIndex);
  }

  static public <A> List<A> subList(List<A> l, IntRange r) {
    return subList(l, r.start, r.end);
  }

  static public Graphics2D antiAliasOn(Graphics2D g) {
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    return g;
  }

  static public <A, B> Map<A, B> synchroIdentityHashMap() {
    return synchroMap(new IdentityHashMap());
  }

  static public <A, B> void mapPut2(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        map.put(key, value);
      else
        map.remove(key);
  }

  static public int localYear() {
    return localYear(now());
  }

  static public int localYear(long time) {
    return parseInt(simpleDateFormat_local("yyyy").format(time));
  }

  static public java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) {
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
    sdf.setTimeZone(timeZone);
    return sdf;
  }

  static public String padLeft(String s, char c, int n) {
    return rep(c, n - l(s)) + s;
  }

  static public String padLeft(String s, int n) {
    return padLeft(s, ' ', n);
  }

  static public int localMonth(long time) {
    return parseInt(simpleDateFormat_local("MM").format(time));
  }

  static public int localMonth() {
    return localMonth(now());
  }

  static public int localDayOfMonth(long time) {
    return parseInt(simpleDateFormat_local("dd").format(time));
  }

  static public int localDayOfMonth() {
    return localDayOfMonth(now());
  }

  static public File standardLogFile() {
    return getProgramFile("log");
  }

  static public void logQuoted(String logFile, String line) {
    logQuoted(getProgramFile(logFile), line);
  }

  static public void logQuoted(File logFile, String line) {
    appendToFile(logFile, quote(line) + "\n");
  }

  static public JTextArea enableWordWrapForTextArea(JTextArea ta) {
    return enableWordWrapForTextArea(ta, true);
  }

  static public JTextArea enableWordWrapForTextArea(JTextArea ta, boolean enabled) {
    if (ta != null) {
      swing(new Runnable() {

        public void run() {
          try {
            ta.setLineWrap(enabled);
            ta.setWrapStyleWord(true);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ta.setLineWrap(enabled);\r\n    ta.setWrapStyleWord(true);\r\n    // Haven't foun...";
        }
      });
    }
    return ta;
  }

  static public JTextArea jtextarea() {
    return jTextArea();
  }

  static public JTextArea jtextarea(String text) {
    return jTextArea(text);
  }

  static public List vmBus_queryAll(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    List out = new ArrayList();
    for (Object o : unnullForIteration(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg));
    for (Object o : unnullForIteration(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg));
    return out;
  }

  static public int toInt_checked(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  static public boolean regexpFinds(String pat, String s) {
    return regexp(pat, s).find();
  }

  static public boolean regexpFinds(Pattern pat, String s) {
    return regexp(pat, s).find();
  }

  static public int[] subIntArray(int[] b, int start) {
    return subIntArray(b, start, l(b));
  }

  static public int[] subIntArray(int[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start == 0 && end == l(b))
      return b;
    if (start >= end)
      return new int[0];
    int[] x = new int[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  static public int[] subIntArray(int[] a, IntRange r) {
    return r == null ? null : subIntArray(a, r.start, r.end);
  }

  static public short[] subShortArray(short[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start == 0 && end == l(b))
      return b;
    if (start >= end)
      return new short[0];
    short[] x = new short[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  static public byte[] subByteArray(byte[] b, int start) {
    return subByteArray(b, start, l(b));
  }

  static public byte[] subByteArray(byte[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start == 0 && end == l(b))
      return b;
    if (start >= end)
      return new byte[0];
    byte[] x = new byte[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  static public byte[] subByteArray(byte[] b, IntRange r) {
    return r == null ? null : subByteArray(b, r.start, r.end);
  }

  static public double[] subDoubleArray(double[] b, int start) {
    return subDoubleArray(b, start, l(b));
  }

  static public double[] subDoubleArray(double[] b, int start, int end) {
    start = max(start, 0);
    end = min(end, l(b));
    if (start == 0 && end == l(b))
      return b;
    if (start >= end)
      return new double[0];
    double[] x = new double[end - start];
    System.arraycopy(b, start, x, 0, end - start);
    return x;
  }

  static public boolean isLetter(char c) {
    return Character.isLetter(c);
  }

  static public <A> A last(List<A> l) {
    return empty(l) ? null : l.get(l.size() - 1);
  }

  static public char last(String s) {
    return empty(s) ? '#' : s.charAt(l(s) - 1);
  }

  static public int last(int[] a) {
    return l(a) != 0 ? a[l(a) - 1] : 0;
  }

  static public double last(double[] a) {
    return l(a) != 0 ? a[l(a) - 1] : 0;
  }

  static public <A> A last(A[] a) {
    return l(a) != 0 ? a[l(a) - 1] : null;
  }

  static public <A> A last(Iterator<A> it) {
    A a = null;
    while (it.hasNext()) {
      ping();
      a = it.next();
    }
    return a;
  }

  static public <A> A last(Collection<A> l) {
    if (l == null)
      return null;
    if (l instanceof List)
      return (A) last((List) l);
    if (l instanceof SortedSet)
      return (A) last((SortedSet) l);
    Iterator<A> it = iterator(l);
    A a = null;
    while (it.hasNext()) {
      ping();
      a = it.next();
    }
    return a;
  }

  static public <A> A last(SortedSet<A> l) {
    return l == null ? null : l.last();
  }

  static public int last(IntBuffer buf) {
    return buf.get(buf.size() - 1);
  }

  static public <A> A last(CompactLinkedHashSet<A> set) {
    return set == null ? null : set.last();
  }

  static public String beautifyStructure(String s) {
    List<String> tok = javaTokForStructure(s);
    structure_addTokenMarkers(tok);
    jreplace(tok, "lhm", "");
    return join(tok);
  }

  static public String struct_noStringSharing(Object o) {
    structure_Data d = new structure_Data();
    d.noStringSharing = true;
    return structure(o, d);
  }

  static public File imageSnippetCacheFile(String snippetID) {
    File dir = imageSnippetsCacheDir();
    if (!loadBufferedImage_useImageCache)
      return null;
    return new File(dir, parseSnippetID(snippetID) + ".png");
  }

  static public String snippetImageURL_noHttps(String snippetID) {
    return snippetImageURL_noHttps(snippetID, "png");
  }

  static public String snippetImageURL_noHttps(String snippetID, String contentType) {
    return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/");
  }

  static public ThreadLocal<Map<String, List<String>>> loadBinaryPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadBinaryPage_extraHeaders = new ThreadLocal();

  static public byte[] loadBinaryPage(String url) {
    try {
      print("Loading " + url);
      return loadBinaryPage(loadPage_openConnection(new URL(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage(URLConnection con) {
    try {
      Map<String, String> extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
      setHeaders(con);
      for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      return loadBinaryPage_noHeaders(con);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] loadBinaryPage_noHeaders(URLConnection con) {
    try {
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      InputStream inputStream = con.getInputStream();
      loadBinaryPage_responseHeaders.set(con.getHeaderFields());
      long len = 0;
      try {
        len = con.getContentLength();
      } catch (Throwable e) {
        printStackTrace(e);
      }
      int n = 0;
      while (true) {
        int ch = inputStream.read();
        if (ch < 0)
          break;
        buf.write(ch);
        if (++n % 100000 == 0)
          println("  " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
      }
      inputStream.close();
      return buf.toByteArray();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static byte[] saveBinaryFile(String fileName, byte[] contents) {
    try {
      File file = new File(fileName);
      File parentFile = file.getParentFile();
      if (parentFile != null)
        parentFile.mkdirs();
      String tempFileName = fileName + "_temp";
      FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
      fileOutputStream.write(contents);
      fileOutputStream.close();
      if (file.exists() && !file.delete())
        throw new IOException("Can't delete " + fileName);
      if (!new File(tempFileName).renameTo(file))
        throw new IOException("Can't rename " + tempFileName + " to " + fileName);
      vmBus_send("wroteFile", file);
      return contents;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] saveBinaryFile(File fileName, byte[] contents) {
    return saveBinaryFile(fileName.getPath(), contents);
  }

  static public File getGlobalCache() {
    File file = new File(javaxCachesDir(), "Binary Snippets");
    file.mkdirs();
    return file;
  }

  static public String dataSnippetLink(String snippetID) {
    long id = parseSnippetID(snippetID);
    if (id >= 1100000 && id < 1200000)
      return imageServerURL() + id;
    if (id >= 1200000 && id < 1300000) {
      String pw = muricaPassword();
      if (empty(pw))
        throw fail("Please set 'murica password by running #1008829");
      return "https://botcompany.de/files/" + id + "?_pass=" + pw;
    }
    return fileServerURL() + "/" + id;
  }

  static public String tb_mainServer_default = "https://code.botcompany.de:9898";

  static public Object tb_mainServer_override;

  static public String tb_mainServer() {
    if (tb_mainServer_override != null)
      return (String) callF(tb_mainServer_override);
    return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
  }

  static public File tb_mainServer_file() {
    return getProgramFile("#1001638", "mainserver.txt");
  }

  static public boolean tb_mainServer_isDefault() {
    return eq(tb_mainServer(), tb_mainServer_default);
  }

  static public <B, A extends B> A addAndReturn(Collection<B> c, A a) {
    if (c != null)
      c.add(a);
    return a;
  }

  static public long psI(String snippetID) {
    return parseSnippetID(snippetID);
  }

  static public List<String> allToString(Iterable c) {
    List<String> l = new ArrayList();
    for (Object o : unnull(c)) l.add(str(o));
    return l;
  }

  static public List<String> allToString(Object[] c) {
    List<String> l = new ArrayList();
    for (Object o : unnull(c)) l.add(str(o));
    return l;
  }

  static public boolean emptyString(String s) {
    return s == null || s.length() == 0;
  }

  static public String formatSnippetIDOpt(String s) {
    return isSnippetID(s) ? formatSnippetID(s) : s;
  }

  static public Class getMainClass() {
    return mc();
  }

  static public Class getMainClass(Object o) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class && eq(((Class) o).getName(), "x30"))
        return (Class) o;
      ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
      if (cl == null)
        return null;
      String name = mainClassNameForClassLoader(cl);
      return loadClassFromClassLoader_orNull(cl, name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  }

  static public void close_pcall(AutoCloseable c) {
    if (c != null) {
      try {
        c.close();
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
  }

  static public <A, B extends A> void addAll(Collection<A> c, Iterable<B> b) {
    if (c != null && b != null)
      for (A a : b) c.add(a);
  }

  static public <A, B extends A> boolean addAll(Collection<A> c, Collection<B> b) {
    return c != null && b != null && c.addAll(b);
  }

  static public <A, B extends A> boolean addAll(Collection<A> c, B... b) {
    return c != null && b != null && c.addAll(Arrays.asList(b));
  }

  static public <A, B> Map<A, B> addAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null && b != null)
      a.putAll(b);
    return a;
  }

  static public DynModule dm_currentModuleMandatory() {
    return dm_current_mandatory();
  }

  static public <A> Set<A> syncIdentityHashSet() {
    return (Set) synchronizedSet(identityHashSet());
  }

  static public <A> AutoCloseable tempAdd(final Collection<A> l, final A a) {
    if (l == null || l.contains(a))
      return null;
    l.add(a);
    return new AutoCloseable() {

      public String toString() {
        return "l.remove(a);";
      }

      public void close() throws Exception {
        l.remove(a);
      }
    };
  }

  static public List<String> splitAt(String s, String splitter) {
    if (empty(splitter))
      return null;
    List<String> parts = new ArrayList();
    int i = 0;
    if (s != null)
      while (i < l(s)) {
        int j = indexOf(s, splitter, i);
        if (j < 0)
          j = l(s);
        parts.add(substring(s, i, j));
        i = j + l(splitter);
      }
    return parts;
  }

  static public String addSuffix(String s, String suffix) {
    return s == null || s.endsWith(suffix) ? s : s + suffix;
  }

  static public Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

  static public File getProgramDir() {
    return programDir();
  }

  static public File getProgramDir(String snippetID) {
    return programDir(snippetID);
  }

  static public ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

  static public void checkFileNotTooBigToRead(File f) {
    callF(checkFileNotTooBigToRead_tl.get(), f);
  }

  static public String addPrefixIfNempty(String prefix, String s) {
    return addPrefixIfNotEmpty(prefix, s);
  }

  static public int countLines(String s) {
    return l(toLines(s));
  }

  static public String fromLines(Iterable lines) {
    StringBuilder buf = new StringBuilder();
    if (lines != null)
      for (Object line : lines) buf.append(str(line)).append('\n');
    return buf.toString();
  }

  static public String fromLines(String... lines) {
    return fromLines(asList(lines));
  }

  static public IterableIterator<String> toLines(File f) {
    return linesFromFile(f);
  }

  static public List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    if (s == null)
      return lines;
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start)
          lines.add(s.substring(start));
        break;
      }
      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
        i += 2;
      else
        ++i;
      start = i;
    }
    return lines;
  }

  static public int toLines_nextLineBreak(String s, int start) {
    int n = s.length();
    for (int i = start; i < n; i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }

  static public Timer installTimer(JComponent component, Object r, long delay) {
    return installTimer(component, r, delay, delay);
  }

  static public Timer installTimer(RootPaneContainer frame, long delay, Object r) {
    return installTimer(frame.getRootPane(), r, delay, delay);
  }

  static public Timer installTimer(JComponent component, long delay, Object r) {
    return installTimer(component, r, delay, delay);
  }

  static public Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
    return installTimer(component, r, delay, firstDelay);
  }

  static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
    return installTimer(component, r, delay, firstDelay, true);
  }

  static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
    if (component == null)
      return null;
    return (Timer) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          final Var<Timer> timer = new Var();
          timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent _evt) {
              try {
                AutoCloseable __1 = tempActivity(r);
                try {
                  try {
                    if (!allPaused())
                      if (isFalse(callF(r)))
                        cancelTimer(timer.get());
                  } catch (Throwable __e) {
                    printStackTrace(__e);
                  }
                } finally {
                  _close(__1);
                }
              } catch (Throwable __e) {
                messageBox(__e);
              }
            }
          }));
          timer.get().setInitialDelay(toInt(firstDelay));
          timer.get().setRepeats(repeats);
          bindTimerToComponent(timer.get(), component);
          return timer.get();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "final new Var<Timer> timer;\r\n    timer.set(new Timer(toInt(delay), actionList...";
      }
    });
  }

  static public Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) {
    return installTimer(frame.getRootPane(), delay, firstDelay, r);
  }

  static public <A> List<A> immutableEmptyList() {
    return Collections.emptyList();
  }

  static public short[] emptyShortArray = new short[0];

  static public short[] emptyShortArray() {
    return emptyShortArray;
  }

  static public <A, B> Map<A, B> immutableEmptyMap() {
    return Collections.emptyMap();
  }

  static public <A> F0<A> if0ToF0(IF0<A> f) {
    return f == null ? null : new F0<A>() {

      public A get() {
        try {
          return f.get();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret f.get();";
      }
    };
  }

  static public String strOrNull(Object o) {
    return o == null ? null : str(o);
  }

  static public String getSelectedItem(JList l) {
    return (String) l.getSelectedValue();
  }

  static public String getSelectedItem(JComboBox cb) {
    return strOrNull(cb.getSelectedItem());
  }

  static public void nohupJavax(final String javaxargs) {
    {
      startThread(new Runnable() {

        public void run() {
          try {
            call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);";
        }
      });
    }
  }

  static public void nohupJavax(final String javaxargs, final String vmArgs) {
    {
      startThread(new Runnable() {

        public void run() {
          try {
            call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);";
        }
      });
    }
  }

  static public String smartJoin(String[] args) {
    if (empty(args))
      return "";
    if (args.length == 1)
      return args[0];
    String[] a = new String[args.length];
    for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
    return join(" ", a);
  }

  static public String smartJoin(List<String> args) {
    return smartJoin(toStringArray(args));
  }

  static public <A> A liftLast(List<A> l) {
    if (empty(l))
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  static public <A> List<A> liftLast(int n, List<A> l) {
    int i = l(l) - n;
    List<A> part = cloneSubList(l, i);
    removeSubList(l, i);
    return part;
  }

  static public boolean isJavaIdentifier(String s) {
    if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
      return false;
    for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
      return false;
    return true;
  }

  static public boolean isInteger(String s) {
    int n = l(s);
    if (n == 0)
      return false;
    int i = 0;
    if (s.charAt(0) == '-')
      if (++i >= n)
        return false;
    while (i < n) {
      char c = s.charAt(i);
      if (c < '0' || c > '9')
        return false;
      ++i;
    }
    return true;
  }

  static public char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  static public boolean isInstance(Class type, Object arg) {
    return type.isInstance(arg);
  }

  static public String imageServerLink(String md5OrID) {
    if (possibleMD5(md5OrID))
      return "https://botcompany.de/images/md5/" + md5OrID;
    return imageServerLink(parseSnippetID(md5OrID));
  }

  static public String imageServerLink(long id) {
    return "https://botcompany.de/images/" + id;
  }

  static public <A> A[] makeArray(Class<A> type, int n) {
    return (A[]) Array.newInstance(type, n);
  }

  static public void smartSet(Field f, Object o, Object value) throws Exception {
    try {
      f.set(o, value);
    } catch (Exception e) {
      Class type = f.getType();
      if (type == int.class && value instanceof Long) {
        f.set(o, ((Long) value).intValue());
        return;
      }
      if (type == boolean.class && value instanceof String) {
        f.set(o, isTrueOrYes(((String) value)));
        return;
      }
      if (type == LinkedHashMap.class && value instanceof Map) {
        f.set(o, asLinkedHashMap((Map) value));
        return;
      }
      try {
        if (f.getType() == Concept.Ref.class) {
          f.set(o, ((Concept) o).new Ref((Concept) value));
          return;
        }
        if (o instanceof Concept.Ref) {
          f.set(o, ((Concept.Ref) o).get());
          return;
        }
      } catch (Throwable _e) {
      }
      throw e;
    }
  }

  static public String asString(Object o) {
    return o == null ? null : o.toString();
  }

  static public Map similarEmptyMap(Map m) {
    if (m instanceof TreeMap)
      return new TreeMap(((TreeMap) m).comparator());
    if (m instanceof LinkedHashMap)
      return new LinkedHashMap();
    return new HashMap();
  }

  static public Map similarEmptyMap(Iterable m) {
    if (m instanceof TreeSet)
      return new TreeMap(((TreeSet) m).comparator());
    if (m instanceof LinkedHashSet)
      return new LinkedHashMap();
    return new HashMap();
  }

  static public <A, B> Map<A, B> getMultipleKeys(Map<A, B> map, A... keys) {
    Map<A, B> map2 = similarEmptyMap(map);
    if (map != null && keys != null)
      for (A key : keys) map2.put(key, map.get(key));
    return map2;
  }

  static public <A, B> Map<A, B> getMultipleKeys(Map<A, B> map, Iterable<A> keys) {
    Map<A, B> map2 = similarEmptyMap(map);
    if (map != null && keys != null)
      for (A key : keys) map2.put(key, map.get(key));
    return map2;
  }

  static public Object vmBus_query(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    {
      Object __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
      if (__1 != null)
        return __1;
    }
    return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

  static public Object vmBus_query(String msg) {
    return vmBus_query(msg, (Object) null);
  }

  static public <A> A getAndClearThreadLocal(ThreadLocal<A> tl) {
    A a = tl.get();
    tl.set(null);
    return a;
  }

  static public int ratioToIntPercent(double x, double y) {
    return roundToInt(x * 100 / y);
  }

  static public String joinMap(Object f, Iterable l) {
    return join(map(f, l));
  }

  static public String joinMap(Iterable l, Object f) {
    return joinMap(f, l);
  }

  static public <A> String joinMap(Iterable<A> l, IF1<A, String> f) {
    return joinMap(f, l);
  }

  static public <A> String joinMap(IF1<A, String> f, Iterable<A> l) {
    return join(map(f, l));
  }

  static public <A, B> String joinMap(String separator, Map<A, B> map, IF2<A, B, String> f) {
    return join(separator, map(map, f));
  }

  static public boolean isDigit(char c) {
    return Character.isDigit(c);
  }

  static public Map synchroHashMap() {
    return synchronizedMap(new HashMap());
  }

  static public Method findMethod_cached(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        _MethodCache cache = callOpt_getCache((Class) o);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
            return m;
        return null;
      } else {
        _MethodCache cache = callOpt_getCache(o.getClass());
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          for (Method m : methods) if (findMethod_checkArgs(m, args, false))
            return m;
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isLetterOrDigit(char c) {
    return Character.isLetterOrDigit(c);
  }

  static public List<String> tok_combineCurlyBrackets_keep(List<String> tok) {
    List<String> l = new ArrayList();
    for (int i = 0; i < l(tok); i++) {
      String t = tok.get(i);
      if (odd(i) && eq(t, "{")) {
        int j = findEndOfCurlyBracketPart(tok, i);
        l.add(joinSubList(tok, i, j));
        i = j - 1;
      } else
        l.add(t);
    }
    return l;
  }

  static public int javaTok_n, javaTok_elements;

  static public boolean javaTok_opt = false;

  static public List<String> javaTok(String s) {
    ++javaTok_n;
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !regionMatches(s, j, "*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(javaTok_substringN(s, i, j));
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
        j += 2;
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
      } else if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j < l && !regionMatches(s, j, "]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

  static public List<String> javaTok(List<String> tok) {
    return javaTokWithExisting(join(tok), tok);
  }

  static public boolean startsWithAndEndsWith(String s, String prefix, String suffix) {
    return startsWith(s, prefix) && endsWith(s, suffix);
  }

  static public <A> List<A> dropFirstThreeAndLastThree(List<A> l) {
    return dropFirstAndLast(3, l);
  }

  static public String htmlencode_noQuotes(String s) {
    if (s == null)
      return "";
    int n = s.length();
    StringBuilder out = null;
    for (int i = 0; i < n; i++) {
      char c = s.charAt(i);
      if (c == '<') {
        if (out == null)
          out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
        out.append("&lt;");
      } else if (c == '>') {
        if (out == null)
          out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
        out.append("&gt;");
      } else if (c > 127 || c == '&') {
        int cp = s.codePointAt(i);
        if (out == null)
          out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
        out.append("&#x");
        out.append(intToHex_flexLength(cp));
        out.append(';');
        i += Character.charCount(cp) - 1;
      } else {
        if (out != null)
          out.append(c);
      }
    }
    return out == null ? s : out.toString();
  }

  static public Font loadFont(String snippetID) {
    try {
      return loadFont(snippetID, 12f);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(InputStream in) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(String snippetID, float fontSize) {
    return loadFont(loadLibrary(snippetID), fontSize);
  }

  static public Font loadFont(File f, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Font loadFont(InputStream in, float fontSize) {
    try {
      return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Set vm_generalWeakSet(Object name) {
    synchronized (vm_generalMap()) {
      Set set = (Set) (vm_generalMap_get(name));
      if (set == null)
        vm_generalMap_put(name, set = newWeakHashSet());
      return set;
    }
  }

  static public String getSnippetTitle(String id) {
    if (id == null)
      return null;
    if (!isSnippetID(id))
      return "?";
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.getSnippetTitle(id);
    return getSnippetTitle_noResourceLoader(id);
  }

  static public String getSnippetTitle_noResourceLoader(String id) {
    try {
      if (isLocalSnippetID(id))
        return localSnippetTitle(id);
      long parsedID = parseSnippetID(id);
      String url;
      if (isImageServerSnippet(parsedID))
        url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
      else if (isGeneralFileServerSnippet(parsedID))
        url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
      else
        url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
      String title = trim(loadPageSilently(url));
      if (title != null)
        try {
          saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
        } catch (Throwable __e) {
          print(exceptionToStringShort(__e));
        }
      return or(title, "?");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String getSnippetTitle(long id) {
    return getSnippetTitle(fsI(id));
  }

  static public boolean substanceLookAndFeelEnabled() {
    return startsWith(getLookAndFeel(), "org.pushingpixels.");
  }

  static public JComponent getTitlePaneComponent(RootPaneContainer window) {
    if (window instanceof JInternalFrame)
      return getInternalFrameTitlePaneComponent((JInternalFrame) window);
    if (!substanceLookAndFeelEnabled() || window == null)
      return null;
    JRootPane rootPane = window.getRootPane();
    if (rootPane != null) {
      Object ui = rootPane.getUI();
      return (JComponent) call(ui, "getTitlePane");
    }
    return null;
  }

  static public RootPaneContainer getPossiblyInternalFrame(Component c) {
    JInternalFrame f = getInternalFrame(c);
    if (f != null)
      return f;
    return optCast(RootPaneContainer.class, getWindow(c));
  }

  static public TreeSet<String> caseInsensitiveSet_treeSet() {
    return new TreeSet(caseInsensitiveComparator());
  }

  static public TreeSet<String> caseInsensitiveSet_treeSet(Collection<String> c) {
    return toCaseInsensitiveSet_treeSet(c);
  }

  static public <A> A[] newObjectArrayOfSameType(A[] a) {
    return newObjectArrayOfSameType(a, a.length);
  }

  static public <A> A[] newObjectArrayOfSameType(A[] a, int n) {
    return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
  }

  static public Map synchroMap() {
    return synchroHashMap();
  }

  static public <A, B> Map<A, B> synchroMap(Map<A, B> map) {
    return Collections.synchronizedMap(map);
  }

  static public Lock appendToFile_lock = lock();

  static public boolean appendToFile_keepOpen = false;

  static public HashMap<String, Writer> appendToFile_writers = new HashMap();

  static public void appendToFile(String path, String s) {
    try {
      Lock __0 = appendToFile_lock;
      lock(__0);
      try {
        mkdirsForFile(new File(path));
        path = getCanonicalPath(path);
        Writer writer = appendToFile_writers.get(path);
        if (writer == null) {
          writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8"));
          if (appendToFile_keepOpen)
            appendToFile_writers.put(path, writer);
        }
        writer.write(s);
        if (!appendToFile_keepOpen)
          writer.close();
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void appendToFile(File path, String s) {
    if (path != null)
      appendToFile(path.getPath(), s);
  }

  static public void cleanMeUp_appendToFile() {
    AutoCloseable __3 = tempCleaningUp();
    try {
      Lock __1 = appendToFile_lock;
      lock(__1);
      try {
        closeAllWriters(values(appendToFile_writers));
        appendToFile_writers.clear();
      } finally {
        unlock(__1);
      }
    } finally {
      _close(__3);
    }
  }

  static public <A> boolean addIfNotNull(Collection<A> l, A a) {
    return a != null && l != null & l.add(a);
  }

  static public <A> void addIfNotNull(MultiSet<A> ms, A a) {
    if (a != null && ms != null)
      ms.add(a);
  }

  static public Matcher regexp(String pat, String s) {
    return regexp(compileRegexp(pat), unnull(s));
  }

  static public Matcher regexp(java.util.regex.Pattern pat, String s) {
    return pat.matcher(unnull(s));
  }

  static public java.util.regex.Pattern regexp(String pat) {
    return compileRegexp(pat);
  }

  static public <A> Iterator<A> iterator(Iterable<A> c) {
    return c == null ? emptyIterator() : c.iterator();
  }

  static public List<String> javaTokForStructure(String s) {
    return javaTok_noMLS(s);
  }

  static public String structure_addTokenMarkers(String s) {
    return join(structure_addTokenMarkers(javaTokForStructure(s)));
  }

  static public List<String> structure_addTokenMarkers(List<String> tok) {
    TreeSet<Integer> refs = new TreeSet();
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("t") && isInteger(t.substring(1)))
        refs.add(parseInt(t.substring(1)));
    }
    if (empty(refs))
      return tok;
    for (int i : refs) {
      int idx = i * 2 + 1;
      if (idx >= l(tok))
        continue;
      String t = "";
      if (endsWithLetterOrDigit(tok.get(idx - 1)))
        t = " ";
      tok.set(idx, t + "m" + i + " " + tok.get(idx));
    }
    return tok;
  }

  static public String jreplace(String s, String in, String out) {
    return jreplace(s, in, out, null);
  }

  static public String jreplace(String s, String in, String out, Object condition) {
    List<String> tok = javaTok(s);
    return jreplace(tok, in, out, condition) ? join(tok) : s;
  }

  static public boolean jreplace(List<String> tok, String in, String out) {
    return jreplace(tok, in, out, false, true, null);
  }

  static public boolean jreplace(List<String> tok, String in, String out, Object condition) {
    return jreplace(tok, in, out, false, true, condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, IF2<List<String>, Integer, Boolean> condition) {
    return jreplace(tok, in, out, (Object) condition);
  }

  static public boolean jreplace(List<String> tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
    String[] toks = javaTokForJFind_array(in);
    int lTokin = toks.length * 2 + 1;
    boolean anyChange = false;
    int i = -1;
    for (int n = 0; n < 10000; n++) {
      i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
      if (i < 0)
        return anyChange;
      List<String> subList = tok.subList(i - 1, i + lTokin - 1);
      String expansion = jreplaceExpandRefs(out, subList);
      int end = i + lTokin - 2;
      clearAllTokens(tok, i, end);
      tok.set(i, expansion);
      if (reTok)
        reTok(tok, i, end);
      i = end;
      anyChange = true;
    }
    throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
  }

  static public boolean jreplace_debug = false;

  static public int loadPage_defaultTimeout = 60000;

  static public ThreadLocal<String> loadPage_charset = new ThreadLocal();

  static public boolean loadPage_allowGzip = true, loadPage_debug;

  static public boolean loadPage_anonymous = false;

  static public int loadPage_verboseness = 100000;

  static public int loadPage_retries = 1;

  static public ThreadLocal<Boolean> loadPage_silent = new ThreadLocal();

  static volatile public int loadPage_forcedTimeout;

  static public ThreadLocal<Integer> loadPage_forcedTimeout_byThread = new ThreadLocal();

  static public ThreadLocal<Map<String, List<String>>> loadPage_responseHeaders = new ThreadLocal();

  static public ThreadLocal<Map<String, String>> loadPage_extraHeaders = new ThreadLocal();

  static public ThreadLocal<Long> loadPage_sizeLimit = new ThreadLocal();

  public static String loadPageSilently(String url) {
    try {
      return loadPageSilently(new URL(loadPage_preprocess(url)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadPageSilently(URL url) {
    try {
      if (!networkAllowanceTest(str(url)))
        throw fail("Not allowed: " + url);
      IOException e = null;
      for (int tries = 0; tries < loadPage_retries; tries++) try {
        URLConnection con = loadPage_openConnection(url);
        return loadPage(con, url);
      } catch (IOException _e) {
        e = _e;
        if (loadPage_debug)
          print(exceptionToStringShort(e));
        if (tries < loadPage_retries - 1)
          sleepSeconds(1);
      }
      throw e;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage_preprocess(String url) {
    if (url.startsWith("tb/"))
      url = tb_mainServer() + "/" + url;
    if (url.indexOf("://") < 0)
      url = "http://" + url;
    return url;
  }

  static public String loadPage(String url) {
    try {
      url = loadPage_preprocess(url);
      if (!isTrue(loadPage_silent.get()))
        printWithTime("Loading: " + hideCredentials(url));
      return loadPageSilently(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadPage(URL url) {
    return loadPage(url.toExternalForm());
  }

  static public String loadPage(URLConnection con, URL url) throws IOException {
    return loadPage(con, url, true);
  }

  static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
    Map<String, String> extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
    Long limit = optPar(loadPage_sizeLimit);
    if (addHeaders)
      try {
        if (!loadPage_anonymous)
          setHeaders(con);
        if (loadPage_allowGzip)
          con.setRequestProperty("Accept-Encoding", "gzip");
        con.setRequestProperty("X-No-Cookies", "1");
        for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
      } catch (Throwable e) {
      }
    vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
    loadPage_responseHeaders.set(con.getHeaderFields());
    InputStream in = null;
    try {
      in = urlConnection_getInputStream(con);
      if (loadPage_debug)
        print("Put stream in map: " + currentThread());
      String contentType = con.getContentType();
      if (contentType == null) {
        throw new IOException("Page could not be read: " + hideCredentials(url));
      }
      String charset = loadPage_charset == null ? null : loadPage_charset.get();
      if (charset == null)
        charset = loadPage_guessCharset(contentType);
      if ("gzip".equals(con.getContentEncoding())) {
        if (loadPage_debug)
          print("loadPage: Using gzip.");
        in = newGZIPInputStream(in);
      }
      Reader r;
      try {
        r = new InputStreamReader(in, unquote(charset));
      } catch (UnsupportedEncodingException e) {
        print(toHex(utf8(charset)));
        throw e;
      }
      boolean silent = isTrue(loadPage_silent.get());
      StringBuilder buf = new StringBuilder();
      int n = 0;
      while (limit == null || n < limit) {
        ping();
        int ch = r.read();
        if (ch < 0)
          break;
        buf.append((char) ch);
        ++n;
        if (!silent && (n % loadPage_verboseness) == 0)
          print("  " + n + " chars read");
      }
      return buf.toString();
    } finally {
      if (loadPage_debug)
        print("loadPage done");
      vm_generalSubMap("URLConnection per thread").remove(currentThread());
      if (in != null)
        in.close();
    }
  }

  static public String loadPage_guessCharset(String contentType) {
    Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
    String match = m.matches() ? m.group(1) : null;
    if (loadPage_debug)
      print("loadPage: contentType=" + contentType + ", match: " + match);
    return or(match, "UTF-8");
  }

  static public URLConnection loadPage_openConnection(URL url) {
    URLConnection con = openConnection(url);
    int timeout = toInt(loadPage_forcedTimeout_byThread.get());
    if (timeout == 0)
      timeout = loadPage_forcedTimeout;
    if (timeout != 0)
      setURLConnectionTimeouts(con, loadPage_forcedTimeout);
    else
      setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
    return con;
  }

  static public <A> A println(A a) {
    return print(a);
  }

  static public String imageServerURL() {
    return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
  }

  static volatile public boolean muricaPassword_pretendNotAuthed = false;

  static public String muricaPassword() {
    if (muricaPassword_pretendNotAuthed)
      return null;
    return trim(loadTextFile(muricaPasswordFile()));
  }

  static public String fileServerURL() {
    return "https://botcompany.de/files";
  }

  static public String mainClassNameForClassLoader(ClassLoader cl) {
    return or((String) callOpt(cl, "mainClassName"), "main");
  }

  static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
    try {
      return cl == null ? null : cl.loadClass(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public <A> Set<A> synchronizedSet() {
    return synchroHashSet();
  }

  static public <A> Set<A> synchronizedSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  static public <A> Set<A> identityHashSet() {
    return Collections.newSetFromMap(new IdentityHashMap());
  }

  static public File programDir_mine;

  static public File programDir() {
    return programDir(getProgramID());
  }

  static public File programDir(String snippetID) {
    boolean me = sameSnippetID(snippetID, programID());
    if (programDir_mine != null && me)
      return programDir_mine;
    File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
    if (me) {
      String c = caseID();
      if (nempty(c))
        dir = newFile(dir, c);
    }
    return dir;
  }

  static public File programDir(String snippetID, String subPath) {
    return new File(programDir(snippetID), subPath);
  }

  static public String addPrefixIfNotEmpty(String prefix, String s) {
    return empty(s) ? "" : prefix + s;
  }

  static public CloseableIterableIterator<String> linesFromFile(File f) {
    return linesFromFile(f, null);
  }

  static public CloseableIterableIterator<String> linesFromFile(File f, IResourceHolder resourceHolder) {
    try {
      if (!f.exists())
        return emptyCloseableIterableIterator();
      if (ewic(f.getName(), ".gz"))
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
      return linesFromReader(utf8bufferedReader(f), resourceHolder);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public CloseableIterableIterator<String> linesFromFile(String path) {
    return linesFromFile(path, null);
  }

  static public CloseableIterableIterator<String> linesFromFile(String path, IResourceHolder resourceHolder) {
    return linesFromFile(newFile(path), resourceHolder);
  }

  static public boolean allPaused() {
    return ping_pauseAll;
  }

  static public void cancelTimer(javax.swing.Timer timer) {
    if (timer != null)
      timer.stop();
  }

  static public void cancelTimer(java.util.Timer timer) {
    if (timer != null)
      timer.cancel();
  }

  static public void cancelTimer(Object o) {
    if (o instanceof java.util.Timer)
      cancelTimer((java.util.Timer) o);
    else if (o instanceof javax.swing.Timer)
      cancelTimer((javax.swing.Timer) o);
    else if (o instanceof AutoCloseable) {
      try {
        ((AutoCloseable) o).close();
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
  }

  static public void bindTimerToComponent(final Timer timer, JFrame f) {
    bindTimerToComponent(timer, f.getRootPane());
  }

  static public void bindTimerToComponent(final Timer timer, JComponent c) {
    if (c.isShowing())
      timer.start();
    c.addAncestorListener(new AncestorListener() {

      public void ancestorAdded(AncestorEvent event) {
        timer.start();
      }

      public void ancestorRemoved(AncestorEvent event) {
        timer.stop();
      }

      public void ancestorMoved(AncestorEvent event) {
      }
    });
  }

  static public Class hotwireOnce(String programID) {
    return hotwireCached(programID, false);
  }

  static public boolean isQuoted(String s) {
    if (isNormalQuoted(s))
      return true;
    return isMultilineQuoted(s);
  }

  static public String[] toStringArray(Collection<String> c) {
    String[] a = new String[l(c)];
    Iterator<String> it = c.iterator();
    for (int i = 0; i < l(a); i++) a[i] = it.next();
    return a;
  }

  static public String[] toStringArray(Object o) {
    if (o instanceof String[])
      return (String[]) o;
    else if (o instanceof Collection)
      return toStringArray((Collection<String>) o);
    else
      throw fail("Not a collection or array: " + getClassName(o));
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
    return newSubList(l, startIndex, endIndex);
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex) {
    return newSubList(l, startIndex);
  }

  static public void removeSubList(List l, int from, int to) {
    if (l != null)
      subList(l, from, to).clear();
  }

  static public void removeSubList(List l, int from) {
    if (l != null)
      subList(l, from).clear();
  }

  static public char firstChar(String s) {
    return s.charAt(0);
  }

  static public boolean possibleMD5(String s) {
    return isMD5(s);
  }

  static public boolean isTrueOrYes(Object o) {
    return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o)));
  }

  static public <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
    if (map instanceof LinkedHashMap)
      return (LinkedHashMap) map;
    LinkedHashMap<A, B> m = new LinkedHashMap();
    if (map != null)
      synchronized (collectionMutex(map)) {
        m.putAll(map);
      }
    return m;
  }

  static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) {
        Object __1 = pcallF(f, args);
        if (__1 != null)
          return __1;
      }
    return null;
  }

  static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
    while (it.hasNext()) {
      Object __2 = pcallF(it.next(), args);
      if (__2 != null)
        return __2;
    }
    return null;
  }

  static public int roundToInt(double d) {
    return (int) Math.round(d);
  }

  static public Map synchronizedMap() {
    return synchroMap();
  }

  static public <A, B> Map<A, B> synchronizedMap(Map<A, B> map) {
    return synchroMap(map);
  }

  static public Method findMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args);
  }

  static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
      if (debug)
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
      return false;
    }
    return true;
  }

  static public int findEndOfCurlyBracketPart(List<String> cnc, int i) {
    int j = i + 2, level = 1;
    while (j < cnc.size()) {
      if (eq(cnc.get(j), "{"))
        ++level;
      else if (eq(cnc.get(j), "}"))
        --level;
      if (level == 0)
        return j + 1;
      ++j;
    }
    return cnc.size();
  }

  static public String joinSubList(List<String> l, int i, int j) {
    return join(subList(l, i, j));
  }

  static public String joinSubList(List<String> l, int i) {
    return join(subList(l, i));
  }

  static public String joinSubList(List<String> l, IntRange r) {
    return r == null ? null : joinSubList(l, r.start, r.end);
  }

  static public boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) {
    return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len);
  }

  static public boolean regionMatches(String a, int offsetA, String b) {
    return regionMatches(a, offsetA, b, 0, l(b));
  }

  static public String javaTok_substringN(String s, int i, int j) {
    if (i == j)
      return "";
    if (j == i + 1 && s.charAt(i) == ' ')
      return " ";
    return s.substring(i, j);
  }

  static public String javaTok_substringC(String s, int i, int j) {
    return s.substring(i, j);
  }

  static public List<String> javaTokWithExisting(String s, List<String> existing) {
    ++javaTok_n;
    int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
    ArrayList<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
    int l = s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
        tok.add(existing.get(n));
      else
        tok.add(javaTok_substringN(s, i, j));
      ++n;
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
        j += 2;
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
      } else if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener) {
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
        tok.add(existing.get(n));
      else
        tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    javaTok_elements += tok.size();
    return tok;
  }

  static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
  }

  static public <A> List<A> dropFirstAndLast(int n, List<A> l) {
    return cloneSubList(l, n, l(l) - n);
  }

  static public <A> List<A> dropFirstAndLast(int m, int n, List<A> l) {
    return cloneSubList(l, m, l(l) - n);
  }

  static public <A> List<A> dropFirstAndLast(List<A> l) {
    return dropFirstAndLast(1, l);
  }

  static public String dropFirstAndLast(String s) {
    return substring(s, 1, l(s) - 1);
  }

  static public String intToHex_flexLength(int i) {
    return Integer.toHexString(i);
  }

  static public File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  static public <A> Set<A> newWeakHashSet() {
    return synchroWeakHashSet();
  }

  static public boolean isLocalSnippetID(String snippetID) {
    return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
  }

  static public boolean isLocalSnippetID(long snippetID) {
    return snippetID >= 1000 && snippetID <= 9999;
  }

  static public String localSnippetTitle(String snippetID) {
    if (!isLocalSnippetID(snippetID))
      return null;
    File f = localSnippetFile(snippetID);
    if (!f.exists())
      return null;
    return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
  }

  static public String muricaCredentialsQuery() {
    return htmlQuery(muricaCredentials());
  }

  static public boolean isGeneralFileServerSnippet(long id) {
    return id >= 1400000 && id < 1500000;
  }

  static public String standardCredentials_noCookies() {
    return standardCredentials() + "&noCookies=1";
  }

  static public boolean saveTextFileIfChanged(File f, String contents) {
    return saveTextFileIfDifferent(f, contents);
  }

  static public File snippetTitle_cacheFile(String snippetID) {
    return javaxCachesDir("Snippet Titles/" + psI(snippetID));
  }

  static public String getLookAndFeel() {
    return getClassName(UIManager.getLookAndFeel());
  }

  static public JComponent getInternalFrameTitlePaneComponent(JInternalFrame f) {
    return (JComponent) childWithClassNameEndingWith(f, "InternalFrameTitlePane");
  }

  static public JInternalFrame getInternalFrame(final Object _o) {
    return _o == null ? null : swing(new F0<JInternalFrame>() {

      public JInternalFrame get() {
        try {
          Object o = _o;
          if (o instanceof ButtonGroup)
            o = first(buttonsInGroup((ButtonGroup) o));
          if (!(o instanceof Component))
            return null;
          Component c = (Component) o;
          while (c != null) {
            if (c instanceof JInternalFrame)
              return (JInternalFrame) c;
            c = c.getParent();
          }
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "O o = _o;\r\n    if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
      }
    });
  }

  static public <A> A optCast(Class<A> c, Object o) {
    return isInstance(c, o) ? (A) o : null;
  }

  static public Comparator<String> caseInsensitiveComparator() {
    return betterCIComparator();
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(Iterable<String> c) {
    if (isCISet(c))
      return (TreeSet) c;
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, c);
    return set;
  }

  static public TreeSet<String> toCaseInsensitiveSet_treeSet(String... x) {
    TreeSet<String> set = caseInsensitiveSet_treeSet();
    addAll(set, x);
    return set;
  }

  static public String getCanonicalPath(File f) {
    try {
      return f == null ? null : f.getCanonicalPath();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String getCanonicalPath(String path) {
    return getCanonicalPath(newFile(path));
  }

  static public AutoCloseable tempCleaningUp() {
    AutoCloseable result = null;
    return result;
  }

  static public void closeAllWriters(Collection<? extends Writer> l) {
    for (Writer w : unnull(l)) {
      try {
        w.close();
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
  }

  static public <A, B> Collection<B> values(Map<A, B> map) {
    return map == null ? emptyList() : map.values();
  }

  static public Collection values(Object map) {
    return values((Map) map);
  }

  static public <A, B> Collection<B> values(MultiMap<A, B> mm) {
    return mm == null ? emptyList() : concatLists(values(mm.data));
  }

  static public Map<String, java.util.regex.Pattern> compileRegexp_cache = syncMRUCache(10);

  static public java.util.regex.Pattern compileRegexp(String pat) {
    java.util.regex.Pattern p = compileRegexp_cache.get(pat);
    if (p == null) {
      compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
    }
    return p;
  }

  static public Iterator emptyIterator() {
    return Collections.emptyIterator();
  }

  static public List<String> javaTok_noMLS(String s) {
    ArrayList<String> tok = new ArrayList();
    int l = s == null ? 0 : s.length();
    int i = 0, n = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(javaTok_substringN(s, i, j));
      ++n;
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          int c2 = s.charAt(j);
          if (c2 == opener || c2 == '\n' && opener == '\'') {
            ++j;
            break;
          } else if (c2 == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      ++n;
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    return tok;
  }

  static public Map<String, String[]> javaTokForJFind_array_cache = synchronizedMRUCache(1000);

  static public String[] javaTokForJFind_array(String s) {
    String[] tok = javaTokForJFind_array_cache.get(s);
    if (tok == null)
      javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
    return tok;
  }

  static public int findCodeTokens(List<String> tok, String... tokens) {
    return findCodeTokens(tok, 1, false, tokens);
  }

  static public int findCodeTokens(List<String> tok, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, 1, ignoreCase, tokens);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String... tokens) {
    return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
  }

  static public HashSet<String> findCodeTokens_specials = lithashset("*", "<quoted>", "<id>", "<int>", "\\*");

  static public int findCodeTokens_bails, findCodeTokens_nonbails;

  static public interface findCodeTokens_Matcher {

    public boolean get(String token);
  }

  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
    int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
    int i = startIdx | 1;
    if (i >= end)
      return -1;
    String firstToken = tokens[0];
    if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
      while (i < end && !firstToken.equals(tok.get(i))) i += 2;
    }
    findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
    for (int j = 0; j < nTokens; j++) {
      String p = tokens[j];
      findCodeTokens_Matcher matcher;
      if (p.equals("*"))
        matcher = t -> true;
      else if (p.equals("<quoted>"))
        matcher = t -> isQuoted(t);
      else if (p.equals("<id>"))
        matcher = t -> isIdentifier(t);
      else if (p.equals("<int>"))
        matcher = t -> isInteger(t);
      else if (p.equals("\\*"))
        matcher = t -> t.equals("*");
      else if (ignoreCase)
        matcher = t -> eqic(p, t);
      else
        matcher = t -> t.equals(p);
      matchers[j] = matcher;
    }
    outer: for (; i < end; i += 2) {
      for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
        continue outer;
      if (condition == null || checkTokCondition(condition, tok, i - 1))
        return i;
    }
    return -1;
  }

  static public String jreplaceExpandRefs(String s, List<String> tokref) {
    if (!contains(s, '$'))
      return s;
    List<String> tok = javaTok(s);
    for (int i = 1; i < l(tok); i += 2) {
      String t = tok.get(i);
      if (t.startsWith("$") && isInteger(t.substring(1))) {
        String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
        tok.set(i, x);
      } else if (t.equals("\\")) {
        tok.set(i, "");
        i += 2;
      }
    }
    return join(tok);
  }

  static public void clearAllTokens(List<String> tok) {
    for (int i = 0; i < tok.size(); i++) tok.set(i, "");
  }

  static public void clearAllTokens(List<String> tok, int i, int j) {
    for (; i < j; i++) tok.set(i, "");
  }

  static public List<String> reTok(List<String> tok) {
    replaceCollection(tok, javaTok(tok));
    return tok;
  }

  static public List<String> reTok(List<String> tok, int i) {
    return reTok(tok, i, i + 1);
  }

  static public List<String> reTok(List<String> tok, int i, int j) {
    i = max(i & ~1, 0);
    j = min(l(tok), j | 1);
    if (i >= j)
      return tok;
    List<String> t = javaTok(joinSubList(tok, i, j));
    replaceListPart(tok, i, j, t);
    return tok;
  }

  static public List<String> reTok(List<String> tok, IntRange r) {
    if (r != null)
      reTok(tok, r.start, r.end);
    return tok;
  }

  static public boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  static public <A> A printWithTime(A a) {
    return printWithTime("", a);
  }

  static public <A> A printWithTime(String s, A a) {
    print(hmsWithColons() + ": " + s, a);
    return a;
  }

  static public Map vm_generalSubMap(Object name) {
    synchronized (vm_generalMap()) {
      Map map = (Map) (vm_generalMap_get(name));
      if (map == null)
        vm_generalMap_put(name, map = synchroMap());
      return map;
    }
  }

  static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
    return con.getInputStream();
  }

  static public GZIPInputStream newGZIPInputStream(File f) {
    return gzInputStream(f);
  }

  static public GZIPInputStream newGZIPInputStream(InputStream in) {
    return gzInputStream(in);
  }

  static public String unquote(String s) {
    if (s == null)
      return null;
    if (startsWith(s, '[')) {
      int i = 1;
      while (i < s.length() && s.charAt(i) == '=') ++i;
      if (i < s.length() && s.charAt(i) == '[') {
        String m = s.substring(1, i);
        if (s.endsWith("]" + m + "]"))
          return s.substring(i + 1, s.length() - i - 1);
      }
    }
    if (s.length() > 1) {
      char c = s.charAt(0);
      if (c == '\"' || c == '\'') {
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
        StringBuilder sb = new StringBuilder(l - 1);
        for (int i = 1; i < l; i++) {
          char ch = s.charAt(i);
          if (ch == '\\') {
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
            if (nextChar >= '0' && nextChar <= '7') {
              String code = "" + nextChar;
              i++;
              if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                code += s.charAt(i + 1);
                i++;
                if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
                  code += s.charAt(i + 1);
                  i++;
                }
              }
              sb.append((char) Integer.parseInt(code, 8));
              continue;
            }
            switch(nextChar) {
              case '\"':
                ch = '\"';
                break;
              case '\\':
                ch = '\\';
                break;
              case 'b':
                ch = '\b';
                break;
              case 'f':
                ch = '\f';
                break;
              case 'n':
                ch = '\n';
                break;
              case 'r':
                ch = '\r';
                break;
              case 't':
                ch = '\t';
                break;
              case '\'':
                ch = '\'';
                break;
              case 'u':
                if (i >= l - 5) {
                  ch = 'u';
                  break;
                }
                int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
                sb.append(Character.toChars(code));
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          sb.append(ch);
        }
        return sb.toString();
      }
    }
    return s;
  }

  static public String toHex(byte[] bytes) {
    return bytesToHex(bytes);
  }

  static public String toHex(byte[] bytes, int ofs, int len) {
    return bytesToHex(bytes, ofs, len);
  }

  static public byte[] utf8(String s) {
    return toUtf8(s);
  }

  static public Matcher regexpMatcher(String pat, String s) {
    return compileRegexp(pat).matcher(unnull(s));
  }

  static public URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) {
    con.setConnectTimeout(toInt(timeout));
    con.setReadTimeout(toInt(timeout));
    if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout)
      print("Warning: Timeouts not set by JDK.");
    return con;
  }

  static public URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
    if (con.getConnectTimeout() == 0) {
      con.setConnectTimeout(toInt(timeout));
      if (con.getConnectTimeout() != timeout)
        print("Warning: URL connect timeout not set by JDK.");
    }
    if (con.getReadTimeout() == 0) {
      con.setReadTimeout(toInt(timeout));
      if (con.getReadTimeout() != timeout)
        print("Warning: URL read timeout not set by JDK.");
    }
    return con;
  }

  static public File muricaPasswordFile() {
    return new File(javaxSecretDir(), "murica/muricaPasswordFile");
  }

  static public <A> Set<A> synchroHashSet() {
    return synchronizedSet(new HashSet<A>());
  }

  static public boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {

    public Object next() {
      throw fail();
    }

    public boolean hasNext() {
      return false;
    }
  };

  static public <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
    return emptyCloseableIterableIterator_instance;
  }

  static public CloseableIterableIterator<String> linesFromReader(Reader r) {
    return linesFromReader(r, null);
  }

  static public CloseableIterableIterator<String> linesFromReader(Reader r, IResourceHolder resourceHolder) {
    final BufferedReader br = bufferedReader(r);
    return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0<String>() {

      public String get() {
        try {
          return readLineFromReaderWithClose(br);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret readLineFromReaderWithClose(br);";
      }
    }, _wrapIOCloseable(r)));
  }

  static public BufferedReader utf8bufferedReader(InputStream in) {
    try {
      return in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public BufferedReader utf8bufferedReader(File f) {
    try {
      return utf8bufferedReader(newFileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public TreeMap<String, Class> hotwireCached_cache = new TreeMap();

  static public Lock hotwireCached_lock = lock();

  static public Class hotwireCached(String programID) {
    return hotwireCached(programID, true);
  }

  static public Class hotwireCached(String programID, boolean runMain) {
    return hotwireCached(programID, runMain, false);
  }

  static public Class hotwireCached(String programID, boolean runMain, boolean dependent) {
    Lock __0 = hotwireCached_lock;
    lock(__0);
    try {
      programID = formatSnippetID(programID);
      Class c = hotwireCached_cache.get(programID);
      if (c == null) {
        c = hotwire(programID);
        if (dependent)
          makeDependent(c);
        if (runMain)
          callMain(c);
        hotwireCached_cache.put(programID, c);
      }
      return c;
    } finally {
      unlock(__0);
    }
  }

  static public boolean isNormalQuoted(String s) {
    int l = l(s);
    if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
      return false;
    int j = 1;
    while (j < l) if (s.charAt(j) == '"')
      return j == l - 1;
    else if (s.charAt(j) == '\\' && j + 1 < l)
      j += 2;
    else
      ++j;
    return false;
  }

  static public boolean isMultilineQuoted(String s) {
    if (!startsWith(s, "["))
      return false;
    int i = 1;
    while (i < s.length() && s.charAt(i) == '=') ++i;
    return i < s.length() && s.charAt(i) == '[';
  }

  static public <A> List<A> newSubList(List<A> l, int startIndex, int endIndex) {
    return cloneList(subList(l, startIndex, endIndex));
  }

  static public <A> List<A> newSubList(List<A> l, int startIndex) {
    return cloneList(subList(l, startIndex));
  }

  static public boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(s);
  }

  static public boolean isTrueOpt(Object o) {
    if (o instanceof Boolean)
      return ((Boolean) o).booleanValue();
    return false;
  }

  static public boolean isTrueOpt(String field, Object o) {
    return isTrueOpt(getOpt(field, o));
  }

  static public boolean eqicOneOf(String s, String... l) {
    for (String x : l) if (eqic(s, x))
      return true;
    return false;
  }

  static public List<String> isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative");

  static public boolean isYes(String s) {
    return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s))));
  }

  static public <A> Set<A> synchroWeakHashSet() {
    return Collections.newSetFromMap((Map) newWeakHashMap());
  }

  static public File localSnippetFile(long snippetID) {
    return localSnippetsDir(snippetID + ".text");
  }

  static public File localSnippetFile(String snippetID) {
    return localSnippetFile(parseSnippetID(snippetID));
  }

  static public String getFileInfoField(File f, String field) {
    return getOneLineFileInfoField(f, field);
  }

  static public File dropExtension(File f) {
    return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
  }

  static public String dropExtension(String s) {
    return takeFirst(s, smartLastIndexOf(s, '.'));
  }

  static public String htmlQuery(Map params) {
    return empty(params) ? "" : "?" + makePostData(params);
  }

  static public String htmlQuery(Object... data) {
    return empty(data) ? "" : "?" + makePostData(data);
  }

  static public Object[] muricaCredentials() {
    String pass = muricaPassword();
    return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
  }

  static public String standardCredentials() {
    String user = standardCredentialsUser();
    String pass = standardCredentialsPass();
    if (nempty(user) && nempty(pass))
      return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
    return "";
  }

  static public boolean saveTextFileIfDifferent(File f, String contents) {
    if (eq(loadTextFile(f), contents))
      return false;
    {
      saveTextFile(f, contents);
      return true;
    }
  }

  static public Component childWithClassNameEndingWith(Component c, String suffix) {
    if (endsWith(className(c), suffix))
      return c;
    Component x;
    for (Component comp : getComponents(c)) if ((x = childWithClassNameEndingWith(comp, suffix)) != null)
      return x;
    return null;
  }

  static public betterCIComparator_C betterCIComparator_instance;

  static public betterCIComparator_C betterCIComparator() {
    if (betterCIComparator_instance == null)
      betterCIComparator_instance = new betterCIComparator_C();
    return betterCIComparator_instance;
  }

  final static public class betterCIComparator_C implements Comparator<String> {

    public int compare(String s1, String s2) {
      if (s1 == null)
        return s2 == null ? 0 : -1;
      if (s2 == null)
        return 1;
      int n1 = s1.length();
      int n2 = s2.length();
      int min = Math.min(n1, n2);
      for (int i = 0; i < min; i++) {
        char c1 = s1.charAt(i);
        char c2 = s2.charAt(i);
        if (c1 != c2) {
          c1 = Character.toUpperCase(c1);
          c2 = Character.toUpperCase(c2);
          if (c1 != c2) {
            c1 = Character.toLowerCase(c1);
            c2 = Character.toLowerCase(c2);
            if (c1 != c2) {
              return c1 - c2;
            }
          }
        }
      }
      return n1 - n2;
    }
  }

  static public boolean isCISet(Iterable<String> l) {
    return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
  }

  static public <A, B> Map<A, B> syncMRUCache(int size) {
    return synchroMap(new MRUCache(size));
  }

  static public <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
    return synchroMap(new MRUCache(maxSize));
  }

  static public String[] codeTokensAsStringArray(List<String> tok) {
    int n = max(0, (l(tok) - 1) / 2);
    String[] out = new String[n];
    for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
    return out;
  }

  static public int jfind(String s, String in) {
    return jfind(javaTok(s), in);
  }

  static public int jfind(List<String> tok, String in) {
    return jfind(tok, 1, in);
  }

  static public int jfind(List<String> tok, int startIdx, String in) {
    return jfind(tok, startIdx, in, null);
  }

  static public int jfind(List<String> tok, String in, Object condition) {
    return jfind(tok, 1, in, condition);
  }

  static public int jfind(List<String> tok, String in, ITokCondition condition) {
    return jfind(tok, 1, in, condition);
  }

  static public int jfind(List<String> tok, int startIndex, String in, ITokCondition condition) {
    return jfind(tok, startIndex, in, (Object) condition);
  }

  static public int jfind(List<String> tok, int startIdx, String in, Object condition) {
    return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
  }

  static public int jfind(List<String> tok, List<String> tokin) {
    return jfind(tok, 1, tokin);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin) {
    return jfind(tok, startIdx, tokin, null);
  }

  static public int jfind(List<String> tok, int startIdx, String[] tokinC, Object condition) {
    return findCodeTokens(tok, startIdx, false, tokinC, condition);
  }

  static public int jfind(List<String> tok, int startIdx, List<String> tokin, Object condition) {
    return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
  }

  static public List<String> jfind_preprocess(List<String> tok) {
    for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
    replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
    return tok;
  }

  static public boolean isIdentifier(String s) {
    return isJavaIdentifier(s);
  }

  static public boolean checkTokCondition(Object condition, List<String> tok, int i) {
    if (condition instanceof TokCondition)
      return ((TokCondition) condition).get(tok, i);
    return checkCondition(condition, tok, i);
  }

  static public <A> void replaceCollection(Collection<A> dest, Collection<A> src) {
    if (dest == src)
      return;
    dest.clear();
    if (src != null)
      dest.addAll(src);
  }

  static public void replaceListPart(List l, int i, int j, List l2) {
    replaceSublist(l, i, j, l2);
  }

  static volatile public Object isAllowed_function;

  static volatile public boolean isAllowed_all = true;

  static public boolean isAllowed(String askingMethod, Object... args) {
    Object f = vm_generalMap_get("isAllowed_function");
    if (f != null && !isTrue(callF(f, askingMethod, args)))
      return false;
    return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
  }

  static public String hmsWithColons() {
    return hmsWithColons(now());
  }

  static public String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

  static public int gzInputStream_defaultBufferSize = 65536;

  static public GZIPInputStream gzInputStream(File f) {
    try {
      return gzInputStream(new FileInputStream(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public GZIPInputStream gzInputStream(File f, int bufferSize) {
    try {
      return gzInputStream(new FileInputStream(f), bufferSize);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public GZIPInputStream gzInputStream(InputStream in) {
    return gzInputStream(in, gzInputStream_defaultBufferSize);
  }

  static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
    try {
      return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  public static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len * 2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs + i]);
      stringBuilder.append(s.substring(s.length() - 2, s.length()));
    }
    return stringBuilder.toString();
  }

  static public byte[] toUtf8(String s) {
    try {
      return s.getBytes(utf8charset());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File javaxSecretDir_dir;

  static public File javaxSecretDir() {
    return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
  }

  static public File javaxSecretDir(String sub) {
    return newFile(javaxSecretDir(), sub);
  }

  static public BufferedReader bufferedReader(Reader r) {
    return bufferedReader(r, 8192);
  }

  static public BufferedReader bufferedReader(Reader r, int bufSize) {
    if (r == null)
      return null;
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r);
  }

  static public <A extends AutoCloseable> A holdResource(IResourceHolder holder, A a) {
    {
      if (holder != null)
        holder.add(a);
    }
    return a;
  }

  static public <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
    class IFF2 extends CloseableIterableIterator<A> {

      public A a;

      public boolean done = false;

      public boolean hasNext() {
        getNext();
        return !done;
      }

      public A next() {
        getNext();
        if (done)
          throw fail();
        A _a = a;
        a = null;
        return _a;
      }

      public void getNext() {
        if (done || a != null)
          return;
        a = f.get();
        done = a == null;
      }

      public void close() throws Exception {
        if (closeable != null)
          closeable.close();
      }
    }
    ;
    return new IFF2();
  }

  static public String readLineFromReaderWithClose(BufferedReader r) {
    try {
      String s = r.readLine();
      if (s == null)
        r.close();
      return s;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
    return c == null ? null : new AutoCloseable() {

      public String toString() {
        return "c.close();\r\n    _registerIO(c, null, false);";
      }

      public void close() throws Exception {
        c.close();
        _registerIO(c, null, false);
      }
    };
  }

  static public <A> A _registerIOWrap(A wrapper, Object wrapped) {
    return wrapper;
  }

  static public FileInputStream newFileInputStream(File path) throws IOException {
    return newFileInputStream(path.getPath());
  }

  static public FileInputStream newFileInputStream(String path) throws IOException {
    FileInputStream f = new FileInputStream(path);
    _registerIO(f, path, true);
    return f;
  }

  static public Class<?> hotwire(String src) {
    return hotwire(src, __1 -> mainClassNameForClassLoader(__1));
  }

  static public Class<?> hotwire(String src, IF1<ClassLoader, String> calculateMainClass) {
    assertFalse(_inCore());
    Class j = getJavaX();
    if (isAndroid()) {
      synchronized (j) {
        List<File> libraries = new ArrayList<File>();
        File srcDir = (File) call(j, "transpileMain", src, libraries);
        if (srcDir == null)
          throw fail("transpileMain returned null (src=" + quote(src) + ")");
        Object androidContext = get(j, "androidContext");
        return (Class) call(j, "loadx2android", srcDir, src);
      }
    } else {
      Class c = (Class) (call(j, "hotwire", src));
      hotwire_copyOver(c);
      return c;
    }
  }

  static public Object makeDependent_postProcess;

  static public void makeDependent(Object c) {
    if (c == null)
      return;
    assertTrue("Not a class", c instanceof Class);
    dependentClasses();
    hotwire_classes.add(new WeakReference(c));
    Object local_log = getOpt(mc(), "local_log");
    if (local_log != null)
      setOpt(c, "local_log", local_log);
    Object print_byThread = getOpt(mc(), "print_byThread");
    if (print_byThread != null)
      setOpt(c, "print_byThread", print_byThread);
    callF(makeDependent_postProcess, c);
  }

  static public <A> A callMain(A c, String... args) {
    callOpt(c, "main", new Object[] { args });
    return c;
  }

  static public void callMain() {
    callMain(mc());
  }

  static public boolean isLowerHexString(String s) {
    for (int i = 0; i < l(s); i++) {
      char c = s.charAt(i);
      if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
      } else
        return false;
    }
    return true;
  }

  static public <A> ArrayList<A> litlist(A... a) {
    ArrayList l = new ArrayList(a.length);
    for (A x : a) l.add(x);
    return l;
  }

  static public String collapseWord(String s) {
    if (s == null)
      return "";
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < l(s); i++) if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i - 1)))
      buf.append(s.charAt(i));
    return buf.toString();
  }

  static public List<String> toLowerCase(List<String> strings) {
    List<String> x = new ArrayList();
    for (String s : strings) x.add(s.toLowerCase());
    return x;
  }

  static public String[] toLowerCase(String[] strings) {
    String[] x = new String[l(strings)];
    for (int i = 0; i < l(strings); i++) x[i] = strings[i].toLowerCase();
    return x;
  }

  static public String toLowerCase(String s) {
    return s == null ? "" : s.toLowerCase();
  }

  static public String firstWord2(String s) {
    s = xltrim(s);
    if (empty(s))
      return "";
    if (isLetterOrDigit(first(s)))
      return takeCharsWhile(__40 -> isLetterOrDigit(__40), s);
    else
      return "" + first(s);
  }

  static public File localSnippetsDir() {
    return javaxDataDir("Personal Programs");
  }

  static public File localSnippetsDir(String sub) {
    return newFile(localSnippetsDir(), sub);
  }

  static public String getOneLineFileInfoField(File f, String field) {
    File infoFile = associatedInfosFile(f);
    List<String> lines = lines(loadTextFile(infoFile));
    return firstStartingWithIC_drop(lines, field + ": ");
  }

  static public String makePostData(Map map) {
    StringBuilder buf = new StringBuilder();
    for (Map.Entry<Object, Object> e : castMapToMapO(map).entrySet()) {
      String key = (String) (e.getKey());
      Object val = e.getValue();
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

  static public String makePostData(Object... params) {
    StringBuilder buf = new StringBuilder();
    int n = l(params);
    for (int i = 0; i + 1 < n; i += 2) {
      String key = (String) (params[i]);
      Object val = params[i + 1];
      if (val != null) {
        String value = str(val);
        if (nempty(buf))
          buf.append("&");
        buf.append(urlencode(key)).append("=").append(urlencode((value)));
      }
    }
    return str(buf);
  }

  static public String standardCredentialsUser() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username"))));
  }

  static public String standardCredentialsPass() {
    return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass"))));
  }

  static public String urlencode(String x) {
    try {
      return URLEncoder.encode(unnull(x), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
  }

  static public List<Component> getComponents(final Component c) {
    return !(c instanceof Container) ? emptyList() : asList(swing(new F0<Component[]>() {

      public Component[] get() {
        try {
          return ((Container) c).getComponents();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret ((Container) c).getComponents();";
      }
    }));
  }

  static public <A> List<A> replaceSublist(List<A> l, List<A> x, List<A> y) {
    if (x == null)
      return l;
    int i = 0;
    while (true) {
      i = indexOfSubList(l, x, i);
      if (i < 0)
        break;
      replaceSublist(l, i, i + l(x), y);
      i += l(y);
    }
    return l;
  }

  static public <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
    int n = y.size(), toIndex_new = fromIndex + n;
    if (toIndex_new < toIndex) {
      removeSubList(l, toIndex_new, toIndex);
      copyListPart(y, 0, l, fromIndex, n);
    } else {
      copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
      if (toIndex_new > toIndex)
        l.addAll(toIndex, subList(y, toIndex - fromIndex));
    }
    return l;
  }

  static public <A> List<A> replaceSublist(List<A> l, IntRange r, List<A> y) {
    return replaceSublist(l, r.start, r.end, y);
  }

  static public boolean checkCondition(Object condition, Object... args) {
    return isTrue(callF(condition, args));
  }

  static public <A> boolean checkCondition(IF1<A, Boolean> condition, A arg) {
    return isTrue(callF(condition, arg));
  }

  static public Charset utf8charset_cache;

  static public Charset utf8charset() {
    if (utf8charset_cache == null)
      utf8charset_cache = utf8charset_load();
    return utf8charset_cache;
  }

  static public Charset utf8charset_load() {
    return Charset.forName("UTF-8");
  }

  static public boolean _inCore() {
    return false;
  }

  static public List hotwire_copyOver_after = synchroList();

  static public void hotwire_copyOver(Class c) {
    for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
    setOptIfNotNull(c, "mainBot", getMainBot());
    setOpt(c, "creator_class", new WeakReference(mc()));
    pcallFAll(hotwire_copyOver_after, c);
  }

  static public List<Class> dependentClasses() {
    return cleanUpAndGetWeakReferencesList(hotwire_classes);
  }

  static public boolean charactersEqualIC(char c1, char c2) {
    if (c1 == c2)
      return true;
    char u1 = Character.toUpperCase(c1);
    char u2 = Character.toUpperCase(c2);
    if (u1 == u2)
      return true;
    return Character.toLowerCase(u1) == Character.toLowerCase(u2);
  }

  static public String xltrim(String s) {
    int i = 0, n = l(s);
    while (i < n && contains(" \t\r\n", s.charAt(i))) ++i;
    return substr(s, i);
  }

  static public String takeCharsWhile(String s, Object pred) {
    int i = 0;
    while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i;
    return substring(s, 0, i);
  }

  static public String takeCharsWhile(IF1<Character, Boolean> f, String s) {
    return takeCharsWhile(s, f);
  }

  static public File associatedInfosFile(File f) {
    return replaceExtension(f, ".infos");
  }

  static public String firstStartingWithIC_drop(Collection<String> l, final String prefix) {
    for (String s : unnull(l)) if (swic(s, prefix))
      return substring(s, l(prefix));
    return null;
  }

  static public String firstStartingWithIC_drop(String prefix, Collection<String> l) {
    return firstStartingWithIC_drop(l, prefix);
  }

  static public Map<Object, Object> castMapToMapO(Map map) {
    return map;
  }

  static public File oneOfTheFiles(String... paths) {
    if (paths != null)
      for (String path : paths) if (fileExists(path))
        return newFile(path);
    return null;
  }

  static public File oneOfTheFiles(File... files) {
    return oneOfTheFiles(asList(files));
  }

  static public File oneOfTheFiles(Iterable<File> files) {
    if (files != null)
      for (File f : files) if (fileExists(f))
        return f;
    return null;
  }

  static public <A> int indexOfSubList(List<A> x, List<A> y) {
    return indexOfSubList(x, y, 0);
  }

  static public <A> int indexOfSubList(List<A> x, List<A> y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j)))
        continue outer;
      return i;
    }
    return -1;
  }

  static public <A> int indexOfSubList(List<A> x, A[] y, int i) {
    outer: for (; i + l(y) <= l(x); i++) {
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j]))
        continue outer;
      return i;
    }
    return -1;
  }

  static public <A, B extends A> void copyListPart(List<B> a, int i1, List<A> b, int i2, int n) {
    if (a == null || b == null)
      return;
    for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i));
  }

  static public List<WeakReference<Class>> hotwire_classes = synchroList();

  static public Class<?> hotwireDependent(String src) {
    Class c = hotwire(src);
    makeDependent(c);
    return c;
  }

  static public void setOptIfNotNull(Object o, String field, Object value) {
    if (value != null)
      setOpt(o, field, value);
  }

  static public Object mainBot;

  static public Object getMainBot() {
    return mainBot;
  }

  static public void pcallFAll(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) pcallF(f, args);
  }

  static public void pcallFAll(Iterator it, Object... args) {
    while (it.hasNext()) pcallF(it.next(), args);
  }

  static public <A> List<A> cleanUpAndGetWeakReferencesList(List<WeakReference<A>> l) {
    if (l == null)
      return null;
    synchronized (l) {
      List<A> out = new ArrayList();
      for (int i = 0; i < l(l); i++) {
        A a = l.get(i).get();
        if (a == null)
          l.remove(i--);
        else
          out.add(a);
      }
      return out;
    }
  }

  static public String substr(String s, int x) {
    return substring(s, x);
  }

  static public String substr(String s, int x, int y) {
    return substring(s, x, y);
  }

  static public boolean fileExists(String path) {
    return path != null && new File(path).exists();
  }

  static public boolean fileExists(File f) {
    return f != null && f.exists();
  }

  static public class JSection extends SingleComponentPanel {

    public JSection(Component c) {
      super(c);
    }

    public String getTitle() {
      Border border = getBorder();
      if (border instanceof TitledBorder)
        return ((TitledBorder) border).getTitle();
      return null;
    }
  }

  static public class Var<A> implements IVar<A>, ISetter<A> {

    public Var() {
    }

    public Var(A v) {
      this.v = v;
    }

    public A v;

    public synchronized void set(A a) {
      if (v != a) {
        v = a;
        notifyAll();
      }
    }

    public synchronized A get() {
      return v;
    }

    public synchronized boolean has() {
      return v != null;
    }

    public void clear() {
      set(null);
    }

    public String toString() {
      return str(this.get());
    }
  }

  static public interface ITokCondition {

    public boolean get(List<String> tok, int i);
  }

  static abstract public class TokCondition implements ITokCondition {

    public abstract boolean get(List<String> tok, int i);
  }

  final static public class PingSource {

    final public PingSource setAction(IF0<Boolean> action) {
      return action(action);
    }

    public PingSource action(IF0<Boolean> action) {
      this.action = action;
      return this;
    }

    final public IF0<Boolean> getAction() {
      return action();
    }

    public IF0<Boolean> action() {
      return action;
    }

    volatile public IF0<Boolean> action;

    public boolean get() {
      var a = action;
      return a != null && a.get();
    }
  }

  static public class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    volatile public A value;

    transient public List onChange = synchroList();

    public SimpleLiveValue(Class<A> type) {
      this.type = type;
    }

    public SimpleLiveValue(Class<A> type, A value) {
      this.value = value;
      this.type = type;
    }

    public Class<A> getType() {
      return type;
    }

    public A get() {
      return value;
    }

    public void onChange(Runnable l) {
      onChange.add(l);
    }

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }

    public void removeOnChangeListener(Runnable l) {
      onChange.remove(l);
    }

    public void fireChanged() {
      pcallFAll(onChange);
    }

    public void set(A a) {
      if (neq(value, a)) {
        value = a;
        fireChanged();
      }
    }
  }

  static public class PrecisePolygon extends Path2D.Double {

    public PrecisePolygon(List<DoublePt> points) {
      var p = first(points);
      moveTo(p.x, p.y);
      for (int i = 1; i < l(points); i++) {
        p = points.get(i);
        lineTo(p.x, p.y);
      }
      closePath();
    }
  }

  static public class WindowDragger extends MouseAdapter {

    public MouseEvent mouseDownEvent;

    public JComponent src;

    public Pt rel;

    public Window window;

    public WindowDragger(MouseEvent mouseDownEvent) {
      this.mouseDownEvent = mouseDownEvent;
      if (mouseDownEvent == null)
        return;
      src = optCast(JComponent.class, mouseDownEvent.getComponent());
      if (src == null)
        return;
      window = getWindow(src);
      if (window == null)
        return;
      rel = pt(mouseDownEvent.getXOnScreen() - window.getX(), mouseDownEvent.getYOnScreen() - window.getY());
      addMouseAndMotionListener(src, this);
    }

    public void mouseDragged(MouseEvent e) {
      updatePosition(e);
    }

    public void mouseReleased(MouseEvent e) {
      if (e.getButton() != mouseDownEvent.getButton())
        return;
      updatePosition(e);
      removeMouseAdapter(src, this);
      dragDone();
    }

    public void updatePosition(MouseEvent e) {
      window.setLocation(e.getXOnScreen() - rel.x, e.getYOnScreen() - rel.y);
    }

    public void dragDone() {
    }
  }

  static public class WindowResizeDragger extends MouseAdapter {

    public int cornerSize = 10;

    public boolean debug = false;

    public Pt minWindowSize = pt(20, 20);

    public MouseEvent mouseDownEvent;

    public JComponent src;

    public Window window;

    public Rect originalPosition, srcBounds;

    public int dragX, dragY;

    public Cursor originalCursor, ourCursor;

    public WindowResizeDragger(JComponent src) {
      this.src = src;
      addMouseAndMotionListener(src, this);
    }

    public boolean engaged() {
      return mouseDownEvent != null;
    }

    public void start(MouseEvent e) {
      this.mouseDownEvent = e;
      window = getWindow(src);
      if (window == null)
        return;
      originalPosition = toRect(getBounds(window));
      cursorCalc(e, true);
    }

    public void cursorCalc(MouseEvent e, boolean inside) {
      srcBounds = toRect(boundsOnScreen(src));
      Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen());
      if (distance(mouse.y, srcBounds.y2()) <= cornerSize)
        dragY = 1;
      else if (distance(mouse.y, srcBounds.y1()) <= cornerSize)
        dragY = -1;
      else
        dragY = 0;
      if (distance(mouse.x, srcBounds.x2()) <= cornerSize)
        dragX = 1;
      else if (distance(mouse.x, srcBounds.x1()) <= cornerSize)
        dragX = -1;
      else
        dragX = 0;
      originalCursor = src.getCursor();
      int iCursor = dragY * 3 + dragX + 4;
      int cursor = new int[] { Cursor.NW_RESIZE_CURSOR, Cursor.N_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR, Cursor.W_RESIZE_CURSOR, -1, Cursor.E_RESIZE_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR, Cursor.SE_RESIZE_CURSOR }[iCursor];
      Cursor newCursor = cursor >= 0 && inside ? Cursor.getPredefinedCursor(cursor) : null;
      if (debug)
        printVars(iCursor, "ourCursor", ourCursor, "newCursor", newCursor);
      if (newCursor != ourCursor) {
        ourCursor = newCursor;
        src.setCursor(newCursor);
      }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
      if (debug)
        print("mouseEntered");
      if (!engaged())
        cursorCalc(e, true);
    }

    @Override
    public void mouseExited(MouseEvent e) {
      if (debug)
        print("mouseExited");
      if (!engaged())
        cursorCalc(e, false);
    }

    public void mousePressed(MouseEvent e) {
      if (e.getButton() != MouseEvent.BUTTON1)
        return;
      if (engaged())
        return;
      start(e);
    }

    public void mouseDragged(MouseEvent e) {
      if (!engaged())
        return;
      updatePosition(e);
    }

    public void mouseMoved(MouseEvent e) {
      cursorCalc(e, true);
    }

    public void mouseReleased(MouseEvent e) {
      if (e.getButton() != mouseDownEvent.getButton())
        return;
      updatePosition(e);
      if (debug)
        print("drag done");
      if (src.getCursor() == ourCursor)
        src.setCursor(originalCursor);
      mouseDownEvent = null;
      dragDone();
    }

    public void updatePosition(MouseEvent e) {
      Rect w = toRect(window.getBounds());
      Pt a = topLeftCorner(w), b = bottomRightCorner(w);
      Pt mouse = pt(e.getXOnScreen(), e.getYOnScreen());
      if (dragX < 0)
        a.x = min(b.x - minWindowSize.x, mouse.x + originalPosition.x - mouseDownEvent.getXOnScreen());
      else if (dragX > 0)
        b.x = max(a.x + minWindowSize.x, mouse.x + originalPosition.x2() - mouseDownEvent.getXOnScreen());
      if (dragY < 0)
        a.y = min(b.y - minWindowSize.y, mouse.y + originalPosition.y - mouseDownEvent.getYOnScreen());
      else if (dragY > 0)
        b.y = max(a.y + minWindowSize.y, mouse.y + originalPosition.y2() - mouseDownEvent.getYOnScreen());
      Rect r = rectFromPoints(a, b);
      if (debug)
        printVars("updatePosition", "w", w, "mouse", mouse, "a", a, "b", b, "dragX", dragX, "dragY", dragY);
      window.setBounds(toRectangle(r));
    }

    public void dragDone() {
    }
  }

  static public class FixedRateTimer extends java.util.Timer implements AutoCloseable {

    public FixedRateTimer() {
      this(false);
    }

    public FixedRateTimer(boolean daemon) {
      this(defaultTimerName(), daemon);
    }

    public FixedRateTimer(String name) {
      this(name, false);
    }

    public FixedRateTimer(String name, boolean daemon) {
      super(name, daemon);
      _registerTimer(this);
    }

    public List<Entry> entries = synchroList();

    static public class Entry implements IFieldsToList {

      public TimerTask task;

      public long firstTime;

      public long period;

      public Entry() {
      }

      public Entry(TimerTask task, long firstTime, long period) {
        this.period = period;
        this.firstTime = firstTime;
        this.task = task;
      }

      public String toString() {
        return shortClassName_dropNumberPrefix(this) + "(" + task + ", " + firstTime + ", " + period + ")";
      }

      public Object[] _fieldsToList() {
        return new Object[] { task, firstTime, period };
      }
    }

    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
      entries.add(new Entry(task, now() + delay, period));
      super.scheduleAtFixedRate(task, delay, period);
    }

    public void cancel() {
      entries.clear();
      super.cancel();
    }

    public int purge() {
      entries.clear();
      return super.purge();
    }

    public FixedRateTimer changeRate(int newPeriod) {
      Object r = ((SmartTimerTask) first(entries).task).r;
      cancel();
      return doEvery(newPeriod, r);
    }

    public void close() {
      try {
        cancel();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  static public class Fail extends RuntimeException implements IFieldsToList {

    public Object[] objects;

    public Fail() {
    }

    public Fail(Object... objects) {
      this.objects = objects;
    }

    public Object[] _fieldsToList() {
      return new Object[] { objects };
    }

    public Fail(Throwable cause, Object... objects) {
      super(cause);
      this.objects = objects;
    }

    public String toString() {
      return joinNemptiesWithColon("Fail", commaCombine(getCause(), objects));
    }
  }

  static public class GridCodec1 implements JavaCodec<BufferedImage>, IFieldsToList {

    public BufferedImage stage0_image;

    public GridCodec1() {
    }

    public GridCodec1(BufferedImage stage0_image) {
      this.stage0_image = stage0_image;
    }

    public Object[] _fieldsToList() {
      return new Object[] { stage0_image };
    }

    final public GridCodec1 setRows(int rows) {
      return rows(rows);
    }

    public GridCodec1 rows(int rows) {
      this.rows = rows;
      return this;
    }

    final public int getRows() {
      return rows();
    }

    public int rows() {
      return rows;
    }

    public int rows = 20;

    static public GridCodec1 demo() {
      return new GridCodec1(defaultScreenshot());
    }

    public Matrix<Integer> stage1_matrix;

    public long dataBytes, dataChars;

    public Matrix<Matrix<Integer>> stage2_grid;

    public JE_CompressEachElementIndividually<List<Integer>> strat;

    public JECompressionSearch<List<List<Integer>>> search;

    public JECompressionSearch<List<List<Integer>>> forward() {
      assertNotNull(stage0_image);
      var m = stage1_matrix = imageToMatrix(stage0_image);
      dataBytes = m.nCells() * 4 + 2;
      dataChars = dataBytes * 2 + l("lInt(\"\")");
      print("Matrix ~ " + shorten_str(60, m));
      print("Trivial comp ~ " + (m.nCells() * 8));
      stage2_grid = matrixToMNGrid_rows(m, rows);
      List<List<Integer>> stage3_cells = matrixOfMatricesToListOfLists(stage2_grid);
      search = jeCompressionSearch(stage3_cells, dataChars);
      strat = new JE_CompressEachElementIndividually<List<Integer>>().elementCompressionStrategy(() -> new JE_RepElement()).onCompressionFail(ints -> javaObjectToIJavaExpr(ints));
      search.addStrategy(strat);
      return search;
    }

    public String stats() {
      return strat == null ? null : strat.stats();
    }

    public JECompressionSearch<List<List<Integer>>>.Submission winner() {
      return search == null ? null : search.bestSubmission();
    }

    public ICachedJavaXExpr<List<List<Integer>>> winnerCodeWithoutPostProcessing() {
      return rCallF(winner(), __1 -> __1 == null ? null : __1.decompressor());
    }

    public ICachedJavaXExpr<BufferedImage> winnerCode() {
      var innerWinner = winnerCodeWithoutPostProcessing();
      if (innerWinner == null)
        return null;
      return addPostProcessing(innerWinner);
    }

    public ICachedJavaXExpr<BufferedImage> addPostProcessing(ICachedJavaXExpr<List<List<Integer>>> inner) {
      List<Integer> cellWidths = lambdaMapMethod(__67 -> __67.getWidth(), rowToList(stage2_grid, 0));
      List<Integer> cellHeights = lambdaMapMethod(__68 -> __68.getHeight(), colToList(stage2_grid, 0));
      return new AbstractJavaXExpr<BufferedImage>() {

        public FunctionCall javaConstruct() {
          return functionCall("gridLOLToImage", toJava(cellWidths), toJava(cellHeights), inner);
        }

        public String toString() {
          return str(javaConstruct());
        }

        public BufferedImage quickEval() {
          return gridLOLToImage(cellWidths, cellHeights, inner.quickEval());
        }
      };
    }

    public BufferedImage renderCellsLinearly() {
      return mergeBufferedImagesHorizontally(map(__41 -> intMatrixToImage(__41), matrixToList(stage2_grid)));
    }
  }

  static public class LeftAlignedLine extends JPanel {

    public LeftAlignedLine(Component... components) {
      setLayout(LetterLayout.leftAlignedRow());
      for (Component component : components) add(component);
    }

    public void add(String text) {
      add(new JLabel(text));
    }
  }

  static abstract public class F2<A, B, C> {

    abstract public C get(A a, B b);
  }

  static abstract public class F3<A, B, C, D> {

    abstract public D get(A a, B b, C c);
  }

  static public interface IProbabilisticScheduler extends Steppable {

    public void at(double probability, Runnable action);

    default public void schedule(double probability, Runnable action) {
      atRelative(probability, action);
    }

    default public void atRelative(double probability, Runnable action) {
      at(currentProbability() * probability, action);
    }

    public double currentProbability();

    public long stepCount();

    public double lastExecutedProbability();

    default public void schedule(Runnable x) {
      run(x);
    }

    default public void at(Runnable x) {
      run(x);
    }

    default public void run(Runnable x) {
      if (x == null)
        return;
      initAction(x);
      x.run();
    }

    default public void scheduleAll(Iterable<WithProbability<? extends Runnable>> l) {
      for (var x : unnullForIteration(l)) at(x.probability(), x.get());
    }

    default public void initAction(Object action) {
      if (action instanceof IProbabilistic)
        ((IProbabilistic) action).setScheduler(this);
    }
  }

  static public interface IBWIntegralImage extends MakesBufferedImage {

    public int getWidth();

    public int getHeight();

    public int getIIValue(int x, int y);

    default public double getPixelAverage(int x1, int y1, int x2, int y2) {
      int area = (x2 - x1) * (y2 - y1);
      return doubleRatio(getPixelSum(x1, y1, x2, y2), area);
    }

    default public double getPixelAverage(Rect r) {
      return getPixelAverage(r.x, r.y, r.x2(), r.y2());
    }

    default public int getPixelSum(int x1, int y1, int x2, int y2) {
      return bwIntegralImage_sumRect(this, x1, y1, x2, y2);
    }

    default public int getPixel(int x, int y) {
      return getPixelSum(x, y, x + 1, y + 1);
    }

    default public int getPixel(Pt p) {
      return getPixel(p.x, p.y);
    }

    default public BufferedImage getBufferedImage() {
      return scaleDownUsingIntegralImageBW(this, getWidth(), getHeight()).getBufferedImage();
    }
  }

  static public interface Hasher<A> {

    public int hashCode(A a);

    public boolean equals(A a, A b);
  }

  static abstract public class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {

    public void close() throws Exception {
    }
  }

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  static public interface IF2<A, B, C> {

    public C get(A a, B b);
  }

  static public class DoublePt {

    public double x, y;

    public DoublePt() {
    }

    public DoublePt(Point p) {
      x = p.x;
      y = p.y;
    }

    public DoublePt(double x, double y) {
      this.y = y;
      this.x = x;
    }

    public boolean equals(Object o) {
      return stdEq2(this, o);
    }

    public int hashCode() {
      return stdHash2(this);
    }

    public String toString() {
      return x + ", " + y;
    }
  }

  static public interface IVar<A> extends IF0<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

  static final public class NotifyingStringBuffer implements CharSequence, Appendable {

    public StringBuilder builder = new StringBuilder();

    public long changes;

    public List onChange;

    public synchronized Appendable append(char c) {
      builder.append(c);
      return change();
    }

    public synchronized Appendable append(CharSequence csq, int start, int end) {
      builder.append(csq, start, end);
      return change();
    }

    public synchronized Appendable append(CharSequence csq) {
      builder.append(csq);
      return change();
    }

    public synchronized void setLength(int i) {
      builder.setLength(i);
      change();
    }

    public synchronized void trimToSize() {
      builder.trimToSize();
    }

    public NotifyingStringBuffer change() {
      ++changes;
      pcallFAll(onChange);
      return this;
    }

    synchronized public String toString() {
      return builder.toString();
    }

    public synchronized char charAt(int index) {
      return builder.charAt(index);
    }

    public synchronized int length() {
      return builder.length();
    }

    public synchronized CharSequence subSequence(int start, int end) {
      return builder.subSequence(start, end);
    }

    synchronized public String substring(int start) {
      return builder.substring(start);
    }

    public int capacity() {
      return builder.capacity();
    }

    public synchronized void onChange(Runnable r) {
      onChange = listCreateAndAdd(onChange, r);
    }
  }

  abstract static public class DynPrintLogAndEnabled extends DynPrintLog {

    public JComponent visualize() {
      return dm_visualizeWithEnabled(super.visualize());
    }

    volatile public boolean enabled = true;

    transient public JPanel buttons;

    transient public SingleComponentPanel scpStretcherControl;

    public JComponent visualizeWithoutEnabled() {
      return super.visualize();
    }

    public JComponent dm_visualizeWithEnabled(JComponent main) {
      return centerAndSouthWithMargins(main, wrapControlArea());
    }

    public JComponent wrapControlArea() {
      return makeControlArea();
    }

    public JPanel makeControlArea() {
      if (scpStretcherControl == null)
        scpStretcherControl = singleComponentPanel();
      buttons = jrightalignedline(makeEnabledCheckBox());
      return centerAndEastWithMargin(scpStretcherControl, buttons);
    }

    static public JCheckBox makeEnabledCheckBox() {
      return dm_fieldCheckBox("enabled");
    }

    public void setEnabled(boolean b) {
      setField("enabled", b);
    }

    final public void addControls(Component... components) {
      addToControlArea(components);
    }

    public void addToControlArea(Component... components) {
      addComponentsFirst(buttons, components);
    }

    final public void addControl(Component component) {
      addButton(component);
    }

    public void addButton(Component component) {
      addComponentsFirst(buttons, component);
    }

    public void setMainControl(JComponent control) {
      scpSet(scpStretcherControl, control);
    }
  }

  static public class Cache<A> {

    public Object maker;

    public A value;

    public long loaded;

    static public boolean debug = false;

    public long changeCount;

    public Lock lock = lock();

    public Cache() {
    }

    public Cache(Object maker) {
      this.maker = maker;
    }

    public Cache(IF0<A> maker) {
      this.maker = maker;
    }

    public A get() {
      if (hasLock(lock))
        return value;
      Lock __0 = lock;
      lock(__0);
      try {
        if (loaded == 0) {
          value = make();
          changeCount++;
          loaded = sysNow();
        }
        return value;
      } finally {
        unlock(__0);
      }
    }

    public void clear() {
      Lock __1 = lock;
      lock(__1);
      try {
        if (debug && loaded != 0)
          print("Clearing cache");
        value = null;
        changeCount++;
        loaded = 0;
      } finally {
        unlock(__1);
      }
    }

    public void clear(double seconds) {
      Lock __2 = lock;
      lock(__2);
      try {
        if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
          clear();
      } finally {
        unlock(__2);
      }
    }

    public void set(A a) {
      Lock __3 = lock;
      lock(__3);
      try {
        value = a;
        ++changeCount;
        loaded = sysNow();
      } finally {
        unlock(__3);
      }
    }

    public A make() {
      return (A) callF(maker);
    }
  }

  final static public class _MethodCache {

    final public Class c;

    final public HashMap<String, List<Method>> cache = new HashMap();

    public _MethodCache(Class c) {
      this.c = c;
      _init();
    }

    public void _init() {
      Class _c = c;
      while (_c != null) {
        for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
          multiMapPut(cache, m.getName(), makeAccessible(m));
        _c = _c.getSuperclass();
      }
      for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
        multiMapPut(cache, m.getName(), makeAccessible(m));
    }

    public Method findMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Method findStaticMethod(String method, Object[] args) {
      try {
        List<Method> m = cache.get(method);
        if (m == null)
          return null;
        int n = m.size();
        for (int i = 0; i < n; i++) {
          Method me = m.get(i);
          if (isStaticMethod(me) && call_checkArgs(me, args, false))
            return me;
        }
        return null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }
  }

  static public class OKOrError<A> implements IF0<A> {

    public A value;

    final public Throwable getError() {
      return error();
    }

    public Throwable error() {
      return error;
    }

    public Throwable error;

    public OKOrError() {
    }

    public OKOrError(A value) {
      this.value = value;
    }

    public OKOrError(boolean dummy, Throwable error) {
      this.error = error;
    }

    final public boolean isOK() {
      return ok();
    }

    public boolean ok() {
      return error == null;
    }

    public String toString() {
      return ok() ? "ok: " + str(value) : "Error: " + str(error);
    }

    public A get() {
      return !ok() ? null : value;
    }

    public A getMandatory() {
      if (!ok())
        throw rethrow(error);
      return value;
    }
  }

  static public class WithTimestamp<A> extends Var<A> {

    public long timestamp;

    final public Timestamp timestamp() {
      return getTimestamp();
    }

    final public Timestamp timeStamp() {
      return getTimestamp();
    }

    public Timestamp getTimestamp() {
      return timestamp == 0 ? null : new Timestamp(timestamp);
    }

    public WithTimestamp() {
    }

    public WithTimestamp(long timestamp, A value) {
      super(value);
      this.timestamp = timestamp;
    }

    public WithTimestamp(A value) {
      this(now(), value);
    }

    public Timestamp timestampObj() {
      return timestamp == 0 ? null : new Timestamp(timestamp);
    }

    public String toString() {
      return toStringWithTimestamp(super.toString());
    }

    public String toStringQuoted() {
      return toStringWithTimestamp(quote(super.toString()));
    }

    public String toStringWithTimestamp(String s) {
      return s + " at " + localDateWithSeconds(timestamp);
    }

    public boolean olderThanMinutes(double minutes) {
      return elapsedMinutes_timestamp(timestamp) >= minutes;
    }

    public boolean olderThanSeconds(double seconds) {
      return elapsedSeconds_timestamp(timestamp) >= seconds;
    }
  }

  static public class Symbol implements CharSequence {

    public String text;

    public Symbol() {
    }

    public Symbol(String text, boolean dummy) {
      this.text = text;
    }

    public int hashCode() {
      return _hashCode(text);
    }

    public String toString() {
      return text;
    }

    public boolean equals(Object o) {
      return this == o;
    }

    public int length() {
      return text.length();
    }

    public char charAt(int index) {
      return text.charAt(index);
    }

    public CharSequence subSequence(int start, int end) {
      return text.substring(start, end);
    }
  }

  static public class BetterThread extends Thread {

    public Runnable target;

    public BetterThread(Runnable target) {
      this.target = target;
      _created();
    }

    public BetterThread(Runnable target, String name) {
      super(name);
      this.target = target;
      _created();
    }

    public void _created() {
      vmBus_send("threadCreated", this);
    }

    public void run() {
      try {
        try {
          vmBus_send("threadStarted", this);
          if (target != null)
            target.run();
        } finally {
          vmBus_send("threadEnded", this);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Runnable getTarget() {
      return target;
    }
  }

  static public interface ISetAndGet<A> extends ISetter<A>, IF0<A> {
  }

  static abstract public class LiveValue<A> {

    abstract public Class<A> getType();

    abstract public A get();

    abstract public void onChange(Runnable l);

    abstract public void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  static public class Dyn_FieldWatcher {

    public DynModule module;

    public String field;

    public Object value;

    public Runnable action;

    transient public IF1<Object, Object> cloneValue;

    public Object cloneValue(Object o) {
      return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o);
    }

    final public Object cloneValue_fallback(IF1<Object, Object> _f, Object o) {
      return _f != null ? _f.get(o) : cloneValue_base(o);
    }

    public Object cloneValue_base(Object o) {
      return o;
    }

    public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
      this(module, field, action, null);
    }

    public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) {
      this.cloneValue = cloneValue;
      this.action = action;
      this.field = field;
      this.module = module;
      value = cloneValue(get(module, field));
      module.onChange(new Runnable() {

        public void run() {
          try {
            check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "check();";
        }
      });
      module.onFieldChange(new VF1<String>() {

        public void get(String f) {
          try {
            if (eq(f, field))
              check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (eq(f, field))\r\n        check();";
        }
      });
    }

    public void check() {
      Object newValue = cloneValue(get(module, field));
      if (eq(value, newValue))
        return;
      value = newValue;
      dm_q(module, action);
    }
  }

  static public class Timestamp implements Comparable<Timestamp>, IFieldsToList {

    public long date;

    public Timestamp(long date) {
      this.date = date;
    }

    public boolean equals(Object o) {
      if (!(o instanceof Timestamp))
        return false;
      Timestamp __1 = (Timestamp) o;
      return date == __1.date;
    }

    public int hashCode() {
      int h = 2059094262;
      h = boostHashCombine(h, _hashCode(date));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { date };
    }

    public Timestamp() {
      date = now();
    }

    public long unixDate() {
      return date;
    }

    public String toString() {
      return formatLocalDateWithSeconds(date);
    }

    public int compareTo(Timestamp t) {
      return t == null ? 1 : cmp(date, t.date);
    }

    public Timestamp plus(Seconds seconds) {
      return plus(seconds == null ? null : seconds.getDouble());
    }

    public Timestamp plus(double seconds) {
      return new Timestamp(date + toMS(seconds));
    }

    public long minus(Timestamp ts) {
      return unixDate() - ts.unixDate();
    }
  }

  static public class DoubleRect {

    public double x, y, w, h;

    public DoubleRect() {
    }

    public DoubleRect(Rectangle r) {
      x = r.x;
      y = r.y;
      w = r.width;
      h = r.height;
    }

    public DoubleRect(double x, double y, double w, double h) {
      this.h = h;
      this.w = w;
      this.y = y;
      this.x = x;
    }

    public boolean eq(Object o) {
      if (!(o instanceof DoubleRect))
        return false;
      if (o == this)
        return true;
      DoubleRect r = (DoubleRect) o;
      return x == r.x && y == r.y && w == r.w && h == r.h;
    }

    public String toString() {
      return x + "," + y + " / " + w + "," + h;
    }

    public double x1() {
      return x;
    }

    public double y1() {
      return y;
    }

    public double x2() {
      return x + w;
    }

    public double y2() {
      return y + h;
    }

    public boolean contains(Pt p) {
      return contains(p.x, p.y);
    }

    public boolean contains(double _x, double _y) {
      return _x >= x && _y >= y && _x < x + w && _y < y + h;
    }

    public boolean empty() {
      return w <= 0 || h <= 0;
    }
  }

  static public class MultiMap<A, B> {

    public Map<A, List<B>> data = new HashMap<A, List<B>>();

    public int fullSize;

    public MultiMap() {
    }

    public MultiMap(boolean useTreeMap) {
      if (useTreeMap)
        data = new TreeMap();
    }

    public MultiMap(MultiMap<A, B> map) {
      putAll(map);
    }

    public MultiMap(Map<A, List<B>> data) {
      this.data = data;
    }

    public void put(A key, B value) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list == null)
          data.put(key, list = _makeEmptyList());
        list.add(value);
        ++fullSize;
      }
    }

    public void add(A key, B value) {
      put(key, value);
    }

    public void addAll(A key, Collection<B> values) {
      putAll(key, values);
    }

    public void addAllIfNotThere(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) setPut(key, value);
      }
    }

    public void setPut(A key, B value) {
      synchronized (data) {
        if (!containsPair(key, value))
          put(key, value);
      }
    }

    public boolean containsPair(A key, B value) {
      synchronized (data) {
        return get(key).contains(value);
      }
    }

    public void putAll(Collection<A> keys, B value) {
      synchronized (data) {
        for (A key : unnullForIteration(keys)) put(key, value);
      }
    }

    public void putAll(A key, Collection<B> values) {
      synchronized (data) {
        if (nempty(values))
          getActual(key).addAll(values);
      }
    }

    public void putAll(Iterable<Pair<A, B>> pairs) {
      synchronized (data) {
        for (Pair<A, B> p : unnullForIteration(pairs)) put(p.a, p.b);
      }
    }

    public void removeAll(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) remove(key, value);
      }
    }

    public List<B> get(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        return list == null ? Collections.<B>emptyList() : list;
      }
    }

    public List<B> getOpt(A key) {
      synchronized (data) {
        return data.get(key);
      }
    }

    public List<B> getAndClear(A key) {
      synchronized (data) {
        List<B> l = cloneList(data.get(key));
        remove(key);
        return l;
      }
    }

    public List<B> getActual(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list == null)
          data.put(key, list = _makeEmptyList());
        return list;
      }
    }

    public void clean(A key) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list != null && list.isEmpty()) {
          fullSize -= l(list);
          data.remove(key);
        }
      }
    }

    public Set<A> keySet() {
      synchronized (data) {
        return data.keySet();
      }
    }

    public Set<A> keys() {
      synchronized (data) {
        return data.keySet();
      }
    }

    public void remove(A key) {
      synchronized (data) {
        fullSize -= l(this.getOpt(key));
        data.remove(key);
      }
    }

    final public void remove(Pair<A, B> p) {
      removePair(p);
    }

    public void removePair(Pair<A, B> p) {
      if (p != null)
        remove(p.a, p.b);
    }

    public void remove(A key, B value) {
      synchronized (data) {
        List<B> list = data.get(key);
        if (list != null) {
          if (list.remove(value))
            fullSize--;
          if (list.isEmpty())
            data.remove(key);
        }
      }
    }

    public void clear() {
      synchronized (data) {
        data.clear();
      }
    }

    public boolean containsKey(A key) {
      synchronized (data) {
        return data.containsKey(key);
      }
    }

    public B getFirst(A key) {
      synchronized (data) {
        List<B> list = get(key);
        return list.isEmpty() ? null : list.get(0);
      }
    }

    public void addAll(MultiMap<A, B> map) {
      putAll(map);
    }

    public void putAll(MultiMap<A, B> map) {
      synchronized (data) {
        for (A key : map.keySet()) putAll(key, map.get(key));
      }
    }

    public void putAll(Map<A, B> map) {
      synchronized (data) {
        if (map != null)
          for (Map.Entry<A, B> e : map.entrySet()) put(e.getKey(), e.getValue());
      }
    }

    final public int keyCount() {
      return keysSize();
    }

    public int keysSize() {
      synchronized (data) {
        return l(data);
      }
    }

    final public int fullSize() {
      return size();
    }

    public int size() {
      synchronized (data) {
        return fullSize;
      }
    }

    public List<A> reverseGet(B b) {
      synchronized (data) {
        List<A> l = new ArrayList();
        for (A key : data.keySet()) if (data.get(key).contains(b))
          l.add(key);
        return l;
      }
    }

    public Map<A, List<B>> asMap() {
      synchronized (data) {
        return cloneMap(data);
      }
    }

    public boolean isEmpty() {
      synchronized (data) {
        return data.isEmpty();
      }
    }

    public List<B> _makeEmptyList() {
      return new ArrayList();
    }

    public Collection<List<B>> allLists() {
      synchronized (data) {
        return new ArrayList(data.values());
      }
    }

    public Collection<List<B>> values() {
      return allLists();
    }

    public List<B> allValues() {
      return concatLists(data.values());
    }

    public Object mutex() {
      return data;
    }

    public String toString() {
      return "mm" + str(data);
    }
  }

  static public class CompressionSearch_AnyType<A, Data> extends Probabilistic {

    final public CompressionSearch_AnyType<A, Data> setRegime(CompressionRegime_AnyType<A> regime) {
      return regime(regime);
    }

    public CompressionSearch_AnyType<A, Data> regime(CompressionRegime_AnyType<A> regime) {
      this.regime = regime;
      return this;
    }

    final public CompressionRegime_AnyType<A> getRegime() {
      return regime();
    }

    public CompressionRegime_AnyType<A> regime() {
      return regime;
    }

    public CompressionRegime_AnyType<A> regime;

    final public Data getInputData() {
      return inputData();
    }

    public Data inputData() {
      return inputData;
    }

    public Data inputData;

    final public CompressionSearch_AnyType<A, Data> setInputSize(long inputSize) {
      return inputSize(inputSize);
    }

    public CompressionSearch_AnyType<A, Data> inputSize(long inputSize) {
      this.inputSize = inputSize;
      return this;
    }

    final public long getInputSize() {
      return inputSize();
    }

    public long inputSize() {
      return inputSize;
    }

    public long inputSize;

    final public CompressionSearch_AnyType<A, Data> setDoFullTesting(boolean doFullTesting) {
      return doFullTesting(doFullTesting);
    }

    public CompressionSearch_AnyType<A, Data> doFullTesting(boolean doFullTesting) {
      this.doFullTesting = doFullTesting;
      return this;
    }

    final public boolean getDoFullTesting() {
      return doFullTesting();
    }

    public boolean doFullTesting() {
      return doFullTesting;
    }

    public boolean doFullTesting = false;

    transient public List<Runnable> onNewBest;

    public CompressionSearch_AnyType<A, Data> onNewBest(Runnable r) {
      onNewBest = syncAddOrCreate(onNewBest, r);
      return this;
    }

    public void newBest() {
      pcallFAll(onNewBest);
    }

    transient public List<IVF1<Submission>> onDisqualified;

    public CompressionSearch_AnyType<A, Data> onDisqualified(IVF1<Submission> f) {
      onDisqualified = syncAddOrCreate(onDisqualified, f);
      return this;
    }

    public void disqualified(Submission s) {
      pcallFAll(onDisqualified, s);
    }

    public Best<Submission> best = new Best();

    public List<AbstractCompressor_AnyType> strategies = new ArrayList();

    public CompressionSearch_AnyType() {
      init();
    }

    public CompressionSearch_AnyType(CompressionRegime_AnyType<A> regime) {
      this.regime = regime;
      init();
    }

    public CompressionSearch_AnyType(CompressionRegime_AnyType<A> regime, Data inputData, long inputSize) {
      this.inputSize = inputSize;
      this.inputData = inputData;
      this.regime = regime;
      init();
    }

    public void init() {
      best.onChange = new Runnable() {

        public void run() {
          try {
            newBest();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "newBest();";
        }
      };
    }

    public Submission submit(A compression) {
      return submit(compression, null);
    }

    public Submission submit(A compression, Object notes) {
      return _submit(compression, notes);
    }

    public class Submission {

      final public Submission setNotes(Object notes) {
        return notes(notes);
      }

      public Submission notes(Object notes) {
        this.notes = notes;
        return this;
      }

      final public Object getNotes() {
        return notes();
      }

      public Object notes() {
        return notes;
      }

      public Object notes;

      public String toString() {
        if (!correct())
          return linesLL("BAD");
        return linesLL((isTrue(isFullChecked()) ? "FULLCHECKED" : "           ") + " " + ifloor(score() * 100), "Exact compression ratio: " + scoreRatio(), "Code:", indentx(shorten(500, str(decompressor()))), "Code as bytes:", indentx(shorten(500, bytesToHex(compressed()))));
      }

      public void setDecompressor(A decompressor) {
        this.decompressor_cache = decompressor;
      }

      public Data inputData() {
        return inputData;
      }

      public byte[] compressed_cache;

      public byte[] compressed() {
        if (compressed_cache == null)
          compressed_cache = compressed_load();
        return compressed_cache;
      }

      public byte[] compressed_load() {
        return decompressor_cache == null ? null : regime.decompressorToBytes(decompressor_cache);
      }

      public A decompressor_cache;

      public A decompressor() {
        if (decompressor_cache == null)
          decompressor_cache = decompressor_load();
        return decompressor_cache;
      }

      public A decompressor_load() {
        return compressed_cache == null ? null : regime.decompressorFromBytes(compressed_cache);
      }

      public String decompressor_str_cache;

      public String decompressor_str() {
        if (decompressor_str_cache == null)
          decompressor_str_cache = decompressor_str_load();
        return decompressor_str_cache;
      }

      public String decompressor_str_load() {
        return strOrNull(decompressor());
      }

      final public int nBytes() {
        return compressedSize();
      }

      public int compressedSize() {
        return l(compressed());
      }

      public Ratio scoreRatio_cache;

      public Ratio scoreRatio() {
        if (scoreRatio_cache == null)
          scoreRatio_cache = scoreRatio_load();
        return scoreRatio_cache;
      }

      public Ratio scoreRatio_load() {
        return new Ratio(inputSize(), compressedSize());
      }

      public Double score_cache;

      public double score() {
        if (score_cache == null)
          score_cache = score_load();
        return score_cache;
      }

      public Double score_load() {
        return scoreRatio().get();
      }

      public boolean decompressed = false;

      public Object decompressedValue;

      public Object decompressed() {
        if (!decompressed) {
          decompressedValue = regime.runDecompressor(decompressor());
          decompressed = true;
        }
        return decompressedValue;
      }

      public boolean checkUnder(CompressionRegime_AnyType<A> regime) {
        return checkResult(regime.runDecompressor(decompressor()));
      }

      public Boolean isFullChecked_cache;

      public Boolean isFullChecked() {
        if (isFullChecked_cache == null)
          isFullChecked_cache = isFullChecked_load();
        return isFullChecked_cache;
      }

      public Boolean isFullChecked_load() {
        if (!isTrue(correct()))
          return false;
        var fullRegime = fullRegime();
        if (fullRegime == null)
          return true;
        return checkUnder(fullRegime);
      }

      public boolean checkResult(Object decompressed) {
        return eq(toByteList(decompressed), inputData());
      }

      public Boolean correct_cache;

      public Boolean correct() {
        if (correct_cache == null)
          correct_cache = correct_load();
        return correct_cache;
      }

      public Boolean correct_load() {
        return eq(toByteList(decompressed()), inputData());
      }
    }

    public Submission _submit(A compression, Object notes) {
      if (compression == null)
        return null;
      print("Received submission");
      print("Code: " + takeFirst(500, str(compression)));
      Submission s = new Submission();
      s.notes(notes);
      print("Notes: " + takeFirst(500, str(notes)));
      s.setDecompressor(compression);
      print("Size: " + nBytes(s.nBytes()));
      if (s.score() > best.score())
        if (!s.correct()) {
          warn("Compressor didn't verify");
          disqualified(s);
        } else {
          print("Score: " + s.score());
          best.put(s, s.score());
        }
      return s;
    }

    public Submission bestSubmission() {
      methodForEach(__69 -> __69.flush(), strategies);
      return best.get();
    }

    final public A get() {
      return bestCompression();
    }

    public A bestCompression() {
      var s = bestSubmission();
      return s == null ? null : s.decompressor();
    }

    public boolean has() {
      return bestSubmission() != null;
    }

    public void addStrategy(AbstractCompressor_AnyType<A, Data> compressor) {
      if (compressor == null)
        return;
      initAction(compressor);
      compressor.setSearch(this);
      strategies.add(compressor);
      compressor.step0();
    }

    transient public IF0<CompressionRegime_AnyType> fullRegime;

    public CompressionRegime_AnyType fullRegime() {
      return fullRegime != null ? fullRegime.get() : fullRegime_base();
    }

    final public CompressionRegime_AnyType fullRegime_fallback(IF0<CompressionRegime_AnyType> _f) {
      return _f != null ? _f.get() : fullRegime_base();
    }

    public CompressionRegime_AnyType fullRegime_base() {
      if (doFullTesting)
        return regime.fullRegime();
      return null;
    }

    public void step0() {
    }
  }

  static public interface IResourceLoader {

    public String loadSnippet(String snippetID);

    public String getTranspiled(String snippetID);

    public int getSnippetType(String snippetID);

    public String getSnippetTitle(String snippetID);

    public File loadLibrary(String snippetID);

    default public File pathToJavaXJar() {
      return pathToJavaxJar_noResourceLoader();
    }

    default public File getSnippetJar(String snippetID, String transpiledSrc) {
      return null;
    }
  }

  static final public class WeakHasherMap<K, V> extends AbstractMap<K, V> implements Map<K, V> {

    public Hasher hasher = null;

    final public boolean keyEquals(Object k1, Object k2) {
      return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2));
    }

    final public int keyHashCode(Object k1) {
      return (hasher == null ? k1.hashCode() : hasher.hashCode(k1));
    }

    final public WeakKey WeakKeyCreate(K k) {
      if (k == null)
        return null;
      else
        return new WeakKey(k);
    }

    final public WeakKey WeakKeyCreate(K k, ReferenceQueue<? super K> q) {
      if (k == null)
        return null;
      else
        return new WeakKey(k, q);
    }

    final public class WeakKey extends WeakReference<K> {

      public int hash;

      public WeakKey(K k) {
        super(k);
        hash = keyHashCode(k);
      }

      final public WeakKey create(K k) {
        if (k == null)
          return null;
        else
          return new WeakKey(k);
      }

      public WeakKey(K k, ReferenceQueue<? super K> q) {
        super(k, q);
        hash = keyHashCode(k);
      }

      final public WeakKey create(K k, ReferenceQueue<? super K> q) {
        if (k == null)
          return null;
        else
          return new WeakKey(k, q);
      }

      @Override
      public boolean equals(Object o) {
        if (o == null)
          return false;
        if (this == o)
          return true;
        if (!(o.getClass().equals(WeakKey.class)))
          return false;
        Object t = this.get();
        @SuppressWarnings("unchecked")
        Object u = ((WeakKey) o).get();
        if ((t == null) || (u == null))
          return false;
        if (t == u)
          return true;
        return keyEquals(t, u);
      }

      @Override
      public int hashCode() {
        return hash;
      }
    }

    public HashMap<WeakKey, V> hash;

    public ReferenceQueue<? super K> queue = new ReferenceQueue<K>();

    @SuppressWarnings("unchecked")
    final public void processQueue() {
      WeakKey wk;
      while ((wk = (WeakKey) queue.poll()) != null) {
        hash.remove(wk);
      }
    }

    public WeakHasherMap(int initialCapacity, float loadFactor) {
      hash = new HashMap<WeakKey, V>(initialCapacity, loadFactor);
    }

    public WeakHasherMap(int initialCapacity) {
      hash = new HashMap<WeakKey, V>(initialCapacity);
    }

    public WeakHasherMap() {
      hash = new HashMap<WeakKey, V>();
    }

    public WeakHasherMap(Hasher h) {
      hash = new HashMap<WeakKey, V>();
      hasher = h;
    }

    @Override
    public int size() {
      return entrySet().size();
    }

    @Override
    public boolean isEmpty() {
      return entrySet().isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.containsKey(WeakKeyCreate(kkey));
    }

    @Override
    public V get(Object key) {
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.get(WeakKeyCreate(kkey));
    }

    @Override
    public V put(K key, V value) {
      processQueue();
      return hash.put(WeakKeyCreate(key, queue), value);
    }

    @Override
    public V remove(Object key) {
      processQueue();
      @SuppressWarnings("unchecked")
      K kkey = (K) key;
      return hash.remove(WeakKeyCreate(kkey));
    }

    @Override
    public void clear() {
      processQueue();
      hash.clear();
    }

    @SuppressWarnings("TypeParameterShadowing")
    final public class Entry<K, V> implements Map.Entry<K, V> {

      public Map.Entry<WeakKey, V> ent;

      public K key;

      public Entry(Map.Entry<WeakKey, V> ent, K key) {
        this.ent = ent;
        this.key = key;
      }

      @Override
      public K getKey() {
        return key;
      }

      @Override
      public V getValue() {
        return ent.getValue();
      }

      @Override
      public V setValue(V value) {
        return ent.setValue(value);
      }

      final public boolean keyvalEquals(K o1, K o2) {
        return (o1 == null) ? (o2 == null) : keyEquals(o1, o2);
      }

      final public boolean valEquals(V o1, V o2) {
        return (o1 == null) ? (o2 == null) : o1.equals(o2);
      }

      @SuppressWarnings("NonOverridingEquals")
      public boolean equals(Map.Entry<K, V> e) {
        return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue()));
      }

      @Override
      public int hashCode() {
        V v;
        return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode()));
      }
    }

    final public class EntrySet extends AbstractSet<Map.Entry<K, V>> {

      public Set<Map.Entry<WeakKey, V>> hashEntrySet = hash.entrySet();

      @Override
      public Iterator<Map.Entry<K, V>> iterator() {
        return new Iterator<Map.Entry<K, V>>() {

          public Iterator<Map.Entry<WeakKey, V>> hashIterator = hashEntrySet.iterator();

          public Map.Entry<K, V> next = null;

          @Override
          public boolean hasNext() {
            while (hashIterator.hasNext()) {
              Map.Entry<WeakKey, V> ent = hashIterator.next();
              WeakKey wk = ent.getKey();
              K k = null;
              if ((wk != null) && ((k = wk.get()) == null)) {
                continue;
              }
              next = new Entry<K, V>(ent, k);
              return true;
            }
            return false;
          }

          @Override
          public Map.Entry<K, V> next() {
            if ((next == null) && !hasNext())
              throw new NoSuchElementException();
            Map.Entry<K, V> e = next;
            next = null;
            return e;
          }

          @Override
          public void remove() {
            hashIterator.remove();
          }
        };
      }

      @Override
      public boolean isEmpty() {
        return !(iterator().hasNext());
      }

      @Override
      public int size() {
        int j = 0;
        for (Iterator<Map.Entry<K, V>> i = iterator(); i.hasNext(); i.next()) j++;
        return j;
      }

      @Override
      public boolean remove(Object o) {
        processQueue();
        if (!(o instanceof Map.Entry<?, ?>))
          return false;
        @SuppressWarnings("unchecked")
        Map.Entry<K, V> e = (Map.Entry<K, V>) o;
        Object ev = e.getValue();
        WeakKey wk = WeakKeyCreate(e.getKey());
        Object hv = hash.get(wk);
        if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) {
          hash.remove(wk);
          return true;
        }
        return false;
      }

      @Override
      public int hashCode() {
        int h = 0;
        for (Iterator<Map.Entry<WeakKey, V>> i = hashEntrySet.iterator(); i.hasNext(); ) {
          Map.Entry<WeakKey, V> ent = i.next();
          WeakKey wk = ent.getKey();
          Object v;
          if (wk == null)
            continue;
          h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode()));
        }
        return h;
      }
    }

    public Set<Map.Entry<K, V>> entrySet = null;

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
      if (entrySet == null)
        entrySet = new EntrySet();
      return entrySet;
    }

    public K findKey(Object key) {
      processQueue();
      K kkey = (K) key;
      WeakKey wkey = WeakKeyCreate(kkey);
      WeakKey found = hashMap_findKey(hash, wkey);
      return found == null ? null : found.get();
    }
  }

  static public class RestartableCountdown implements AutoCloseable {

    public java.util.Timer timer;

    public long targetTime;

    public long totalSleepTime;

    synchronized public void setTargetTime(long targetTime, Runnable action) {
      if (targetTime <= 0)
        stop();
      else if (targetTime != this.targetTime) {
        start(targetTime - sysNow(), action);
        this.targetTime = targetTime;
      }
    }

    synchronized public void start(long delayMS, Object action) {
      stop();
      if (delayMS <= 0) {
        startThread(new Runnable() {

          public void run() {
            try {
              callF(action);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "callF(action);";
          }
        });
      } else {
        totalSleepTime += delayMS;
        timer = doLater_daemon(delayMS, action);
        targetTime = sysNow() + delayMS;
      }
    }

    public void start(double delaySeconds, Object action) {
      start(toMS(delaySeconds), action);
    }

    synchronized public void stop() {
      cancelTimer(timer);
      timer = null;
      targetTime = 0;
    }

    public void close() {
      stop();
    }
  }

  static public interface Steppable {

    public boolean step();
  }

  static public class proxy_InvocationHandler implements InvocationHandler {

    public Object target;

    public proxy_InvocationHandler() {
    }

    public proxy_InvocationHandler(Object target) {
      this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) {
      return call(target, method.getName(), unnull(args));
    }
  }

  static public class Pair<A, B> implements Comparable<Pair<A, B>> {

    public A a;

    public B b;

    public Pair() {
    }

    public Pair(A a, B b) {
      this.b = b;
      this.a = a;
    }

    public int hashCode() {
      return hashCodeFor(a) + 2 * hashCodeFor(b);
    }

    public boolean equals(Object o) {
      if (o == this)
        return true;
      if (!(o instanceof Pair))
        return false;
      Pair t = (Pair) o;
      return eq(a, t.a) && eq(b, t.b);
    }

    public String toString() {
      return "<" + a + ", " + b + ">";
    }

    public int compareTo(Pair<A, B> p) {
      if (p == null)
        return 1;
      int i = ((Comparable<A>) a).compareTo(p.a);
      if (i != 0)
        return i;
      return ((Comparable<B>) b).compareTo(p.b);
    }
  }

  static public interface IResourceHolder {

    public <A extends AutoCloseable> A add(A a);

    public Collection<AutoCloseable> takeAll();
  }

  static public interface Swingable {

    public JComponent visualize();
  }

  static public class Average {

    public double sum;

    public double n;

    public void add(double d) {
      ++n;
      sum += d;
    }

    public void add(double d, double weight) {
      n += weight;
      sum += d * weight;
    }

    public double get() {
      return doubleRatio(sum, n);
    }

    public String toString() {
      return get() + " (n=" + n + ")";
    }

    public void clear() {
      n = 0;
      sum = 0;
    }
  }

  static public class BWIntegralImage extends Meta implements MakesBufferedImage, IBWIntegralImage, IIntegralImage {

    public int w, h;

    public int[] data;

    public BWIntegralImage() {
    }

    public BWIntegralImage(File f) {
      this(loadImage2(f));
    }

    public BWIntegralImage(MakesBufferedImage img) {
      this(toBufferedImage(img));
    }

    public BWIntegralImage(BufferedImage image) {
      try {
        if (image.getType() == BufferedImage.TYPE_BYTE_GRAY)
          grab(grabbableGrayPixels(image));
        else {
          grab(grabbableIntPixels_fastOrSlow(image));
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public BWIntegralImage(GrabbableIntPixels gp) {
      grab(gp);
    }

    public BWIntegralImage(GrabbableGrayPixels gp) {
      grab(gp);
    }

    public void grab(GrabbableIntPixels gp) {
      alloc(gp.w, gp.h);
      int offset = gp.offset;
      int[] image = gp.data;
      int sum = 0;
      for (int x = 0; x < w; x++) {
        int packed = image[offset + x];
        int brightness = packedToBrightness(packed);
        data[x] = (sum += brightness);
      }
      int scanlineExtra = gp.scanlineStride - w;
      int iImage = offset + gp.scanlineStride, i = w;
      for (int y = 1; y < h; y++) {
        sum = 0;
        for (int x = 0; x < w; x++) {
          int packed = image[iImage];
          int brightness = packedToBrightness(packed);
          sum += brightness;
          data[i] = sum + data[i - w];
          iImage++;
          i++;
        }
        iImage += scanlineExtra;
      }
    }

    public void grab(GrabbableGrayPixels gp) {
      alloc(gp.w, gp.h);
      int offset = gp.offset;
      byte[] image = gp.data;
      int sum = 0;
      for (int x = 0; x < w; x++) {
        int brightness = image[offset + x];
        data[x] = (sum += brightness);
      }
      int scanlineExtra = gp.scanlineStride - w;
      int iImage = offset + gp.scanlineStride, i = w;
      for (int y = 1; y < h; y++) {
        sum = 0;
        for (int x = 0; x < w; x++) {
          int brightness = image[iImage];
          sum += brightness;
          data[i] = sum + data[i - w];
          iImage++;
          i++;
        }
        iImage += scanlineExtra;
      }
    }

    public BWIntegralImage(BWImage img) {
      alloc(img.w(), img.h());
      data = new int[w * h];
      int i = 0;
      for (int y = 0; y < h; y++) {
        int sum = 0;
        for (int x = 0; x < w; x++) {
          sum += img.getByte(x, y) & 0xFF;
          data[i] = y > 0 ? sum + data[i - w] : sum;
          i++;
        }
      }
    }

    final public void alloc(int w, int h) {
      this.w = w;
      this.h = h;
      if (w * h > 8 * 1024 * 1024)
        throw fail("Image too large (more than 8 MP): " + w + "*" + h);
      data = new int[w * h];
    }

    public int get(int x, int y) {
      return x < 0 || y < 0 ? 0 : data[min(y, h - 1) * w + min(x, w - 1)];
    }

    public int getIIValue(int x, int y) {
      return get(x, y);
    }

    public double getIntegralValue(int x, int y, int channel) {
      return get(x, y);
    }

    public double getPixelAverage(int x1, int y1, int x2, int y2) {
      int area = (x2 - x1) * (y2 - y1);
      return doubleRatio(bwIntegralImage_sumRect(this, x1, y1, x2, y2), area);
    }

    public int getWidth() {
      return w;
    }

    public int getHeight() {
      return h;
    }

    public BufferedImage getBufferedImage() {
      return scaleDownUsingIntegralImageBW(this, w).getBufferedImage();
    }

    public int packedToBrightness(int packed) {
      int b = (packed & 0xFF);
      int r = ((packed >> 16) & 0xFF);
      int g = ((packed >> 8) & 0xFF);
      return (r + g + b + 1) / 3;
    }

    public int getPixel(int x, int y) {
      int r = iround(rectSum(x, y, x + 1, y + 1, 0));
      int g = iround(rectSum(x, y, x + 1, y + 1, 1));
      int b = iround(rectSum(x, y, x + 1, y + 1, 2));
      return rgbInt(r, g, b);
    }
  }

  static public class MRUCache<A, B> extends LinkedHashMap<A, B> {

    public int maxSize = 10;

    public MRUCache() {
    }

    public MRUCache(int maxSize) {
      this.maxSize = maxSize;
    }

    public boolean removeEldestEntry(Map.Entry eldest) {
      return size() > maxSize;
    }

    public Object _serialize() {
      return ll(maxSize, cloneLinkedHashMap(this));
    }

    static public MRUCache _deserialize(List l) {
      MRUCache m = new MRUCache();
      m.maxSize = (int) first(l);
      m.putAll((LinkedHashMap) second(l));
      return m;
    }
  }

  static public class Scored<A> extends Var<A> {

    public float score;

    public Scored() {
    }

    public Scored(A a, float score) {
      super(a);
      this.score = score;
    }

    public Scored(A a, double score) {
      super(a);
      this.score = (float) score;
    }

    public float score() {
      return score;
    }

    public String toString() {
      return toIntPercent(score) + "%: " + str(get());
    }
  }

  abstract static public class AbstractCompressor_AnyType<A, Data> extends Probabilistic {

    public CompressionSearch_AnyType<A, Data> search;

    public AbstractCompressor_AnyType() {
    }

    public AbstractCompressor_AnyType(CompressionSearch_AnyType<A, Data> search) {
      this.search = search;
    }

    public void setSearch(CompressionSearch_AnyType<A, Data> search) {
      if (this.search != null && this.search != search)
        throw fail();
      this.search = search;
    }

    public CompressionRegime_AnyType<A> regime() {
      return search == null ? null : search.regime();
    }

    public Data inputData() {
      return search.inputData();
    }

    public void flush() {
    }

    public CompressionSearch_AnyType<A, Data>.Submission submit(A a) {
      return submit(a, null);
    }

    public CompressionSearch_AnyType<A, Data>.Submission submit(A a, Object notes) {
      return search.submit(a, notes);
    }
  }

  static public class Meta implements IMeta {

    volatile public Object meta;

    public void _setMeta(Object meta) {
      this.meta = meta;
    }

    public Object _getMeta() {
      return meta;
    }
  }

  static public class JE_RepElement<A> extends JEInstantCompressor_AnyType<List<A>> {

    public ICachedJavaXExpr compress(List<A> data) {
      if (metaGet("scaffolding") != null)
        scaffoldCalled(this, "compress", data);
      boolean sc = scaffoldingEnabled(this);
      if (empty(data))
        return null;
      A a = first(data);
      int n = l(data);
      for (int i = 1; i < n; i++) if (!eq(data.get(i), a)) {
        if (sc)
          scaffoldCalled(this, "diff at " + i + "/" + n);
        return null;
      }
      return javaExpr(functionCall("repSimple", n, elementToJava(a)), () -> repSimple(n, a));
    }

    transient public IF1<A, ICachedJavaXExpr> elementToJava;

    public ICachedJavaXExpr elementToJava(A o) {
      return elementToJava != null ? elementToJava.get(o) : elementToJava_base(o);
    }

    final public ICachedJavaXExpr elementToJava_fallback(IF1<A, ICachedJavaXExpr> _f, A o) {
      return _f != null ? _f.get(o) : elementToJava_base(o);
    }

    public ICachedJavaXExpr elementToJava_base(A o) {
      var e = javaObjectToIJavaExpr(o);
      if (e == null)
        throw fail("elementToJava: " + className(o));
      return e;
    }
  }

  abstract static public class Probabilistic extends Meta implements IProbabilistic, Steppable {

    public IProbabilisticScheduler ps;

    public void initScheduler() {
      if (ps == null)
        setScheduler(new ProbabilisticScheduler());
    }

    public void setScheduler(IProbabilisticScheduler ps) {
      this.ps = ps;
    }

    public IProbabilisticScheduler scheduler() {
      initScheduler();
      return ps;
    }

    final public void at(Runnable action) {
      schedule(action);
    }

    public void schedule(Runnable action) {
      scheduleRelative(1.0, action);
    }

    final public void at(double probability, Runnable action) {
      schedule(probability, action);
    }

    public void schedule(double probability, Runnable action) {
      initScheduler();
      ps.at(probability, action);
    }

    final public void atRelative(double probability, Runnable action) {
      scheduleRelative(probability, action);
    }

    public void scheduleRelative(double probability, Runnable action) {
      initScheduler();
      ps.atRelative(probability, action);
    }

    public void scheduleAll(Iterable<? extends Runnable> actions) {
      forEach(__61 -> schedule(__61), actions);
    }

    public void scheduleAll(double probability, Iterable<? extends Runnable> actions) {
      forEach(actions, a -> schedule(probability, a));
    }

    public void scheduleAllRelative(double probability, Iterable<? extends Runnable> actions) {
      forEach(actions, a -> scheduleRelative(probability, a));
    }

    public void stepAll() {
      main.stepAll(scheduler());
    }

    public boolean step() {
      return scheduler().step();
    }

    public void runFor(double seconds) {
      stepForNSeconds(seconds, scheduler());
    }
  }

  static public interface ISetter<A> {

    public void set(A a);
  }

  static public class GrabbableGrayPixels implements IFieldsToList {

    static final public String _fieldOrder = "data w h offset scanlineStride";

    public byte[] data;

    public int w;

    public int h;

    public int offset;

    public int scanlineStride;

    public GrabbableGrayPixels() {
    }

    public GrabbableGrayPixels(byte[] data, int w, int h, int offset, int scanlineStride) {
      this.scanlineStride = scanlineStride;
      this.offset = offset;
      this.h = h;
      this.w = w;
      this.data = data;
    }

    public String toString() {
      return shortClassName_dropNumberPrefix(this) + "(" + data + ", " + w + ", " + h + ", " + offset + ", " + scanlineStride + ")";
    }

    public boolean equals(Object o) {
      if (!(o instanceof GrabbableGrayPixels))
        return false;
      GrabbableGrayPixels __1 = (GrabbableGrayPixels) o;
      return eq(data, __1.data) && w == __1.w && h == __1.h && offset == __1.offset && scanlineStride == __1.scanlineStride;
    }

    public int hashCode() {
      int h = 1984426208;
      h = boostHashCombine(h, _hashCode(data));
      h = boostHashCombine(h, _hashCode(w));
      h = boostHashCombine(h, _hashCode(h));
      h = boostHashCombine(h, _hashCode(offset));
      h = boostHashCombine(h, _hashCode(scanlineStride));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { data, w, h, offset, scanlineStride };
    }
  }

  static public interface IProbabilistic {

    public void setScheduler(IProbabilisticScheduler ps);

    public IProbabilisticScheduler scheduler();

    default public <A> A initAction(A a) {
      scheduler().initAction(a);
      return a;
    }

    public void step0();
  }

  abstract static public class AbstractJavaXExpr<A> extends Meta implements ICachedJavaXExpr<A> {
  }

  static public class LetterLayout implements LayoutManager {

    public String[] lines;

    public Map<String, Component> map = new TreeMap();

    public Map<Component, String> constraints = new HashMap();

    public RC[] rows;

    public RC[] cols;

    public Cell[][] cells;

    public int spacingX = 10, spacingY = 10;

    public int insetTop, insetBottom, insetLeft, insetRight;

    public int template;

    public boolean formWideLeftSide, formWideRightSide;

    static final public int STALACTITE = 1, LEFT_ALIGNED_ROW = 2, CENTERED_ROW = 3, FORM = 4, RIGHT_ALIGNED_ROW = 5;

    public boolean debug = false;

    public void setLeftBorder(int border) {
      insetLeft = border;
    }

    public void setRightBorder(int border) {
      insetRight = border;
    }

    public static JComponent withBorder(JComponent component, int border) {
      JPanel panel = new JPanel(new LetterLayout("C").setBorder(border));
      panel.add("C", component);
      return panel;
    }

    public static JPanel panel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public static JPanel stalactitePanel() {
      return new JPanel(stalactite());
    }

    static public class DummyComponent extends JComponent {
    }

    static public class Cell {

      public boolean aux = false;

      public int minWidth, minHeight;

      public Component component;

      public int colspan, rowspan;

      public double weightX, weightY;
    }

    static public class RC {

      public int min;

      public double weightSum;

      public int start;

      public int minEnd;
    }

    public LetterLayout(int template) {
      this.template = template;
    }

    public LetterLayout(String... lines) {
      this.lines = lines;
    }

    public void layoutContainer(Container container) {
      prepareLayout(container);
      if (debug)
        System.out.println("Container size: " + container.getSize());
      Insets insets = getInsets(container);
      for (int r = 0; r < rows.length; r++) {
        for (int i = 0; i < cols.length; ) {
          Cell cell = cells[i][r];
          if (cell.aux)
            ++i;
          else {
            if (cell.component != null) {
              int x1 = cols[i].start;
              int y1 = rows[r].start;
              int x2 = i + cell.colspan < cols.length ? cols[i + cell.colspan].start - spacingX : container.getWidth() - insets.right;
              int y2 = r + cell.rowspan < rows.length ? rows[r + cell.rowspan].start - spacingY : container.getHeight() - insets.bottom;
              if (debug)
                System.out.println("Layouting (" + i + ", " + r + ", " + cell.component.getClass().getName() + "): " + x1 + " " + y1 + " " + x2 + " " + y2);
              cell.component.setBounds(x1, y1, x2 - x1, y2 - y1);
            }
            i += cells[i][r].colspan;
          }
        }
      }
    }

    final public void prepareLayout(Container container) {
      applyTemplate(container);
      int numRows = lines.length, numCols = lines[0].length();
      for (int i = 1; i < numRows; i++) if (lines[i].length() != numCols)
        throw new IllegalArgumentException("Lines have varying length");
      cells = new Cell[numCols][numRows];
      rows = new RC[numRows];
      cols = new RC[numCols];
      for (int r = 0; r < numRows; r++) rows[r] = new RC();
      for (int i = 0; i < numCols; i++) cols[i] = new RC();
      for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r] = new Cell();
      for (int r = 0; r < numRows; r++) {
        String line = lines[r];
        for (int i = 0; i < numCols; ) {
          Cell cell = cells[i][r];
          if (cell.aux) {
            ++i;
            continue;
          }
          char ch = line.charAt(i);
          int iNext = i;
          do ++iNext; while (iNext < numCols && ch == line.charAt(iNext));
          int rNext = r;
          do ++rNext; while (rNext < numRows && ch == lines[rNext].charAt(i));
          cell.weightX = numCols == 1 || iNext > i + 1 ? 1.0 : 0.0;
          cell.weightY = numRows == 1 || rNext > r + 1 ? 1.0 : 0.0;
          Component c = map.get(String.valueOf(ch));
          cell.component = c;
          if (c != null) {
            cell.minWidth = c.getMinimumSize().width + spacingX;
            cell.minHeight = getMinimumHeight(c) + spacingY;
          }
          cell.colspan = iNext - i;
          cell.rowspan = rNext - r;
          if (cell.colspan == 1)
            cols[i].min = Math.max(cols[i].min, cell.minWidth);
          if (cell.rowspan == 1)
            rows[r].min = Math.max(rows[r].min, cell.minHeight);
          for (int r2 = r; r2 < rNext; r2++) for (int i2 = i; i2 < iNext; i2++) if (r2 != r || i2 != i)
            cells[i2][r2].aux = true;
          i = iNext;
        }
      }
      while (true) {
        for (int i = 0; i < numCols; i++) {
          int minStart = i == 0 ? 0 : cols[i - 1].minEnd;
          double weightStart = i == 0 ? 0.0 : cols[i - 1].weightSum;
          for (int r = 0; r < numRows; r++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = cols[i + cell.colspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minWidth);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightX);
            }
          }
        }
        for (int r = 0; r < numRows; r++) {
          int minStart = r == 0 ? 0 : rows[r - 1].minEnd;
          double weightStart = r == 0 ? 0.0 : rows[r - 1].weightSum;
          for (int i = 0; i < numCols; i++) {
            Cell cell = cells[i][r];
            if (!cell.aux) {
              RC rc = rows[r + cell.rowspan - 1];
              rc.minEnd = Math.max(rc.minEnd, minStart + cell.minHeight);
              rc.weightSum = Math.max(rc.weightSum, weightStart + cell.weightY);
            }
          }
        }
        if (allWeightsZero(cols)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightX = 1.0;
          continue;
        }
        if (allWeightsZero(rows)) {
          for (int r = 0; r < numRows; r++) for (int i = 0; i < numCols; i++) cells[i][r].weightY = 1.0;
          continue;
        }
        break;
      }
      Insets insets = getInsets(container);
      determineStarts(cols, insets.left, container.getWidth() - insets.left - insets.right + spacingX, spacingX);
      determineStarts(rows, insets.top, container.getHeight() - insets.top - insets.bottom + spacingY, spacingY);
    }

    final public boolean allWeightsZero(RC[] rcs) {
      for (int i = 0; i < rcs.length; i++) if (rcs[i].weightSum != 0.0)
        return false;
      return true;
    }

    static public int getMinimumHeight(Component c) {
      return c.getMinimumSize().height;
    }

    final public void applyTemplate(Container container) {
      if (template == STALACTITE) {
        Component[] components = container.getComponents();
        lines = new String[components.length + 2];
        map.clear();
        for (int i = 0; i < components.length; i++) {
          String s = String.valueOf(makeIndexChar(i));
          map.put(s, components[i]);
          lines[i] = s;
        }
        lines[components.length] = lines[components.length + 1] = " ";
      } else if (template == FORM) {
        Component[] components = container.getComponents();
        int numRows = components.length / 2;
        lines = new String[numRows + 2];
        map.clear();
        for (int row = 0; row < numRows; row++) {
          String lower = String.valueOf(makeIndexChar(row));
          String upper = String.valueOf(makeAlternateIndexChar(row));
          Component rightComponent = components[row * 2 + 1];
          if (rightComponent instanceof DummyComponent)
            upper = lower;
          lines[row] = (formWideLeftSide ? lower + lower : lower) + (formWideRightSide ? upper + upper : upper);
          map.put(lower, components[row * 2]);
          if (!(rightComponent instanceof DummyComponent))
            map.put(upper, rightComponent);
        }
        lines[numRows] = lines[numRows + 1] = (formWideLeftSide ? "  " : " ") + (formWideRightSide ? "  " : " ");
      } else if (template == LEFT_ALIGNED_ROW) {
        lines = new String[] { makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == CENTERED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) + RIGHT_CHAR + RIGHT_CHAR };
      } else if (template == RIGHT_ALIGNED_ROW) {
        lines = new String[] { "" + LEFT_CHAR + LEFT_CHAR + makeSingleRow(container) };
      }
    }

    final public String makeSingleRow(Container container) {
      Component[] components = container.getComponents();
      StringBuffer buf = new StringBuffer();
      map.clear();
      for (int i = 0; i < components.length; i++) {
        var c = components[i];
        String s = constraints.get(c);
        if (isOneOfSingleChars(s, LEFT_CHAR, RIGHT_CHAR))
          continue;
        s = str(makeAlternateIndexChar(i));
        setConstraints(c, s);
        buf.append(s);
      }
      return buf.toString();
    }

    static public void determineStarts(RC[] rcs, int start, int totalSize, int spacing) {
      int minTotal = rcs[rcs.length - 1].minEnd;
      double weightSum = rcs[rcs.length - 1].weightSum;
      int spare = (int) ((totalSize - minTotal) / (weightSum == 0.0 ? 1.0 : weightSum));
      int x = start, minSum = 0;
      double prevWeightSum = 0.0;
      for (int i = 0; i < rcs.length; i++) {
        int width = rcs[i].minEnd - minSum + (int) ((rcs[i].weightSum - prevWeightSum) * spare) - spacing;
        rcs[i].start = x;
        x += width + spacing;
        prevWeightSum = rcs[i].weightSum;
        minSum = rcs[i].minEnd;
      }
    }

    public void addLayoutComponent(String s, Component component) {
      setConstraints(component, s);
    }

    public void setConstraints(Component component, String s) {
      mapPutOrRemove(map, s, component);
      mapPutOrRemove(constraints, component, s);
    }

    public void removeLayoutComponent(Component component) {
      map.values().remove(component);
      constraints.remove(component);
    }

    public Dimension minimumLayoutSize(Container container) {
      prepareLayout(container);
      Insets insets = getInsets(container);
      Dimension result = new Dimension(insets.left + cols[cols.length - 1].minEnd + insets.right - spacingX, insets.top + rows[rows.length - 1].minEnd + insets.bottom - spacingY);
      return result;
    }

    final public Insets getInsets(Container container) {
      Insets insets = container.getInsets();
      return new Insets(insets.top + insetTop, insets.left + insetLeft, insets.bottom + insetBottom, insets.right + insetRight);
    }

    public Dimension preferredLayoutSize(Container container) {
      return minimumLayoutSize(container);
    }

    public LetterLayout setSpacing(int x, int y) {
      spacingX = x;
      spacingY = y;
      return this;
    }

    public LetterLayout setSpacing(int spacing) {
      return setSpacing(spacing, spacing);
    }

    public LetterLayout setBorder(int top, int left, int bottom, int right) {
      insetTop = top;
      insetLeft = left;
      insetBottom = bottom;
      insetRight = right;
      return this;
    }

    public LetterLayout setBorder(int inset) {
      return setBorder(inset, inset, inset, inset);
    }

    public LetterLayout setTopBorder(int inset) {
      insetTop = inset;
      return this;
    }

    public static LetterLayout stalactite() {
      return new LetterLayout(STALACTITE);
    }

    public static LetterLayout leftAlignedRow() {
      return new LetterLayout(LEFT_ALIGNED_ROW);
    }

    public static LetterLayout leftAlignedRow(int spacing) {
      return leftAlignedRow().setSpacing(spacing);
    }

    public static LetterLayout centeredRow() {
      return new LetterLayout(CENTERED_ROW);
    }

    public static LetterLayout rightAlignedRow() {
      return new LetterLayout(RIGHT_ALIGNED_ROW);
    }

    public static JPanel rightAlignedRowPanel(JComponent... components) {
      return makePanel(new LetterLayout(RIGHT_ALIGNED_ROW), components);
    }

    static public JPanel makePanel(LetterLayout letterLayout, JComponent[] components) {
      JPanel panel = new JPanel(letterLayout);
      for (JComponent component : components) {
        panel.add(component);
      }
      return panel;
    }

    public static LetterLayout form() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideLeftSide = true;
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static LetterLayout formWideRightSide() {
      LetterLayout letterLayout = new LetterLayout(FORM);
      letterLayout.formWideRightSide = true;
      return letterLayout;
    }

    public static Component getDummyComponent() {
      return new DummyComponent();
    }

    public static JPanel newPanel(String... lines) {
      return new JPanel(new LetterLayout(lines));
    }

    public boolean isDebug() {
      return debug;
    }

    public void setDebug(boolean debug) {
      this.debug = debug;
    }

    public static char makeIndexChar(int idx) {
      return (char) ('a' + idx * 2);
    }

    public static char makeAlternateIndexChar(int idx) {
      return (char) ('b' + idx * 2);
    }

    public static char LEFT_CHAR = ',', RIGHT_CHAR = '.';

    public static void main(String[] args) {
      System.out.println((int) makeIndexChar(0));
      System.out.println((int) makeAlternateIndexChar(0));
      System.out.println((int) makeIndexChar(32000));
      System.out.println((int) makeAlternateIndexChar(32000));
      System.out.println((int) LEFT_CHAR);
      System.out.println((int) RIGHT_CHAR);
    }
  }

  static public class GrabbableIntPixels implements IFieldsToList {

    static final public String _fieldOrder = "data w h offset scanlineStride";

    public int[] data;

    public int w;

    public int h;

    public int offset;

    public int scanlineStride;

    public GrabbableIntPixels() {
    }

    public GrabbableIntPixels(int[] data, int w, int h, int offset, int scanlineStride) {
      this.scanlineStride = scanlineStride;
      this.offset = offset;
      this.h = h;
      this.w = w;
      this.data = data;
    }

    public String toString() {
      return shortClassName_dropNumberPrefix(this) + "(" + data + ", " + w + ", " + h + ", " + offset + ", " + scanlineStride + ")";
    }

    public boolean equals(Object o) {
      if (!(o instanceof GrabbableIntPixels))
        return false;
      GrabbableIntPixels __1 = (GrabbableIntPixels) o;
      return eq(data, __1.data) && w == __1.w && h == __1.h && offset == __1.offset && scanlineStride == __1.scanlineStride;
    }

    public int hashCode() {
      int h = -1183022196;
      h = boostHashCombine(h, _hashCode(data));
      h = boostHashCombine(h, _hashCode(w));
      h = boostHashCombine(h, _hashCode(h));
      h = boostHashCombine(h, _hashCode(offset));
      h = boostHashCombine(h, _hashCode(scanlineStride));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { data, w, h, offset, scanlineStride };
    }
  }

  static public class JE_CompressEachElementIndividually<El> extends AbstractCompressor_AnyType<ICachedJavaXExpr, List<El>> {

    final public JE_CompressEachElementIndividually<El> setElementCompressionStrategy(IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy) {
      return elementCompressionStrategy(elementCompressionStrategy);
    }

    public JE_CompressEachElementIndividually<El> elementCompressionStrategy(IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy) {
      this.elementCompressionStrategy = elementCompressionStrategy;
      return this;
    }

    final public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> getElementCompressionStrategy() {
      return elementCompressionStrategy();
    }

    public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy() {
      return elementCompressionStrategy;
    }

    public IF0<AbstractCompressor_AnyType<ICachedJavaXExpr<El>, El>> elementCompressionStrategy;

    public List<CompressionSearch_AnyType<ICachedJavaXExpr<El>, El>> searches = new ArrayList();

    final public JE_CompressEachElementIndividually<El> setMakeLiteral(IF1<El, ICachedJavaXExpr> makeLiteral) {
      return makeLiteral(makeLiteral);
    }

    public JE_CompressEachElementIndividually<El> makeLiteral(IF1<El, ICachedJavaXExpr> makeLiteral) {
      this.makeLiteral = makeLiteral;
      return this;
    }

    final public IF1<El, ICachedJavaXExpr> getMakeLiteral() {
      return makeLiteral();
    }

    public IF1<El, ICachedJavaXExpr> makeLiteral() {
      return makeLiteral;
    }

    public IF1<El, ICachedJavaXExpr> makeLiteral;

    public JE_CompressEachElementIndividually<El> onCompressionFail(IF1<El, ICachedJavaXExpr> f) {
      makeLiteral = f;
      return this;
    }

    final public JE_CompressEachElementIndividually<El> setDebug(boolean debug) {
      return debug(debug);
    }

    public JE_CompressEachElementIndividually<El> debug(boolean debug) {
      this.debug = debug;
      return this;
    }

    final public boolean getDebug() {
      return debug();
    }

    public boolean debug() {
      return debug;
    }

    public boolean debug = false;

    public List<ICachedJavaXExpr> renderedElements = new ArrayList();

    public ICachedJavaXExpr renderedCode;

    public BitSet dirtyElements = new BitSet();

    public int size() {
      return l(inputData());
    }

    public int nNotLiteral() {
      return countPred(searches, search -> search.has());
    }

    public ICachedJavaXExpr getRenderedElement(int i) {
      if (metaGet("scaffolding") != null)
        scaffoldCalled(this, "getRenderedElement", i);
      if (contains(dirtyElements, i) || _get(renderedElements, i) == null) {
        remove(dirtyElements, i);
        var e = renderElement(i);
        listSet(renderedElements, i, e);
      }
      return renderedElements.get(i);
    }

    public ICachedJavaXExpr renderElement(int i) {
      var search = _get(searches, i);
      ICachedJavaXExpr comp = search == null ? null : search.get();
      if (comp != null)
        return comp;
      ICachedJavaXExpr java = makeLiteral.get(_get(inputData(), i));
      metaSet(java, "gaveUp", this);
      return java;
    }

    public boolean dirty() {
      return nempty(dirtyElements) || l(renderedElements) < size();
    }

    public void flush() {
      if (!dirty())
        return;
      submit(code());
    }

    public List<ICachedJavaXExpr> codeForElements() {
      return countIteratorToList(__62 -> getRenderedElement(__62), size());
    }

    public ICachedJavaXExpr code() {
      if (dirty() || renderedCode == null) {
        List<ICachedJavaXExpr> els = codeForElements();
        int iNull = indexOf(els, null);
        if (iNull >= 0)
          throw fail("Null element: " + iNull + "/" + l(els));
        renderedCode = javaExpr(functionCall_list("ll", els), () -> mapQuickEval_javaExpr(els));
      }
      return renderedCode;
    }

    public void step0() {
      if (elementCompressionStrategy == null)
        return;
      probabilisticForEach(scheduler(), 1.0, 0.5, indexAsSideValue(inputData()), ivf1WithToString("Compress element", data -> {
        int i = data.sideValue();
        var subSearch = new CompressionSearch_AnyType<ICachedJavaXExpr<El>, El>(assertNotNull("childRegime", childRegime()), data.get(), 1);
        subSearch.onNewBest(() -> set(dirtyElements, i));
        listSet(searches, i, subSearch);
        subSearch.addStrategy(elementCompressionStrategy.get());
      }));
    }

    public String stats() {
      return renderVars("nNotLiteral", nNotLiteral() + " of " + size());
    }

    transient public IF0<CompressionRegime_AnyType<ICachedJavaXExpr<El>>> childRegime;

    public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime() {
      return childRegime != null ? childRegime.get() : childRegime_base();
    }

    final public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime_fallback(IF0<CompressionRegime_AnyType<ICachedJavaXExpr<El>>> _f) {
      return _f != null ? _f.get() : childRegime_base();
    }

    public CompressionRegime_AnyType<ICachedJavaXExpr<El>> childRegime_base() {
      return (CompressionRegime_AnyType) regime();
    }
  }

  public interface Matrix<A> {

    public int getWidth();

    public int getHeight();

    public A get(int x, int y);

    public void set(int x, int y, A a);

    default public Pt size() {
      return pt(getWidth(), getHeight());
    }

    default public int nCells() {
      return getWidth() * getHeight();
    }

    default public List<A> getLine(int y) {
      return new RandomAccessAbstractList<A>() {

        public int size() {
          return getWidth();
        }

        public A get(int x) {
          return Matrix.this.get(x, y);
        }

        public A set(int x, A val) {
          A old = Matrix.this.get(x, y);
          Matrix.this.set(x, y, val);
          return old;
        }
      };
    }
  }

  public interface JavaCodec<Data> {
  }

  static public class JECompressionSearch<Data> extends CompressionSearch_AnyType<ICachedJavaXExpr, Data> {

    public JECompressionSearch() {
    }

    public JECompressionSearch(Data data, long inputSize) {
      super(jeCompressionRegime(), data, inputSize);
    }
  }

  static public class Ratio implements IFieldsToList {

    static final public String _fieldOrder = "numerator denominator";

    public double numerator;

    public double denominator;

    public Ratio() {
    }

    public Ratio(double numerator, double denominator) {
      this.denominator = denominator;
      this.numerator = numerator;
    }

    public boolean equals(Object o) {
      if (!(o instanceof Ratio))
        return false;
      Ratio __1 = (Ratio) o;
      return numerator == __1.numerator && denominator == __1.denominator;
    }

    public int hashCode() {
      int h = 78733291;
      h = boostHashCombine(h, _hashCode(numerator));
      h = boostHashCombine(h, _hashCode(denominator));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { numerator, denominator };
    }

    public double get() {
      return doubleRatio(numerator, denominator);
    }

    public String toString() {
      return numerator + "/" + denominator + "=" + (denominator == 0 ? "oops" : str(get()));
    }
  }

  public interface CompressionRegime_AnyType<A> {

    public byte[] decompressorToBytes(A decompressor);

    public A decompressorFromBytes(byte[] compressed);

    public Object runDecompressor(A a);

    public CompressionRegime_AnyType<A> fullRegime();
  }

  static public class Seconds implements Comparable<Seconds>, IFieldsToList {

    public double seconds;

    public Seconds() {
    }

    public Seconds(double seconds) {
      this.seconds = seconds;
    }

    public boolean equals(Object o) {
      if (!(o instanceof Seconds))
        return false;
      Seconds __1 = (Seconds) o;
      return seconds == __1.seconds;
    }

    public int hashCode() {
      int h = -660217249;
      h = boostHashCombine(h, _hashCode(seconds));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { seconds };
    }

    final public double get() {
      return seconds();
    }

    final public double getDouble() {
      return seconds();
    }

    public double seconds() {
      return seconds;
    }

    public String toString() {
      return formatDouble(seconds, 3) + " s";
    }

    public int compareTo(Seconds s) {
      return cmp(seconds, s.seconds);
    }

    public Seconds div(double x) {
      return new Seconds(get() / x);
    }

    public Seconds minus(Seconds x) {
      return new Seconds(get() - x.get());
    }
  }

  static public class FunctionCall implements Transformable, IFieldsToList {

    public Object function;

    public Object[] args;

    public FunctionCall() {
    }

    public Object[] _fieldsToList() {
      return new Object[] { function, args };
    }

    static public String _fieldOrder = "function args";

    public FunctionCall(Object function, Object... args) {
      this.args = args;
      this.function = function;
      if (empty(this.args))
        this.args = null;
    }

    public String toString() {
      return function + "(" + joinWithComma(allToString(args)) + ")";
    }

    public boolean equals(Object o) {
      return o instanceof FunctionCall && eq(function, ((FunctionCall) o).function) && objectArraysEqual(args, ((FunctionCall) o).args);
    }

    public int hashCode() {
      return hashAboutObjects(function, asList(args));
    }

    public List args() {
      return asList(args);
    }

    public Object transformUsing(IF1 f) {
      return new FunctionCall(f.get(function), mapObjectArray(f, args));
    }
  }

  static public class Best<A> {

    public A best;

    public double score;

    public boolean verboseNewBest, replaceIfSameScore;

    transient public Object onChange;

    transient public Object stringifier;

    synchronized public boolean isNewBest(double score) {
      return best == null || !isNaN(score) && (replaceIfSameScore ? score >= this.score : score > this.score);
    }

    synchronized public double bestScore() {
      return best == null ? minusInfinity() : score;
    }

    public double score() {
      return bestScore();
    }

    public double getScore() {
      return bestScore();
    }

    synchronized public float floatScoreOr(float defaultValue) {
      return best == null ? defaultValue : (float) score;
    }

    public boolean put(Pair<? extends A, Double> p) {
      return p != null && put(p.a, p.b);
    }

    public boolean put(Best<? extends A> b) {
      return b != null && put(b.get(), b.score);
    }

    public boolean put(A a, double score) {
      ping();
      boolean change = false;
      if (a != null)
        synchronized (this) {
          if (isNewBest(score)) {
            best = a;
            this.score = score;
            change = true;
          }
        }
      if (change) {
        if (verboseNewBest)
          print("New best! " + this);
        pcallF(onChange);
      }
      return change;
    }

    synchronized public A get() {
      return best;
    }

    synchronized public boolean has() {
      return best != null;
    }

    synchronized public Pair<A, Double> pair() {
      return main.pair(best, bestScore());
    }

    synchronized public Scored<A> scored() {
      return best == null ? null : new Scored<A>(best, bestScore());
    }

    synchronized public A getIfScoreAbove(double x) {
      return score() >= x ? best : null;
    }

    public String toString() {
      return "Score " + formatDouble_significant2(score, 4) + ": " + callStringifier(stringifier, best);
    }

    public boolean putAndPrintIfNewBest(A a, double score) {
      if (!put(a, score))
        return false;
      {
        print(this);
        return true;
      }
    }

    synchronized public void clear() {
      best = null;
      score = 0;
    }
  }

  static public interface IIntegralImage extends MakesBufferedImage {

    public int getWidth();

    public int getHeight();

    default public Pt getSize() {
      return pt(getWidth(), getHeight());
    }

    default public int defaultChannel() {
      return 0;
    }

    default public int nChannels() {
      return 3;
    }

    public double getIntegralValue(int x, int y, int channel);

    default public double getIntegralValue(double x, double y, int channel) {
      return getIntegralValue(ifloor(x), ifloor(y), channel);
    }

    default public double getIntegralValue(int x, int y) {
      return getIntegralValue(x, y, 0) + getIntegralValue(x, y, 1) + getIntegralValue(x, y, 2);
    }

    default public double rectSum(int x1, int y1, int x2, int y2, int channel) {
      double bottomLeft = getIntegralValue(x1 - 1, y2 - 1, channel);
      double bottomRight = getIntegralValue(x2 - 1, y2 - 1, channel);
      double topLeft = getIntegralValue(x1 - 1, y1 - 1, channel);
      double topRight = getIntegralValue(x2 - 1, y1 - 1, channel);
      return bottomRight + topLeft - topRight - bottomLeft;
    }

    default public double rectSum(double x1, double y1, double x2, double y2, int channel) {
      return rectSum(iround(x1), iround(y1), iround(x2), iround(y2), channel);
    }

    default public double rectSum(int x1, int y1, int x2, int y2) {
      double bottomLeft = getIntegralValue(x1 - 1, y2 - 1);
      double bottomRight = getIntegralValue(x2 - 1, y2 - 1);
      double topLeft = getIntegralValue(x1 - 1, y1 - 1);
      double topRight = getIntegralValue(x2 - 1, y1 - 1);
      return bottomRight + topLeft - topRight - bottomLeft;
    }

    default public double rectAverage(int x1, int y1, int x2, int y2, int channel) {
      return doubleRatio(rectSum(x1, y1, x2, y2, channel), areaFromPoints(x1, y1, x2, y2));
    }

    default public double rectAverage(Rect r, int channel) {
      return doubleRatio(rectSum(r, channel), rectArea(r));
    }

    default public double rectSum(Rect r) {
      return rectSum(r.x, r.y, r.x2(), r.y2());
    }

    default public double rectSum(Rect r, int channel) {
      return rectSum(r.x, r.y, r.x2(), r.y2(), channel);
    }

    default public double pixelSum(DoubleRect r) {
      return rectSum(toRect_floor(r), defaultChannel());
    }

    default public IIntegralImage clip(int x, int y, int w, int h) {
      return new IIVirtualClip(this, x, y, w, h);
    }

    default public double averageBrightness() {
      int w = getWidth(), h = getHeight();
      return doubleRatio(getIntegralValue(w - 1, h - 1), w * h * 3 * 255.0);
    }

    default public double getPixel(int x, int y, int channel) {
      return rectSum(x, y, x + 1, y + 1, channel);
    }

    default public int getPixel(int x, int y) {
      int r = iround(rectSum(x, y, x + 1, y + 1, 0));
      int g = iround(rectSum(x, y, x + 1, y + 1, 1));
      int b = iround(rectSum(x, y, x + 1, y + 1, 2));
      return rgbInt(r, g, b);
    }

    default public BufferedImage getBufferedImage() {
      int w = getWidth(), h = getHeight();
      int[] pixels = new int[w * h];
      int i = 0;
      for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) pixels[i++] = getPixel(x, y) | fullAlphaMask();
      return intArrayToBufferedImage(pixels, w, h);
    }
  }

  static public class WithProbability<A> extends Var<A> implements Comparable<WithProbability<A>> {

    public double probability;

    public WithProbability() {
    }

    public WithProbability(A a) {
      this(1, a);
    }

    public WithProbability(double probability, A a) {
      super(a);
      this.probability = probability;
    }

    public String toString() {
      return "p=" + renderedProbability() + ": " + str(get());
    }

    public String renderedProbability() {
      return formatDouble_noLeadingZero(probability, 2);
    }

    public double probability() {
      return probability;
    }

    public int hashCode() {
      return boostHashCombine(main.hashCode(probability), main.hashCode(get()));
    }

    public boolean equals(Object o) {
      if (o instanceof WithProbability) {
        return probability == ((WithProbability) o).probability && eq(get(), ((WithProbability) o).get());
      }
      return false;
    }

    public int compareTo(WithProbability<A> wp) {
      return wp == null ? 1 : cmp(wp.probability, probability);
    }
  }

  abstract static public class JEInstantCompressor_AnyType<Data> extends AbstractCompressor_AnyType<ICachedJavaXExpr, Data> {

    abstract public ICachedJavaXExpr compress(Data data);

    public void step0() {
      search.submit(compress(search.inputData()));
    }
  }

  static public class IIVirtualClip extends Meta implements IIntegralImage {

    public RegisteredReference<IIntegralImage> fullImage = new RegisteredReference<>(this);

    public int x1, y1, w, h;

    public IIVirtualClip() {
    }

    public IIVirtualClip(IIntegralImage fullImage, int x1, int y1, int w, int h) {
      this.fullImage.set(fullImage);
      this.h = h;
      this.w = w;
      this.y1 = y1;
      this.x1 = x1;
    }

    public int getWidth() {
      return w;
    }

    public int getHeight() {
      return h;
    }

    public double getIntegralValue(int x, int y, int channel) {
      return fullImage.get().getIntegralValue(x + x1, y + y1, channel);
    }

    public double getIntegralValue(int x, int y) {
      return fullImage.get().getIntegralValue(x + x1, y + y1);
    }

    public BufferedImage getBufferedImage() {
      return clipBufferedImage(fullImage.get().getBufferedImage(), x1, y1, w, h);
    }
  }

  static public class ProbabilisticScheduler extends Meta implements IProbabilisticScheduler, Steppable {

    public TreeSetWithDuplicates<Entry> entries = new TreeSetWithDuplicates<>(byProbability());

    public long stepCount;

    public boolean verbose = false;

    public double cutoffProbabilityOnAdd = 0;

    public double cutoffProbabilityOnExecute = 0;

    public Comparator<Entry> byProbability() {
      return (a, b) -> cmp(b.probability, a.probability);
    }

    public long dropped;

    public double lastExecutedProbability = 1.0;

    public ThreadLocal<Double> threadProbability = new ThreadLocal();

    public class Entry {

      public Entry() {
      }

      public double probability;

      public Runnable action;

      public Entry(double probability, Runnable action) {
        this.action = action;
        this.probability = probability;
      }

      public void run() {
        try {
          initAction(action);
          AutoCloseable __1 = tempSetTL(threadProbability, probability);
          try {
            action.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return str(new WithProbability(probability, action));
      }
    }

    final public void at(double probability, Runnable action) {
      add(probability, action);
    }

    public void add(double probability, Runnable action) {
      if (action == null)
        return;
      if (probability < cutoffProbabilityOnAdd) {
        ++dropped;
        {
          if (scaffoldingEnabled(this))
            scaffoldCalled(this, "Not scheduling " + withProbability(probability, action) + " (below threshold of " + cutoffProbabilityOnAdd + ")");
        }
        return;
      }
      {
        if (scaffoldingEnabled(this))
          scaffoldCalled(this, "Scheduling " + withProbability(probability, action));
      }
      entries.add(new Entry(probability, action));
    }

    public boolean step() {
      return stepFirstUnstepped();
    }

    public Entry nextSteppable() {
      Entry s = first(entries);
      if (s != null && s.probability <= cutoffProbabilityOnExecute)
        return null;
      return s;
    }

    public boolean stepFirstUnstepped() {
      Entry s = nextSteppable();
      if (s == null)
        return false;
      if (verbose)
        print("Current scheduler probability: " + s.probability);
      entries.remove(s);
      ++stepCount;
      lastExecutedProbability = s.probability;
      s.run();
      return true;
    }

    public void reset() {
      entries.clear();
    }

    public void run() {
      try {
        stepAll(this);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void run(int maxSteps) {
      stepMax(maxSteps, this);
    }

    public void printStats() {
      Entry first = entries.first(), last = entries.last();
      Entry next = nextSteppable();
      print("ProbabilisticScheduler. " + nEntries(entries) + ", highest probability in queue: " + (first == null ? "-" : first.probability) + ", lowest probability in queue: " + (last == null ? "-" : last.probability) + ", cutoff probability: " + cutoffProbabilityOnAdd + "/" + cutoffProbabilityOnExecute + ", " + (next == null ? "done" : "next step: " + next.action));
    }

    final public double current() {
      return currentProbability();
    }

    public double currentProbability() {
      return or(threadProbability.get(), 1.0);
    }

    public double remainingProbability() {
      Entry s = nextSteppable();
      return s == null ? 0.0 : s.probability;
    }

    public double lastExecutedProbability() {
      return lastExecutedProbability;
    }

    public long stepCount() {
      return stepCount;
    }

    public boolean isEmpty() {
      return empty(entries);
    }
  }

  static public interface IMeta {

    public void _setMeta(Object meta);

    public Object _getMeta();

    default public IAutoCloseableF0 _tempMetaMutex() {
      return new IAutoCloseableF0() {

        public Object get() {
          return IMeta.this;
        }

        public void close() {
        }
      };
    }

    default public Object getMeta(Object obj, Object key) {
      return metaGet(obj, key);
    }

    default public Object metaGet(Object obj, Object key) {
      return metaMapGet(obj, key);
    }

    default public Object getMeta(Object key) {
      return metaGet(key);
    }

    default public Object metaGet(Object key) {
      if (key == null)
        return null;
      Object meta = _getMeta();
      if (meta instanceof Map)
        return ((Map) meta).get(key);
      return null;
    }

    default public void metaSet(IMeta obj, Object key, Object value) {
      metaPut(obj, key, value);
    }

    default public void metaPut(IMeta obj, Object key, Object value) {
      metaMapPut(obj, key, value);
    }

    default public void metaSet(Object key, Object value) {
      metaPut(key, value);
    }

    default public void metaPut(Object key, Object value) {
      if (key == null)
        return;
      Map map = convertObjectMetaToMap(this);
      syncMapPutOrRemove(map, key, value);
    }
  }

  static public interface ICachedJavaXExpr<A> extends IMeta {

    public default A quickEval() {
      throw fail("Can't quick eval: " + toStringWithClassName(this));
    }

    public default Object javaConstruct() {
      return this;
    }

    default public int sourceCodeLength() {
      return l(toString());
    }
  }

  static public interface Transformable {

    public Object transformUsing(IF1 f);
  }

  abstract static public class RandomAccessAbstractList<A> extends AbstractList<A> implements RandomAccess {
  }

  static public class TreeSetWithDuplicates<A> extends AbstractSet<A> {

    public NavigableSet<CompactLinkedHashSet<A>> sets;

    public Comparator<A> comparator;

    public int size;

    public TreeSetWithDuplicates() {
      this((Comparator<A>) null);
    }

    public TreeSetWithDuplicates(Comparator<A> comparator) {
      this.comparator = comparator;
      sets = new TreeSet<CompactLinkedHashSet<A>>(comparator == null ? (setA, setB) -> cmp(main.first(setA), main.first(setB)) : (setA, setB) -> comparator.compare(main.first(setA), main.first(setB)));
    }

    public TreeSetWithDuplicates(NavigableSet<CompactLinkedHashSet<A>> sets) {
      this.sets = sets;
    }

    public CompactLinkedHashSet<A> makeInnerSet() {
      return new CompactLinkedHashSet();
    }

    public boolean add(A a) {
      var probe = probe(a);
      CompactLinkedHashSet<A> found = navigableSet_find(sets, probe);
      if (found != null) {
        if (!found.add(a))
          return false;
      } else
        sets.add(probe);
      ++size;
      return true;
    }

    public boolean remove(Object a) {
      CompactLinkedHashSet<A> newSet = makeInnerSet();
      newSet.add((A) a);
      CompactLinkedHashSet<A> found = navigableSet_find(sets, newSet);
      if (found == null)
        return false;
      if (l(found) == 1)
        sets.remove(found);
      else
        found.remove(a);
      --size;
      return true;
    }

    public A first() {
      return main.first(main.first(sets));
    }

    public A last() {
      var last = sets.last();
      return last == null ? null : last.last();
    }

    public IterableIterator<A> iterator() {
      return nestedIterator(sets, __1 -> __1.iterator());
    }

    public int size() {
      return size;
    }

    public Set<A> tiedForFirst() {
      return main.first(sets);
    }

    public CompactLinkedHashSet<A> probe(Object a) {
      return addAndReturnCollection(makeInnerSet(), (A) a);
    }

    public boolean contains(Object a) {
      return navigableSet_find(sets, probe(a)) != null;
    }
  }

  static public interface IAutoCloseableF0<A> extends IF0<A>, AutoCloseable {
  }

  static public class RegisteredReference<A> implements IRef<A> {

    public Meta owner;

    public A value;

    public RegisteredReference() {
    }

    public RegisteredReference(Meta owner) {
      this(owner, null);
    }

    public RegisteredReference(Meta owner, A value) {
      this.value = value;
      this.owner = owner;
      index();
    }

    public Meta owner() {
      return owner;
    }

    public A get() {
      return value;
    }

    public boolean has() {
      return value != null;
    }

    public boolean set_trueIfChanged(A a) {
      if (eq(a, value))
        return false;
      unindex();
      value = a;
      index();
      return true;
    }

    public void set(A a) {
      set_trueIfChanged(a);
    }

    public void setIfEmpty(A a) {
      if (!has())
        set(a);
    }

    public void set(IRef<A> ref) {
      set(ref == null ? null : ref.get());
    }

    public void clear() {
      set((A) null);
    }

    public boolean validRef() {
      return true;
    }

    public void index() {
      if (!validRef())
        return;
      var br = lookupInterface(IHasBackRefs.class, get());
      {
        if (br != null)
          br._registerBackRef(this);
      }
    }

    public void unindex() {
      if (!validRef())
        return;
      var br = lookupInterface(IHasBackRefs.class, get());
      {
        if (br != null)
          br._unregisterBackRef(this);
      }
    }

    public void change() {
    }

    public String toString() {
      return str(value);
    }
  }

  static public interface IHasBackRefs {

    public void _registerBackRef(IRef ref);

    public void _unregisterBackRef(IRef ref);
  }

  static public interface IRef<A> extends IF0<A> {

    public default void replaceValue(A oldValue, A newValue) {
    }
  }

  static public class CompactLinkedHashSet<A> extends AbstractSet<A> {

    public UnsynchronizedCompactHashSet<Entry<A>> entries = new UnsynchronizedCompactHashSet();

    public Entry<A> head, tail;

    static public class Entry<A> {

      public A value;

      public Entry<A> prev, next;

      public int hashCode() {
        return _hashCode(value);
      }

      public boolean equals(Object o) {
        return o == this || eq(value, o);
      }
    }

    public boolean add(A a) {
      if (entries.contains(a))
        return false;
      Entry<A> n = new Entry();
      n.value = a;
      n.prev = tail;
      if (tail != null)
        tail.next = n;
      tail = n;
      if (head == null)
        head = n;
      entries.add(n);
      return true;
    }

    public boolean remove(Object a) {
      return remove(entries.find(a));
    }

    public boolean remove(Entry<A> node) {
      if (node == null)
        return false;
      if (node.next != null)
        node.next.prev = node.prev;
      else
        tail = node.prev;
      if (node.prev != null)
        node.prev.next = node.next;
      else
        head = node.next;
      entries.remove(node);
      return true;
    }

    public int size() {
      return entries.size();
    }

    public IterableIterator<A> iterator() {
      return new IterableIterator<A>() {

        public Entry<A> entry = head, prev = null;

        public boolean hasNext() {
          return entry != null;
        }

        public A next() {
          A a = entry.value;
          prev = entry;
          entry = entry.next;
          return a;
        }

        public void remove() {
          if (prev == null)
            throw new IllegalStateException();
          CompactLinkedHashSet.this.remove(prev);
          prev = null;
        }
      };
    }

    public void clear() {
      entries.clear();
      head = tail = null;
    }

    public boolean contains(Object a) {
      return entries.contains(a);
    }

    public A find(Object o) {
      Entry<A> e = entries.find(o);
      return e == null ? null : e.value;
    }

    public A prevElement(A a) {
      Entry<A> e = entries.find(a);
      if (e == null || e.prev == null)
        return null;
      return e.prev.value;
    }

    public A nextElement(A a) {
      Entry<A> e = entries.find(a);
      if (e == null || e.next == null)
        return null;
      return e.next.value;
    }

    public A first() {
      return head == null ? null : head.value;
    }

    public A last() {
      return tail == null ? null : tail.value;
    }

    public boolean removeIfSame(Object o) {
      A value = find(o);
      if (value == o) {
        remove(value);
        return true;
      }
      return false;
    }
  }

  static public class UnsynchronizedCompactHashSet<A> extends java.util.AbstractSet<A> {

    final static public int INITIAL_SIZE = 3;

    public final static double LOAD_FACTOR = 0.75;

    final static public Object nullObject = new Object();

    final static public Object deletedObject = new Object();

    public int elements;

    public int freecells;

    public A[] objects;

    public int modCount;

    public UnsynchronizedCompactHashSet() {
      this(INITIAL_SIZE);
    }

    public UnsynchronizedCompactHashSet(int size) {
      objects = (A[]) new Object[(size == 0 ? 1 : size)];
      elements = 0;
      freecells = objects.length;
      modCount = 0;
    }

    public UnsynchronizedCompactHashSet(Collection<A> c) {
      this(c.size());
      addAll(c);
    }

    @Override
    public Iterator<A> iterator() {
      return new CompactHashIterator<A>();
    }

    @Override
    public int size() {
      return elements;
    }

    @Override
    public boolean isEmpty() {
      return elements == 0;
    }

    @Override
    public boolean contains(Object o) {
      return find(o) != null;
    }

    public A find(Object o) {
      if (o == null)
        o = nullObject;
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % objects.length;
      int offset = 1;
      while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
        index = ((index + offset) & 0x7FFFFFFF) % objects.length;
        offset = offset * 2 + 1;
        if (offset == -1)
          offset = 2;
      }
      return objects[index];
    }

    public boolean removeIfSame(Object o) {
      A value = find(o);
      if (value == o) {
        remove(value);
        return true;
      }
      return false;
    }

    @Override
    public boolean add(Object o) {
      if (o == null)
        o = nullObject;
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % objects.length;
      int offset = 1;
      int deletedix = -1;
      while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
        if (objects[index] == deletedObject)
          deletedix = index;
        index = ((index + offset) & 0x7FFFFFFF) % objects.length;
        offset = offset * 2 + 1;
        if (offset == -1)
          offset = 2;
      }
      if (objects[index] == null) {
        if (deletedix != -1)
          index = deletedix;
        else
          freecells--;
        modCount++;
        elements++;
        objects[index] = (A) o;
        if (1 - (freecells / (double) objects.length) > LOAD_FACTOR)
          rehash();
        return true;
      } else
        return false;
    }

    @Override
    public boolean remove(Object o) {
      if (o == null)
        o = nullObject;
      int hash = o.hashCode();
      int index = (hash & 0x7FFFFFFF) % objects.length;
      int offset = 1;
      while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
        index = ((index + offset) & 0x7FFFFFFF) % objects.length;
        offset = offset * 2 + 1;
        if (offset == -1)
          offset = 2;
      }
      if (objects[index] != null) {
        objects[index] = (A) deletedObject;
        modCount++;
        elements--;
        return true;
      } else
        return false;
    }

    @Override
    public void clear() {
      elements = 0;
      for (int ix = 0; ix < objects.length; ix++) objects[ix] = null;
      freecells = objects.length;
      modCount++;
    }

    @Override
    public Object[] toArray() {
      Object[] result = new Object[elements];
      Object[] objects = this.objects;
      int pos = 0;
      for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          result[pos++] = null;
        else
          result[pos++] = objects[i];
      }
      return result;
    }

    @Override
    public <T> T[] toArray(T[] a) {
      int size = elements;
      if (a.length < size)
        a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
      A[] objects = this.objects;
      int pos = 0;
      for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) {
        if (objects[i] == nullObject)
          a[pos++] = null;
        else
          a[pos++] = (T) objects[i];
      }
      return a;
    }

    public void rehash() {
      int garbagecells = objects.length - (elements + freecells);
      if (garbagecells / (double) objects.length > 0.05)
        rehash(objects.length);
      else
        rehash(objects.length * 2 + 1);
    }

    public void rehash(int newCapacity) {
      int oldCapacity = objects.length;
      @SuppressWarnings("unchecked")
      A[] newObjects = (A[]) new Object[newCapacity];
      for (int ix = 0; ix < oldCapacity; ix++) {
        Object o = objects[ix];
        if (o == null || o == deletedObject)
          continue;
        int hash = o.hashCode();
        int index = (hash & 0x7FFFFFFF) % newCapacity;
        int offset = 1;
        while (newObjects[index] != null) {
          index = ((index + offset) & 0x7FFFFFFF) % newCapacity;
          offset = offset * 2 + 1;
          if (offset == -1)
            offset = 2;
        }
        newObjects[index] = (A) o;
      }
      objects = newObjects;
      freecells = objects.length - elements;
    }

    public class CompactHashIterator<T> implements Iterator<T> {

      public int index;

      public int lastReturned = -1;

      public int expectedModCount;

      @SuppressWarnings("empty-statement")
      public CompactHashIterator() {
        for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ;
        expectedModCount = modCount;
      }

      @Override
      public boolean hasNext() {
        return index < objects.length;
      }

      @SuppressWarnings("empty-statement")
      @Override
      public T next() {
        int length = objects.length;
        if (index >= length) {
          lastReturned = -2;
          throw new NoSuchElementException();
        }
        lastReturned = index;
        for (index += 1; index < length && (objects[index] == null || objects[index] == deletedObject); index++) ;
        if (objects[lastReturned] == nullObject)
          return null;
        else
          return (T) objects[lastReturned];
      }

      @Override
      public void remove() {
        if (modCount != expectedModCount)
          throw new ConcurrentModificationException();
        if (lastReturned == -1 || lastReturned == -2)
          throw new IllegalStateException();
        if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) {
          objects[lastReturned] = (A) deletedObject;
          elements--;
          modCount++;
          expectedModCount = modCount;
        }
      }
    }

    public int capacity() {
      return objects.length;
    }

    public boolean shrinkToFactor(double factor) {
      if (factor > LOAD_FACTOR)
        throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR);
      int newCapacity = max(INITIAL_SIZE, iround(size() / factor));
      if (newCapacity >= capacity())
        return false;
      rehash(newCapacity);
      return true;
    }
  }

  static public Graphics2D graphics(BufferedImage img) {
    return imageGraphics(img);
  }

  static public Border getBorder(final JComponent c) {
    return c == null ? null : swing(new F0<Border>() {

      public Border get() {
        try {
          return c.getBorder();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.getBorder();";
      }
    });
  }

  static public <A extends JSpinner> A onChange(A spinner, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            spinner.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "spinner.addChangeListener(changeListener(r));";
        }
      });
    }
    return spinner;
  }

  static public <A extends AbstractButton> A onChange(A b, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            b.addItemListener(itemListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addItemListener(itemListener(r));";
        }
      });
    }
    return b;
  }

  static public void onChange(JTextComponent tc, Object r) {
    onUpdate(tc, r);
  }

  static public <A extends JSlider> A onChange(A slider, final Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            slider.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "slider.addChangeListener(changeListener(r));";
        }
      });
    }
    return slider;
  }

  static public JComboBox onChange(Object r, JComboBox cb) {
    return onChange(cb, r);
  }

  static public JComboBox onChange(JComboBox cb, final Object r) {
    if (isEditableComboBox(cb))
      onChange(textFieldFromComboBox(cb), r);
    else
      onSelectedItem(cb, new VF1<String>() {

        public void get(String s) {
          try {
            callF(r);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(r)";
        }
      });
    return cb;
  }

  static public Pt pt(int x, int y) {
    return new Pt(x, y);
  }

  static public Pt pt(int x) {
    return new Pt(x, x);
  }

  static public void addMouseAndMotionListener(JComponent c, MouseAdapter ma) {
    if (c != null && ma != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.addMouseListener(ma);
            c.addMouseMotionListener(ma);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.addMouseListener(ma);\r\n    c.addMouseMotionListener(ma);";
        }
      });
    }
  }

  static public void removeMouseAdapter(Component c, MouseAdapter a) {
    if (c != null && a != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.removeMouseListener(a);
            c.removeMouseMotionListener(a);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.removeMouseListener(a);\r\n    c.removeMouseMotionListener(a);";
        }
      });
    }
  }

  static public Rectangle boundsOnScreen(Component c) {
    if (c == null)
      return null;
    if (c.getParent() instanceof JViewport && c.getParent().getParent() instanceof JScrollPane)
      c = c.getParent().getParent();
    try {
      return new Rectangle(c.getLocationOnScreen(), c.getSize());
    } catch (IllegalComponentStateException e) {
      return null;
    }
  }

  static public double distance(double ax, double ay, double bx, double by) {
    return sqrt(sqr(bx - ax) + sqr(by - ay));
  }

  static public int distance(int a, int b) {
    return abs(a - b);
  }

  static public void printVars(Object... params) {
    printVars_str(params);
  }

  static public Pt topLeftCorner(Rect r) {
    return rectTopLeftCorner(r);
  }

  static public Pt bottomRightCorner(Rect r) {
    return r == null ? null : pt(r.x2(), r.y2());
  }

  static public Rect rectFromPoints(int x1, int y1, int x2, int y2) {
    return pointsRect(x1, y1, x2, y2);
  }

  static public Rect rectFromPoints(Pt a, Pt b) {
    return pointsRect(a.x, a.y, b.x, b.y);
  }

  static public Rectangle toRectangle(Rect r) {
    return r == null ? null : r.getRectangle();
  }

  static public Set<java.util.Timer> _registerTimer_list = newWeakHashSet();

  static public void _registerTimer(java.util.Timer timer) {
    _registerTimer_list.add(timer);
  }

  static public void cleanMeUp__registerTimer() {
    cancelTimers(getAndClearList(_registerTimer_list));
  }

  static public String joinNemptiesWithColon(String... strings) {
    return joinNempties(": ", strings);
  }

  static public String joinNemptiesWithColon(Collection<String> strings) {
    return joinNempties(": ", strings);
  }

  static public String commaCombine(Object... l) {
    return joinNemptiesWithComma(flattenCollectionsAndArrays(ll(l)));
  }

  static public BufferedImage defaultScreenshot() {
    if (hasGlobalOption("canDefaultScreenshot"))
      return shootScreen2();
    return null;
  }

  static public String forward(String bot, String msg, Object... args) {
    return format("please forward to bot *: *", bot, format(msg, args));
  }

  static public <A> A assertNotNull(A a) {
    assertTrue(a != null);
    return a;
  }

  static public <A> A assertNotNull(String msg, A a) {
    assertTrue(msg, a != null);
    return a;
  }

  static public Matrix<Integer> imageToMatrix(MakesBufferedImage img) {
    return imageToMatrix(toBufferedImage(img));
  }

  static public Matrix<Integer> imageToMatrix(BufferedImage img) {
    if (img == null)
      return null;
    int _w = img.getWidth(), _h = img.getHeight();
    class ImageToMatrix extends AbstractMatrix<Integer> {

      public ImageToMatrix() {
        super(_w, _h);
      }

      public Integer get(int x, int y) {
        assertPointInBounds(x, y, w, h);
        return img.getRGB(x, y);
      }

      public void set(int x, int y, Integer val) {
        assertPointInBounds(x, y, w, h);
        img.setRGB(x, y, val);
      }
    }
    ;
    return new ImageToMatrix();
  }

  static public String shorten_str(Object o) {
    return shorten(str(o));
  }

  static public String shorten_str(Object o, int max) {
    return shorten(str(o), max);
  }

  static public String shorten_str(int max, Object o) {
    return shorten_str(o, max);
  }

  static public <A> Matrix<Matrix<A>> matrixToMNGrid_rows(Matrix<A> m, int rows) {
    if (m == null)
      return null;
    int cols = widthForHeight(m.getWidth(), m.getHeight(), rows);
    return matrixToMNGrid(m, cols, rows);
  }

  static public <A> List<List<A>> matrixOfMatricesToListOfLists(Matrix<Matrix<A>> mm) {
    return map(__63 -> matrixToList(__63), matrixToList(mm));
  }

  static public <Data> JECompressionSearch<Data> jeCompressionSearch(Data data, long inputSize) {
    return new JECompressionSearch<Data>(data, inputSize);
  }

  static public ICachedJavaXExpr javaObjectToIJavaExpr(Object o) {
    if (isListOfElementType(Integer.class, o))
      return javaExpr(functionCall("lInts", naiveQuote(intsToHex_withLineBreaks((List<Integer>) o))), () -> o);
    if (o instanceof List)
      return javaExpr(functionCall("ll", map(__64 -> javaObjectToIJavaExpr(__64), (List) o)), () -> ((List) o));
    Object code = toJavaOpt(o);
    return javaExpr(code, () -> o);
  }

  static public <A, B> B rCallF(A a, IF1<A, B> f) {
    return f == null ? null : f.get(a);
  }

  static public <A> void rCallF(A a, IVF1<A> f) {
    {
      if (f != null)
        f.get(a);
    }
  }

  static public <A, B> List<B> lambdaMapMethod(IF1<A, B> f, Iterable<A> l) {
    return lambdaMethodMap(f, l);
  }

  static public <A, B> List<B> lambdaMapMethod(IF1<A, B> f, A[] l) {
    return lambdaMethodMap(f, l);
  }

  static public <A> List<A> rowToList(Matrix<A> m, int y) {
    if (m == null)
      return null;
    rangeCheck(y, m.getHeight());
    int w = m.getWidth();
    return new RandomAccessAbstractList<A>() {

      public int size() {
        return w;
      }

      public A get(int x) {
        return m.get(x, y);
      }

      public A set(int x, A val) {
        A old = m.get(x, y);
        m.set(x, y, val);
        return old;
      }
    };
  }

  static public <A> List<A> colToList(Matrix<A> m, int x) {
    if (m == null)
      return null;
    rangeCheck(x, m.getWidth());
    int h = m.getHeight();
    return new RandomAccessAbstractList<A>() {

      public int size() {
        return h;
      }

      public A get(int y) {
        return m.get(x, y);
      }

      public A set(int y, A val) {
        A old = m.get(x, y);
        m.set(x, y, val);
        return old;
      }
    };
  }

  static public FunctionCall functionCall(Object fname, Object... args) {
    return new FunctionCall(fname, args);
  }

  static public BufferedImage gridLOLToImage(List<Integer> cellWidths, List<Integer> cellHeights, List<List<Integer>> lol) {
    List<Matrix<Integer>> lom = mapWithIndex(lol, (i, m) -> listToMatrix(cyclicGet(cellWidths, i), m));
    Matrix<Matrix<Integer>> mom = listToMatrix_cols(l(cellWidths), lom);
    List<Integer> cellX1s = partialSums_firstIs0(cellWidths);
    List<Integer> cellY1s = partialSums_firstIs0(cellHeights);
    int w = last(cellX1s), h = last(cellY1s);
    BufferedImage restored = newBufferedImage(w, h);
    forEachWithPosition(mom, (x, y, cell) -> drawIntMatrix(restored, cell, cyclicGet(cellX1s, x), cyclicGet(cellY1s, y)));
    return restored;
  }

  static public String toJava(Object o) {
    return str(new ToJava().get(o));
  }

  static public Object quickEval(String t) {
    if (isQuoted(t))
      return unquote(t);
    if (isInteger(t))
      return parseIntOrLong(t);
    if (isLongConstant(t))
      return parseLong(t);
    if (eq(t, "null"))
      return null;
    if (eq(t, "false"))
      return false;
    if (eq(t, "true"))
      return true;
    if (isIdentifier(t))
      return getMC(t);
    if (isSnippetID(t))
      return t;
    throw quickFail("Can't quick eval: " + t);
  }

  static public BufferedImage mergeBufferedImagesHorizontally(BufferedImage... images) {
    return mergeBufferedImagesHorizontally(toList(images));
  }

  static public BufferedImage mergeBufferedImagesHorizontally(List<BufferedImage> images, Object... __) {
    if (empty(images))
      return null;
    int spacing = optPar("spacing", __, imageMergeSpacing());
    RGB spaceColor = new RGB(0.9f);
    int w = intSum(mapMethod("getWidth", images)) + (l(images) - 1) * spacing, h = intMax(mapMethod("getHeight", images));
    BufferedImage out = newBufferedImage(w, h, spaceColor);
    int x = 0;
    for (int i = 0; i < l(images); i++) {
      BufferedImage img = images.get(i);
      int y = (h - img.getHeight()) / 2;
      copyBufferedImage(img, out, x, y);
      x += img.getWidth() + spacing;
    }
    return out;
  }

  static public BufferedImage intMatrixToImage(Matrix<Integer> m) {
    return intMatrixToBufferedImage(m);
  }

  static public <A> List<A> matrixToList(Matrix<A> m) {
    if (m == null)
      return null;
    int w = m.getWidth(), h = m.getHeight(), n = w * h;
    return new RandomAccessAbstractList<A>() {

      public int size() {
        return n;
      }

      public A get(int i) {
        return m.get(i % w, i / w);
      }

      public A set(int i, A val) {
        A old = m.get(i % w, i % h);
        m.set(i % w, i / w, val);
        return old;
      }
    };
  }

  static public void add(BitSet bs, int i) {
    bs.set(i);
  }

  static public <A> boolean add(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  static public void add(Container c, Component x) {
    addToContainer(c, x);
  }

  static public long add(AtomicLong l, long b) {
    return l.addAndGet(b);
  }

  static public Class run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

  static public int getPixel(BufferedImage img, int x, int y) {
    return img.getRGB(x, y);
  }

  static public int getPixel(BufferedImage img, Pt p) {
    return img.getRGB(p.x, p.y);
  }

  static public boolean stdEq2(Object a, Object b) {
    if (a == null)
      return b == null;
    if (b == null)
      return false;
    if (a.getClass() != b.getClass())
      return false;
    for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field)))
      return false;
    return true;
  }

  static public int stdHash2(Object a) {
    if (a == null)
      return 0;
    return stdHash(a, toStringArray(allFields(a)));
  }

  static public void change() {
    callOpt(getOptMC("mainConcepts"), "allChanged");
  }

  static public <A> List<A> listCreateAndAdd(List<A> l, A a) {
    return addDyn(l, a);
  }

  static public boolean hasLock(Lock lock) {
    return ((ReentrantLock) lock).isHeldByCurrentThread();
  }

  static public void clear(Collection c) {
    if (c != null)
      c.clear();
  }

  static public void clear(Map map) {
    if (map != null)
      map.clear();
  }

  static public boolean isAbstract(Class c) {
    return (c.getModifiers() & Modifier.ABSTRACT) != 0;
  }

  static public boolean isAbstract(Method m) {
    return (m.getModifiers() & Modifier.ABSTRACT) != 0;
  }

  static public boolean reflection_isForbiddenMethod(Method m) {
    return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
  }

  static public <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
    List<B> l = map.get(a);
    if (l == null)
      map.put(a, l = new ArrayList());
    l.add(b);
  }

  static public <A, B> void multiMapPut(MultiMap<A, B> mm, A key, B value) {
    if (mm != null && key != null && value != null)
      mm.put(key, value);
  }

  static public Set<Class> allInterfacesImplementedBy(Class c) {
    if (c == null)
      return null;
    HashSet<Class> set = new HashSet();
    allInterfacesImplementedBy_find(c, set);
    return set;
  }

  static public void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
    if (c.isInterface() && !set.add(c))
      return;
    do {
      for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
    } while ((c = c.getSuperclass()) != null);
  }

  static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length) {
      if (debug)
        print("Bad parameter length: " + args.length + " vs " + types.length);
      return false;
    }
    for (int i = 0; i < types.length; i++) {
      Object arg = args[i];
      if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
        if (debug)
          print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
        return false;
      }
    }
    return true;
  }

  static public Method findStaticMethod(Class c, String method, Object... args) {
    Class _c = c;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (!m.getName().equals(method))
          continue;
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
          continue;
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    if (types.length != args.length)
      return false;
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
      return false;
    return true;
  }

  static public RuntimeException error() {
    throw new RuntimeException("fail");
  }

  static public RuntimeException error(String msg) {
    throw new RuntimeException(msg);
  }

  static public String ok(Object o) {
    return format("ok *", o);
  }

  static public String localDateWithSeconds(long time) {
    SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss");
    return format.format(time);
  }

  static public String localDateWithSeconds() {
    return localDateWithSeconds(now());
  }

  static public double elapsedMinutes_timestamp(long time) {
    return toMinutes(now() - time);
  }

  static public double elapsedSeconds_timestamp(long time) {
    return toSeconds(now() - time);
  }

  static public Q dm_q() {
    return dm_current_mandatory().q();
  }

  static public void dm_q(Runnable r) {
    dm_inQ(r);
  }

  static public void dm_q(DynModule module, Runnable r) {
    module.q().add(r);
  }

  static public <A> A dm_q(IF0<A> f) {
    return dm_evalInQ(if0ToF0(f));
  }

  static public String formatLocalDateWithSeconds(long time) {
    return localDateWithSeconds(time);
  }

  static public String formatLocalDateWithSeconds() {
    return localDateWithSeconds();
  }

  static public int cmp(Number a, Number b) {
    return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
  }

  static public int cmp(double a, double b) {
    return a < b ? -1 : a == b ? 0 : 1;
  }

  static public int cmp(int a, int b) {
    return a < b ? -1 : a == b ? 0 : 1;
  }

  static public int cmp(long a, long b) {
    return a < b ? -1 : a == b ? 0 : 1;
  }

  static public int cmp(Object a, Object b) {
    if (a == null)
      return b == null ? 0 : -1;
    if (b == null)
      return 1;
    return ((Comparable) a).compareTo(b);
  }

  static public BigInteger plus(BigInteger a, BigInteger b) {
    return a.add(b);
  }

  static public BigInteger plus(BigInteger a, long b) {
    return a.add(bigint(b));
  }

  static public <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null && b != null)
      a.putAll(b);
    return a;
  }

  static public <A, B> MultiMap<A, B> putAll(MultiMap<A, B> a, Map<? extends A, ? extends B> b) {
    if (a != null)
      a.putAll((Map) b);
    return a;
  }

  static public <A, B> Map<A, B> putAll(Map<A, B> a, Object... b) {
    if (a != null)
      litmap_impl(a, b);
    return a;
  }

  static public <A, B> void put(Map<A, B> map, A a, B b) {
    if (map != null)
      map.put(a, b);
  }

  static public <A> void put(List<A> l, int i, A a) {
    if (l != null && i >= 0 && i < l(l))
      l.set(i, a);
  }

  static public <A> void remove(List<A> l, int i) {
    if (l != null && i >= 0 && i < l(l))
      l.remove(i);
  }

  static public <A> void remove(Collection<A> l, A a) {
    if (l != null)
      l.remove(a);
  }

  static public <A, B> B remove(Map<A, B> map, Object a) {
    return map == null ? null : map.remove(a);
  }

  static public void remove(BitSet bs, int i) {
    bs.clear(i);
  }

  static public <A> A getAndClear(IVar<A> v) {
    A a = v.get();
    v.set(null);
    return a;
  }

  static public <A, B> Set<A> keySet(Map<A, B> map) {
    return map == null ? new HashSet() : map.keySet();
  }

  static public Set keySet(Object map) {
    return keys((Map) map);
  }

  static public <A> Set<A> keySet(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public <A, B> Set<A> keySet(MultiMap<A, B> mm) {
    return mm.keySet();
  }

  static public <A, B> int keysSize(MultiMap<A, B> mm) {
    return lKeys(mm);
  }

  static public <A> A reverseGet(List<A> l, int idx) {
    if (l == null || idx < 0)
      return null;
    int n = l(l);
    return idx < n ? l.get(n - 1 - idx) : null;
  }

  static public <A> List<A> syncAddOrCreate(List<A> l, A a) {
    if (l == null)
      l = syncList();
    l.add(a);
    return l;
  }

  static public String linesLL(Object... x) {
    return lines(ll(x));
  }

  static public int ifloor(double d) {
    return (int) Math.floor(d);
  }

  static public IntRange ifloor(DoubleRange r) {
    return r == null ? null : intRange(ifloor(r.start), ifloor(r.end));
  }

  static public String indentx(String s) {
    return indentx(indent_default, s);
  }

  static public String indentx(int n, String s) {
    return dropSuffix(repeat(' ', n), indent(n, s));
  }

  static public String indentx(String indent, String s) {
    return dropSuffix(indent, indent(indent, s));
  }

  static public List<Byte> toByteList(Object o) {
    if (o == null)
      return null;
    if (o instanceof List)
      return ((List) o);
    if (o instanceof Iterable)
      return toList((Iterable) o);
    if (o instanceof byte[])
      return wrapPrimitiveArrayAsImmutableList((byte[]) o);
    throw fail();
  }

  static public String nBytes(long n) {
    return n2(n, "byte");
  }

  static public String nBytes(Collection l) {
    return nBytes(l(l));
  }

  static public String nBytes(byte[] l) {
    return nBytes(l(l));
  }

  static public <A> void methodForEach(IVF1<A> f, Iterable<A> l) {
    forEach(f, l);
  }

  static public <A> void methodForEach(IVF1<A> f, A[] l) {
    forEach(f, l);
  }

  static public File pathToJavaxJar() {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.pathToJavaXJar();
    return pathToJavaxJar_noResourceLoader();
  }

  static public File pathToJavaxJar_noResourceLoader() {
    try {
      int x = latestInstalledJavaX();
      File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar");
      if (!xfile.isFile()) {
        print("Saving " + f2s(xfile));
        String url = x30JarServerURL();
        byte[] data = loadBinaryPage(url);
        if (data.length < 1000000)
          throw fail("Could not load " + url);
        saveBinaryFile(xfile.getPath(), data);
      }
      return xfile;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Method hashMap_findKey_method;

  static public <A, B> A hashMap_findKey(HashMap<A, B> map, Object key) {
    try {
      if (hashMap_findKey_method == null)
        hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode");
      Map.Entry<A, B> entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key);
      return entry == null ? null : entry.getKey();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public java.util.Timer doLater_daemon(long delay, final Object r) {
    final java.util.Timer timer = new java.util.Timer(true);
    timer.schedule(timerTask(r, timer), delay);
    return timer;
  }

  static public java.util.Timer doLater_daemon(double delaySeconds, final Object r) {
    return doLater_daemon(toMS(delaySeconds), r);
  }

  static public int hashCodeFor(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public BufferedImage toBufferedImage(Object o) {
    return toBufferedImageOpt(o);
  }

  static public Boolean grabbableGrayPixels_succeeded;

  static public Throwable grabbableGrayPixels_error;

  static public boolean grabbableGrayPixels_enable = true;

  static public GrabbableGrayPixels grabbableGrayPixels(BufferedImage img) {
    if (img == null || !grabbableGrayPixels_enable)
      return null;
    try {
      var result = grabbableGrayPixels_impl(img);
      grabbableGrayPixels_succeeded = result != null;
      return result;
    } catch (Throwable e) {
      grabbableGrayPixels_error = e;
      grabbableGrayPixels_succeeded = false;
      throw rethrow(e);
    }
  }

  static public GrabbableGrayPixels grabbableGrayPixels_impl(BufferedImage img) {
    Raster raster = img.getRaster();
    SampleModel sampleModel = raster.getSampleModel();
    if (!(sampleModel instanceof PixelInterleavedSampleModel))
      return null;
    DataBufferByte dataBuffer = (DataBufferByte) (raster.getDataBuffer());
    assertEquals(1, dataBuffer.getNumBanks());
    assertEquals(DataBuffer.TYPE_BYTE, dataBuffer.getDataType());
    int w = img.getWidth(), h = img.getHeight();
    int scanlineStride = ((PixelInterleavedSampleModel) sampleModel).getScanlineStride();
    byte[] pixels = dataBuffer.getData();
    int offset = dataBuffer.getOffset();
    int translateX = raster.getSampleModelTranslateX();
    int translateY = raster.getSampleModelTranslateY();
    offset += -translateX - translateY * scanlineStride;
    return new GrabbableGrayPixels(pixels, w, h, offset, scanlineStride);
  }

  static public GrabbableIntPixels grabbableIntPixels_fastOrSlow(BufferedImage image) {
    try {
      try {
        GrabbableIntPixels gp = grabbableIntPixels(image);
        if (gp != null)
          return gp;
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
      int w = image.getWidth(), h = image.getHeight();
      int[] data = new int[w * h];
      PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, w, h, data, 0, w);
      if (!pixelGrabber.grabPixels())
        throw fail("Could not grab pixels");
      return new GrabbableIntPixels(data, w, h, 0, w);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int rgbInt(int r, int g, int b) {
    return (clamp(r, 0, 255) << 16) | (clamp(g, 0, 255) << 8) | clamp(b, 0, 255);
  }

  static public <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
    return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
  }

  static public <A> A second(List<A> l) {
    return get(l, 1);
  }

  static public <A> A second(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    if (!it.hasNext())
      return null;
    it.next();
    return it.hasNext() ? it.next() : null;
  }

  static public <A> A second(A[] bla) {
    return bla == null || bla.length <= 1 ? null : bla[1];
  }

  static public <A, B> B second(Pair<A, B> p) {
    return p == null ? null : p.b;
  }

  static public <A, B, C> B second(T3<A, B, C> t) {
    return t == null ? null : t.b;
  }

  static public <A> A second(Producer<A> p) {
    if (p == null)
      return null;
    if (p.next() == null)
      return null;
    return p.next();
  }

  static public char second(String s) {
    return charAt(s, 1);
  }

  static public <A, B> B second(Either<A, B> e) {
    return e == null ? null : e.bOpt();
  }

  static public int toIntPercent(double ratio) {
    return roundToInt(ratio * 100);
  }

  static public int toIntPercent(float ratio) {
    return toIntPercent((double) ratio);
  }

  static public Object metaGet(IMeta o, Object key) {
    return metaMapGet(o, key);
  }

  static public Object metaGet(Object o, Object key) {
    return metaMapGet(o, key);
  }

  static public void scaffoldCalled(Object obj, Object function, Object... args) {
    printShortenedFunctionCall(100, (obj == null ? "" : obj + " :: ") + function, args);
  }

  static public boolean scaffoldingEnabled(Object o) {
    return metaGet(o, "scaffolding") != null;
  }

  static public ICachedJavaXExpr javaExpr(Object expr) {
    if (expr instanceof ICachedJavaXExpr)
      return ((ICachedJavaXExpr) expr);
    return new LiteralJavaXExpr(expr);
  }

  static public <A> ICachedJavaXExpr<A> javaExpr(Object expr, IF0<A> quickEval) {
    LiteralJavaXExpr<A> e = new LiteralJavaXExpr<>(expr);
    e.quickEval = quickEval;
    return e;
  }

  static public String repSimple(int n, char c) {
    return repeat(c, n);
  }

  static public <A> List<A> repSimple(int n, A a) {
    return repeat(n, a);
  }

  static public <A> void forEach(Iterable<A> l, IVF1<A> f) {
    if (f != null && l != null)
      for (A a : l) callF(f, a);
  }

  static public <A> void forEach(IVF1<A> f, Iterable<A> l) {
    forEach(l, f);
  }

  static public <A> void forEach(A[] l, IVF1<A> f) {
    if (f != null && l != null)
      for (A a : l) callF(f, a);
  }

  static public <A> void forEach(IVF1<A> f, A[] l) {
    forEach(l, f);
  }

  static public <A, B> void forEach(Map<A, B> map, IVF2<A, B> f) {
    for (Map.Entry<? extends A, ? extends B> __0 : _entrySet(map)) {
      A a = __0.getKey();
      B b = __0.getValue();
      f.get(a, b);
    }
  }

  static public void stepAll(Steppable s) {
    if (s != null)
      while (s.step()) {
        ping();
      }
  }

  static public boolean isOneOfSingleChars(String s, char... chars) {
    if (l(s) != 1)
      return false;
    char real = s.charAt(0);
    for (char c : unnullForIteration(chars)) if (real == c)
      return true;
    return false;
  }

  static public int countPred(Iterable c, Object pred) {
    return nfilter(c, pred);
  }

  static public int countPred(Object pred, Iterable c) {
    return nfilter(pred, c);
  }

  static public <A> int countPred(Iterable<A> c, IF1<A, Boolean> pred) {
    return nfilter(c, pred);
  }

  static public <A> A _get(List<A> l, int idx) {
    return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
  }

  static public Object _get(Object o, String field) {
    return get(o, field);
  }

  static public Object _get(String field, Object o) {
    return get(o, field);
  }

  static public <A> A _get(A[] l, int idx) {
    return idx >= 0 && idx < l(l) ? l[idx] : null;
  }

  static public <A> void listSet(List<A> l, int i, A a, A emptyElement) {
    if (i < 0)
      return;
    while (i >= l(l)) l.add(emptyElement);
    l.set(i, a);
  }

  static public <A> void listSet(List<A> l, int i, A a) {
    listSet(l, i, a, null);
  }

  static public void metaSet(IMeta o, Object key, Object value) {
    metaMapPut(o, key, value);
  }

  static public List<Integer> countIteratorToList(int b) {
    return countIteratorToList(0, b);
  }

  static public List<Integer> countIteratorToList(int a, int b) {
    return asList(countIterator(a, b));
  }

  static public <A> List<A> countIteratorToList(int b, IF1<Integer, A> f) {
    return countIteratorToList(0, b, f);
  }

  static public <A> List<A> countIteratorToList(int a, int b, IF1<Integer, A> f) {
    return asList(countIterator(a, b, f));
  }

  static public List<Integer> countIteratorToList(int a, int b, int step) {
    return asList(countIterator(a, b, step));
  }

  static public <A> List<A> countIteratorToList(double a, double b, double step, IF1<Double, A> f) {
    return asList(countIterator(a, b, step, f));
  }

  static public <A> List<Double> countIteratorToList(double a, double b, double step) {
    return asList(countIterator(a, b, step));
  }

  static public <A> List<A> countIteratorToList(IF1<Double, A> f, double a, double b, double step) {
    return asList(countIterator(f, a, b, step));
  }

  static public <A> List<A> countIteratorToList(IF1<Integer, A> f, int b) {
    return countIteratorToList(f, 0, b);
  }

  static public <A> List<A> countIteratorToList(IF1<Integer, A> f, int a, int b) {
    return asList(countIterator(f, a, b));
  }

  static public FunctionCall functionCall_list(Object fname, Iterable args) {
    return new FunctionCall(fname, toObjectArray(args));
  }

  static public List mapQuickEval_javaExpr(Iterable<ICachedJavaXExpr> l) {
    return map(e -> e.quickEval(), l);
  }

  static public <A> void probabilisticForEach(IProbabilisticScheduler scheduler, double pStart, double pEnd, Collection<A> l, IVF1<A> f) {
    if (scheduler == null || f == null)
      return;
    probabilisticForEach(scheduler, pStart, pEnd, iterator(l), 0, l(l), 1.0, f);
  }

  static public <A> void probabilisticForEach(IProbabilisticScheduler scheduler, double pStart, double pEnd, Iterator<A> it, int i, int n, double myProb, IVF1<A> f) {
    assertTrue(pEnd <= pStart);
    if (scheduler == null || f == null || !it.hasNext())
      return;
    A a = it.next();
    double p = blend(pStart, pEnd, doubleRatio(i, n - 1));
    scheduler.at(new Runnable() {

      public void run() {
        try {
          f.get(a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return formatFunctionCall(f, a);
      }
    });
    scheduler.atRelative(doubleRatio(p, myProb), () -> probabilisticForEach(scheduler, pStart, pEnd, it, i + 1, n, p, f));
  }

  static public <A> List<WithSideValue<Integer, A>> indexAsSideValue(List<A> l) {
    List<WithSideValue<Integer, A>> out = emptyList(l);
    int n = l(l);
    for (int i = 0; i < n; i++) out.add(withSideValue(i, l.get(i)));
    return out;
  }

  static public <A> IVF1<A> ivf1WithToString(String toString, IVF1<A> f) {
    return f == null ? null : new IVF1<A>() {

      public void get(A a) {
        f.get(a);
      }

      public String toString() {
        return toString;
      }
    };
  }

  static public String renderVars(Object... params) {
    return renderVars_str(params);
  }

  static public String getLine(String s, int lineNr) {
    return safeGet(toLines(s), lineNr - 1);
  }

  static public JECompressionRegime jeCompressionRegime() {
    return new JECompressionRegime();
  }

  static public int seconds() {
    return seconds(Calendar.getInstance());
  }

  static public int seconds(Calendar c) {
    return c.get(Calendar.SECOND);
  }

  static public String div(Object contents, Object... params) {
    return hfulltag("div", contents, params);
  }

  static public String div() {
    return div("");
  }

  static public BigInteger div(BigInteger a, BigInteger b) {
    return a.divide(b);
  }

  static public BigInteger div(BigInteger a, int b) {
    return a.divide(bigint(b));
  }

  static public Complex div(Complex a, double b) {
    return new Complex(a.re / b, a.im / b);
  }

  static public double div(double a, double b) {
    return a / b;
  }

  static public <A> List<A> minus(Collection<A> a, Object... b) {
    Set set = asSet(b);
    List l = new ArrayList();
    for (Object s : unnull(a)) if (!set.contains(s))
      l.add(s);
    return l;
  }

  static public BigInteger minus(BigInteger a, BigInteger b) {
    return a.subtract(b);
  }

  static public Complex minus(Complex c) {
    return c == null ? null : complex(-c.re(), -c.im());
  }

  static public boolean objectArraysEqual(Object[] a, Object[] b) {
    return arraysEqual(a, b);
  }

  static public int hashAboutObjects(Object... l) {
    int hash = 0, n = l(l);
    for (int i = 0; i < n; i++) hash = boostHashCombine(hash, hashCode(l[i]));
    return hash;
  }

  static public Object[] mapObjectArray(IF1 f, Object[] l) {
    if (empty(l))
      return l;
    int n = l.length;
    Object[] a2 = new Object[n];
    for (int i = 0; i < n; i++) a2[i] = f.get(l[i]);
    return a2;
  }

  static public boolean isNaN(double d) {
    return Double.isNaN(d);
  }

  static public boolean isNaN(float f) {
    return Float.isNaN(f);
  }

  static public double minusInfinity() {
    return negativeInfinity();
  }

  static public <A> Scored<A> scored(A a, float score) {
    return new Scored(a, score);
  }

  static public <A> Scored<A> scored(A a, double score) {
    return new Scored(a, (float) score);
  }

  static public <A> Scored<A> scored(A a, Scored scored) {
    return new Scored(a, getScore(scored));
  }

  static public <A> Scored<A> scored(double score, A a) {
    return scored(a, score);
  }

  static public String formatDouble_significant2(double d, int digits) {
    try {
      digits -= max(0, Math.floor(Math.log10(abs(d)) + 1));
      return formatDouble(d, digits);
    } catch (Throwable _e) {
      print("Had number: " + d + ", digits: " + digits);
      throw rethrow(_e);
    }
  }

  static public String callStringifier(Object stringifier, Object o) {
    return stringifier != null ? str(callF(stringifier, o)) : str(o);
  }

  static public int areaFromPoints(int x1, int y1, int x2, int y2) {
    return (x1 - x1) * (y2 - y1);
  }

  static public Rect toRect_floor(DoubleRect r) {
    if (r == null)
      return null;
    int x = ifloor(r.x), y = ifloor(r.y);
    return new Rect(x, y, ifloor(r.x2()) - x, ifloor(r.y2()) - y);
  }

  static public int fullAlphaMask() {
    return 0xFF000000;
  }

  static public String formatDouble_noLeadingZero(double d, int digits) {
    String s = formatDouble(d, digits);
    if (startsWith(s, "-"))
      return startsWith(s, "-0.") ? "-." + dropFirst(3, s) : s;
    else
      return startsWith(s, "0.") ? dropFirst(s) : s;
  }

  static public int hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
    return clipBufferedImage(src, new Rect(clip));
  }

  static public BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
    if (src == null || r == null)
      return null;
    r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
    if (rectEmpty(r))
      return null;
    return src.getSubimage(r.x, r.y, r.w, r.h);
  }

  static public BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
    return clipBufferedImage(src, new Rect(x, y, w, h));
  }

  static public <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
    return tempSetThreadLocal(tl, a);
  }

  static public <A> AutoCloseable tempSetTL(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
    return tempSetThreadLocalIfNecessary(tl, a);
  }

  static public <A> WithProbability<A> withProbability(double probability, A a) {
    return new WithProbability(probability, a);
  }

  static public <A> List<WithProbability<A>> withProbability(IF1<A, Double> makeProbability, Iterable<A> l) {
    return map(a -> withProbability(makeProbability.get(a), a), l);
  }

  static public void stepMax(int max, Steppable s) {
    if (s == null)
      return;
    while (max-- > 0 && s.step()) {
      ping();
    }
  }

  static public void stepMax(Steppable s, int max) {
    stepMax(max, s);
  }

  static public String nEntries(long n) {
    return n2(n, "entry", "entries");
  }

  static public String nEntries(Collection l) {
    return nEntries(l(l));
  }

  static public String nEntries(Map map) {
    return nEntries(l(map));
  }

  static public Object metaMapGet(IMeta o, Object key) {
    return o == null ? null : o.metaGet(key);
  }

  static public Object metaMapGet(Object o, Object key) {
    if (o instanceof IMeta)
      return metaMapGet(((IMeta) o), key);
    return null;
  }

  static public void metaMapPut(IMeta o, Object key, Object value) {
    {
      if (o != null)
        o.metaPut(key, value);
    }
  }

  static public Map convertObjectMetaToMap(IMeta o) {
    return convertObjectMetaToMap(o, () -> synchroLinkedHashMap());
  }

  static public Map convertObjectMetaToMap(IMeta o, IF0<Map> createEmptyMap) {
    if (o == null)
      return null;
    Object meta = o._getMeta();
    if (meta instanceof Map)
      return ((Map) meta);
    var mutex = tempMetaMutex(o);
    try {
      var actualMutex = mutex.get();
      synchronized (actualMutex) {
        meta = o._getMeta();
        if (meta instanceof Map)
          return ((Map) meta);
        Map map = createEmptyMap.get();
        if (meta != null)
          map.put("previousMeta", meta);
        o._setMeta(map);
        return map;
      }
    } finally {
      _close(mutex);
    }
  }

  static public <A, B> void syncMapPutOrRemove(Map<A, B> map, A key, B value) {
    syncMapPut2(map, key, value);
  }

  static public String toStringWithClassName(Object o) {
    return toStringWithClass(o);
  }

  static public String toString(Object o) {
    return strOrNull(o);
  }

  static public <A> A navigableSet_find(NavigableSet<A> set, A a) {
    if (set == null || a == null)
      return null;
    A b = set.floor(a);
    return b != null && sortedSet_compare(set, a, b) == 0 ? b : null;
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterable<A> c, final F1<A, C> makeInnerIterator) {
    return nestedIterator(iterator(c), makeInnerIterator);
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Collection<A> c, final IF1<A, C> makeInnerIterator) {
    return nestedIterator(iterator(c), makeInnerIterator);
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(Iterator<A> it1, IF1<A, C> makeInnerIterator) {
    return nestedIterator(it1, toF1(makeInnerIterator));
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(final Iterator<A> it1, final F1<A, C> makeInnerIterator) {
    if (it1 == null || !it1.hasNext())
      return emptyIterableIterator();
    return iff(new F0() {

      public A a;

      public Iterator<B> innerIterator;

      {
        nextOuter();
      }

      public void nextOuter() {
        a = it1.next();
        innerIterator = makeInnerIterator.get(a);
      }

      public Object get() {
        while (true) {
          ping();
          if (innerIterator != null && innerIterator.hasNext())
            return innerIterator.next();
          if (!it1.hasNext())
            return endMarker();
          nextOuter();
        }
      }
    });
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Iterator<A> it1) {
    return nestedIterator(it1, makeInnerIterator);
  }

  static public <A, B, C extends Iterator<B>> IterableIterator<B> nestedIterator(IF1<A, C> makeInnerIterator, Collection<A> l) {
    return nestedIterator(l, makeInnerIterator);
  }

  static public <B, A extends Collection<B>> A addAndReturnCollection(A c, B a) {
    if (c != null)
      c.add(a);
    return c;
  }

  static public boolean set_trueIfChanged(Object o, String field, Object value) {
    if (eq(get(o, field), value))
      return false;
    set(o, field, value);
    return true;
  }

  static public <A> boolean set_trueIfChanged(IVar<A> v, A value) {
    return setVar_trueIfChanged(v, value);
  }

  static public boolean has(String a, String b, String c) {
    return false;
  }

  static public boolean has(T3<String, String, String> t) {
    return false;
  }

  static public <A> A lookupInterface(Class<A> intrface, Object o) {
    return lookupDynamicInterface(intrface, o);
  }

  static public <A> A lookupInterface(Object o, Class<A> intrface) {
    return lookupDynamicInterface(o, intrface);
  }

  static public String find(String pattern, String text) {
    Matcher matcher = Pattern.compile(pattern).matcher(text);
    if (matcher.find())
      return matcher.group(1);
    return null;
  }

  static public <A> A find(Collection<A> c, Object... data) {
    for (A x : c) if (checkFields(x, data))
      return x;
    return null;
  }

  static public ChangeListener changeListener(final Object r) {
    return new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(r);
      }
    };
  }

  static public ItemListener itemListener(final Object r) {
    return new ItemListener() {

      public void itemStateChanged(ItemEvent e) {
        pcallF(r);
      }
    };
  }

  static public void onUpdate(JComponent c, final Object r) {
    if (c instanceof JTextComponent)
      ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
          call(r);
        }

        public void removeUpdate(DocumentEvent e) {
          call(r);
        }

        public void changedUpdate(DocumentEvent e) {
          call(r);
        }
      });
    else if (c instanceof ItemSelectable)
      ((ItemSelectable) c).addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
          call(r);
        }
      });
    else
      print("Warning: onUpdate doesn't know " + getClassName(c));
  }

  static public void onUpdate(List<? extends JComponent> l, Object r) {
    for (JComponent c : l) onUpdate(c, r);
  }

  static public boolean isEditableComboBox(final JComboBox cb) {
    return cb != null && swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return cb.isEditable();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret cb.isEditable();";
      }
    });
  }

  static public JTextField textFieldFromComboBox(JComboBox cb) {
    return (JTextField) cb.getEditor().getEditorComponent();
  }

  static public JComboBox onSelectedItem(final JComboBox cb, final VF1<String> f) {
    addActionListener(cb, new Runnable() {

      public void run() {
        try {
          pcallF(f, selectedItem(cb));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(f, selectedItem(cb))";
      }
    });
    return cb;
  }

  static public double sqrt(double x) {
    return Math.sqrt(x);
  }

  static public int sqr(int i) {
    return i * i;
  }

  static public long sqr(long l) {
    return l * l;
  }

  static public double sqr(double d) {
    return d * d;
  }

  static public float sqr(float f) {
    return f * f;
  }

  static public float abs(float f) {
    return Math.abs(f);
  }

  static public int abs(int i) {
    return Math.abs(i);
  }

  static public double abs(double d) {
    return Math.abs(d);
  }

  static public double abs(Complex c) {
    return c.abs();
  }

  static public void printVars_str(Object... params) {
    print(renderVars_str(params));
  }

  static public Pt rectTopLeftCorner(Rect r) {
    return r == null ? null : pt(r.x, r.y);
  }

  static public Rect pointsRect(int x1, int y1, int x2, int y2) {
    return new Rect(x1, y1, x2 - x1, y2 - y1);
  }

  static public void cancelTimers(Collection timers) {
    for (Object timer : timers) cancelTimer(timer);
  }

  static public <A> List<A> getAndClearList(Collection<A> l) {
    if (l == null)
      return emptyList();
    synchronized (collectionMutex(l)) {
      List<A> out = cloneList(l);
      l.clear();
      return out;
    }
  }

  static public String joinNempties(String sep, Object... strings) {
    return joinStrings(sep, strings);
  }

  static public String joinNempties(String sep, Iterable strings) {
    return joinStrings(sep, strings);
  }

  static public String joinNemptiesWithComma(Object... strings) {
    return joinNempties(", ", strings);
  }

  static public String joinNemptiesWithComma(Iterable strings) {
    return joinNempties(", ", strings);
  }

  static public List flattenCollectionsAndArrays(Iterable a) {
    List l = new ArrayList();
    for (Object x : a) if (x instanceof Collection)
      l.addAll(flattenCollectionsAndArrays((Collection) x));
    else if (x instanceof Object[])
      l.addAll(flattenCollectionsAndArrays(asList((Object[]) x)));
    else
      l.add(x);
    return l;
  }

  static public Boolean hasGlobalOption(String option) {
    String question = print(option + "?");
    return askTripleBool(question);
  }

  static public String format(String pat, Object... args) {
    return format3(pat, args);
  }

  static public void assertPointInBounds(int x, int y, int w, int h) {
    if (x < 0)
      throw fail("x < 0", x);
    if (y < 0)
      throw fail("y < 0", y);
    if (x >= w)
      throw fail("x >= w", x, w);
    if (y >= h)
      throw fail("y >= h", y, h);
  }

  static public int widthForHeight(int w, int h, int newHeight) {
    return iround(newHeight * doubleRatio(w, h));
  }

  static public int widthForHeight(double w, double h, int newHeight) {
    return iround(newHeight * doubleRatio(w, h));
  }

  static public <A> Matrix<Matrix<A>> matrixToMNGrid(Matrix<A> m, int cols, int rows) {
    if (m == null)
      return null;
    cols = clamp(cols, 1, m.getWidth());
    rows = clamp(rows, 1, m.getHeight());
    List<List<Rect>> rects = gridOfRects3(m.getWidth(), m.getHeight(), cols, rows);
    List<List<Matrix<A>>> matrices = mapLevelTwo(r -> new SubMatrix(m, r), rects);
    return listOfListsToMatrix(matrices);
  }

  static public boolean isListOfElementType(Object o, Class type) {
    if (!(o instanceof List))
      return false;
    return allElementsAreOfType((List) o, type);
  }

  static public boolean isListOfElementType(Class type, Object o) {
    return isListOfElementType(o, type);
  }

  static public List<Integer> lInts(String hex) {
    return byteArrayToIntList_littleEndian(hexToBytes_dropSpaces(hex));
  }

  static public String naiveQuote(String s) {
    return simpleQuote(s);
  }

  static public String intsToHex_withLineBreaks(List<Integer> l) {
    return intsToHex_withLineBreaks(80, l);
  }

  static public String intsToHex_withLineBreaks(int charsPerLine, List<Integer> l) {
    return regularLineBreaks(charsPerLine, intsToHex(l));
  }

  static public Object toJavaOpt(Object o) {
    return new ToJava().getOpt(o);
  }

  static public <A, B> List<B> lambdaMethodMap(IF1<A, B> f, Iterable<A> l) {
    return map(f, l);
  }

  static public <A, B> List<B> lambdaMethodMap(IF1<A, B> f, A[] l) {
    return map(f, l);
  }

  static public void rangeCheck(int i, int n) {
    if (i < 0 || i >= n)
      throw fail("Range check fail: " + i + "/" + n);
  }

  static public void rangeCheck(long i, long n) {
    if (i < 0 || i >= n)
      throw fail("Range check fail: " + i + "/" + n);
  }

  static public <A, B> List<B> mapWithIndex(List<A> l, IF2<Integer, A, B> f) {
    List<B> out = emptyList(l);
    for (int i = 0; i < l(l); i++) out.add(f.get(i, l.get(i)));
    return out;
  }

  static public <A> Matrix<A> listToMatrix(int w, List<A> data) {
    int n = l(data);
    int h = n / w;
    if (w * h != n)
      throw fail("Bad size", "n", n, "w", w, "h", h);
    return new ListToMatrix(w, h, data);
  }

  static public <A> A cyclicGet(List<A> l, int i) {
    return empty(l) ? null : get(l, mod(i, l(l)));
  }

  static public <A> Matrix<A> listToMatrix_cols(int w, List<A> data) {
    return listToMatrix(w, data);
  }

  static public List<Integer> partialSums_firstIs0(List<Integer> l) {
    int n = l(l);
    IntBuffer out = new IntBuffer(n);
    int sum = 0;
    for (int i = 0; i < n; i++) {
      out.add(sum);
      sum += l.get(i);
    }
    out.add(sum);
    return out.asVirtualList();
  }

  static public <A> void forEachWithPosition(Matrix<A> m, IVF3<Integer, Integer, A> f) {
    if (m == null || f == null)
      return;
    int w = m.getWidth(), h = m.getHeight();
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) f.get(x, y, m.get(x, y));
  }

  static public void drawIntMatrix(BufferedImage g, Matrix<Integer> m, int x, int y) {
    drawIntMatrix(graphics(g), m, x, y);
  }

  static public void drawIntMatrix(Graphics2D g, Matrix<Integer> m, int x, int y) {
    if (g == null || m == null)
      return;
    drawImage(g, matrixToImage(m), x, y);
  }

  static public Number parseIntOrLong(String s) {
    long l = parseLong(s);
    return longIsInt(l) ? (Number) (int) l : (Number) l;
  }

  static public boolean isLongConstant(String s) {
    if (!s.endsWith("L"))
      return false;
    s = s.substring(0, l(s) - 1);
    return isInteger(s);
  }

  static public Object getMC(String field) {
    return get(mc(), field);
  }

  static public RuntimeException quickFail() {
    throw new QuickException("fail");
  }

  static public RuntimeException quickFail(Throwable e) {
    throw asQuickException(e);
  }

  static public RuntimeException quickFail(Object msg) {
    throw new QuickException(String.valueOf(msg));
  }

  static public RuntimeException quickFail(String msg) {
    throw new QuickException(unnull(msg));
  }

  static public RuntimeException quickFail(String msg, Throwable innerException) {
    throw new QuickException(msg, innerException);
  }

  static public int imageMergeSpacing = 5;

  static public int imageMergeSpacing() {
    return imageMergeSpacing;
  }

  static public void imageMergeSpacing(int pixels) {
    imageMergeSpacing = pixels;
  }

  static public List mapMethod(Object[] l, final String methodName) {
    return map(l, new F1<Object, Object>() {

      public Object get(Object o) {
        try {
          return callOpt(o, methodName);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callOpt(o, methodName)";
      }
    });
  }

  static public List mapMethod(Iterable c, final String methodName) {
    return map(c, new F1<Object, Object>() {

      public Object get(Object o) {
        try {
          return callOpt(o, methodName);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callOpt(o, methodName)";
      }
    });
  }

  static public List mapMethod(String methodName, Iterable c) {
    return mapMethod(c, methodName);
  }

  static public List mapMethod(String methodName, Enumeration c) {
    return mapMethod(methodName, enumerationToIterator(c));
  }

  static public int intMax(Collection c, String field) {
    int max = Integer.MIN_VALUE;
    for (Object o : c) max = Math.max(max, toInt(getOpt(o, field)));
    return max;
  }

  static public int intMax(Iterable<Integer> l) {
    int max = Integer.MIN_VALUE;
    for (int i : unnullForIteration(l)) max = Math.max(max, i);
    return max;
  }

  static public int intMax(int... l) {
    int max = Integer.MIN_VALUE;
    if (l != null)
      for (int i : l) max = Math.max(max, i);
    return max;
  }

  static public void copyBufferedImage(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) {
    copyImagePart(src, srcx, srcy, dest, destx, desty, w, h);
  }

  static public void copyBufferedImage(BufferedImage src, BufferedImage dest, int destx, int desty) {
    if (src != null)
      copyBufferedImage(src, 0, 0, dest, destx, desty, src.getWidth(), src.getHeight());
  }

  static public BufferedImage intMatrixToBufferedImage(Matrix<Integer> m) {
    if (m == null)
      return null;
    int w = m.getWidth(), h = m.getHeight();
    int[] pixels = matrixToIntArray(m);
    return newBufferedImage(w, h, pixels);
  }

  static public Map<Class, Set<String>> allFields_cache = weakHashMap();

  static public Set<String> allFields(Object o) {
    if (o == null)
      return emptySet();
    Class _c = _getClass(o);
    Set<String> fields = allFields_cache.get(_c);
    if (fields == null)
      allFields_cache.put(_c, fields = asTreeSet(keys(getOpt_getFieldMap(o))));
    return fields;
  }

  static public int stdHash(Object a, String... fields) {
    if (a == null)
      return 0;
    int hash = getClassName(a).hashCode();
    for (String field : fields) hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
    return hash;
  }

  static public Object getOptMC(String field) {
    return getOpt(mc(), field);
  }

  static public <A> List<A> addDyn(List<A> l, A a) {
    if (l == null)
      l = new ArrayList();
    l.add(a);
    return l;
  }

  static public double toMinutes(long ms) {
    return ms / 60000.0;
  }

  static public void dm_inQ(Runnable r) {
    dm_q().add(r);
  }

  static public void dm_inQ(DynModule mod, Runnable r) {
    dm_q(mod, r);
  }

  static public <A> A dm_evalInQ(F0<A> f) {
    return dm_evalInQ(dm_current_mandatory(), f);
  }

  static public <A> A dm_evalInQ(IF0<A> f) {
    return dm_evalInQ(dm_current_mandatory(), if0ToF0(f));
  }

  static public <A> A dm_evalInQ(DynModule module, F0<A> f) {
    return evalInQ(module.q(), f);
  }

  static public BigInteger bigint(String s) {
    return new BigInteger(s);
  }

  static public BigInteger bigint(long l) {
    return BigInteger.valueOf(l);
  }

  static public <A, B> int lKeys(MultiMap<A, B> mm) {
    return mm == null ? 0 : mm.keysSize();
  }

  static public <A> List<A> syncList() {
    return synchroList();
  }

  static public <A> List<A> syncList(List<A> l) {
    return synchroList(l);
  }

  static public IntRange intRange(int start, int end) {
    return new IntRange(start, end);
  }

  static public int indent_default = 2;

  static public String indent(int indent) {
    return repeat(' ', indent);
  }

  static public String indent(int indent, String s) {
    return indent(repeat(' ', indent), s);
  }

  static public String indent(String indent, String s) {
    return indent + s.replace("\n", "\n" + indent);
  }

  static public String indent(String s) {
    return indent(indent_default, s);
  }

  static public List<String> indent(String indent, List<String> lines) {
    List<String> l = new ArrayList();
    if (lines != null)
      for (String s : lines) l.add(indent + s);
    return l;
  }

  static public List wrapPrimitiveArrayAsImmutableList(Object array) {
    int n = Array.getLength(array);
    return new RandomAccessAbstractList() {

      public int size() {
        return n;
      }

      public Object get(int i) {
        return Array.get(array, i);
      }
    };
  }

  static public int latestInstalledJavaX() {
    File[] files = new File(userHome(), ".javax").listFiles();
    int v = 0;
    if (files != null)
      for (File f : files) {
        Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName());
        if (m.matches())
          v = Math.max(v, Integer.parseInt(m.group(1)));
      }
    return v;
  }

  static public String x30JarServerURL() {
    return "http://botcompany.de:8081/x30.jar";
  }

  static public Method findMethodNamed(Object obj, String method) {
    if (obj == null)
      return null;
    if (obj instanceof Class)
      return findMethodNamed((Class) obj, method);
    return findMethodNamed(obj.getClass(), method);
  }

  static public Method findMethodNamed(Class c, String method) {
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
        makeAccessible(m);
        return m;
      }
      c = c.getSuperclass();
    }
    return null;
  }

  static public int hashMap_internalHash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }

  static public BufferedImage toBufferedImageOpt(Object o) {
    if (o instanceof BufferedImage)
      return ((BufferedImage) o);
    if (o instanceof Image)
      return copyImage((Image) o);
    if (o instanceof MakesBufferedImage)
      return ((MakesBufferedImage) o).getBufferedImage();
    if (o instanceof File)
      if (isImageFile((File) o))
        return loadBufferedImageFile((File) o);
    String c = getClassName(o);
    if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
      return (BufferedImage) call(o, "getBufferedImage");
    if (eq(c, "main$PNGFile"))
      return (BufferedImage) call(o, "getImage");
    return null;
  }

  static public <A> A assertEquals(Object x, A y) {
    return assertEquals("", x, y);
  }

  static public <A> A assertEquals(String msg, Object x, A y) {
    if (assertVerbose())
      return assertEqualsVerbose(msg, x, y);
    if (!(x == null ? y == null : x.equals(y)))
      throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
    return y;
  }

  static public Boolean grabbableIntPixels_succeeded;

  static public boolean grabbableIntPixels_enable = true;

  static public GrabbableIntPixels grabbableIntPixels(BufferedImage img) {
    if (img == null || !grabbableIntPixels_enable)
      return null;
    try {
      var result = grabbableIntPixels_impl(img);
      grabbableIntPixels_succeeded = result != null;
      return result;
    } catch (Throwable _e) {
      grabbableIntPixels_succeeded = false;
      throw rethrow(_e);
    }
  }

  static public GrabbableIntPixels grabbableIntPixels_impl(BufferedImage img) {
    Raster raster = img.getRaster();
    SampleModel _sampleModel = raster.getSampleModel();
    if (!(_sampleModel instanceof SinglePixelPackedSampleModel))
      return null;
    SinglePixelPackedSampleModel sampleModel = (SinglePixelPackedSampleModel) _sampleModel;
    DataBufferInt dataBuffer = (DataBufferInt) (raster.getDataBuffer());
    assertEquals(1, dataBuffer.getNumBanks());
    assertEquals(DataBuffer.TYPE_INT, dataBuffer.getDataType());
    int w = img.getWidth(), h = img.getHeight();
    int scanlineStride = sampleModel.getScanlineStride();
    int[] pixels = dataBuffer.getData();
    int offset = dataBuffer.getOffset();
    int translateX = raster.getSampleModelTranslateX();
    int translateY = raster.getSampleModelTranslateY();
    offset += -translateX - translateY * scanlineStride;
    return new GrabbableIntPixels(pixels, w, h, offset, scanlineStride);
  }

  static public char charAt(String s, int i) {
    return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
  }

  static public void printShortenedFunctionCall(Object fname, Object... args) {
    printShortenedFunctionCall(100, fname, args);
  }

  static public void printShortenedFunctionCall(int len, Object fname, Object... args) {
    print(shorten(len, formatFunctionCall(fname, args)));
  }

  static public <A> int nfilter(Iterable<A> c, IF1<A, Boolean> pred) {
    return nfilter(pred, c);
  }

  static public <A> int nfilter(IF1<A, Boolean> pred, Iterable<A> c) {
    int n = 0;
    if (c != null)
      for (A o : c) if (pred.get(o))
        ++n;
    return n;
  }

  static public int nfilter(Iterable c, Object pred) {
    int n = 0;
    if (c != null)
      for (Object o : c) if (isTrue(callF(pred, o)))
        ++n;
    return n;
  }

  static public int nfilter(Object pred, Iterable c) {
    return nfilter(c, pred);
  }

  static public IterableIterator<Integer> countIterator(int b) {
    return countIterator(0, b);
  }

  static public IterableIterator<Integer> countIterator(int a, int b) {
    return countIterator_exclusive(a, b);
  }

  static public <A> IterableIterator<A> countIterator(int b, IF1<Integer, A> f) {
    return countIterator(0, b, f);
  }

  static public <A> IterableIterator<A> countIterator(int a, int b, IF1<Integer, A> f) {
    return countIterator_exclusive(a, b, f);
  }

  static public IterableIterator<Integer> countIterator(int a, int b, int step) {
    return countIterator_exclusive_step(a, b, step);
  }

  static public <A> IterableIterator<A> countIterator(double a, double b, double step, IF1<Double, A> f) {
    return countIterator_exclusive_step(a, b, step, f);
  }

  static public <A> IterableIterator<Double> countIterator(double a, double b, double step) {
    return countIterator_exclusive_step(a, b, step);
  }

  static public <A> IterableIterator<A> countIterator(IF1<Double, A> f, double a, double b, double step) {
    return countIterator(a, b, step, f);
  }

  static public <A> IterableIterator<A> countIterator(IF1<Integer, A> f, int b) {
    return countIterator(f, 0, b);
  }

  static public <A> IterableIterator<A> countIterator(IF1<Integer, A> f, int a, int b) {
    return countIterator_exclusive(a, b, f);
  }

  static public int blend(int x, int y, double yish) {
    double xish = 1 - yish;
    return (int) (x * xish + y * yish);
  }

  static public double blend(double x, double y, double yish) {
    double xish = 1 - yish;
    return x * xish + y * yish;
  }

  static public String formatFunctionCall(String fname, Object... args) {
    return formatFunctionCall((Object) fname, args);
  }

  static public String formatFunctionCall(Object fname, Object... args) {
    return fname + "(" + joinWithComma(allToString(args)) + ")";
  }

  static public String formatFunctionCall(String fname, Iterable args) {
    return formatFunctionCall((Object) fname, args);
  }

  static public String formatFunctionCall(Object fname, Iterable args) {
    return formatFunctionCall(fname, toObjectArray(args));
  }

  static public <A, B> WithSideValue<A, B> withSideValue(A sideValue, B value) {
    return new WithSideValue(sideValue, value);
  }

  static public String renderVars_str(Object... params) {
    List<String> l = new ArrayList();
    int i = 0;
    if (odd(l(params))) {
      l.add(strOrNull(first(params)));
      ++i;
    }
    for (; i + 1 < l(params); i += 2) l.add(params[i] + "=" + params[i + 1]);
    return trim(joinWithComma(l));
  }

  static public <A> A safeGet(List<A> l, int i) {
    return i >= 0 && i < l(l) ? l.get(i) : null;
  }

  static public String hfulltag(String tag) {
    return hfulltag(tag, "");
  }

  static public String hfulltag(String tag, Object contents, Object... params) {
    return hopeningTag(tag, params) + str(contents) + "</" + tag + ">";
  }

  static public Complex complex(double re, double im) {
    return new Complex(re, im);
  }

  static public Complex complex(double re) {
    return new Complex(re, 0.0);
  }

  static public Complex complex(double[] reIm) {
    if (empty(reIm))
      return null;
    if (l(reIm) != 2)
      throw fail("Need 2 doubles to make complex number");
    return complex(reIm[0], reIm[1]);
  }

  static public boolean arraysEqual(Object[] a, Object[] b) {
    if (a.length != b.length)
      return false;
    for (int i = 0; i < a.length; i++) if (neq(a[i], b[i]))
      return false;
    return true;
  }

  static public double negativeInfinity() {
    return Double.NEGATIVE_INFINITY;
  }

  static public <A> float getScore(Scored<A> s) {
    return s == null ? 0 : s.score;
  }

  static public Rect intersectRects(Rect a, Rect b) {
    int x = max(a.x, b.x), y = max(a.y, b.y);
    int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h);
    return new Rect(x, y, x2 - x, y2 - y);
  }

  static public Rect intersectRects(Rect a, int x1, int y1, int w, int h) {
    if (a == null || a.x >= x1 && a.y >= y1 && a.x2() < x1 + w && a.y2() < y1 + h)
      return a;
    return rectFromPoints(max(a.x, x1), max(a.y, y1), min(a.x2(), x1 + w), min(a.y2(), y1 + h));
  }

  static public boolean rectEmpty(Rect r) {
    return r == null || r.w <= 0 || r.h <= 0;
  }

  static public <A> AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal<A> tl, A a) {
    if (tl == null)
      return null;
    A prev = tl.get();
    if (eq(prev, a))
      return null;
    tl.set(a);
    return new AutoCloseable() {

      public String toString() {
        return "tl.set(prev);";
      }

      public void close() throws Exception {
        tl.set(prev);
      }
    };
  }

  static public <A> AutoCloseable tempSetThreadLocalIfNecessary(x30_pkg.x30_util.BetterThreadLocal<A> tl, A a) {
    if (tl == null)
      return null;
    A prev = tl.get();
    if (eq(prev, a))
      return null;
    tl.set(a);
    return new AutoCloseable() {

      public String toString() {
        return "tl.set(prev);";
      }

      public void close() throws Exception {
        tl.set(prev);
      }
    };
  }

  static public Map synchroLinkedHashMap() {
    return synchronizedMap(new LinkedHashMap());
  }

  static public IAutoCloseableF0 tempMetaMutex(IMeta o) {
    return o == null ? null : o._tempMetaMutex();
  }

  static public <A, B> void syncMapPut2(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      synchronized (collectionMutex(map)) {
        if (value != null)
          map.put(key, value);
        else
          map.remove(key);
      }
  }

  static public String toStringWithClass(Object o) {
    return o == null ? null : className(o) + " - " + o;
  }

  static public <A> int sortedSet_compare(SortedSet<A> set, A a, A b) {
    return compareWithComparator(set.comparator(), a, b);
  }

  static public F1 toF1(final Object f) {
    return functionToF1(f);
  }

  static public IterableIterator emptyIterableIterator_instance = new IterableIterator() {

    public Object next() {
      throw fail();
    }

    public boolean hasNext() {
      return false;
    }
  };

  static public <A> IterableIterator<A> emptyIterableIterator() {
    return emptyIterableIterator_instance;
  }

  static public <A> IterableIterator<A> iff(Object f) {
    return iteratorFromFunction_withEndMarker(f);
  }

  static public IterableIterator iff(F0 f) {
    return iteratorFromFunction_withEndMarker(f);
  }

  static public <A> IterableIterator iff(IF0 f) {
    return iteratorFromFunction_withEndMarker(f);
  }

  static public Object endMarker() {
    return iteratorFromFunction_endMarker;
  }

  static public <A> boolean setVar_trueIfChanged(IVar<A> v, A value) {
    if (v == null)
      return false;
    synchronized (v) {
      if (eq(v.get(), value))
        return false;
      v.set(value);
      return true;
    }
  }

  static public <A> A lookupDynamicInterface(Class<A> intrface, Object o) {
    if (o instanceof DynamicObject) {
      A a = (A) (mapGet((Map) ((DynamicObject) o).fieldValues, intrface));
      if (a != null)
        return a;
    }
    if (isInstance(intrface, o))
      return (A) o;
    return null;
  }

  static public <A> A lookupDynamicInterface(Object o, Class<A> intrface) {
    return lookupDynamicInterface(intrface, o);
  }

  static public boolean checkFields(Object x, Object... data) {
    for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1]))
      return false;
    return true;
  }

  static public Object iteratorFromFunction_endMarker = new Object();

  static public <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final Object f) {
    class IFF extends IterableIterator<A> {

      public A a;

      public boolean have, done;

      public boolean hasNext() {
        getNext();
        return !done;
      }

      public A next() {
        getNext();
        if (done)
          throw fail();
        A _a = a;
        a = null;
        have = false;
        return _a;
      }

      public void getNext() {
        if (done || have)
          return;
        Object o = callF(f);
        if (o == iteratorFromFunction_endMarker) {
          done = true;
          return;
        }
        a = (A) o;
        have = true;
      }
    }
    ;
    return new IFF();
  }

  static public <A> IterableIterator<A> iteratorFromFunction_withEndMarker(final F0 f) {
    return iteratorFromFunction_withEndMarker_f0(f);
  }

  static public String selectedItem(JList l) {
    return getSelectedItem(l);
  }

  static public String selectedItem(JComboBox cb) {
    return getSelectedItem(cb);
  }

  static public String joinStrings(String sep, Object... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  static public String joinStrings(String sep, Iterable strings) {
    StringBuilder buf = new StringBuilder();
    for (Object o : unnull(strings)) {
      String s = strOrNull(o);
      if (nempty(s)) {
        if (nempty(buf))
          buf.append(sep);
        buf.append(s);
      }
    }
    return str(buf);
  }

  static public Boolean askTripleBool(String q) {
    print(q + " no idea");
    return null;
  }

  static public List<List<Rect>> gridOfRects3(int w, int h, int cols, int rows) {
    return gridOfRects3(new Rect(0, 0, w, h), cols, rows);
  }

  static public List<List<Rect>> gridOfRects3(Rect r, int cols, int rows) {
    List<List<Rect>> l = new ArrayList();
    for (int row = 0; row < rows; row++) {
      List<Rect> line = new ArrayList();
      int y1 = r.y + iround(r.h * (double) row / rows);
      int y2 = r.y + iround(r.h * (double) (row + 1) / rows);
      for (int col = 0; col < cols; col++) {
        int x1 = r.x + iround(r.w * (double) col / cols);
        int x2 = r.x + iround(r.w * (double) (col + 1) / cols);
        line.add(new Rect(x1, y1, x2 - x1, y2 - y1));
      }
      l.add(line);
    }
    return l;
  }

  static public <A, B> List<List<B>> mapLevelTwo(IF1<A, B> f, Iterable<List<A>> l) {
    return mapTwoLevelsDown(f, l);
  }

  static public <A> Matrix<A> listOfListsToMatrix(List<List<A>> data) {
    if (data == null)
      return null;
    int _h = l(data);
    if (_h == 0)
      return null;
    int _w = l(data.get(0));
    class ListsToMatrix extends AbstractMatrix<A> {

      public ListsToMatrix() {
        super(_w, _h);
      }

      public A get(int x, int y) {
        return data.get(y).get(x);
      }

      public void set(int x, int y, A a) {
        data.get(y).set(x, a);
      }
    }
    ;
    return new ListsToMatrix();
  }

  static public boolean allElementsAreOfType(Collection c, Class type) {
    for (Object o : c) if (!isInstanceX(type, o))
      return false;
    return true;
  }

  static public List<Integer> byteArrayToIntList_littleEndian(byte[] a) {
    if (a == null)
      return null;
    int n = (a.length + 3) / 4;
    return new RandomAccessAbstractList<Integer>() {

      public int size() {
        return n;
      }

      public Integer get(int i) {
        return intFromBytes_littleEndian_partial(a, i * 4);
      }

      public Integer set(int i, Integer val) {
        Integer old = get(i);
        if ((int) old != (int) val)
          intToBytes_inArray_littleEndian_partial(val, a, i * 4);
        return old;
      }
    };
  }

  static public byte[] hexToBytes_dropSpaces(String s) {
    return hexToBytes(dropSpaceEtc(s));
  }

  static public String simpleQuote(String s) {
    return s == null ? "null" : "\"" + s + "\"";
  }

  static public String regularLineBreaks(int charsPerLine, String s) {
    if (l(s) < charsPerLine)
      return s;
    StringBuilder buf = new StringBuilder();
    int n = l(s), j = 0;
    for (int i = 0; i < n; i++) {
      buf.append(s.charAt(i));
      if (++j >= charsPerLine) {
        buf.append('\n');
        j = 0;
      }
    }
    return str(buf);
  }

  static public String intsToHex(List<Integer> l) {
    if (l == null)
      return null;
    return bytesToHex(intListToByteArray(l));
  }

  static public int mod(int n, int m) {
    return (n % m + m) % m;
  }

  static public long mod(long n, long m) {
    return (n % m + m) % m;
  }

  static public BigInteger mod(BigInteger n, int m) {
    return n.mod(bigint(m));
  }

  static public double mod(double n, double m) {
    return (n % m + m) % m;
  }

  static public BufferedImage drawImage(BufferedImage canvas, Image img, Pt p) {
    return drawImageOnImage(img, canvas, p.x, p.y);
  }

  static public void drawImage(BufferedImage g, Image img) {
    drawImage(graphics(g), img);
  }

  static public void drawImage(Graphics2D g, Image img) {
    drawImage(g, img, 0, 0);
  }

  static public void drawImage(Graphics2D g, Image img, Pt p) {
    drawImage(g, img, p.x, p.y);
  }

  static public void drawImage(Graphics2D g, Image img, int x, int y) {
    {
      if (g != null)
        g.drawImage(img, x, y, null);
    }
  }

  static public BufferedImage matrixToImage(Matrix<Integer> m) {
    return intMatrixToBufferedImage(m);
  }

  static public boolean longIsInt(long l) {
    return l == (int) l;
  }

  static public RuntimeException asQuickException(Throwable t) {
    return t instanceof RuntimeException ? (RuntimeException) t : new QuickException(t);
  }

  static public <A> IterableIterator<A> enumerationToIterator(final Enumeration<A> e) {
    return e == null ? null : new IterableIterator() {

      public boolean hasNext() {
        return e.hasMoreElements();
      }

      public A next() {
        return e.nextElement();
      }
    };
  }

  static public void copyImagePart(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) {
    Graphics2D g = dest.createGraphics();
    BufferedImage sub = src.getSubimage(srcx, srcy, w, h);
    g.drawImage(sub, destx, desty, null);
    g.dispose();
  }

  static public int[] matrixToIntArray(Matrix<Integer> m) {
    int w = m.getWidth(), h = m.getHeight(), n = w * h;
    int[] a = new int[n];
    int i = 0;
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) a[i++] = m.get(x, y);
    return a;
  }

  static public Set emptySet() {
    return new HashSet();
  }

  static public <A> TreeSet<A> asTreeSet(Collection<A> set) {
    return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
  }

  static public class getOpt_Map extends WeakHashMap {

    public getOpt_Map() {
      if (getOpt_special == null)
        getOpt_special = new HashMap();
      clear();
    }

    public void clear() {
      super.clear();
      put(Class.class, getOpt_special);
      put(String.class, getOpt_special);
    }
  }

  static final public Map<Class, HashMap<String, Field>> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));

  static public HashMap getOpt_special;

  static public Map<String, Field> getOpt_getFieldMap(Object o) {
    Class c = _getClass(o);
    HashMap<String, Field> map = getOpt_cache.get(c);
    if (map == null)
      map = getOpt_makeCache(c);
    return map;
  }

  static public Object getOpt_cached(Object o, String field) {
    try {
      if (o == null)
        return null;
      Map<String, Field> map = getOpt_getFieldMap(o);
      if (map == getOpt_special) {
        if (o instanceof Class)
          return getOpt((Class) o, field);
        if (o instanceof Map)
          return ((Map) o).get(field);
      }
      Field f = map.get(field);
      if (f != null)
        return f.get(o);
      if (o instanceof DynamicObject)
        return syncMapGet2(((DynamicObject) o).fieldValues, field);
      return null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Field> getOpt_makeCache(Class c) {
    HashMap<String, Field> map;
    if (isSubtypeOf(c, Map.class))
      map = getOpt_special;
    else {
      map = new HashMap();
      if (!reflection_classesNotToScan().contains(c.getName())) {
        Class _c = c;
        do {
          for (Field f : _c.getDeclaredFields()) {
            makeAccessible(f);
            String name = f.getName();
            if (!map.containsKey(name))
              map.put(name, f);
          }
          _c = _c.getSuperclass();
        } while (_c != null);
      }
    }
    if (getOpt_cache != null)
      getOpt_cache.put(c, map);
    return map;
  }

  static public <A> A evalInQ(Q q, final F0<A> f) {
    if (isInQ(q))
      return callF(f);
    final Var<Either<A, Throwable>> var = new Var();
    q.add(new Runnable() {

      public void run() {
        try {
          try {
            var.set(eitherA(callF(f)));
          } catch (Throwable e) {
            var.set(eitherB(e));
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "try {\r\n      var.set(eitherA(callF(f)));\r\n    } catch (Throwable e) {\r\n      ...";
      }
    });
    return returnOrThrow_either(waitForVarToBeNotNull(var));
  }

  static public BufferedImage copyImage(Image img) {
    if (img == null)
      return null;
    if (img instanceof BufferedImage)
      return copyImage((BufferedImage) img);
    int w = img.getWidth(null), h = img.getHeight(null);
    BufferedImage bi = newBufferedImage(w, h);
    drawImage(bi, img);
    return bi;
  }

  static public BufferedImage copyImage(BufferedImage bi) {
    if (bi == null)
      return null;
    ColorModel cm = bi.getColorModel();
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
    return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
  }

  static public boolean isImageFile(File f) {
    return isImageFileName(fileName(f));
  }

  static public ThreadLocal<Boolean> assertVerbose_value = new ThreadLocal();

  static public void assertVerbose(boolean b) {
    assertVerbose_value.set(b);
  }

  static public boolean assertVerbose() {
    return isTrue(assertVerbose_value.get());
  }

  static public <A> A assertEqualsVerbose(Object x, A y) {
    assertEqualsVerbose((String) null, x, y);
    return y;
  }

  static public <A> A assertEqualsVerbose(String msg, Object x, A y) {
    if (!eq(x, y)) {
      throw fail((nempty(msg) ? msg + ": " : "") + "expected: " + x + ", got: " + y);
    } else
      print("OK" + (empty(msg) ? "" : " " + msg) + ": " + (x));
    return y;
  }

  static public IterableIterator<Integer> countIterator_exclusive(int b) {
    return countIterator_exclusive(0, b);
  }

  static public IterableIterator<Integer> countIterator_exclusive(int a, int b) {
    return new IterableIterator<Integer>() {

      public int i = a;

      public boolean hasNext() {
        return i < b;
      }

      public Integer next() {
        return i++;
      }
    };
  }

  static public <A> IterableIterator<A> countIterator_exclusive(int b, IF1<Integer, A> f) {
    return countIterator_exclusive(0, b, f);
  }

  static public <A> IterableIterator<A> countIterator_exclusive(int a, int b, IF1<Integer, A> f) {
    return mapI_if1(f, countIterator_exclusive(a, b));
  }

  static public IterableIterator<Integer> countIterator_exclusive_step(final int a, final int b, final int step) {
    assertTrue("step > 0", step > 0);
    return new IterableIterator<Integer>() {

      public int i = a;

      public boolean hasNext() {
        return i < b;
      }

      public Integer next() {
        var j = i;
        i += step;
        return j;
      }
    };
  }

  static public IterableIterator<Double> countIterator_exclusive_step(double a, double b, double step) {
    assertTrue("step > 0", step > 0);
    return new IterableIterator<Double>() {

      public double i = a;

      public boolean hasNext() {
        return i < b;
      }

      public Double next() {
        var j = i;
        i += step;
        return j;
      }
    };
  }

  static public <A> IterableIterator<A> countIterator_exclusive_step(double a, double b, double step, IF1<Double, A> f) {
    return mapI_if1(f, countIterator_exclusive_step(a, b, step));
  }

  static public String hopeningTag(String tag, Map params) {
    return hopeningTag(tag, mapToParams(params));
  }

  static public String hopeningTag(String tag, Object... params) {
    StringBuilder buf = new StringBuilder();
    buf.append("<" + tag);
    params = unrollParams(params);
    for (int i = 0; i < l(params); i += 2) {
      String name = (String) get(params, i);
      Object val = get(params, i + 1);
      if (nempty(name) && val != null) {
        if (eqOneOf(val, html_valueLessParam(), true))
          buf.append(" " + name);
        else {
          String s = str(val);
          if (!empty(s))
            buf.append(" " + name + "=" + htmlQuote(s));
        }
      }
    }
    buf.append(">");
    return str(buf);
  }

  static public <A> int compareWithComparator(Comparator<A> comparator, A a, A b) {
    return comparator == null ? cmp(a, b) : comparator.compare(a, b);
  }

  static public F1 functionToF1(final Object f) {
    if (isString(f))
      return mainFunctionToF1((String) f);
    if (f instanceof F1)
      return (F1) f;
    return new F1<Object, Object>() {

      public Object get(Object a) {
        try {
          return callF(f, a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret callF(f, a);";
      }
    };
  }

  static public <A> IterableIterator<A> iteratorFromFunction_withEndMarker_f0(final F0<A> f) {
    class IFF2 extends IterableIterator<A> {

      public A a;

      public boolean have, done;

      public boolean hasNext() {
        getNext();
        return !done;
      }

      public A next() {
        getNext();
        if (done)
          throw fail();
        A _a = a;
        a = null;
        have = false;
        return _a;
      }

      public void getNext() {
        if (done || have)
          return;
        Object o = f.get();
        if (o == iteratorFromFunction_endMarker) {
          done = true;
          return;
        }
        a = (A) o;
        have = true;
      }
    }
    ;
    return new IFF2();
  }

  static public <A, B> List<List<B>> mapTwoLevelsDown(F1<A, B> f, Iterable<List<A>> l) {
    List<List<B>> out = new ArrayList();
    if (l != null)
      for (List<A> x : l) out.add(map(f, x));
    return out;
  }

  static public <A, B> List<List<B>> mapTwoLevelsDown(IF1<A, B> f, Iterable<List<A>> l) {
    List<List<B>> out = new ArrayList();
    if (l != null)
      for (List<A> x : l) out.add(map(f, x));
    return out;
  }

  static public int intFromBytes_littleEndian_partial(byte[] a, int i) {
    return (ubyteToInt(i + 3 >= a.length ? 0 : a[i + 3]) << 24 | (ubyteToInt(i + 2 >= a.length ? 0 : a[i + 2]) << 16 | (ubyteToInt(i + 1 >= a.length ? 0 : a[i + 1]) << 8 | ubyteToInt(a[i]))));
  }

  static public void intToBytes_inArray_littleEndian_partial(int i, byte[] array, int idx) {
    if (idx < array.length)
      array[idx] = (byte) i;
    if (idx + 1 < array.length)
      array[idx + 1] = (byte) (i >>> 8);
    if (idx + 2 < array.length)
      array[idx + 2] = (byte) (i >>> 16);
    if (idx + 3 < array.length)
      array[idx + 3] = (byte) (i >>> 24);
  }

  static public byte[] intListToByteArray(List<Integer> l) {
    return intListToByteArray_littleEndian(l);
  }

  static public BufferedImage drawImageOnImage(Image img, BufferedImage canvas, int x, int y) {
    createGraphics(canvas).drawImage(img, x, y, null);
    return canvas;
  }

  static public List<Pair> _registerDangerousWeakMap_preList;

  static public <A> A _registerDangerousWeakMap(A map) {
    return _registerDangerousWeakMap(map, null);
  }

  static public <A> A _registerDangerousWeakMap(A map, Object init) {
    callF(init, map);
    if (init instanceof String) {
      final String f = (String) init;
      init = new VF1<Map>() {

        public void get(Map map) {
          try {
            callMC(f, map);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callMC(f, map)";
        }
      };
    }
    if (javax() == null) {
      if (_registerDangerousWeakMap_preList == null)
        _registerDangerousWeakMap_preList = synchroList();
      _registerDangerousWeakMap_preList.add(pair(map, init));
      return map;
    }
    call(javax(), "_registerDangerousWeakMap", map, init);
    return map;
  }

  static public void _onLoad_registerDangerousWeakMap() {
    assertNotNull(javax());
    if (_registerDangerousWeakMap_preList == null)
      return;
    for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b);
    _registerDangerousWeakMap_preList = null;
  }

  static public <A, B> B syncMapGet2(Map<A, B> map, A a) {
    if (map == null)
      return null;
    synchronized (collectionMutex(map)) {
      return map.get(a);
    }
  }

  static public <A, B> B syncMapGet2(A a, Map<A, B> map) {
    return syncMapGet2(map, a);
  }

  static public boolean isSubtypeOf(Class a, Class b) {
    return b.isAssignableFrom(a);
  }

  static public Set<String> reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath");

  static public Set<String> reflection_classesNotToScan() {
    return reflection_classesNotToScan_value;
  }

  static public boolean isInQ(Q q) {
    return q != null && isCurrentThread(q.rst.thread);
  }

  static public <A, B> Either<A, B> eitherA(A a) {
    return new Either(1, a);
  }

  static public <A, B> Either<A, B> eitherB(B b) {
    return new Either(2, b);
  }

  static public <A> A returnOrThrow_either(Either<A, Throwable> e) {
    if (isEitherB(e))
      throw rethrow(e.b());
    return eitherAOpt(e);
  }

  static public <A> A waitForVarToBeNotNull(Var<A> v) {
    try {
      synchronized (v) {
        while (!v.has()) v.wait();
        return v.get();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isImageFileName(String s) {
    return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
  }

  static public String fileName(File f) {
    return f == null ? null : f.getName();
  }

  static public String appendColonIfNempty(String s) {
    return empty(s) ? "" : s + ": ";
  }

  static public class mapI_if1_It<A, B> extends IterableIterator<B> {

    public IF1<A, B> f;

    public Iterator<A> i;

    public mapI_if1_It() {
    }

    public mapI_if1_It(IF1<A, B> f, Iterator<A> i) {
      this.i = i;
      this.f = f;
    }

    public boolean hasNext() {
      return i.hasNext();
    }

    public B next() {
      return f.get(i.next());
    }

    public String toString() {
      return formatFunctionCall("mapI_if1", f, i);
    }
  }

  static public <A, B> IterableIterator<B> mapI_if1(IF1<A, B> f, Iterable<A> i) {
    return new mapI_if1_It(f, i.iterator());
  }

  static public <A, B> IterableIterator<B> mapI_if1(Iterable<A> i, IF1<A, B> f) {
    return mapI_if1(f, i);
  }

  static public Object[] mapToParams(Map map) {
    return mapToObjectArray(map);
  }

  static public Object[] unrollParams(Object[] params) {
    if (l(params) == 1 && params[0] instanceof Map)
      return mapToParams((Map) params[0]);
    return params;
  }

  static public Object html_valueLessParam_cache;

  static public Object html_valueLessParam() {
    if (html_valueLessParam_cache == null)
      html_valueLessParam_cache = html_valueLessParam_load();
    return html_valueLessParam_cache;
  }

  static public Object html_valueLessParam_load() {
    return new Object();
  }

  static public String htmlQuote(String s) {
    return "\"" + htmlencode_forParams(s) + "\"";
  }

  static public boolean isString(Object o) {
    return o instanceof String;
  }

  static public F1 mainFunctionToF1(final String fname) {
    return new F1<Object, Object>() {

      public Object get(Object a) {
        try {
          return callMC(fname, a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callMC(fname, a)";
      }
    };
  }

  static public byte[] intListToByteArray_littleEndian(List<Integer> l) {
    if (l == null)
      return null;
    int n1 = l(l), n = n1 * 4;
    byte[] a = new byte[n];
    for (int i = 0; i < n1; i++) intToBytes_inArray_littleEndian(l.get(i), a, i * 4);
    return a;
  }

  static public <A> HashSet<A> litset(A... items) {
    return lithashset(items);
  }

  static public boolean isCurrentThread(Thread t) {
    return t != null && t == currentThread();
  }

  static public <A, B> boolean isEitherB(Either<A, B> e) {
    return eitherIsB(e);
  }

  static public <A, B> A eitherAOpt(Either<A, B> e) {
    return e != null && e.isA() ? e.a() : null;
  }

  static public Object[] mapToObjectArray(Map map) {
    List l = new ArrayList();
    for (Object o : keys(map)) {
      l.add(o);
      l.add(map.get(o));
    }
    return toObjectArray(l);
  }

  static public Object[] mapToObjectArray(Object f, Collection l) {
    int n = l(l);
    Object[] array = new Object[n];
    if (n != 0) {
      Iterator it = iterator(l);
      for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
    }
    return array;
  }

  static public Object[] mapToObjectArray(Object f, Object[] l) {
    int n = l(l);
    Object[] array = new Object[n];
    for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
    return array;
  }

  static public <A> Object[] mapToObjectArray(Collection<A> l, IF1<A, Object> f) {
    return mapToObjectArray(f, l);
  }

  static public <A> Object[] mapToObjectArray(A[] l, IF1<A, Object> f) {
    return mapToObjectArray(f, l);
  }

  static public <A> Object[] mapToObjectArray(IF1<A, Object> f, A[] l) {
    int n = l(l);
    Object[] array = new Object[n];
    for (int i = 0; i < n; i++) array[i] = f.get(l[i]);
    return array;
  }

  static public <A> Object[] mapToObjectArray(IF1<A, Object> f, Collection<A> l) {
    int n = l(l);
    Object[] array = new Object[n];
    if (n != 0) {
      Iterator it = iterator(l);
      for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
    }
    return array;
  }

  static public ThreadLocal<Boolean> htmlencode_forParams_useV2 = new ThreadLocal();

  static public String htmlencode_forParams(String s) {
    if (s == null)
      return "";
    if (isTrue(htmlencode_forParams_useV2.get()))
      return htmlencode_forParams_v2(s);
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>') {
        out.append("&#");
        out.append((int) c);
        out.append(';');
      } else
        out.append(c);
    }
    return out.toString();
  }

  static public void intToBytes_inArray_littleEndian(int i, byte[] array, int idx) {
    array[idx] = (byte) i;
    array[idx + 1] = (byte) (i >>> 8);
    array[idx + 2] = (byte) (i >>> 16);
    array[idx + 3] = (byte) (i >>> 24);
  }

  static public <A, B> boolean eitherIsB(Either<A, B> e) {
    return e != null && e.isB();
  }

  static public String htmlencode_forParams_v2(String s) {
    if (s == null)
      return "";
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
        out.append("&#");
        out.append((int) c);
        out.append(';');
      } else
        out.append(c);
    }
    return out.toString();
  }

  abstract static public class AbstractMatrix<A> implements Matrix<A> {

    public AbstractMatrix() {
    }

    public int w, h;

    public AbstractMatrix(int w, int h) {
      this.h = h;
      this.w = w;
    }

    public int getWidth() {
      return w;
    }

    public int getHeight() {
      return h;
    }

    public String toString() {
      return flexLines(roundBracket(w + "x" + h), countIteratorToList(y -> str(getLine(y)), getHeight()));
    }
  }

  static public class IntRange {

    public int start, end;

    public IntRange() {
    }

    public IntRange(int start, int end) {
      this.end = end;
      this.start = start;
    }

    public IntRange(IntRange r) {
      start = r.start;
      end = r.end;
    }

    public boolean equals(Object o) {
      return stdEq2(this, o);
    }

    public int hashCode() {
      return stdHash2(this);
    }

    final public int length() {
      return end - start;
    }

    final public boolean empty() {
      return start >= end;
    }

    final public boolean isEmpty() {
      return start >= end;
    }

    static public String _fieldOrder = "start end";

    public String toString() {
      return "[" + start + ";" + end + "]";
    }
  }

  static public class ListToMatrix<A> extends AbstractMatrix<A> {

    public ListToMatrix() {
    }

    public List<A> data;

    public ListToMatrix(int w, int h, List<A> data) {
      super(w, h);
      this.data = data;
    }

    public int xyToIndex(int x, int y) {
      return y * w + x;
    }

    public A get(int x, int y) {
      return data.get(xyToIndex(x, y));
    }

    public void set(int x, int y, A a) {
      data.set(xyToIndex(x, y), a);
    }
  }

  static public class LiteralJavaXExpr<A> extends Meta implements ICachedJavaXExpr<A>, IFieldsToList {

    public Object expr;

    public LiteralJavaXExpr() {
    }

    public LiteralJavaXExpr(Object expr) {
      this.expr = expr;
    }

    public boolean equals(Object o) {
      if (!(o instanceof LiteralJavaXExpr))
        return false;
      LiteralJavaXExpr __1 = (LiteralJavaXExpr) o;
      return eq(expr, __1.expr);
    }

    public int hashCode() {
      int h = 1878341052;
      h = boostHashCombine(h, _hashCode(expr));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { expr };
    }

    public String toString() {
      return str(expr);
    }

    public transient IF0<A> quickEval;

    public A quickEval() {
      return quickEval != null ? quickEval.get() : quickEval_base();
    }

    final public A quickEval_fallback(IF0<A> _f) {
      return _f != null ? _f.get() : quickEval_base();
    }

    public A quickEval_base() {
      return ICachedJavaXExpr.super.quickEval();
    }
  }

  static public class JECompressionRegime<Data> implements CompressionRegime_AnyType<ICachedJavaXExpr<Data>> {

    final public JECompressionRegime<Data> setQuickEval(boolean quickEval) {
      return quickEval(quickEval);
    }

    public JECompressionRegime<Data> quickEval(boolean quickEval) {
      this.quickEval = quickEval;
      return this;
    }

    final public boolean getQuickEval() {
      return quickEval();
    }

    public boolean quickEval() {
      return quickEval;
    }

    public boolean quickEval = true;

    final public JECompressionRegime<Data> setFullEval(boolean fullEval) {
      return fullEval(fullEval);
    }

    public JECompressionRegime<Data> fullEval(boolean fullEval) {
      this.fullEval = fullEval;
      return this;
    }

    final public boolean getFullEval() {
      return fullEval();
    }

    public boolean fullEval() {
      return fullEval;
    }

    public boolean fullEval = false;

    public byte[] metaCompress(byte[] c) {
      return c;
    }

    public byte[] decompressorToBytes(ICachedJavaXExpr decompressor) {
      return metaCompress(toUtf8(str(decompressor)));
    }

    public ICachedJavaXExpr decompressorFromBytes(byte[] compressed) {
      print("decompressorFromBytes");
      return javaExpr(fromUtf8(gunzipBytes(compressed)));
    }

    public Object runDecompressor(ICachedJavaXExpr code) {
      if (code == null)
        return null;
      if (quickEval)
        try {
          return code.quickEval();
        } catch (Throwable e) {
          if (!fullEval)
            rethrow(e);
          else
            printStackTrace(e);
        }
      if (fullEval) {
        print("*** FULL JAVA EVAL ***");
        return dm_javaEval(str(code));
      }
      throw fail("No way to eval " + shorten(100, sfu(code)));
    }

    public transient IF0<CompressionRegime_AnyType> fullRegime;

    public CompressionRegime_AnyType fullRegime() {
      return fullRegime != null ? fullRegime.get() : fullRegime_base();
    }

    final public CompressionRegime_AnyType fullRegime_fallback(IF0<CompressionRegime_AnyType> _f) {
      return _f != null ? _f.get() : fullRegime_base();
    }

    public CompressionRegime_AnyType fullRegime_base() {
      return null;
    }
  }

  static public class ToJava {

    public Object get(Object o) {
      {
        Object __1 = getOpt(o);
        if (__1 != null)
          return __1;
      }
      throw fail("Can't ToJava: " + className(o));
    }

    public Object getOpt(Object o) {
      if (o == null)
        return "null";
      if (o instanceof String)
        return quote(o);
      if (o instanceof Number)
        return str(o);
      if (o instanceof IFieldsToList)
        return formatFunctionCall("new " + shortName((IFieldsToList) o), map(__65 -> get(__65), ((IFieldsToList) o)._fieldsToList()));
      if (o instanceof List)
        return functionCall_list("ll", map(__66 -> get(__66), (List) o));
      return null;
    }
  }

  static public class WithSideValue<A, B> extends Var<B> implements IWithSideValue<A, B> {

    public A sideValue;

    public WithSideValue() {
    }

    public WithSideValue(A sideValue, B value) {
      super(value);
      this.sideValue = sideValue;
    }

    public WithSideValue(B value) {
      super(value);
    }

    public A sideValue() {
      return sideValue;
    }

    public String toString() {
      return prependSquareBracketed(sideValue) + super.toString();
    }
  }

  static public class SubMatrix<A> extends AbstractMatrix<A> {

    public SubMatrix() {
    }

    public Matrix<A> matrix;

    public int x1, y1;

    public SubMatrix(Matrix<A> matrix, Rect r) {
      super(r.w, r.h);
      this.matrix = matrix;
      x1 = r.x;
      y1 = r.y;
    }

    public A get(int x, int y) {
      try {
        return matrix.get(x + x1, y + y1);
      } catch (Throwable e) {
        throw augmentException(e, this);
      }
    }

    public void set(int x, int y, A a) {
      matrix.set(x + x1, y + y1, a);
    }

    public String toString() {
      return renderFunctionCall("SubMatrix", x1, y1, w, h);
    }
  }

  static public class Complex implements IFieldsToList {

    static final public String _fieldOrder = "re im";

    public double re;

    public double im;

    public Complex() {
    }

    public Complex(double re, double im) {
      this.im = im;
      this.re = re;
    }

    public boolean equals(Object o) {
      if (!(o instanceof Complex))
        return false;
      Complex __1 = (Complex) o;
      return re == __1.re && im == __1.im;
    }

    public int hashCode() {
      int h = -1679819632;
      h = boostHashCombine(h, _hashCode(re));
      h = boostHashCombine(h, _hashCode(im));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { re, im };
    }

    public double abs() {
      return sqrt(re * re + im * im);
    }

    public double re() {
      return re;
    }

    public double im() {
      return im;
    }

    final public double angle() {
      return phase();
    }

    public double phase() {
      return Math.atan2(im, re);
    }

    public double fracAngle() {
      return fracNonNeg(angle() / twoPi());
    }

    public String toString() {
      if (im != 0)
        return re == 0 ? im + "i" : re + plusPrefixUnlessMinus(str(im)) + "i";
      else
        return str(re);
    }
  }

  final static public class DoubleRange implements Comparable<DoubleRange> {

    final public double getStart() {
      return start();
    }

    public double start() {
      return start;
    }

    public double start;

    final public double getEnd() {
      return end();
    }

    public double end() {
      return end;
    }

    public double end;

    public DoubleRange() {
    }

    public DoubleRange(double start, double end) {
      this.end = end;
      this.start = start;
    }

    public boolean equals(Object o) {
      return stdEq2(this, o);
    }

    public int hashCode() {
      return stdHash2(this);
    }

    public double length() {
      return end - start;
    }

    public boolean isEmpty() {
      return start >= end;
    }

    public double center() {
      return (start + end) / 2;
    }

    static public String _fieldOrder = "start end";

    public String toString() {
      return "[" + start + ";" + end + "]";
    }

    @Override
    public int compareTo(DoubleRange r) {
      int c = cmp(start, r.start);
      if (c != 0)
        return c;
      return cmp(end, r.end);
    }
  }

  static public class QuickException extends RuntimeException {

    public Throwable fillInStackTrace() {
      return this;
    }

    public QuickException() {
    }

    public QuickException(Throwable e) {
      super(e);
    }

    public QuickException(String msg) {
      super(msg);
    }

    public QuickException(String msg, Throwable e) {
      super(msg, e);
    }
  }

  static public class IntBuffer implements Iterable<Integer> {

    public int[] data;

    public int size;

    public IntBuffer() {
    }

    public IntBuffer(int size) {
      if (size != 0)
        data = new int[size];
    }

    public IntBuffer(Iterable<Integer> l) {
      this(l(l));
      addAll(l);
    }

    public void add(int i) {
      if (size >= lIntArray(data)) {
        data = resizeIntArray(data, Math.max(1, toInt(Math.min(maximumSafeArraySize(), lIntArray(data) * 2L))));
        if (size >= data.length)
          throw fail("IntBuffer too large: " + size);
      }
      data[size++] = i;
    }

    public void addAll(Iterable<Integer> l) {
      if (l != null)
        for (int i : l) add(i);
    }

    public int[] toArray() {
      return size == 0 ? null : resizeIntArray(data, size);
    }

    public List<Integer> toList() {
      return intArrayToList(data, 0, size);
    }

    public List<Integer> asVirtualList() {
      return new RandomAccessAbstractList<Integer>() {

        public int size() {
          return size;
        }

        public Integer get(int i) {
          return IntBuffer.this.get(i);
        }

        public Integer set(int i, Integer val) {
          Integer a = get(i);
          data[i] = val;
          return a;
        }
      };
    }

    public void reset() {
      size = 0;
    }

    public void clear() {
      reset();
    }

    public int size() {
      return size;
    }

    public boolean isEmpty() {
      return size == 0;
    }

    public int get(int idx) {
      if (idx >= size)
        throw fail("Index out of range: " + idx + "/" + size);
      return data[idx];
    }

    public void set(int idx, int value) {
      if (idx >= size)
        throw fail("Index out of range: " + idx + "/" + size);
      data[idx] = value;
    }

    public int popLast() {
      if (size == 0)
        throw fail("empty buffer");
      return data[--size];
    }

    public int last() {
      return data[size - 1];
    }

    public int nextToLast() {
      return data[size - 2];
    }

    public String toString() {
      return squareBracket(joinWithSpace(toList()));
    }

    public Iterator<Integer> iterator() {
      return new IterableIterator<Integer>() {

        public int i = 0;

        public boolean hasNext() {
          return i < size;
        }

        public Integer next() {
          return data[i++];
        }
      };
    }

    public IntegerIterator integerIterator() {
      return new IntegerIterator() {

        public int i = 0;

        public boolean hasNext() {
          return i < size;
        }

        public int next() {
          return data[i++];
        }

        public String toString() {
          return "Iterator@" + i + " over " + IntBuffer.this;
        }
      };
    }

    public void trimToSize() {
      data = resizeIntArray(data, size);
    }
  }

  static public interface IVF3<A, B, C> {

    public void get(A a, B b, C c);
  }

  static public class Either<A, B> {

    public byte which;

    public Object value;

    public Either() {
    }

    public Either(int which, Object value) {
      this.which = (byte) which;
      this.value = value;
    }

    public boolean isA() {
      return which == 1;
    }

    public boolean isB() {
      return which == 2;
    }

    public A a() {
      if (which != 1)
        _failMe();
      return (A) value;
    }

    public B b() {
      if (which != 2)
        _failMe();
      return (B) value;
    }

    public A aOpt() {
      return which != 1 ? null : (A) value;
    }

    public B bOpt() {
      return which != 2 ? null : (B) value;
    }

    public void _failMe() {
      throw fail("Either object is of wrong type: " + shortClassName(value));
    }

    public String toString() {
      return "Either" + (isA() ? "A" : "B") + "(" + value + ")";
    }
  }

  static public class T3<A, B, C> {

    public A a;

    public B b;

    public C c;

    public T3() {
    }

    public T3(A a, B b, C c) {
      this.c = c;
      this.b = b;
      this.a = a;
    }

    public T3(T3<A, B, C> t) {
      a = t.a;
      b = t.b;
      c = t.c;
    }

    public int hashCode() {
      return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c);
    }

    public boolean equals(Object o) {
      if (o == this)
        return true;
      if (!(o instanceof T3))
        return false;
      T3 t = (T3) o;
      return eq(a, t.a) && eq(b, t.b) && eq(c, t.c);
    }

    public String toString() {
      return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")";
    }
  }

  public interface IWithSideValue<A, B> extends IF0<B> {

    public A sideValue();
  }

  abstract static public class IntegerIterator {

    abstract public boolean hasNext();

    abstract public int next();
  }

  static public JPanel centerAndSouthWithMargins(Component c, Component s) {
    return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
  }

  static public JPanel centerAndSouthWithMargins(int margin, Component c, Component s) {
    return applyMargin(margin, centerAndSouth(c, withTopMargin(margin, s)));
  }

  static public SingleComponentPanel singleComponentPanel() {
    return singleComponentPanel(null);
  }

  static public SingleComponentPanel singleComponentPanel(final Component c) {
    return swing(new F0<SingleComponentPanel>() {

      public SingleComponentPanel get() {
        try {
          return new SingleComponentPanel(c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new SingleComponentPanel(c);";
      }
    });
  }

  static public JPanel jrightalignedline(Component... components) {
    return jrightAlignedLine(components);
  }

  static public JPanel jrightalignedline(List<Component> components) {
    return jrightAlignedLine(components);
  }

  static public JPanel centerAndEastWithMargin(Component c, Component e) {
    return centerAndEastWithMarginInbetween(c, e);
  }

  static public JCheckBox dm_fieldCheckBox(String field) {
    return dm_fieldCheckBox(humanizeFormLabel(field), field);
  }

  static public JCheckBox dm_fieldCheckBox(String text, String field) {
    if (isIdentifier(text) && !isIdentifier(field)) {
      String temp = field;
      field = text;
      text = temp;
    }
    return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
  }

  static public void addComponentsFirst(Container c, Component... l) {
    containerAddFirst(c, l);
  }

  static public void scpSet(SingleComponentPanel scp, Component c) {
    setSCPComponent(scp, c);
  }

  static public String flexLines(Object... l) {
    return lines(flattenIterablesAndArrays(ll(l)));
  }

  static public String fromUtf8(byte[] bytes) {
    try {
      return bytes == null ? null : new String(bytes, utf8charset());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public byte[] gunzipBytes(byte[] data) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      copyStreamAndCloseAll(newGZIPInputStream(new ByteArrayInputStream(data)), baos);
      return baos.toByteArray();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object dm_javaEval(String expression) {
    return dm_evalJava_withModule(expression);
  }

  static public Object dm_javaEval(ICachedJavaXExpr expression) {
    return dm_evalJava_withModule(str(expression));
  }

  static public String sfu(Object o) {
    return structureForUser(o);
  }

  static public String shortName(Object o) {
    return shortClassName(o);
  }

  static public String prependSquareBracketed(Object o) {
    String s = strOrEmpty(o);
    return empty(s) ? "" : squareBracketed(s) + " ";
  }

  static public RuntimeException augmentException(Throwable e, Object... info) {
    return new Fail(e, info);
  }

  static public String renderFunctionCall(String fname, Object... args) {
    return formatFunctionCall(fname, args);
  }

  static public double fracNonNeg(double d) {
    return frac_nonNeg(d);
  }

  static public double twoPi() {
    return Math.PI * 2;
  }

  static public String plusPrefixUnlessMinus(String s) {
    return startsWith(s, "-") ? s : "+" + s;
  }

  static public int lIntArray(int[] a) {
    return a == null ? 0 : a.length;
  }

  static public int[] resizeIntArray(int[] a, int n) {
    if (n == lIntArray(a))
      return a;
    int[] b = new int[n];
    arraycopy(a, 0, b, 0, Math.min(lIntArray(a), n));
    return b;
  }

  static public int maximumSafeArraySize() {
    return Integer.MAX_VALUE - 8;
  }

  static public <A> ArrayList<Integer> intArrayToList(int[] a) {
    if (a == null)
      return null;
    return intArrayToList(a, 0, a.length);
  }

  static public <A> ArrayList<Integer> intArrayToList(int[] a, int from, int to) {
    if (a == null)
      return null;
    ArrayList<Integer> l = new ArrayList<>(to - from);
    for (int i = from; i < to; i++) l.add(a[i]);
    return l;
  }

  static public <A> List<A> asVirtualList(A[] a) {
    return wrapArrayAsList(a);
  }

  static public String squareBracket(String s) {
    return "[" + s + "]";
  }

  static public IntegerIterator integerIterator(int[] l) {
    return l == null ? null : new IntegerIterator() {

      public int i = 0;

      public boolean hasNext() {
        return i < l.length;
      }

      public int next() {
        return l[i++];
      }
    };
  }

  static public String b(Object contents, Object... params) {
    return tag("b", contents, params);
  }

  static public <A, B> boolean isA(Either<A, B> e) {
    return eitherIsA(e);
  }

  static public String quoteBorderless(Object o) {
    if (o == null)
      return "null";
    return quoteBorderless(str(o));
  }

  static public String quoteBorderless(String s) {
    if (s == null)
      return "null";
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5));
    quoteBorderless_impl(s, out);
    return out.toString();
  }

  static public void quoteBorderless_impl(String s, StringBuilder out) {
    int l = s.length();
    for (int i = 0; i < l; i++) {
      char c = s.charAt(i);
      if (c == '\\' || c == '"')
        out.append('\\').append(c);
      else if (c == '\r')
        out.append("\\r");
      else if (c == '\n')
        out.append("\\n");
      else
        out.append(c);
    }
  }

  static public <A extends JComponent> A applyDefaultMargin(final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
        }
      });
    }
    return c;
  }

  static public JPanel centerAndSouth(final Component c, final Component s) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(BorderLayout.CENTER, wrap(c));
          if (s != null)
            panel.add(BorderLayout.SOUTH, wrap(s));
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new BorderLayout);\r\n    panel.add(BorderLayout.CENT...";
      }
    });
  }

  static public int withTopMargin_defaultWidth = 6;

  static public JPanel withTopMargin(Component c) {
    return withTopMargin(withTopMargin_defaultWidth, c);
  }

  static public JPanel withTopMargin(final int w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public <A extends JComponent> A applyMargin(int top, int left, int bottom, int right, A c) {
    return addMargin(top, left, bottom, right, c);
  }

  static public <A extends JComponent> A applyMargin(int w, A c) {
    return addMargin(w, c);
  }

  static public JPanel jrightAlignedLine(final Component... components) {
    return swing(new F0<RightAlignedLine>() {

      public RightAlignedLine get() {
        try {
          return new RightAlignedLine(components);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret RightAlignedLine(components);";
      }
    });
  }

  static public JPanel jrightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(asArray(Component.class, components));
  }

  static public JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
    return centerAndEast(c, withLeftMargin(e));
  }

  static public Map<String, String> humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");

  static public String humanizeFormLabel(String s) {
    if (containsSpace(s))
      return s;
    return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
  }

  static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue<Boolean> lv) {
    final JCheckBox cb = jCheckBox(text);
    bindCheckBoxToLiveValue(cb, lv);
    return cb;
  }

  static public void containerAddFirst(final Container c, final Component... l) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            for (int i = 0; i < l(l); i++) c.add(l[i], i);
            revalidate(c);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "for (int i = 0; i < l(l); i++)\r\n      c.add(l[i], i);\r\n    revalidate(c);";
        }
      });
    }
  }

  static public void setSCPComponent(SingleComponentPanel scp, Component c) {
    if (scp != null)
      scp.setComponent(c);
  }

  static public List flattenIterablesAndArrays(Iterable a) {
    List l = new ArrayList();
    for (Object x : a) if (x instanceof Iterable)
      l.addAll(flattenIterablesAndArrays((Iterable) x));
    else if (x instanceof Iterator)
      l.addAll(flattenIterablesAndArrays(asList((Iterator) x)));
    else if (x instanceof Object[])
      l.addAll(flattenIterablesAndArrays(asList((Object[]) x)));
    else
      l.add(x);
    return l;
  }

  static public void copyStreamAndCloseAll(InputStream in, OutputStream out) {
    try {
      try {
        copyStreamAndCloseInput(in, out);
      } finally {
        out.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object dm_evalJava_veryQuickJava;

  static public Object dm_evalJava_withModule(String expression, Object... args) {
    Object m = dm_current_generic();
    String code = evalJava_prep(expression) + "\r\n    static new InheritableThreadLocal<WeakReference> dm_currentModule_value;\r\n    \r\n    sO dm_current_mandatory_generic_value;\r\n    \r\n    sO dm_current_mandatory_generic() { ret dm_current_mandatory_generic_value; }\r\n    sO dm_current_generic() { ret dm_current_mandatory_generic(); }\r\n  ";
    Object obj;
    if (dm_evalJava_veryQuickJava != null)
      obj = callF(dm_evalJava_veryQuickJava, code);
    else
      obj = veryQuickJava(code);
    setOpt(obj, "programID", programID());
    makeDependent(obj);
    setOpt(obj, "creator_class", newWeakReference(dm_os()));
    dm_pointSubmoduleToMe(obj, m);
    return evalJava_myProgramID_main_2(obj, args);
  }

  static public String squareBracketed(String s) {
    return "[" + s + "]";
  }

  static public double frac_nonNeg(double d) {
    return mod(d, 1);
  }

  static public <A> List<A> wrapArrayAsList(A[] a) {
    return a == null ? null : Arrays.asList(a);
  }

  static public String tag(String tag) {
    return htag(tag);
  }

  static public String tag(String tag, Object contents, Object... params) {
    return htag(tag, str(contents), params);
  }

  static public String tag(String tag, StringBuilder contents, Object... params) {
    return htag(tag, contents, params);
  }

  static public String tag(String tag, StringBuffer contents, Object... params) {
    return htag(tag, contents, params);
  }

  static public <A, B> boolean eitherIsA(Either<A, B> e) {
    return e != null && e.isA();
  }

  static public <A extends JComponent> A addMargin(final int top, final int left, final int bottom, final int right, final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right);
            c.setBorder(jCompoundBorder(c.getBorder(), margin));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right);\r\n ...";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A addMargin(int w, A c) {
    return addMargin(w, w, w, w, c);
  }

  static public int withLeftMargin_defaultWidth = 6;

  static public JPanel withLeftMargin(Component c) {
    return withLeftMargin(withLeftMargin_defaultWidth, c);
  }

  static public JPanel withLeftMargin(final int margin, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = new JPanel(new BorderLayout());
          p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = new JPanel(new BorderLayout);\r\n    p.setBorder(BorderFactory.creat...";
      }
    });
  }

  static public boolean containsSpace(String s) {
    return containsSpaces(s);
  }

  static public String firstToUpper(String s) {
    if (empty(s))
      return s;
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
  }

  static public <A> List<A> replaceElementsUsingMap(Iterable<A> l, final Map<A, A> map) {
    return map(l, new F1<A, A>() {

      public A get(A a) {
        try {
          return getOrKeep(map, a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "getOrKeep(map, a)";
      }
    });
  }

  static public List<String> splitCamelCase(String s) {
    return ai_splitCamelCase(s);
  }

  static public JCheckBox jCheckBox() {
    return swingNu(JCheckBox.class);
  }

  static public JCheckBox jCheckBox(boolean checked) {
    return swingNu(JCheckBox.class, "", checked);
  }

  static public JCheckBox jCheckBox(String text, boolean checked) {
    return swingNu(JCheckBox.class, text, checked);
  }

  static public JCheckBox jCheckBox(String text) {
    return swingNu(JCheckBox.class, text);
  }

  static public JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
    JCheckBox cb = jCheckBox(checked, onChange);
    cb.setText(text);
    return cb;
  }

  static public JCheckBox jCheckBox(boolean checked, final Object onChange) {
    final JCheckBox cb = jCheckBox(checked);
    cb.addChangeListener(new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(onChange, cb.isSelected());
      }
    });
    return cb;
  }

  static public <A extends JCheckBox> A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue<Boolean> lv) {
    bindLiveValueListenerToComponent(cb, lv, new Runnable() {

      public void run() {
        try {
          setChecked(cb, isTrue(lv.get()));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    onChange(cb, new Runnable() {

      public void run() {
        try {
          lv.set(isChecked(cb));
          ;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ifdef bindCheckBoxToLiveValue_debug\r\n      print(\"bindCheckBoxToLiveValue: se...";
      }
    });
    return cb;
  }

  static public void copyStreamAndCloseInput(InputStream in, OutputStream out) {
    try {
      try {
        copyStream(in, out);
      } finally {
        in.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String evalJava_prep(String code) {
    return evalJava_prep(code, "calc");
  }

  static public String evalJava_prep(String code, String mainName) {
    return evalJava_prep(code, mainName, "");
  }

  static public ThreadLocal<String> evalJava_prep_args = new ThreadLocal();

  static public String evalJava_prep(String code, String mainName, String preCode) {
    EvalJavaPrep prep = new EvalJavaPrep();
    List<String> tok = evalJava_prePrep(code, prep);
    code = tok_addReturn(tok);
    String returnType = containsReturnWithArgument(code) ? "O" : "void";
    String main = lines(prep.global) + "static " + returnType + " " + mainName + "(" + unnull(evalJava_prep_args.get()) + ") throws Exception {\n" + preCode + code + "\n" + "}";
    return main;
  }

  static public Class veryQuickJava(CharSequence mainJava) {
    return veryQuickJava3(str(mainJava));
  }

  static public void dm_pointSubmoduleToMe(Object subModule) {
    dm_pointSubmoduleToMe(subModule, dm_current_mandatory_generic());
  }

  static public void dm_pointSubmoduleToMe(Object subModule, Object me) {
    setOpt(subModule, "dm_current_mandatory_generic_value", me);
  }

  static public ThreadLocal<Long> evalJava_myProgramID_main_time = new ThreadLocal();

  static public ThreadLocal<Object> evalJava_myProgramID_main_mainClass = new ThreadLocal();

  static public Object evalJava_myProgramID_main(String main, Object... args) {
    Object obj = veryQuickJava(main);
    setOpt(obj, "programID", programID());
    makeDependent(obj);
    if (evalJava_myProgramID_main_mainClass.get() != null)
      evalJava_myProgramID_main_mainClass.set(obj);
    return evalJava_myProgramID_main_2(obj, args);
  }

  static public Object evalJava_myProgramID_main_2(Object obj, Object... args) {
    long time = sysNow();
    try {
      return callCalc(obj, args);
    } finally {
      evalJava_myProgramID_main_time.set(sysNow() - time);
    }
  }

  static public String htag(String tag) {
    return htag(tag, "");
  }

  static public String htag(String tag, Object contents, Object... params) {
    String openingTag = hopeningTag(tag, params);
    String s = str(contents);
    if (empty(s) && neqic(tag, "script"))
      return dropLast(openingTag) + "/>";
    return openingTag + s + "</" + tag + ">";
  }

  static public Border jCompoundBorder(Border inner, Border outer) {
    if (inner == null)
      return outer;
    if (outer == null)
      return inner;
    return BorderFactory.createCompoundBorder(inner, outer);
  }

  static public boolean containsSpaces(String s) {
    return indexOf(s, ' ') >= 0;
  }

  static public <A> A getOrKeep(Map<A, ? extends A> map, A a) {
    if (map == null)
      return a;
    A v = map.get(a);
    return v != null ? v : a;
  }

  static public List<String> ai_splitCamelCase(String s) {
    int j = 0;
    List<String> l = new ArrayList();
    if (isAllUpperCase(s)) {
      l.add(s);
      return l;
    }
    for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
      l.add(substring(s, j, i));
      j = i;
    }
    if (j < l(s))
      l.add(substring(s, j));
    return l;
  }

  static public void setChecked(JCheckBox checkBox, boolean b) {
    if (checkBox != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (isChecked(checkBox) != b)
              checkBox.setSelected(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (isChecked(checkBox) != b)\r\n      checkBox.setSelected(b);";
        }
      });
    }
  }

  static public void setChecked(JCheckBoxMenuItem mi, boolean b) {
    if (mi != null) {
      swing(new Runnable() {

        public void run() {
          try {
            mi.setSelected(b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "mi.setSelected(b);";
        }
      });
    }
  }

  static public ThreadLocal<Boolean> evalJava_prep_voidMagic = new ThreadLocal();

  static public List<String> evalJava_prePrep(String code) {
    return evalJava_prePrep(code, new EvalJavaPrep());
  }

  static public List<String> evalJava_prePrep(String code, EvalJavaPrep prep) {
    List<String> tok = javaTok(trim(code));
    int idx;
    while ((idx = jfind(tok, "global {")) >= 0) {
      int j = findEndOfBracketPart(tok, idx + 2);
      prep.global.add(joinSubList(tok, idx + 3, j - 1));
      clearTokens_reTok(tok, idx, j + 1);
    }
    if (eqGet(tok, 1, "="))
      tok = subList(tok, 2);
    if (tok_isStaticLevelCode(tok))
      return tok;
    if (!isFalse(evalJava_prep_voidMagic.get()) && tok_shouldAddReturn(tok) && eqGet(tok, 3, "(") && isIdentifier(get(tok, 1)) && isKnownVoidFunction_uncached(get(tok, 1)))
      tokAppend_reTok(tok, l(tok) - 2, ";");
    String name = null;
    if (l(tok) == 3 && isIdentifier(name = firstToken(tok)))
      tokAppend_reTok(tok, 1, "()" + (isKnownVoidFunction_uncached(name) ? ";" : ""));
    return tok;
  }

  static public String tok_addReturn(List<String> tok) {
    if (tok_shouldAddReturn(tok)) {
      tokPrepend(tok, 1, "ret ");
      tokAppend(tok, l(tok) - 2, ";");
    }
    return join(tok);
  }

  static public String tok_addReturn(String s) {
    return tok_addReturn(javaTok(s));
  }

  static public boolean containsReturnWithArgument(List<String> tok) {
    for (int i = 1; i + 2 < l(tok); i += 2) {
      String t = tok.get(i);
      if (eqOneOf(t, "ret", "return") && neqOneOf(tok.get(i + 2), ";", "if", "unless", "with"))
        return true;
      if (eqOneOf(t, "embedded", "class") && isIdentifier(get(tok, i + 2)))
        i = tok_findEndOfMethodDecl(tok, i) - 1;
      if (eqOneOf(t, "r", ">") && eqGet(tok, i + 2, "{"))
        i = findEndOfBlock(tok, i + 2) - 1;
    }
    return false;
  }

  static public boolean containsReturnWithArgument(String code) {
    return containsReturnWithArgument(javaTok(code));
  }

  static public boolean veryQuickJava_silent = true;

  static public boolean veryQuickJava_useCompilerBot = true;

  static public ThreadLocal<String> veryQuickJava_transpiled = new ThreadLocal();

  static public Object veryQuickJava3_cacheFunction;

  static public ThreadLocal<IVF1<String>> veryQuickJava_onJavaSource = new ThreadLocal();

  static public Class veryQuickJava3(String mainJava) {
    return veryQuickJava3(mainJava, emptyList());
  }

  static public Class veryQuickJava3(String mainJava, List<String> libs) {
    Class c = (Class) (callF(veryQuickJava3_cacheFunction, mainJava, libs));
    if (c != null)
      return c;
    transpileRaw_silent = veryQuickJava_silent;
    String src = transpileRaw(mainJava);
    if (empty(src)) {
      printWithIndent("JAVAX> ", mainJava);
      throw fail("Transpiler returned empty result");
    }
    if (veryQuickJava_transpiled.get() != null)
      veryQuickJava_transpiled.set(src);
    callF(veryQuickJava_onJavaSource.get(), src);
    return veryQuickJava_finish(src, libs);
  }

  static public Object callCalc(Object o, Object... args) {
    return call(o, "calc", args);
  }

  static public boolean neqic(String a, String b) {
    return !eqic(a, b);
  }

  static public boolean neqic(char a, char b) {
    return !eqic(a, b);
  }

  static public boolean isAllUpperCase(String s) {
    return hasLettersAllUpperCase(s);
  }

  static public boolean isUpperCaseLetter(char c) {
    return Character.isUpperCase(c);
  }

  static public int findEndOfBracketPart(List<String> cnc, int i) {
    int j = i + 2, level = 1;
    while (j < cnc.size()) {
      if (eqOneOf(cnc.get(j), "{", "("))
        ++level;
      else if (eqOneOf(cnc.get(j), "}", ")"))
        --level;
      if (level == 0)
        return j + 1;
      ++j;
    }
    return cnc.size();
  }

  static public void clearTokens_reTok(List<String> tok, int i, int j) {
    clearTokens(tok, i, j);
    reTok(tok, i, j);
  }

  static public boolean eqGet(List l, int i, Object o) {
    return eq(get(l, i), o);
  }

  static public <A, B> boolean eqGet(Map<A, B> map, A key, Object o) {
    return eq(mapGet(map, key), o);
  }

  static public boolean tok_isStaticLevelCode(List<String> tok) {
    return eqOneOf(firstCodeToken(tok), "static", "sclass", "sinterface", "sS", "sO");
  }

  static public boolean tok_isStaticLevelCode(String src) {
    return tok_isStaticLevelCode(javaTok(src));
  }

  static public boolean tok_shouldAddReturn(List<String> tok) {
    String lastToken = get(tok, l(tok) - 2);
    if (eqOneOf(lastToken, ";", null))
      return false;
    if (eq(lastToken, "}")) {
      int i = findBeginningOfBlock(tok, l(tok) - 2);
      return eqGet(tok, i - 4, "-") && eqGet(tok, i - 3, "") && eqGet(tok, i - 2, ">");
    }
    return true;
  }

  static public boolean tok_shouldAddReturn(String s) {
    return tok_shouldAddReturn(javaTok(s));
  }

  static public boolean isKnownVoidFunction_uncached(String name) {
    return standardFunctionAlwaysReturnsVoid_uncached(name);
  }

  static public void tokAppend_reTok(List<String> tok, int i, String s) {
    tok.set(i, tok.get(i) + s);
    reTok(tok, i, i + 1);
  }

  static public String firstToken(String s) {
    return firstJavaToken(s);
  }

  static public String firstToken(List<String> tok) {
    return get(tok, 1);
  }

  static public void tokPrepend(List<String> tok, String s) {
    tokPrepend(tok, 0, s);
  }

  static public void tokPrepend(List<String> tok, int i, String s) {
    tok.set(i, s + tok.get(i));
  }

  static public void tokAppend(List<String> tok, int i, String s) {
    tok.set(i, tok.get(i) + s);
  }

  static public boolean neqOneOf(Object o, Object... l) {
    for (Object x : l) if (eq(o, x))
      return false;
    return true;
  }

  static public int tok_findEndOfMethodDecl(List<String> tok, int i) {
    i = tok_findEndOfMethodHeader(tok, i);
    return findEndOfBlock(tok, i);
  }

  static public int findEndOfBlock(List<String> tok, int i) {
    return tok_findEndOfBlock(tok, i);
  }

  static public boolean transpileRaw_silent = true;

  static public boolean transpileRaw_useDiskCache = false;

  static public Class transpileRaw_trans;

  static public boolean transpileRaw_mine = true;

  static public boolean transpileRaw_verySilent = false;

  static public boolean transpileRaw_dontCopyFromCreator = false;

  static public Lock transpileRaw_lock = lock();

  static public ThreadLocal<Boolean> transpileRaw_asInclude = new ThreadLocal();

  static public String transpileRaw(String mainJava) {
    return transpileRaw(mainJava, false, transpileRaw_useDiskCache);
  }

  static public String transpileRaw(String mainJava, boolean fragment) {
    return transpileRaw(mainJava, fragment, transpileRaw_useDiskCache);
  }

  static public String transpileRaw(String mainJava, boolean fragment, boolean useDiskCache) {
    mainJava = dropTranslators(mainJava);
    if (!transpileRaw_dontCopyFromCreator)
      transpileRaw_copyFromCreator();
    Lock __0 = transpileRaw_lock;
    lock(__0);
    try {
      File cacheFile = null;
      if (useDiskCache) {
        cacheFile = new File(javaxCodeDir(), "Transpilations/" + uniqueFileNameUsingMD5_80_v2(mainJava) + ".java");
        {
          String __3 = loadTextFile(cacheFile);
          if (!empty(__3))
            return __3;
        }
      }
      AutoCloseable __4 = transpileRaw_verySilent ? null : tempLoadingAnim("Transpiling...");
      try {
        transpileRaw_translator();
        setOpt(transpileRaw_trans, "localStuffOnly", fragment);
        setOpt(transpileRaw_trans, "asInclude", isTrue(transpileRaw_asInclude.get()));
        set(transpileRaw_trans, "mainJava", mainJava);
        set(transpileRaw_trans, "print_byThread", print_byThread);
        if (!transpileRaw_verySilent)
          print("Running translator " + getOpt(transpileRaw_trans, "programID"));
        callMain(transpileRaw_trans);
        String main = (String) (get(transpileRaw_trans, "mainJava"));
        if (useDiskCache) {
          saveTextFile(new File(cacheFile.getPath() + "x"), mainJava);
          saveTextFile(cacheFile, main);
        }
        return main;
      } finally {
        _close(__4);
      }
    } finally {
      unlock(__0);
    }
  }

  static public Class transpileRaw_translator() {
    if (transpileRaw_trans == null) {
      transpileRaw_trans = hotwireSharingLibraries_silently(defaultJavaXTranslatorID());
      transpileRaw_mine = true;
      makeDependent(transpileRaw_trans);
    }
    setOpt(transpileRaw_trans, "print_silent", transpileRaw_silent);
    return transpileRaw_trans;
  }

  static public void transpileRaw_copyFromCreator() {
    Lock __1 = transpileRaw_lock;
    lock(__1);
    try {
      if (transpileRaw_trans != null)
        return;
      Object c = creator();
      if (c == null)
        return;
      Class trans = (Class) (getOpt(c, "transpileRaw_trans"));
      Lock lock = (Lock) (getOpt(c, "transpileRaw_lock"));
      if (trans != null && lock != null) {
        print("Using creator's transpiler: " + getProgramID(c) + " => " + programID());
        transpileRaw_lock = lock;
        transpileRaw_trans = trans;
        transpileRaw_mine = false;
      }
    } finally {
      unlock(__1);
    }
  }

  static public void cleanMeUp_transpileRaw() {
    if (transpileRaw_mine)
      cleanUp(transpileRaw_trans);
    transpileRaw_trans = null;
  }

  static public <A> A printWithIndent(A o) {
    return printIndent(o);
  }

  static public <A> A printWithIndent(String indent, A o) {
    return printIndent(indent, o);
  }

  static public void printWithIndent(int indent, Object o) {
    printIndent(indent, o);
  }

  static public Class veryQuickJava_finish(String src, List<String> libs) {
    libs = cloneList(libs);
    src = findTranslators2(src, libs);
    String dehlibs = join(" ", libs);
    File bytecode = null;
    bytecode = javaCompile_overInternalBot(src, dehlibs);
    return hotwireCore(concatLists(ll(bytecode), loadLibraries(libs)));
  }

  static public boolean hasLettersAllUpperCase(String s) {
    return hasLetters(s) && !containsLowerCase(s);
  }

  static public void clearTokens(List<String> tok) {
    clearAllTokens(tok);
  }

  static public void clearTokens(List<String> tok, int i, int j) {
    clearAllTokens(tok, i, j);
  }

  static public void clearTokens(List<String> tok, IntRange r) {
    clearAllTokens(tok, r.start, r.end);
  }

  static public String firstCodeToken(String s) {
    return firstJavaToken(s);
  }

  static public String firstCodeToken(List<String> tok) {
    return get(tok, 1);
  }

  static public int findBeginningOfBlock(List<String> cnc, int i) {
    int j = i - 2, level = 1;
    while (j > 0) {
      if (eq(cnc.get(j), "}"))
        ++level;
      else if (eq(cnc.get(j), "{"))
        --level;
      if (level == 0)
        return j;
      j -= 2;
    }
    return -1;
  }

  static public boolean standardFunctionAlwaysReturnsVoid_uncached(String name) {
    return tok_staticFunctionAlwaysReturnsVoid(javaTok(textOfStandardFunction_uncached(name)), name);
  }

  static public String firstJavaToken(String s) {
    if (s == null)
      return null;
    int l = s.length();
    int j = 0;
    char c, d;
    while (j < l) {
      c = s.charAt(j);
      d = j + 1 >= l ? '\0' : s.charAt(j + 1);
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ++j;
      else if (c == '/' && d == '*') {
        do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
        j = Math.min(j + 2, l);
      } else if (c == '/' && d == '/') {
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
      } else
        break;
    }
    if (j >= l)
      return null;
    int i = j;
    c = s.charAt(i);
    d = i + 1 >= l ? '\0' : s.charAt(i + 1);
    if (c == '\'' || c == '"') {
      char opener = c;
      ++j;
      while (j < l) {
        if (s.charAt(j) == opener || s.charAt(j) == '\n') {
          ++j;
          break;
        } else if (s.charAt(j) == '\\' && j + 1 < l)
          j += 2;
        else
          ++j;
      }
    } else if (Character.isJavaIdentifierStart(c))
      do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
    else if (Character.isDigit(c)) {
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      if (j < l && s.charAt(j) == 'L')
        ++j;
    } else if (c == '[' && d == '[') {
      do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
      j = Math.min(j + 2, l);
    } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
      do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
      j = Math.min(j + 3, l);
    } else
      ++j;
    return quickSubstring(s, i, j);
  }

  static public int tok_findEndOfMethodHeader(List<String> tok, int i) {
    i |= 1;
    int level = 0;
    while (i < l(tok)) {
      String t = tok.get(i);
      if (eq(t, "("))
        ++level;
      else if (eq(t, ")"))
        --level;
      else if (level == 0 && eqOneOf(t, "{", ";"))
        return i;
      i += 2;
    }
    return i;
  }

  static public int tok_findEndOfBlock(List<String> tok, int i) {
    int j = i + 2, level = 1, n = l(tok);
    while (j < n) {
      String t = tok.get(j);
      if ("{".equals(t))
        ++level;
      else if ("}".equals(t))
        --level;
      if (level == 0)
        return j + 1;
      j += 2;
    }
    return n;
  }

  static public String dropTranslators(String src) {
    return findTranslators2(src, null);
  }

  static public List<String> dropTranslators(List<String> tok) {
    return findTranslators2(tok, null);
  }

  static public String uniqueFileNameUsingMD5_80_v2(String fullName) {
    return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName));
  }

  static public String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) {
    return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5;
  }

  static public <A> AutoCloseable tempLoadingAnim(String msg) {
    return tempDisposeWindow(loadingAnim(msg));
  }

  static public Class<?> hotwireSharingLibraries_silently(String progID) {
    AutoCloseable __1 = temp_loadPage_silent();
    try {
      return hotwireSharingLibraries(progID);
    } finally {
      _close(__1);
    }
  }

  static public String defaultJavaXTranslatorID_value = "#759";

  static public String defaultJavaXTranslatorID() {
    return defaultJavaXTranslatorID_value;
  }

  static public boolean cleanUp_interruptThreads = false;

  static public void cleanUp(Object c) {
    if (c == null)
      return;
    if (c instanceof AutoCloseable) {
      close_pcall((AutoCloseable) c);
      return;
    }
    if (c instanceof java.util.Timer) {
      ((java.util.Timer) c).cancel();
      return;
    }
    if (c instanceof Collection) {
      cleanUp((Collection) c);
      return;
    }
    if (c instanceof Map) {
      for (Object o : keys((Map) c)) cleanUp(o);
      for (Object o : values((Map) c)) cleanUp(o);
      ((Map) c).clear();
      return;
    }
    try {
      preCleanUp(c);
      setOpt(c, "ping_pauseAll", false);
      innerCleanUp(c);
      List androids = (List) getOpt(c, "record_list");
      for (Object android : unnull(androids)) pcallOpt(android, "dispose");
      List<WeakReference> classes = (List<WeakReference>) (getOpt(c, "hotwire_classes"));
      if (classes != null)
        for (WeakReference cc : classes) {
          try {
            cleanUp(cc.get());
          } catch (Throwable __e) {
            printStackTrace(__e);
          }
        }
      if (cleanUp_interruptThreads) {
        List<Thread> threads = registeredThreads(c);
        if (nempty(threads)) {
          print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
          interruptThreads(threads);
        }
      }
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
    setOpt(c, "cleaningUp_flag", false);
    if (c instanceof Class && ((Class) c).getName().equals("main"))
      retireClassLoader(((Class) c).getClassLoader());
  }

  static public void cleanUp(Collection l) {
    if (l == null)
      return;
    for (Object c : l) cleanUp(c);
    l.clear();
  }

  static public <A> A printIndent(A o) {
    print(indentx(str(o)));
    return o;
  }

  static public <A> A printIndent(String indent, A o) {
    print(indentx(indent, str(o)));
    return o;
  }

  static public void printIndent(int indent, Object o) {
    print(indentx(indent, str(o)));
  }

  static public String findTranslators2(String src, List<String> libsOut) {
    return join(findTranslators2(javaTok(src), libsOut));
  }

  static public List<String> findTranslators2(List<String> tok, List<String> libsOut) {
    int i;
    while ((i = jfind(tok, "!<int>")) >= 0) {
      setAdd(libsOut, tok.get(i + 2));
      clearTokens(tok, i, i + 3);
    }
    return tok;
  }

  static public File javaCompile_overInternalBot(String src) {
    return javaCompile_overInternalBot(src, "");
  }

  static synchronized public File javaCompile_overInternalBot(String src, String dehlibs) {
    return CompilerBot.compile(src, dehlibs);
  }

  static public Class hotwireCore(List<File> files) {
    try {
      JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
      Class<?> theClass = classLoader.loadClass("main");
      setOpt(theClass, "__javax", getJavaX());
      if (getOpt(theClass, "programID") == null)
        setOpt(theClass, "programID", "#3999999");
      if (!_inCore())
        hotwire_copyOver(theClass);
      return theClass;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public List<File> loadLibraries(List<String> snippetIDs) {
    return map("loadLibrary", snippetIDs);
  }

  static public boolean hasLetters(String s) {
    for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
      return true;
    return false;
  }

  static public boolean containsLowerCase(String s) {
    for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
      return true;
    return false;
  }

  static public boolean tok_staticFunctionAlwaysReturnsVoid(List<String> tok, String name) {
    Set<String> types = tok_returnTypesOfStaticFunction_uncleaned(tok, name);
    if (empty(types))
      return false;
    for (String type : types) if (!containsOneOf(javaTokC(type), javaxVoidAliases()))
      return false;
    return true;
  }

  static public String textOfStandardFunction_uncached(String sfName) {
    return loadSnippet(stdFunctions_uncached().get(sfName));
  }

  static public String quickSubstring(String s, int i, int j) {
    if (i == j)
      return "";
    return s.substring(i, j);
  }

  static public String md5(String text) {
    try {
      if (text == null)
        return "-";
      return bytesToHex(md5_impl(toUtf8(text)));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String md5(byte[] data) {
    if (data == null)
      return "-";
    return bytesToHex(md5_impl(data));
  }

  static public byte[] md5_impl(byte[] data) {
    try {
      return MessageDigest.getInstance("MD5").digest(data);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String md5(File file) {
    return md5OfFile(file);
  }

  static public String fileNameEncode_safeChars = " ";

  static public String fileNameEncode(String s) {
    s = dropLeadingDots(s);
    StringBuilder buf = new StringBuilder();
    int n = l(s);
    for (int i = 0; i < n; i++) {
      char c = s.charAt(i);
      if (contains(fileNameEncode_safeChars, c))
        buf.append(c);
      else
        buf.append(urlencode(str(c)));
    }
    return str(buf);
  }

  static public <A> AutoCloseable tempDisposeWindow(final Window w) {
    return new AutoCloseable() {

      public void close() {
        disposeWindow(w);
      }
    };
  }

  static public JWindow loadingAnim() {
    return showLoadingAnimation();
  }

  static public JWindow loadingAnim(String text) {
    return showLoadingAnimation(text);
  }

  static public AutoCloseable temp_loadPage_silent() {
    return tempSetThreadLocal(loadPage_silent, true);
  }

  static public Class<?> hotwireSharingLibraries(String progID) {
    try {
      Pair<File, String> p = CompilerBot.compileSnippet2(progID);
      File jar = p.a;
      assertTrue(f2s(jar), jar.isFile());
      List<File> files = ll(jar);
      String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
      List<File> myLibraries = myLibraryFiles();
      Matcher matcher = Pattern.compile("\\d+").matcher(dehlibs);
      while (matcher.find()) {
        String libID = matcher.group();
        File lib = loadLibrary(libID);
        if (myLibraries.contains(lib)) {
        } else {
          files.add(lib);
        }
      }
      JavaXClassLoaderWithParent classLoader = new JavaXClassLoaderWithParent(progID, files, myClassLoader());
      return hotwire_finish(classLoader, progID, p.b);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void preCleanUp(Object c) {
    if (c instanceof Collection) {
      for (Object o : ((Collection) c)) preCleanUp(o);
      return;
    }
    callOpt(c, "licensed_off");
    setOpt(c, "ping_anyActions", true);
    setOpt(c, "cleaningUp_flag", true);
  }

  static public void innerCleanUp(Object c) {
    if (!isFalse(pcallOpt(c, "cleanMeUp")))
      for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try {
        callOpt(c, name);
      } catch (Throwable e) {
        print("Error cleaning up: " + programID(c));
        _handleException(e);
      }
  }

  static public void innerCleanUp() {
    innerCleanUp(mc());
  }

  static public List<Thread> registeredThreads(Object o) {
    Map<Thread, Boolean> map = (Map<Thread, Boolean>) (getOpt(o, "_registerThread_threads"));
    if (map == null)
      return ll();
    map.size();
    synchronized (map) {
      return asList(keys(map));
    }
  }

  static public List<Thread> registeredThreads() {
    _registerThread_threads.size();
    return asList(keys(_registerThread_threads));
  }

  static public void interruptThreads(Collection<Thread> threads) {
    for (Thread t : unnull(threads)) interruptThread(t);
  }

  static public void interruptThreads(Class mainClass) {
    interruptThreads(registeredThreads(mainClass));
  }

  static public void retireClassLoader(ClassLoader cl) {
    if (isJavaXClassLoader(cl))
      setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader());
  }

  static public <A> boolean setAdd(Collection<A> c, A a) {
    if (c == null || c.contains(a))
      return false;
    c.add(a);
    return true;
  }

  static public JavaXClassLoader hotwire_makeClassLoader(List<File> files) {
    Collection<String> toShare = hotwire_classesToShare();
    return nempty(toShare) ? new JavaXClassLoaderWithParent2(null, files, myClassLoader(), cloneList(toShare)) : new JavaXClassLoader(null, files);
  }

  static public boolean isLowerCase(char c) {
    return Character.isLowerCase(c);
  }

  static public Set<String> tok_returnTypesOfStaticFunction_uncleaned(List<String> tok, String functionName) {
    List<List<String>> funcs = findFullFunctionDefs(tok, true);
    TreeSet<String> out = new TreeSet();
    for (List<String> tokF : funcs) {
      int i = indexOfAny(tokF, 0, "(", "{");
      if (i < 0)
        continue;
      String fname = get(tokF, i - 2);
      if (!eq(fname, functionName))
        continue;
      out.add(joinSubList(tokF, 1, i - 3));
    }
    return out;
  }

  static public List<String> javaTokC(String s) {
    if (s == null)
      return null;
    int l = s.length();
    ArrayList<String> tok = new ArrayList();
    int i = 0;
    while (i < l) {
      int j = i;
      char c, d;
      while (j < l) {
        c = s.charAt(j);
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (c == '/' && d == '*') {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (c == '/' && d == '/') {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          if (s.charAt(j) == opener || s.charAt(j) == '\n') {
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
      } else if (Character.isJavaIdentifierStart(c))
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
      else if (Character.isDigit(c)) {
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
        if (j < l && s.charAt(j) == 'L')
          ++j;
      } else if (c == '[' && d == '[') {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
        j = Math.min(j + 3, l);
      } else
        ++j;
      tok.add(javaTok_substringC(s, i, j));
      i = j;
    }
    return tok;
  }

  static public Set<String> javaxVoidAliases_cache;

  static public Set<String> javaxVoidAliases() {
    if (javaxVoidAliases_cache == null)
      javaxVoidAliases_cache = javaxVoidAliases_load();
    return javaxVoidAliases_cache;
  }

  static public Set<String> javaxVoidAliases_load() {
    return litset("void", "svoid");
  }

  static public Map<String, String> stdFunctions_uncached() {
    return stdFunctions_uncached(new HashMap());
  }

  static public Map<String, String> stdFunctions_uncached(Map<String, String> map) {
    parseStdFunctionsList(loadSnippetSilently("#1006654"), map);
    parseStdFunctionsList(loadSnippetSilently("#761"), map);
    return map;
  }

  static public boolean md5OfFile_verbose = false;

  static public String md5OfFile(String path) {
    return md5OfFile(newFile(path));
  }

  static public String md5OfFile(File f) {
    try {
      if (!f.exists())
        return "-";
      if (md5OfFile_verbose)
        print("Getting MD5 of " + f);
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      FileInputStream in = new FileInputStream(f);
      try {
        byte[] buf = new byte[65536];
        int l;
        while (true) {
          l = in.read(buf);
          if (l <= 0)
            break;
          md5.update(buf, 0, l);
        }
        return bytesToHex(md5.digest());
      } finally {
        _close(in);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String dropLeadingDots(String s) {
    int i = 0;
    while (charAt(s, i) == '.') ++i;
    return dropFirst(s, i);
  }

  static public JWindow showLoadingAnimation() {
    return showLoadingAnimation("Hold on user...");
  }

  static public JWindow showLoadingAnimation(String text) {
    try {
      return showAnimationInTopRightCorner("#1003543", text);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public String loadTextFileFromZip(File inZip, String fileName) {
    return loadTextFileFromZipFile(inZip, fileName);
  }

  static public List<File> myLibraryFiles() {
    return asList((Collection<File>) get(myClassLoader(), "files"));
  }

  static public ClassLoader myClassLoader() {
    return _getClass(mc()).getClassLoader();
  }

  static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) {
    return hotwire_finish(classLoader, progID, javaSource, "main");
  }

  static public Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) {
    try {
      Class<?> theClass = classLoader.loadClass(mainClass);
      Class j = getJavaX();
      setOpt(theClass, "myJavaSource_code", javaSource);
      synchronized (j) {
        call(j, "setVars", theClass, progID);
        callOpt(j, "addInstance", progID, theClass);
      }
      hotwire_copyOver(theClass);
      vmBus_send("hotwireFinished", theClass, mc());
      return theClass;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> List<A> sorted(Collection<A> c, Object comparator) {
    List<A> l = cloneList(c);
    sort(l, makeComparator(comparator));
    return l;
  }

  static public <A> List<A> sorted(Collection<A> c) {
    List<A> l = cloneList(c);
    sort(l);
    return l;
  }

  static public <A> List<A> sorted(Comparator<A> comparator, Collection<A> c) {
    List<A> l = cloneList(c);
    sort(l, comparator);
    return l;
  }

  static volatile public PersistableThrowable _handleException_lastException;

  static public List _handleException_onException = synchroList(ll((IVF1<Throwable>) (__1 -> printStackTrace2(__1))));

  static public boolean _handleException_showThreadCancellations = false;

  static public void _handleException(Throwable e) {
    _handleException_lastException = persistableThrowable(e);
    Throwable e2 = innerException(e);
    if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
      if (_handleException_showThreadCancellations)
        System.out.println(getStackTrace_noRecord(e2));
      return;
    }
    for (Object f : cloneList(_handleException_onException)) try {
      callF(f, e);
    } catch (Throwable e3) {
      try {
        printStackTrace2(e3);
      } catch (Throwable e4) {
        System.out.println(getStackTrace(e3));
        System.out.println(getStackTrace(e4));
      }
    }
  }

  static public boolean interruptThread_verbose = false;

  static public void interruptThread(Thread t) {
    if (t == null)
      return;
    if (interruptThread_verbose)
      print("Interrupting thread " + t);
    vm_threadInterruptionReasonsMap().put(t, getStackTrace());
    t.interrupt();
    URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t));
    if (c != null) {
      try {
        print("Closing URLConnection of interrupted thread.");
        call(c, "disconnect");
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
    }
  }

  static public boolean isJavaXClassLoader(ClassLoader cl) {
    return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader");
  }

  static public void setOptAll(Object o, Map<String, Object> fields) {
    if (fields == null)
      return;
    for (String field : keys(fields)) setOpt(o, field, fields.get(field));
  }

  static public void setOptAll(Object o, Object... values) {
    warnIfOddCount(values);
    for (int i = 0; i + 1 < l(values); i += 2) {
      String field = (String) values[i];
      Object value = values[i + 1];
      setOpt(o, field, value);
    }
  }

  static public Set<String> hotwire_classesToShare = synchroSet();

  static public Set<String> hotwire_classesToShare() {
    return hotwire_classesToShare;
  }

  static public Set<String> findFullFunctionDefs_keywords = new HashSet(splitAtSpace("static svoid ssvoid ssynchronized sbool sS sO sL"));

  static public List<List<String>> findFullFunctionDefs(List<String> tok, boolean topLevelOnly) {
    int n = l(tok);
    List<List<String>> functions = new ArrayList();
    for (int i = 1; i < n; i += 2) {
      String t = tok.get(i);
      if (topLevelOnly && eq(t, "{"))
        i = findEndOfBlock(tok, i) - 1;
      else if (findFullFunctionDefs_keywords.contains(t)) {
        int j = i + 2;
        while (j < n && !eqOneOf(tok.get(j), ";", "=", "(", "{")) j += 2;
        if ((eqGet(tok, j, "(") || eq(t, "svoid") && eqGet(tok, j, "{")) && isIdentifier(tok.get(j - 2)) && !contains(subList(tok, i, j), "new")) {
          int k = smartIndexOf(tok, "{", j);
          if (k < l(tok)) {
            k = findEndOfBlock(tok, k) + 1;
            functions.add(subList(tok, i - 1, k));
            i = k - 2;
          }
        }
      }
    }
    return functions;
  }

  static public List<List<String>> findFullFunctionDefs(String s, boolean topLevelOnly) {
    return findFullFunctionDefs(javaTok(s), topLevelOnly);
  }

  static public <A> int indexOfAny(List<A> l, int i, A... x) {
    while (i < l(l)) if (eqOneOf(l.get(i), x))
      return i;
    else
      ++i;
    return -1;
  }

  static public <A> int indexOfAny(List<A> l, Collection<A> x) {
    return indexOfAny(l, 0, x);
  }

  static public <A> int indexOfAny(List<A> l, int i, Collection<A> x) {
    if (nempty(x))
      while (i < l(l)) if (x.contains(l.get(i)))
        return i;
      else
        ++i;
    return -1;
  }

  static public int indexOfAny(String s, int i, String chars) {
    for (; i < l(s); i++) if (chars.indexOf(s.charAt(i)) >= 0)
      return i;
    return -1;
  }

  static public int indexOfAny(String s, String chars) {
    return indexOfAny(s, 0, chars);
  }

  static public Map<String, String> parseStdFunctionsList(String snippetSrc) {
    return parseStdFunctionsList(snippetSrc, new LinkedHashMap());
  }

  static public Map<String, String> parseStdFunctionsList(String snippetSrc, Map<String, String> map) {
    List<String> tok = javaTok(snippetSrc);
    int i = findCodeTokens(tok, "standardFunctions", "=", "litlist", "(");
    int opening = i + 6;
    int closing = indexOf(tok, ")", opening) - 1;
    for (i = opening + 2; i < closing; i += 4) {
      String[] f = unquote(tok.get(i)).split("/");
      map.put(f[1], f[0]);
    }
    return map;
  }

  static public String loadSnippetSilently(Snippet s) {
    return loadSnippetQuietly(s);
  }

  static public String loadSnippetSilently(String snippetID) {
    return loadSnippetQuietly(snippetID);
  }

  static public boolean showAnimationInTopRightCorner_alwaysOnTop = true;

  static public boolean showAnimationInTopRightCorner_on = true;

  static public JWindow showAnimationInTopRightCorner(String imageID, String text) {
    if (isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return showAnimationInTopRightCorner(imageIcon(imageID), text);
  }

  static public JWindow showAnimationInTopRightCorner(final Image image, final String text) {
    if (image == null || isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return showAnimationInTopRightCorner(imageIcon(image), text);
  }

  static public JWindow showAnimationInTopRightCorner(final ImageIcon imageIcon, final String text) {
    if (isHeadless() || !showAnimationInTopRightCorner_on)
      return null;
    return (JWindow) swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          JLabel label = new JLabel(imageIcon);
          if (nempty(text)) {
            label.setText(text);
            label.setVerticalTextPosition(SwingConstants.BOTTOM);
            label.setHorizontalTextPosition(SwingConstants.CENTER);
          }
          final JWindow window = showInTopRightCorner(label);
          onClick(label, new Runnable() {

            public void run() {
              try {
                window.dispose();
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "window.dispose()";
            }
          });
          if (showAnimationInTopRightCorner_alwaysOnTop)
            window.setAlwaysOnTop(true);
          return window;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JLabel label = new JLabel(imageIcon);\r\n    if (nempty(text)) {\r\n      label.s...";
      }
    });
  }

  static public JWindow showAnimationInTopRightCorner(final String imageID) {
    return showAnimationInTopRightCorner(imageID, "");
  }

  static public JWindow showAnimationInTopRightCorner(String imageID, double seconds) {
    return showAnimationInTopRightCorner(imageID, "", seconds);
  }

  static public JWindow showAnimationInTopRightCorner(String imageID, String text, double seconds) {
    if (isHeadless())
      return null;
    return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(imageID, text));
  }

  static public JWindow showAnimationInTopRightCorner(BufferedImage img, String text, double seconds) {
    return disposeWindowAfter(iround(seconds * 1000), showAnimationInTopRightCorner(img, text));
  }

  static public String loadTextFileFromZipFile(File inZip, String fileName) {
    try {
      if (!fileExists(inZip))
        return null;
      try {
        ZipFile zip = new ZipFile(inZip);
        try {
          return loadTextFileFromZipFile(zip, fileName);
        } finally {
          _close(zip);
        }
      } catch (Throwable e) {
        throw fail(f2s(inZip), e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadTextFileFromZipFile(ZipFile zip, String fileName) {
    try {
      ZipEntry entry = zip.getEntry(fileName);
      if (entry == null)
        return null;
      InputStream fin = zip.getInputStream(entry);
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copyStream(fin, baos);
        return fromUTF8(baos.toByteArray());
      } finally {
        _close(fin);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <T> void sort(T[] a, Comparator<? super T> c) {
    if (a != null)
      Arrays.sort(a, c);
  }

  static public <T> void sort(T[] a) {
    if (a != null)
      Arrays.sort(a);
  }

  static public void sort(int[] a) {
    if (a != null)
      Arrays.sort(a);
  }

  static public <T> void sort(List<T> a, Comparator<? super T> c) {
    if (a != null)
      Collections.sort(a, c);
  }

  static public void sort(List a) {
    if (a != null)
      Collections.sort(a);
  }

  static public Comparator makeComparator(final Object f) {
    if (f instanceof Comparator)
      return (Comparator) f;
    return new Comparator() {

      public int compare(Object a, Object b) {
        return (Integer) callF(f, a, b);
      }
    };
  }

  static public Throwable printStackTrace2(Throwable e) {
    print(getStackTrace2(e));
    return e;
  }

  static public void printStackTrace2() {
    printStackTrace2(new Throwable());
  }

  static public void printStackTrace2(String msg) {
    printStackTrace2(new Throwable(msg));
  }

  static public Throwable innerException(Throwable e) {
    return getInnerException(e);
  }

  static public void warnIfOddCount(Object... list) {
    if (odd(l(list)))
      printStackTrace("Odd list size: " + list);
  }

  static public <A> Set<A> synchroSet() {
    return synchroHashSet();
  }

  static public <A> Set<A> synchroSet(Set<A> set) {
    return Collections.synchronizedSet(set);
  }

  static public List<String> splitAtSpace(String s) {
    return empty(s) ? emptyList() : asList(s.split("\\s+"));
  }

  static public JWindow showInTopRightCorner(Component c) {
    return swing(() -> {
      JWindow w = new JWindow();
      w.add(c);
      w.pack();
      moveToTopRightCorner(w);
      w.setVisible(true);
      return w;
    });
  }

  static public String fromUTF8(byte[] bytes) {
    return fromUtf8(bytes);
  }

  static public String getStackTrace2(Throwable e) {
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
  }

  static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
    if (e == null)
      return e;
    while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
    return e;
  }

  static public class EvalJavaPrep {

    public List<String> global = new ArrayList();

    public List<String> outer = new ArrayList();
  }

  static public class JavaXClassLoaderWithParent2 extends JavaXClassLoader {

    public ClassLoader virtualParent;

    public List<String> classesToSkip;

    public JavaXClassLoaderWithParent2(String progID, List<File> files, ClassLoader virtualParent, List<String> classesToSkip) {
      super(progID, files);
      this.virtualParent = virtualParent;
      this.classesToSkip = classesToSkip;
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      if (shouldDelegate(name)) {
        Class<?> c = virtualParent.loadClass(name);
        if (c != null)
          return c;
      }
      return super.findClass(name);
    }

    public boolean shouldDelegate(String name) {
      for (String s : classesToSkip) if (eq(name, s) || startsWith(name, s + "$"))
        return true;
      return false;
    }
  }

  static public class JavaXClassLoader extends URLClassLoader {

    public String progID;

    public Set<File> files = syncLinkedHashSet();

    public Set<String> libraryIDs = syncLinkedHashSet();

    public Set<String> triedToLoad = synchroSet();

    public Set<Class> loadedClasses = synchroSet();

    public boolean retired = false;

    public Object retiredMarker;

    public IF1<String, Class> findClass_extension;

    public String mainClassName;

    public boolean verbose = false;

    public JavaXClassLoader(String progID, List<File> files) {
      this(progID, files, getSystemClassLoader());
    }

    public JavaXClassLoader(String progID, List<File> files, ClassLoader parent) {
      super(new URL[0], parent);
      this.progID = progID;
      for (File f : unnullForIteration(files)) addFile(f);
      fixACCInClassLoader(this);
    }

    public Class<?> super_findClass(String name) throws ClassNotFoundException {
      return super.findClass(name);
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      if (verbose)
        System.out.println(this + " findClass: " + name);
      if (findClass_extension != null) {
        Class<?> c = findClass_extension.get(name);
        if (verbose)
          System.out.println("extension returned: " + c);
        if (c != null)
          return c;
      }
      boolean triedBefore = !triedToLoad.add(name);
      try {
        Class<?> c = super.findClass(name);
        if (verbose)
          System.out.println("super.findClass returned: " + c);
        loadedClasses.add(c);
        if (eq(name, mainClassName()))
          callOpt(javax(), "registerAMainClass", c);
        return c;
      } catch (ClassNotFoundException e) {
        if (verbose)
          System.out.println(getStackTrace(e));
        throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map(__82 -> f2s(__82), files)) + " (progID=" + progID + ")" + (triedBefore ? ", tried to load before" : ""), e);
      }
    }

    public String toString() {
      return shortClassName(this) + "[" + systemHashCodeHex(this) + "] - " + progID;
    }

    public String mainClassName() {
      if (mainClassName == null)
        mainClassName = or2(trim(loadTextFileResource(this, "main-class")), "main");
      return mainClassName;
    }

    public boolean addFile(File f, String libraryID) {
      if (nempty(libraryID))
        if (!libraryIDs.add(libraryID))
          return false;
      return addFile(f);
    }

    public boolean addFile(File f) {
      try {
        if (!files.add(f))
          return false;
        addURL(f.toURI().toURL());
        mainClassName();
        return true;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Set<String> libraryIDs() {
      return libraryIDs;
    }

    public boolean hasLibraryID(String libraryID) {
      return libraryIDs.contains(libraryID);
    }

    transient public IF1<String, String> findLibrary;

    public String findLibrary(String libname) {
      return findLibrary != null ? findLibrary.get(libname) : findLibrary_base(libname);
    }

    final public String findLibrary_fallback(IF1<String, String> _f, String libname) {
      return _f != null ? _f.get(libname) : findLibrary_base(libname);
    }

    public String findLibrary_base(String libname) {
      return super.findLibrary(libname);
    }

    public void addURL(URL url) {
      super.addURL(url);
    }
  }

  static public class DefunctClassLoader {
  }

  static public class JavaXClassLoaderWithParent extends JavaXClassLoader {

    public ClassLoader virtualParent;

    public JavaXClassLoaderWithParent(String progID, List<File> files, ClassLoader virtualParent) {
      super(progID, files);
      this.virtualParent = virtualParent;
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
      if (virtualParent != null && !eq(name, "main") && !name.startsWith("main$")) {
        try {
          return virtualParent.loadClass(name);
        } catch (ClassNotFoundException e) {
        }
      }
      return super.findClass(name);
    }

    public URL findResource(String name) {
      if (virtualParent != null) {
        URL url = virtualParent.getResource(name);
        if (url != null)
          return url;
      }
      return super.findResource(name);
    }

    public ClassLoader getVirtualParent() {
      return virtualParent;
    }
  }

  static public class RightAlignedLine extends JPanel {

    public RightAlignedLine(Component... components) {
      setLayout(LetterLayout.rightAlignedRow());
      for (Component component : components) add(component);
    }

    public void add(String text) {
      add(new JLabel(text));
    }
  }

  static public class CompilerBot {

    static public boolean verbose = false;

    static public File compileSnippet(String snippetID) {
      return compileSnippet(snippetID, "");
    }

    static public Pair<File, String> compileSnippet2(String snippetID) {
      return compileSnippet2(snippetID, "");
    }

    static public File compileSnippet(String snippetID, String javaTarget) {
      return compileSnippet2(snippetID, javaTarget).a;
    }

    static public Pair<File, String> compileSnippet2(String snippetID, String javaTarget) {
      String transpiledSrc = getServerTranspiled2(snippetID);
      if (transpiledSrc == null)
        throw fail("Snippet not found or not public: " + snippetID);
      int i = transpiledSrc.indexOf('\n');
      String libs = transpiledSrc.substring(0, Math.max(0, i));
      if (verbose)
        print("Compiling snippet: " + snippetID + ". Libs: " + libs);
      transpiledSrc = transpiledSrc.substring(i + 1);
      return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc);
    }

    static public File compile(String src) {
      return compile(src, "");
    }

    static public File compile(String src, String libs) {
      return compile(src, libs, null);
    }

    static public File compile(String src, String dehlibs, String javaTarget) {
      return compile(src, dehlibs, javaTarget, null);
    }

    static public File compile(String src, String dehlibs, String javaTarget, String progID) {
      if (verbose)
        print("Compiling " + l(src) + " chars");
      String md5 = md5(dehlibs + "\n" + src + "\n" + fsIOpt(progID));
      File jar = getJarFile(md5);
      if (jar == null || jar.length() <= 22) {
        List<String> tok = javaTok(src);
        List<String> mainClass = findMainClass(tok);
        boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public");
        if (verbose)
          print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID);
        String mainClassName = joinNemptiesWithDot(tok_packageName(tok), or(getClassDeclarationName(mainClass), "main"));
        AutoCloseable __1 = tempSetTL(javaCompileToJar_addMoreFiles, dir -> {
          if (!eq(mainClassName, "main"))
            saveTextFile(newFile(dir, "main-class"), mainClassName);
          saveTextFile(newFile(dir, manifestPathInJar()), manifestTextForMainClass(mainClassName));
        });
        try {
          javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID);
        } finally {
          _close(__1);
        }
      } else {
        if (verbose)
          print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)");
        touchFile(jar);
      }
      return jar;
    }

    static public File getJarFile(String md5) {
      assertTrue(isMD5(md5));
      String fileName = md5 + ".jar";
      File f = newFile(destDir(), fileName);
      return fileExists(f) ? f : userDir(appendSlash(compilerBotDestDirSubName()) + fileName);
    }

    static public File destDir() {
      return compilerBotDestDir();
    }
  }

  static public HashMap<String, Class> findClass_cache = new HashMap();

  static public Class findClass(String name) {
    synchronized (findClass_cache) {
      if (findClass_cache.containsKey(name))
        return findClass_cache.get(name);
      if (!isJavaIdentifier(name))
        return null;
      Class c;
      try {
        c = Class.forName("main$" + name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_cache.put(name, c);
      return c;
    }
  }

  static public <A> Set<A> syncLinkedHashSet() {
    return synchroLinkedHashSet();
  }

  static public void fixACCInClassLoader(Object o) {
  }

  static public String systemHashCodeHex(Object o) {
    return intToHex(identityHashCode(o));
  }

  static public String loadTextFileResource(ClassLoader cl, String name) {
    return inputStreamToString(cl.getResourceAsStream(name));
  }

  static public ClassLoader getVirtualParent(ClassLoader cl) {
    return (ClassLoader) rcallOpt("getVirtualParent", cl);
  }

  static public boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true;

  static public Map<String, String> getServerTranspiled2_tempCache;

  static public String getServerTranspiled2(String id) {
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return rl.getTranspiled(id);
    return getServerTranspiled2_noResourceLoader(id);
  }

  static public String getServerTranspiled2_noResourceLoader(String id) {
    id = fsIOpt(id);
    String transpiled = mapGet(getServerTranspiled2_tempCache, id);
    if (transpiled != null)
      return transpiled;
    transpiled = loadCachedTranspilation(id);
    String md5 = null;
    if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id))
      return transpiled;
    if (transpiled != null)
      md5 = md5(transpiled);
    String transpiledSrc;
    try {
      transpiledSrc = getServerTranspiled(formatSnippetID(id), md5);
    } catch (Throwable e) {
      if (!getServerTranspiled2_allowLocalFallback)
        rethrow(e);
      printExceptionShort(e);
      if (getServerTranspiled2_localFallbackVerbose)
        print("Fallback to local code");
      return transpiled;
    }
    if (eq(transpiledSrc, "SAME")) {
      if (!isTrue(loadPage_silent.get()))
        print("SAME");
      return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiled);
    }
    return mapPut_returnValue(getServerTranspiled2_tempCache, id, transpiledSrc);
  }

  static public String fsIOpt(String s) {
    return formatSnippetIDOpt(s);
  }

  static public List<String> findMainClass(List<String> tok) {
    for (List<String> c : reversedList(allClasses(tok))) {
      String name = getClassDeclarationName(c);
      if (eq(name, "main") || name.startsWith("x"))
        return c;
    }
    return findBlock("m {", tok);
  }

  static public boolean useDummyMainClasses() {
    return true;
  }

  static public boolean tok_classHasModifier(List<String> classDecl, String modifier) {
    if (classDecl == null)
      return false;
    int i = classDecl.indexOf("class");
    return subList(classDecl, 0, i).contains(modifier);
  }

  static public String joinNemptiesWithDot(Object... strings) {
    return joinNempties(".", strings);
  }

  static public String joinNemptiesWithDot(Iterable strings) {
    return joinNempties(".", strings);
  }

  static public String tok_packageName(List<String> tok) {
    int i = jfind(tok, "package");
    if (i < 0)
      return "";
    i += 2;
    int j = jfind(tok, i, ";");
    if (j < 0)
      return "";
    return join(codeTokensOnly(subList(tok, i - 1, j)));
  }

  static public String tok_packageName(String src) {
    Producer<String> p = javaTokC_producer(src);
    String t = p.next();
    if (!eq(t, "package"))
      return "";
    StringBuilder buf = new StringBuilder();
    while (!eqOneOf(t = p.next(), null, ";")) buf.append(t);
    return str(buf);
  }

  static public String getClassDeclarationName(List<String> tok) {
    if (tok != null)
      for (int i = 1; i + 2 < tok.size(); i += 2) if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i + 2))) {
        while (contains(getClassDeclarationName_skippables(), get(tok, i + 2))) i += 2;
        return tok.get(i + 2);
      }
    return null;
  }

  static public String manifestPathInJar() {
    return "META-INF/MANIFEST.MF";
  }

  static public String manifestTextForMainClass(String mainClass) {
    return "Manifest-Version: 1.0\n" + "Main-Class: " + mainClass + "\n\n";
  }

  static public boolean javaCompileToJar_useRAMDisk = false;

  static public ThreadLocal<List<File>> javaCompileToJar_localLibraries = new ThreadLocal();

  static public ThreadLocal<IVF1<File>> javaCompileToJar_addMoreFiles = new ThreadLocal();

  static public File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) {
    return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename);
  }

  static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) {
    return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null);
  }

  static synchronized public File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) {
    String javaTarget = null;
    String dummyClass = "main";
    if (progIDForRename != null) {
      dummyClass = dummyMainClassName(progIDForRename);
      src += "\nclass " + dummyClass + "{}";
    }
    String md5 = md5(src);
    File jar = destJar;
    Class j = getJavaX();
    if (javaTarget != null)
      setOpt(j, "javaTarget", javaTarget);
    File srcDir = tempDir();
    String fileName = dummyClass + ".java";
    List<String> tok = javaTok(src);
    String packageName = tok_packageName(tok);
    if (packageName != null)
      fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java";
    File mainJava = new File(srcDir, fileName);
    saveTextFile(mainJava, src);
    File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir();
    try {
      List<File> libraries = cloneList(getAndClearTL(javaCompileToJar_localLibraries));
      Matcher m = Pattern.compile("\\d+").matcher(dehlibs);
      while (m.find()) {
        String libID = m.group();
        assertTrue(isSnippetID(libID));
        print("Adding library " + libID);
        libraries.add(loadLibraryOrSrcLib(libID));
      }
      libraries.add(pathToJavaxJar());
      String compilerOutput;
      try {
        compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
      } catch (Throwable e) {
        compilerOutput = (String) get(getJavaX(), "javaCompilerOutput");
        compilerOutput = indentx("> ", cleanJavaCompilerOutput(compilerOutput));
        if (!swic(e.getMessage(), "Java compiler returned errors."))
          compilerOutput = appendWithNewLine(compilerOutput, str(e));
        throw fail(compilerOutput, e);
      }
      compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM");
      if (nempty(compilerOutput)) {
        print("Compiler said: " + compilerOutput);
      }
      if (!anyFileWithExtensionInDir(classesDir, ".class")) {
        printWithIndent("SRC> ", src);
        throw fail("No classes generated (was compiling " + nChars(src) + ")");
      }
      saveTextFile(new File(classesDir, "main.java"), src);
      if (nempty(dehlibs))
        saveTextFile(new File(classesDir, "libraries"), dehlibs);
      saveTextFile(new File(classesDir, "progID"), progID);
      callF(javaCompileToJar_addMoreFiles.get(), classesDir);
      dir2zip_recurse_verbose = false;
      int n = dir2zip_recurse(classesDir, jar);
      return jar;
    } finally {
      if (isInRAMDisk(classesDir))
        deleteDirectory(classesDir);
    }
  }

  static public File touchFile(File file) {
    try {
      closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw"));
      return file;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String appendSlash(String s) {
    return addSlash(s);
  }

  static public String compilerBotDestDirSubName() {
    return "JavaX-Caches/Compilations";
  }

  static public File compilerBotDestDir() {
    return actualUserDir(compilerBotDestDirSubName());
  }

  static public HashSet<String> allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord", "strecord", "asclass", "concept");

  static public List<List<String>> allClasses(List<String> tok) {
    List<List<String>> l = new ArrayList();
    int n = tok.size();
    HashSet<String> _allClasses_keywords = allClasses_keywords;
    for (int i = 1; i < n; i += 2) {
      String t = tok.get(i);
      if ("{".equals(t))
        i = findEndOfBlock(tok, i) - 1;
      else if (_allClasses_keywords.contains(t) && (tok_isJavaxMetaCommandLeftOf(tok, i) || !(eqGetOneOf(tok, i - 2, ".", "include") && !containsNewLine(tok.get(i - 1))))) {
        int j = i;
        while (j < n && !tok.get(j).equals("{")) j += 2;
        j = findEndOfBlock(tok, j) + 1;
        i = leftScanModifiers(tok, i);
        l.add(subList(tok, i - 1, Math.min(n, j)));
        i = j - 2;
      }
    }
    return l;
  }

  static public List<List<String>> allClasses(String text) {
    return allClasses(javaTok(text));
  }

  static public <A> Set<A> synchroLinkedHashSet() {
    return Collections.synchronizedSet(new CompactLinkedHashSet());
  }

  static public String intToHex(int i) {
    return bytesToHex(intToBytes(i));
  }

  static public int identityHashCode(Object o) {
    return System.identityHashCode(o);
  }

  static public String inputStreamToString(InputStream in) {
    return utf8streamToString(in);
  }

  static public Object rcallOpt(String method, Object o, Object... args) {
    return callOpt_withVarargs(o, method, args);
  }

  static public String loadCachedTranspilation(String id) {
    try {
      return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
    } catch (Throwable __e) {
      return null;
    }
  }

  static public boolean machineIsOffline() {
    return isFalse(callF(vmGeneralMap_get("areWeOnline")));
  }

  static public boolean isOfflineMode() {
    return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode")));
  }

  static public boolean isLocalSnippet(String snippetID) {
    return isLocalSnippetID(snippetID);
  }

  static public boolean isLocalSnippet(long snippetID) {
    return isLocalSnippetID(snippetID);
  }

  static public String getServerTranspiled(String snippetID) {
    return getServerTranspiled(snippetID, null);
  }

  static public boolean getServerTranspiled_printStackTrace = false;

  static public String getServerTranspiled(String snippetID, String expectedMD5) {
    try {
      if (getServerTranspiled_printStackTrace)
        printStackTrace();
      long id = parseSnippetID(snippetID);
      String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials());
      if (nempty(text) && neq(text, "SAME"))
        saveTranspiledCode(snippetID, text);
      return text;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void printExceptionShort(Throwable e) {
    printExceptionShort("", e);
  }

  static public void printExceptionShort(String prefix, Throwable e) {
    print(prefix, exceptionToStringShort(e));
  }

  static public <A, B> B mapPut_returnValue(Map<A, B> map, A key, B value) {
    mapPut(map, key, value);
    return value;
  }

  static public <A> List<A> reversedList(Iterable<A> l) {
    List<A> x = cloneList(l);
    Collections.reverse(x);
    return x;
  }

  static public List<String> findBlock(String pat, List<String> tok) {
    List<String> tokpat = javaTok(pat);
    int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat)));
    if (i < 0)
      return null;
    int bracketIdx = i + tokpat.size() - 3;
    assertEquals("{", tok.get(bracketIdx));
    int endIdx = findEndOfBlock(tok, bracketIdx);
    return subList(tok, i - 1, endIdx + 1);
  }

  static public List<String> codeTokensOnly(List<String> tok) {
    int n = l(tok);
    List<String> l = emptyList(n / 2);
    for (int i = 1; i < n; i += 2) l.add(tok.get(i));
    return l;
  }

  static public Producer<String> javaTokC_producer(String s) {
    return javaTokC_iterator(s);
  }

  static public Set<String> getClassDeclarationName_skippables_cache;

  static public Set<String> getClassDeclarationName_skippables() {
    if (getClassDeclarationName_skippables_cache == null)
      getClassDeclarationName_skippables_cache = getClassDeclarationName_skippables_load();
    return getClassDeclarationName_skippables_cache;
  }

  static public Set<String> getClassDeclarationName_skippables_load() {
    return litset("noeq", "mapMethodLike");
  }

  static public String dummyMainClassName(String progID) {
    return "m" + psI(progID);
  }

  static public File tempDir() {
    return makeTempDir();
  }

  static public String tok_firstClassName(List<String> tok) {
    int i = jfind(tok, "class <id>");
    return i < 0 ? null : tok.get(i + 2);
  }

  static public File tempDirPossiblyInRAMDisk() {
    File f = linux_fileInRamDisk(aGlobalID());
    if (f != null) {
      f.mkdirs();
      return f;
    }
    return makeTempDir();
  }

  static public <A> A getAndClearTL(ThreadLocal<A> tl) {
    return getAndClearThreadLocal(tl);
  }

  static public boolean loadLibraryOrSrcLib_srcLibsEnabled = true;

  static public ThreadLocal<Map<Long, File>> loadLibraryOrSrcLib_tempCache = new ThreadLocal();

  static public File loadLibraryOrSrcLib(String snippetID) {
    try {
      vmBus_send("loadLibraryOrSrcLib", snippetID);
      long id = parseSnippetID(snippetID);
      if (loadLibraryOrSrcLib_tempCache.get() != null) {
        File f = loadLibraryOrSrcLib_tempCache.get().get(id);
        if (f != null) {
          print(snippetID + " from tempCache: " + f);
          return f;
        }
      }
      boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID);
      if (srcLib) {
        print(snippetID + " marked as src lib, compiling");
        File f = pairA(hotwire_compile(snippetID));
        mapPut(loadLibraryOrSrcLib_tempCache.get(), id, f);
        return f;
      }
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) != 0) {
        print(snippetID + " from disk cache: " + f);
        return f;
      }
      try {
        print("Trying " + snippetID + " as binary library");
        return loadDataSnippetToFile(snippetID);
      } catch (Throwable e) {
        if (loadLibraryOrSrcLib_srcLibsEnabled) {
          print("Trying " + snippetID + " as src lib");
          if (nempty(loadSnippet(snippetID))) {
            print("Is src lib.");
            markAsSrcLib(snippetID);
            return pairA(hotwire_compile(snippetID));
          }
        }
        throw rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String cleanJavaCompilerOutput(String s) {
    return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s);
  }

  static public String appendWithNewLine(String a, String b) {
    if (empty(b))
      return a;
    if (empty(a))
      return b;
    return addSuffix(a, "\n") + b;
  }

  static public boolean anyFileWithExtensionInDir(File dir, String ext) {
    return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir)));
  }

  static public String nChars(long n) {
    return n2(n, "char");
  }

  static public String nChars(String s) {
    return nChars(l(s));
  }

  static public boolean dir2zip_recurse_verbose = false;

  static public int dir2zip_recurse(File inDir, File zip) {
    return dir2zip_recurse(inDir, zip, "");
  }

  static public int dir2zip_recurse(File inDir, File zip, String outPrefix) {
    try {
      mkdirsForFile(zip);
      FileOutputStream fout = newFileOutputStream(zip);
      ZipOutputStream outZip = new ZipOutputStream(fout);
      try {
        return dir2zip_recurse(inDir, outZip, outPrefix, 0);
      } finally {
        outZip.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public int dir2zip_recurse(File inDir, ZipOutputStream outZip) {
    return dir2zip_recurse(inDir, outZip, "", 0);
  }

  static public int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) {
    try {
      if (++level >= 20)
        throw fail("woot? 20 levels in zip?");
      List<File> files = new ArrayList();
      for (File f : listFiles(inDir)) files.add(f);
      int n = 0;
      sortFilesByName(files);
      for (File f : files) {
        if (f.isDirectory()) {
          if (dir2zip_recurse_verbose)
            print("dir2zip_recurse: Scanning " + f.getAbsolutePath());
          n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level);
        } else {
          if (dir2zip_recurse_verbose)
            print("Copying " + f.getName());
          outZip.putNextEntry(new ZipEntry(outPrefix + f.getName()));
          InputStream fin = new FileInputStream(f);
          copyStream(fin, outZip);
          fin.close();
          ++n;
        }
      }
      return n;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isInRAMDisk(File f) {
    return startsWithOneOf(f2s(f), "/dev/shm/", "/run/shm/");
  }

  static public void deleteDirectory(File dir) {
    deleteDirectory(dir, false, false);
  }

  static public void deleteDirectory(File dir, boolean verbose, boolean testRun) {
    deleteAllFilesInDirectory(dir, verbose, testRun);
    if (verbose)
      print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath());
    if (!testRun)
      dir.delete();
  }

  static public void closeRandomAccessFile(RandomAccessFile f) {
    if (f != null)
      try {
        f.close();
        callJavaX("dropIO", f);
      } catch (Throwable e) {
        printStackTrace(e);
      }
  }

  static public RandomAccessFile newRandomAccessFile(File path, String mode) {
    try {
      boolean forWrite = mode.indexOf('w') >= 0;
      if (forWrite)
        mkdirsForFile(path);
      RandomAccessFile f = new RandomAccessFile(path, mode);
      callJavaX("registerIO", f, path, forWrite);
      return f;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String addSlash(String s) {
    return empty(s) || s.endsWith("/") ? s : s + "/";
  }

  static public File actualUserDir() {
    return new File(actualUserHome());
  }

  static public File actualUserDir(String path) {
    return new File(actualUserHome(), path);
  }

  static public boolean tok_isJavaxMetaCommandLeftOf(List<String> tok, int i) {
    int j = i - 2 * 4 - 1;
    if (j >= 0 && jfind(subList(tok, j, i), "set flag <id> .") == 1)
      return true;
    return false;
  }

  static public <A> boolean eqGetOneOf(List<A> l, int i, A... options) {
    return eqOneOf(get(l, i), options);
  }

  static public int leftScanModifiers(List<String> tok, int i) {
    List<String> mod = getJavaModifiers();
    while (i > 1 && mod.contains(tok.get(i - 2))) i -= 2;
    return i;
  }

  static public byte[] intToBytes(int i) {
    return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i };
  }

  static public String utf8streamToString(InputStream in) {
    return readerToString(utf8bufferedReader(in));
  }

  static public Object callOpt_withVarargs(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me == null) {
          return null;
        }
        if ((me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me != null)
          return invokeMethod(me, o, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, o, newArgs);
          }
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadTextFilePossiblyGZipped(String fileName) {
    return loadTextFilePossiblyGZipped(fileName, null);
  }

  static public String loadTextFilePossiblyGZipped(String fileName, String defaultContents) {
    File gz = new File(fileName + ".gz");
    return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents);
  }

  static public String loadTextFilePossiblyGZipped(File fileName) {
    return loadTextFilePossiblyGZipped(fileName, null);
  }

  static public String loadTextFilePossiblyGZipped(File fileName, String defaultContents) {
    return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents);
  }

  static public File getCachedTranspilationFile(String id) {
    return newFile(getCodeProgramDir(id), "Transpilation");
  }

  static public Object vmGeneralMap_get(Object key) {
    return vm_generalMap_get(key);
  }

  static public String loadProgramTextFile(String name) {
    return loadTextFile(getProgramFile(name));
  }

  static public String loadProgramTextFile(String progID, String name) {
    return loadTextFile(getProgramFile(progID, name));
  }

  static public String loadProgramTextFile(String progID, String name, String defaultText) {
    return loadTextFile(getProgramFile(progID, name), defaultText);
  }

  static public void saveTranspiledCode(String progID, String code) {
    File dir = getCodeProgramDir(progID);
    new File(dir, "Transpilation").delete();
    saveGZTextFile(new File(dir, "Transpilation.gz"), code);
  }

  static public <A, B> void mapPut(Map<A, B> map, A key, B value) {
    if (map != null && key != null && value != null)
      map.put(key, value);
  }

  static public <A, B> void mapPut(Map<A, B> map, Pair<A, B> p) {
    if (map != null && p != null)
      map.put(p.a, p.b);
  }

  static public Producer<String> javaTokC_iterator(String s) {
    return new Producer<String>() {

      final public int l = strL(s);

      public int i = 0;

      public String next() {
        if (i >= l)
          return null;
        int j = i;
        char c, d;
        while (j < l) {
          c = s.charAt(j);
          d = j + 1 >= l ? '\0' : s.charAt(j + 1);
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            ++j;
          else if (c == '/' && d == '*') {
            do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
            j = Math.min(j + 2, l);
          } else if (c == '/' && d == '/') {
            do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
          } else
            break;
        }
        i = j;
        if (i >= l)
          return null;
        c = s.charAt(i);
        d = i + 1 >= l ? '\0' : s.charAt(i + 1);
        if (c == '\'' || c == '"') {
          char opener = c;
          ++j;
          while (j < l) {
            if (s.charAt(j) == opener || s.charAt(j) == '\n') {
              ++j;
              break;
            } else if (s.charAt(j) == '\\' && j + 1 < l)
              j += 2;
            else
              ++j;
          }
        } else if (Character.isJavaIdentifierStart(c))
          do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
        else if (Character.isDigit(c)) {
          do ++j; while (j < l && Character.isDigit(s.charAt(j)));
          if (j < l && s.charAt(j) == 'L')
            ++j;
        } else if (c == '[' && d == '[') {
          do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
          j = Math.min(j + 2, l);
        } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
          do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
          j = Math.min(j + 3, l);
        } else
          ++j;
        String t = quickSubstring(s, i, j);
        i = j;
        return t;
      }
    };
  }

  static public File makeTempDir() {
    return (File) call(getJavaX(), "TempDirMaker_make");
  }

  static public String aGlobalID() {
    return randomID(globalIDLength());
  }

  static public String aGlobalID(Random random) {
    return randomID(random, globalIDLength());
  }

  static public boolean isMarkedAsSrcLib(String snippetID) {
    if (snippetID == null)
      return false;
    IResourceLoader rl = vm_getResourceLoader();
    if (rl != null)
      return isJavaxCompilableSnippetType(rl.getSnippetType(snippetID));
    return fileExists(javaxCodeDir("srclibs/" + psI(snippetID)));
  }

  static public <A, B> A pairA(Pair<A, B> p) {
    return p == null ? null : p.a;
  }

  static public Object hotwire_onCompile;

  static public boolean hotwire_serially = false;

  static public Lock hotwire_overInternalBot_lock = lock();

  static public boolean hotwire_compileOnServer = false;

  static public Class<?> hotwire_overInternalBot(String progID) {
    return hotwire_overInternalBot(progID, "main");
  }

  static public Class<?> hotwire_overInternalBot(String progID, String mainClass) {
    return hotwire_overInternalBot(progID, __ -> mainClass);
  }

  static public Class<?> hotwire_overInternalBot(String progID, IF1<ClassLoader, String> calculateMainClass) {
    try {
      Pair<File, String> p;
      try {
        p = hotwire_compile(progID);
      } catch (Throwable e) {
        throw rethrow("Error hotwiring " + progID, e);
      }
      File jar = p.a;
      assertTrue(jar.getAbsolutePath(), jar.isFile());
      List<File> files = hotwire_collectJars(jar);
      JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
      classLoader.progID = progID;
      String mainClass = calculateMainClass == null ? "main" : calculateMainClass.get(classLoader);
      return hotwire_finish(classLoader, progID, p.b, mainClass);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Pair<File, String> hotwire_compile(String progID) {
    Pair<File, String> p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID);
    Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null;
    lock(__0);
    try {
      callF(hotwire_onCompile, p);
      return p;
    } finally {
      unlock(__0);
    }
  }

  static public void markAsSrcLib(String snippetID) {
    saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), "");
  }

  static public String dropPrefixTrim(String prefix, String s) {
    return trim(dropPrefix(prefix, s));
  }

  static public List<File> filesWithExtension(String ext, List<File> files) {
    return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext));
  }

  static public List<File> findAllFiles_noDirs(List dirs) {
    return findAllFiles_noDirs(asObjectArray(dirs));
  }

  static public List<File> findAllFiles_noDirs(Object... dirs) {
    List<File> l = new ArrayList();
    for (Object dir : dirs) {
      ping();
      if (dir instanceof String && ((String) dir).endsWith("/.")) {
        for (File f : listFiles(dropSuffix("/.", ((String) dir)))) {
          ping();
          if (f.isFile())
            l.add(f);
        }
      } else
        findAllFiles_noDirs_impl(toFile(dir), l);
    }
    return l;
  }

  static public void findAllFiles_noDirs_impl(File dir, List<File> l) {
    for (File f : listFiles(dir)) {
      ping();
      if (f.isDirectory())
        findAllFiles_noDirs_impl(f, l);
      else
        l.add(f);
    }
  }

  static public List<File> sortFilesByName(List<File> l) {
    sort(l, (a, b) -> stdcompare(a.getName(), b.getName()));
    return l;
  }

  static public int deleteAllFilesInDirectory_minPathLength = 10;

  static public void deleteAllFilesInDirectory(File dir) {
    deleteAllFilesInDirectory(dir, false, false);
  }

  static public void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) {
    dir = getCanonicalFile(dir);
    assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength);
    File[] files = dir.listFiles();
    if (files == null)
      return;
    for (File f : files) {
      if (!isSymLink(f) && f.isDirectory())
        deleteDirectory(f, verbose, testRun);
      else {
        if (verbose)
          print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath());
        if (!testRun)
          f.delete();
      }
    }
  }

  static public Object callJavaX(String method, Object... args) {
    return callOpt(getJavaX(), method, args);
  }

  static public List<String> getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient", "default");

  static public List<String> getJavaModifiers() {
    return getJavaModifiers_list;
  }

  static public String readerToString(Reader r) {
    try {
      if (r == null)
        return null;
      try {
        StringBuilder buf = new StringBuilder();
        int n = 0;
        while (true) {
          int ch = r.read();
          if (ch < 0)
            break;
          buf.append((char) ch);
          ++n;
        }
        return buf.toString();
      } finally {
        r.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String loadGZTextFile(File file) {
    try {
      if (!file.isFile())
        return null;
      ping();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      InputStream fis = new FileInputStream(file);
      try {
        GZIPInputStream gis = newGZIPInputStream(fis);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = gis.read(buffer)) != -1) baos.write(buffer, 0, len);
        baos.close();
        return fromUtf8(baos.toByteArray());
      } finally {
        _close(fis);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File getCodeProgramDir() {
    return getCodeProgramDir(getProgramID());
  }

  static public File getCodeProgramDir(String snippetID) {
    return new File(javaxCodeDir(), formatSnippetID(snippetID));
  }

  static public File getCodeProgramDir(long snippetID) {
    return getCodeProgramDir(formatSnippetID(snippetID));
  }

  static public int globalIDLength() {
    return 16;
  }

  static public boolean isJavaxCompilableSnippetType(int type) {
    return isJavaxCompilableSnippetTypeExceptInclude(type) || type == javaxIncludeSnippetType();
  }

  static public List<File> hotwire_collectJars(File jar) {
    List<String> libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar);
    List<File> files = ll(jar);
    for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID));
    return files;
  }

  static public Pair<File, String> compileSnippetThroughServer(String progID) {
    String transpiledSrc = getServerTranspiled2(progID);
    String md5 = md5(transpiledSrc + "\n" + progID);
    File jar = CompilerBot.getJarFile(md5);
    if (jar == null || jar.length() <= 22) {
      byte[] jarData = null;
      boolean dontLoad = false;
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null) {
        dontLoad = true;
        File jar2 = rl.getSnippetJar(progID, transpiledSrc);
        if (jar2 != null)
          return pair(jar2, transpiledSrc);
      }
      if (!dontLoad) {
        try {
          jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc));
        } catch (Throwable __e) {
          printStackTrace(__e);
        }
      }
      if (!isJAR(jarData)) {
        if (jarData != null) {
          print(bytesToHex(takeFirstOfByteArray(8, jarData)));
          print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData)));
        }
        return CompilerBot.compileSnippet2(progID);
      }
      saveBinaryFile(jar, jarData);
    }
    return pair(jar, transpiledSrc);
  }

  static public List<File> filesEndingWith(File dir, String suffix) {
    return listFilesWithSuffix(dir, suffix);
  }

  static public List<File> filesEndingWith(List<File> l, String suffix) {
    List<File> out = new ArrayList();
    for (File f : unnull(l)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      out.add(f);
    return out;
  }

  static public List<File> filesEndingWith(String suffix, File dir) {
    return filesEndingWith(dir, suffix);
  }

  static public File toFile(Object o) {
    if (o instanceof File)
      return (File) o;
    if (o instanceof String)
      return new File((String) o);
    throw fail("Not a file: " + o);
  }

  static public int stdcompare(Number a, Number b) {
    return cmp(a, b);
  }

  static public int stdcompare(String a, String b) {
    return cmp(a, b);
  }

  static public int stdcompare(long a, long b) {
    return a < b ? -1 : a > b ? 1 : 0;
  }

  static public int stdcompare(Object a, Object b) {
    return cmp(a, b);
  }

  static public File getCanonicalFile(File f) {
    try {
      return f == null ? null : f.getCanonicalFile();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isSymLink(File f) {
    return f != null && Files.isSymbolicLink(toPath(f));
  }

  static public boolean isJavaxCompilableSnippetTypeExceptInclude(int type) {
    return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule();
  }

  static public int javaxIncludeSnippetType() {
    return 42;
  }

  static public List<String> hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) {
    try {
      return hotwire_libraryIDsFromJar(jar);
    } catch (Throwable _e) {
      jar.delete();
      throw rethrow(_e);
    }
  }

  static public byte[] isJAR_magic = bytesFromHex("504B0304");

  static public boolean isJAR(byte[] data) {
    return byteArrayStartsWith(data, isJAR_magic);
  }

  static public boolean isJAR(File f) {
    return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic)));
  }

  static public List<File> listFilesWithSuffix(File dir, String suffix) {
    List<File> l = new ArrayList();
    for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
      l.add(f);
    return l;
  }

  static public Path toPath(File f) {
    return f == null ? null : f.toPath();
  }

  static public boolean isJavaxApplicationSnippetType(int type) {
    return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop();
  }

  static public boolean isJavaxModuleSnippetType(int type) {
    return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule();
  }

  static public int snippetType_dynModule() {
    return 57;
  }

  static public List<String> hotwire_libraryIDsFromJar(File jar) {
    String dehlibs = unnull(loadTextFileFromZip(jar, "libraries"));
    return regexpExtractAll("\\d+", dehlibs);
  }

  static public int snippetType_javaxSource() {
    return 34;
  }

  static public int snippetType_JavaXDesktop() {
    return 55;
  }

  static public int snippetType_javaxModule() {
    return 54;
  }

  static public int snippetType_javaxDesktopModule() {
    return 58;
  }

  static public List<String> regexpExtractAll(String pat, String s) {
    if (s == null)
      return null;
    Matcher m = regexpMatcher(pat, s);
    List<String> out = new ArrayList();
    while (m.find()) out.add(m.group());
    return out;
  }

  static public interface Producer<A> {

    public A next();
  }
}