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.fail;
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 static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
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.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
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.structure_ClassInfo;
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.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.TitledBorder;
import javax.swing.border.*;
import java.awt.datatransfer.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;

class main {

  static public String chatBotID = "#1026221";

  static public class MultiComm extends DynMultiComm {

    public void blablu() {
    }

    public void start() {
      try {
        super.start();
        dm_vmBus_onMessage_q("chatBot_userPolling", new VF2<Object, Object>() {

          public void get(Object mc, Object conv) {
            try {
              Customer c = customerFromConv(mc, conv);
              if (c == null)
                return;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "Customer c = customerFromConv(mc, conv);\r\n      if (c == null) ret;";
          }
        });
        dm_vmBus_onMessage_q("chatBot_messageAdded", new VF3<Object, Object, Object>() {

          public void get(Object mc, Object conv, Object msg) {
            try {
              Customer c = customerFromConv(mc, conv);
              if (c == null)
                return;
              String text = getString("text", msg);
              boolean fromUser = getBool("fromUser", msg);
              if (fromUser)
                cnew(IncomingMessage.class, "customer", c, "text", text, "unread", true);
              else
                cnew(OutgoingMessage.class, "customer", c, "text", text);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "Customer c = customerFromConv(mc, conv);\r\n      if (c == null) ret;\r\n      S ...";
          }
        });
        dm_registerAs_direct("iptvMultiComm");
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public Customer customerFromConv(Object mc, Object conv) {
      String cookie = getString("cookie", conv);
      if (empty(cookie))
        return null;
      Customer c = uniq(Customer.class, "cookie", cookie);
      cset(c, "ip", getString("ip", conv));
      cset(c, "lastPing", now(), "botConversationID", new BotConversationID(programID(mc), getLong("id", conv)));
      return c;
    }
  }

  static public boolean _moduleClass_MultiComm = true;

  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 void _onLoad_initUtils() {
    utils.__javax = javax();
  }

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

      public Class get(String name) {
        try {
          Class c = findClass_fullName(name);
          if (c != null)
            return c;
          if (startsWith(name, "main$"))
            return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Class c = findClass_fullName(name);\r\n    if (c != null) ret c;\r\n    if (start...";
      }
    });
  }

  static public String programID() {
    return getProgramID();
  }

  static public String programID(Object o) {
    return getProgramID(o);
  }

  static volatile public StringBuffer local_log = new StringBuffer();

  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((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
    return o;
  }

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

  static public void print_noNewLine(String s) {
    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;
    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);
  }

  static public void print_autoRotate() {
  }

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

  static public <A> AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF1<A> onMessage) {
    final DynModule m = dm_current_mandatory();
    return dm_vmBus_onMessage(msg, new VF1<A>() {

      public void get(final A a) {
        try {
          m.q().add(new Runnable() {

            public void run() {
              try {
                callF(onMessage, a);
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "callF(onMessage, a);";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "switch to m.q();\r\n    callF(onMessage, a);";
      }
    });
  }

  static public <A, B> AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF2<A, B> onMessage) {
    final DynModule m = dm_current_mandatory();
    return dm_vmBus_onMessage(msg, new VF2<A, B>() {

      public void get(final A a, final B b) {
        try {
          m.q().add(new Runnable() {

            public void run() {
              try {
                callF(onMessage, a, b);
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "callF(onMessage, a, b);";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "switch to m.q();\r\n    callF(onMessage, a, b);";
      }
    });
  }

  static public <A, B, C> AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF3<A, B, C> onMessage) {
    final DynModule m = dm_current_mandatory();
    return dm_vmBus_onMessage(msg, new VF3<A, B, C>() {

      public void get(final A a, final B b, final C c) {
        try {
          m.q().add(new Runnable() {

            public void run() {
              try {
                callF(onMessage, a, b, c);
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "callF(onMessage, a, b, c);";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "switch to m.q();\r\n    callF(onMessage, a, b, c);";
      }
    });
  }

  static public <A> AutoCloseable dm_vmBus_onMessage_q(final String msg, final Runnable onMessage) {
    final DynModule m = dm_current_mandatory();
    return dm_vmBus_onMessage(msg, new VF1<A>() {

      public void get(final A a) {
        try {
          m.q().add(new Runnable() {

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

            public String toString() {
              return "callF(onMessage);";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "switch to m.q();\r\n    callF(onMessage);";
      }
    });
  }

  static public RuntimeException rethrow(Throwable t) {
    if (t instanceof Error)
      _handleError((Error) t);
    throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
  }

  static public RuntimeException rethrow(String msg, Throwable t) {
    throw new RuntimeException(msg, t);
  }

  static public String getString(Map map, Object key) {
    return map == null ? null : (String) map.get(key);
  }

  static public String getString(List l, int idx) {
    return (String) get(l, idx);
  }

  static public String getString(Object o, Object key) {
    if (o instanceof Map)
      return getString((Map) o, key);
    if (key instanceof String)
      return (String) getOpt(o, (String) key);
    throw fail("Not a string key: " + getClassName(key));
  }

  static public String getString(String key, Object o) {
    return getString(o, (Object) key);
  }

  static public boolean getBool(Object o, String field) {
    return isTrue(getOpt(o, field));
  }

  static public boolean getBool(String field, Object o) {
    return getBool(o, field);
  }

  static public Concept cnew(String name, Object... values) {
    Class<? extends Concept> cc = findClass(name);
    Concept c = cc != null ? nuObject(cc) : new Concept(name);
    csetAll(c, values);
    return c;
  }

  static public Concept cnew(Concepts concepts, String name, Object... values) {
    Class<? extends Concept> cc = findClass(name);
    concepts_unlisted.set(true);
    Concept c;
    try {
      c = cc != null ? nuObject(cc) : new Concept(name);
    } finally {
      concepts_unlisted.set(null);
    }
    concepts.register(c);
    csetAll(c, values);
    return c;
  }

  static public <A extends Concept> A cnew(Class<A> cc, Object... values) {
    A c = nuObject(cc);
    csetAll(c, values);
    return c;
  }

  static public <A extends Concept> A cnew(Concepts concepts, Class<A> cc, Object... values) {
    concepts_unlisted.set(true);
    A c;
    try {
      c = nuObject(cc);
    } finally {
      concepts_unlisted.set(null);
    }
    concepts.register(c);
    csetAll(c, values);
    return c;
  }

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

  static public boolean empty(Collection c) {
    return c == null || c.isEmpty();
  }

  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(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(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(File f) {
    return getFileSize(f) == 0;
  }

  static public <A extends Concept> A uniq(Class<A> c, Object... params) {
    return uniqueConcept(c, params);
  }

  static public <A extends Concept> A uniq(Concepts cc, Class<A> c, Object... params) {
    return uniqueConcept(cc, c, params);
  }

  static public long now_virtualTime;

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

  static public long getLong(Object o, String field) {
    return toLong(getOpt(o, field));
  }

  static public long getLong(String field, Object o) {
    return getLong(o, field);
  }

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

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

  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 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 boolean startsWith(String a, String b) {
    return a != null && a.startsWith(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;
    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 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;
    if (x >= s.length())
      return "";
    if (y < x)
      y = x;
    if (y > s.length())
      y = s.length();
    return s.substring(x, y);
  }

  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public String programID;

  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 boolean endsWithLetterOrDigit(String s) {
    return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
  }

  static public void ping_okInCleanUp() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
  }

  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 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 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> AutoCloseable dm_vmBus_onMessage(final String msg, final VF1<A> onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

  static public <A, B> AutoCloseable dm_vmBus_onMessage(String msg, final VF2<A, B> onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

  static public <A, B, C> AutoCloseable dm_vmBus_onMessage(String msg, final VF3<A, B, C> onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

  static public AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) {
    return dm_ownResource(vmBus_onMessage(msg, onMessage));
  }

  static public void _handleError(Error e) {
    call(javax(), "_handleError", e);
  }

  static public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  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 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 int csetAll(Concept c, Object... values) {
    return cset(c, values);
  }

  static public int csetAll(Iterable<? extends Concept> l, Object... values) {
    int n = 0;
    for (Concept c : unnull(l)) n += cset(c, values);
    return n;
  }

  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 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 <A extends Concept> A uniqueConcept(Class<A> c, Object... params) {
    return uniqueConcept(db_mainConcepts(), c, params);
  }

  static public <A extends Concept> A uniqueConcept(Concepts cc, Class<A> c, Object... params) {
    AutoCloseable __0 = tempDBLock(cc);
    try {
      params = expandParams(c, params);
      A x = findConceptWhere(cc, c, params);
      if (x == null) {
        x = unlisted(c);
        csetAll(x, params);
        cc.register(x);
      }
      return x;
    } finally {
      _close(__0);
    }
  }

  static public long toLong(Object o) {
    if (o instanceof Number)
      return ((Number) o).longValue();
    if (o instanceof String)
      return parseLong((String) o);
    return 0;
  }

  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) {
    synchronized (callOpt_cache) {
      _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(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 Class __javax;

  static public Class getJavaX() {
    try {
      return __javax;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean nemptyString(String s) {
    return s != null && s.length() > 0;
  }

  static public int strL(String s) {
    return s == null ? 0 : s.length();
  }

  static public int listL(Collection l) {
    return l == null ? 0 : l.size();
  }

  static public boolean neq(Object a, Object b) {
    return !eq(a, b);
  }

  static public Object defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        try {
          Class c = findClass_fullName(name);
          if (c != null)
            return c;
          if (startsWith(name, "loadableUtils.utils$"))
            return findClass_fullName("main" + substring(name, 19));
          return null;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "Class c = findClass_fullName(name);\r\n    if (c != null) ret c;\r\n    if (start...";
      }
    };
  }

  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(Map m) {
    return !empty(m);
  }

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

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

  static public String formatSnippetIDOpt(String s) {
    return isSnippetID(s) ? formatSnippetID(s) : s;
  }

  static public String formatSnippetID(String id) {
    return "#" + parseSnippetID(id);
  }

  static public String formatSnippetID(long id) {
    return "#" + id;
  }

  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;
      return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static volatile public boolean ping_pauseAll = false;

  static public int ping_sleep = 100;

  static volatile public boolean ping_anyActions = false;

  static public Map<Thread, Object> ping_actions = newWeakHashMap();

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

  static public boolean ping() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    try {
      if (ping_pauseAll && !isAWTThread()) {
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
        return true;
      }
      if (ping_anyActions) {
        if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
          failIfUnlicensed();
        Object action = null;
        synchronized (ping_actions) {
          if (!ping_actions.isEmpty()) {
            action = ping_actions.get(currentThread());
            if (action instanceof Runnable)
              ping_actions.remove(currentThread());
            if (ping_actions.isEmpty())
              ping_anyActions = false;
          }
        }
        if (action instanceof Runnable)
          ((Runnable) action).run();
        else if (eq(action, "cancelled"))
          throw fail("Thread cancelled.");
      }
      return false;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

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

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

  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 <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 extends AutoCloseable> A dm_ownResource(A resource) {
    dm_currentModuleMandatory().ownResource(resource);
    return resource;
  }

  static public <A> AutoCloseable vmBus_onMessage(final String msg, final VF1<A> onMessage) {
    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, new VF2<String, Object>() {

        public void get(String _msg, Object arg) {
          try {
            callF(onMessage, arg);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(onMessage, arg)";
        }
      });
    }
  }

  static public <A, B> AutoCloseable vmBus_onMessage(String msg, final VF2<A, B> onMessage) {
    return vmBus_onMessage(msg, new VF1<Object[]>() {

      public void get(Object[] o) {
        try {
          callF(onMessage, first(o), second(o));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onMessage, first(o), second(o));";
      }
    });
  }

  static public <A, B, C> AutoCloseable vmBus_onMessage(String msg, final VF3<A, B, C> onMessage) {
    return vmBus_onMessage(msg, new VF1<Object[]>() {

      public void get(Object[] o) {
        try {
          callF(onMessage, first(o), second(o), third(o));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onMessage, first(o), second(o), third(o));";
      }
    });
  }

  static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
    return vmBus_onMessage(msg, runnableToVF1(onMessage));
  }

  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 Map<String, Class> classForName_cache = synchroHashMap();

  static public Class classForName(String name) {
    try {
      if (classForName_cache == null)
        return Class.forName(name);
      Class c = classForName_cache.get(name);
      if (c == null)
        classForName_cache.put(name, c = Class.forName(name));
      return c;
    } 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 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 <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[]) new Object[0] : 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 <A, B> Pair<A, B> unnull(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
    return a == null ? b : b == null ? a : new AutoCloseable() {

      public String toString() {
        return "a.close(); b.close();";
      }

      public void close() throws Exception {
        a.close();
        b.close();
      }
    };
  }

  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 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) 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) 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) 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) 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()) {
        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 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 __0 = m.enter();
          try {
            return callF(f);
          } finally {
            _close(__0);
          }
        } 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 __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 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 __2 = m.enter();
          try {
            return callF(f, arg);
          } finally {
            _close(__2);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "temp m.enter();\r\n    ret callF(f, arg);";
      }
    }));
  }

  static public <A> F0<A> fConst(A a) {
    return f0_const(a);
  }

  static volatile public Concepts mainConcepts;

  static public Concepts db_mainConcepts() {
    if (mainConcepts == null) {
      mainConcepts = new Concepts(getDBProgramID());
      mainConcepts.classFinder = _defaultClassFinder();
    }
    return mainConcepts;
  }

  static public AutoCloseable tempDBLock(Concepts concepts) {
    return tempLock(concepts.lock);
  }

  static public AutoCloseable tempDBLock() {
    return tempDBLock(db_mainConcepts());
  }

  static public <A extends Concept> Object[] expandParams(Class<A> c, Object[] params) {
    if (l(params) == 1)
      params = new Object[] { singleFieldName(c), params[0] };
    else
      warnIfOddCount(params);
    return params;
  }

  static public <A extends Concept> A findConceptWhere(Class<A> c, Object... params) {
    return findConceptWhere(db_mainConcepts(), c, params);
  }

  static public <A extends Concept> A findConceptWhere(Concepts concepts, Class<A> c, Object... params) {
    params = expandParams(c, params);
    if (concepts.fieldIndices != null)
      for (int i = 0; i < l(params); i += 2) {
        IFieldIndex<A, Object> index = concepts.getFieldIndex(c, (String) params[i]);
        if (index != null) {
          for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params))
            return x;
          return null;
        }
      }
    for (A x : concepts.list(c)) if (checkConceptFields(x, params))
      return x;
    return null;
  }

  static public Concept findConceptWhere(Concepts concepts, String c, Object... params) {
    for (Concept x : concepts.list(c)) if (checkConceptFields(x, params))
      return x;
    return null;
  }

  static public <A extends Concept> A unlisted(Class<A> c, Object... args) {
    concepts_unlisted.set(true);
    try {
      return nuObject(c, args);
    } finally {
      concepts_unlisted.set(null);
    }
  }

  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 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 Throwable getExceptionCause(Throwable e) {
    Throwable c = e.getCause();
    return c != null ? c : e;
  }

  static public String joinWithSpace(Collection<String> 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, 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);
  }

  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));
  }

  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 String str(Object o) {
    return o == null ? "null" : o.toString();
  }

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

  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;
  }

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

  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 isAWTThread() {
    if (isAndroid())
      return false;
    if (isHeadless())
      return false;
    return isAWTThread_awt();
  }

  static public boolean isAWTThread_awt() {
    return SwingUtilities.isEventDispatchThread();
  }

  static public void failIfUnlicensed() {
    assertTrue("license off", licensed());
  }

  static public Thread currentThread() {
    return Thread.currentThread();
  }

  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 DynModule dm_currentModuleMandatory() {
    return dm_current_mandatory();
  }

  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 <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 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> 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 <A, B> A first(Pair<A, B> p) {
    return p == null ? null : p.a;
  }

  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> 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> A third(List<A> l) {
    return _get(l, 2);
  }

  static public <A> A third(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      if (!it.hasNext())
        return null;
      it.next();
    }
    return it.hasNext() ? it.next() : null;
  }

  static public <A> A third(Producer<A> p) {
    if (p == null)
      return null;
    for (int _repeat_1 = 0; _repeat_1 < 2; _repeat_1++) {
      if (p.next() == null)
        return null;
    }
    return p.next();
  }

  static public <A> A third(A[] bla) {
    return bla == null || bla.length <= 2 ? null : bla[2];
  }

  static public <A> VF1<A> runnableToVF1(final Runnable r) {
    return r == null ? null : new VF1<A>() {

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

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

  static public Map synchroHashMap() {
    return Collections.synchronizedMap(new HashMap());
  }

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

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

  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 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 getClass(realm).getClassLoader().loadClass(classNameToVM(name));
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Map emptyMap() {
    return new HashMap();
  }

  static public <A> List<A> concatLists(Collection<A>... lists) {
    List<A> l = new ArrayList();
    if (lists != null)
      for (Collection<A> list : lists) if (list != null)
        l.addAll(list);
    return l;
  }

  static public <A> List<A> concatLists(Collection<? extends Collection<A>> lists) {
    List<A> l = new ArrayList();
    if (lists != null)
      for (Collection<A> list : lists) if (list != null)
        l.addAll(list);
    return l;
  }

  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;
  }

  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> 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 String getDBProgramID_id;

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

  static public AutoCloseable tempLock(final Lock lock) {
    if (lock == null)
      return null;
    lock(lock);
    return new AutoCloseable() {

      public String toString() {
        return "unlock(lock);";
      }

      public void close() throws Exception {
        unlock(lock);
      }
    };
  }

  static public String singleFieldName(Class c) {
    Set<String> l = listFields(c);
    if (l(l) != 1)
      throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
    return first(l);
  }

  static public void warnIfOddCount(Object... list) {
    if (odd(l(list)))
      printStackTrace("Odd list size: " + list);
  }

  static public boolean checkConceptFields(Concept x, Object... data) {
    for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1])))
      return false;
    return true;
  }

  static public String dropSuffix(String suffix, String s) {
    return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  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 <A> A[] makeArray(Class<A> type, int n) {
    return (A[]) Array.newInstance(type, n);
  }

  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 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 <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 <A> Iterator<A> iterator(Iterable<A> c) {
    return c == null ? emptyIterator() : c.iterator();
  }

  static public char charAt(String s, int i) {
    return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
  }

  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 Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

  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 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 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 Class<?> getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class getClass(Object o) {
    return o instanceof Class ? (Class) o : o.getClass();
  }

  static public Class getClass(Object realm, String name) {
    try {
      try {
        return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
      } catch (ClassNotFoundException e) {
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String classNameToVM(String name) {
    return name.replace(".", "$");
  }

  static public String programIDWithCase() {
    return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        lock.lockInterruptibly();
      } catch (InterruptedException e) {
        print("Locking interrupted! I probably deadlocked, oops.");
        printStackTrace(e);
        rethrow(e);
      }
      ping();
    } 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 void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    print("Unlocking: " + msg);
    lock.unlock();
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
  }

  static public Set<String> listFields(Object c) {
    TreeSet<String> fields = new TreeSet();
    for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
    return fields;
  }

  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 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 <A extends Throwable> A printStackTrace(A e) {
    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 <A> A cget(Object c, String field) {
    Object o = getOpt(c, field);
    if (o instanceof Concept.Ref)
      return (A) ((Concept.Ref) o).get();
    return (A) o;
  }

  static public <A> A cget(String field, Object c) {
    return cget(c, field);
  }

  static public Object deref(Object o) {
    if (o instanceof Derefable)
      o = ((Derefable) o).get();
    return o;
  }

  static public <A> Set<A> synchroHashSet() {
    return Collections.synchronizedSet(new HashSet<A>());
  }

  static public Iterator emptyIterator() {
    return Collections.emptyIterator();
  }

  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(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) {
      _handleException(__e);
    }
  }

  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 void lockOrFail(Lock lock, long timeout) {
    try {
      ping();
      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);
      }
      ping();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  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 = litset("time", "machine", "line");

  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 List<String> getPlural_specials = ll("sheep", "fish");

  static public String getPlural(String s) {
    if (containsIgnoreCase(getPlural_specials, s))
      return s;
    if (ewic(s, "y"))
      return dropSuffixIgnoreCase("y", s) + "ies";
    if (ewic(s, "ss"))
      return s + "es";
    if (ewic(s, "s"))
      return s;
    return s + "s";
  }

  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);
    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 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 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 Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  static volatile public PersistableThrowable _handleException_lastException;

  static public List _handleException_onException = synchroList(ll("printStackTrace2"));

  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)
      return;
    for (Object f : cloneList(_handleException_onException)) try {
      callF(f, e);
    } catch (Throwable e3) {
      printStackTrace2(e3);
    }
  }

  static public String quoteIfNotIdentifierOrInteger(String s) {
    if (s == null)
      return null;
    return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
  }

  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 <A> HashSet<A> litset(A... items) {
    return lithashset(items);
  }

  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 String[] dropLast(String[] a, int n) {
    n = Math.min(n, a.length);
    String[] b = new String[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 boolean containsIgnoreCase(Collection<String> l, String s) {
    if (l != null)
      for (String x : l) if (eqic(x, s))
        return true;
    return false;
  }

  static public boolean containsIgnoreCase(String[] l, String s) {
    if (l != null)
      for (String x : l) if (eqic(x, s))
        return true;
    return false;
  }

  static public boolean containsIgnoreCase(String s, char c) {
    return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
  }

  static public boolean containsIgnoreCase(String a, String b) {
    return indexOfIgnoreCase(a, b) >= 0;
  }

  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 dropSuffixIgnoreCase(String suffix, String s) {
    return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  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 volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

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

  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)=[^&\\s\"]*", "$1$2=<hidden>");
  }

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

  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 String className(Object o) {
    return getClassName(o);
  }

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

  static public Object callFunction(Object f, Object... args) {
    return callF(f, args);
  }

  static public <A> List<A> synchroList() {
    return Collections.synchronizedList(new ArrayList<A>());
  }

  static public <A> List<A> synchroList(List<A> l) {
    return Collections.synchronizedList(l);
  }

  static public PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

  static public Throwable innerException(Throwable e) {
    return getInnerException(e);
  }

  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 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 == '\0')
        out.append("\\0");
      else
        out.append(c);
    }
    out.append('"');
  }

  static public <A> HashSet<A> lithashset(A... items) {
    HashSet<A> set = new HashSet();
    for (A a : items) set.add(a);
    return set;
  }

  static public char lastChar(String s) {
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
  }

  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, 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 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(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 int indexOfIgnoreCase(List<String> a, String b) {
    return indexOfIgnoreCase(a, b, 0);
  }

  static public int indexOfIgnoreCase(List<String> a, String b, int i) {
    int n = a == null ? 0 : a.size();
    for (; i < n; i++) if (eqic(a.get(i), b))
      return i;
    return -1;
  }

  static public int indexOfIgnoreCase(String a, String b) {
    return indexOfIgnoreCase_manual(a, b);
  }

  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;
    m.m = new String[] { substring(a, 0, l(a) - l(b)) };
    return true;
  }

  static public boolean emptyString(String s) {
    return s == null || s.length() == 0;
  }

  static public boolean startsWithOneOf(String s, String... l) {
    for (String x : l) if (startsWith(s, x))
      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 String getStackTrace2(Throwable e) {
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
  }

  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 asString(Object o) {
    return o == null ? null : o.toString();
  }

  static public int indexOfIgnoreCase_manual(String a, String b) {
    int la = strL(a), lb = strL(b);
    if (la < lb)
      return -1;
    int n = la - lb;
    loop: for (int i = 0; i <= n; i++) {
      for (int j = 0; j < lb; j++) {
        char c1 = a.charAt(i + j), c2 = b.charAt(j);
        if (!eqic(c1, c2))
          continue loop;
      }
      return i;
    }
    return -1;
  }

  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 boolean domainIsUnder(String domain, String mainDomain) {
    return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
  }

  static public String theAGIBlueDomain() {
    return "agi.blue";
  }

  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 String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

  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 Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  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 (!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 interface IF0<A> {

    public A get();
  }

  static abstract public class VF3<A, B, C> {

    abstract public void get(A a, B b, C c);
  }

  static abstract public class VF2<A, B> {

    abstract public void get(A a, B b);
  }

  static public interface IF2<A, B, C> {

    public C get(A a, B b);
  }

  static public long longPollMaxWait = 30 * 1000;

  static public long clientLatency = 10 * 1000;

  static public class BotConversationID implements IFieldsToList {

    static final public String _fieldOrder = "dbID convoID";

    public String dbID;

    public long convoID;

    public BotConversationID() {
    }

    public BotConversationID(String dbID, long convoID) {
      this.convoID = convoID;
      this.dbID = dbID;
    }

    public boolean equals(Object o) {
      if (!(o instanceof BotConversationID))
        return false;
      BotConversationID x = (BotConversationID) o;
      return eq(dbID, x.dbID) && eq(convoID, x.convoID);
    }

    public int hashCode() {
      int h = -1311362459;
      h = boostHashCombine(h, _hashCode(dbID));
      h = boostHashCombine(h, _hashCode(convoID));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { dbID, convoID };
    }

    public String toString() {
      return dbID + "/" + convoID;
    }
  }

  static public class Customer extends Concept {

    public String cookie, ip;

    public long lastPing;

    public boolean active = false;

    public BotConversationID botConversationID;

    public boolean active() {
      _setField("active", elapsedMS_timestamp(lastPing) <= longPollMaxWait + clientLatency);
      return active;
    }

    public Message lastMessage() {
      return highestByField("created", conceptsWhere(Message.class, "customer", this));
    }
  }

  static public class Message extends Concept {

    public Customer customer;

    public String text;

    public boolean unread = false;
  }

  static public class IncomingMessage extends Message {
  }

  static public class OutgoingMessage extends Message {
  }

  abstract static public class DynMultiComm extends DynModule {

    transient public ConceptTable<Customer> ct;

    transient public boolean considerAllActive = false;

    public void start() {
      try {
        super.start();
        dbIndexing(Customer.class, "cookie", Customer.class, "active", Message.class, "customer");
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public JComponent visualize() {
      ct = new ConceptTable(Customer.class);
      if (!considerAllActive)
        ct.filter = c -> c.active();
      IF1<Customer, Map> renderer = defaultConceptRendererForTable(Customer.class);
      ct.renderer = c -> {
        Map map = renderer.get(c);
        map.remove("lastPing");
        transformValueInPlace("str", map, "botConversationID");
        map.put("Last activity", iround(toSeconds(elapsedMS_timestamp(c.lastPing))));
        Message msg = c.lastMessage();
        map.put("Last message", msg == null ? "" : msg.text);
        return map;
      };
      awtEvery(ct.getTable(), 5.0, new Runnable() {

        public void run() {
          try {
            ct.update();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ct.update()";
        }
      });
      return jhsplit(jCenteredSection("Active Customers", ct.getTable()), jCenteredSection("Messages", makeConceptsTable(Message.class)));
    }

    public List<Customer> activeCustomers() {
      return cloneList(conceptsWhere(Customer.class, "active", true));
    }

    public List<Message> messagesForCustomer(Customer c) {
      return cloneList(conceptsWhere(Message.class, "customer", c));
    }
  }

  static abstract public class F2<A, B, C> {

    abstract public C get(A a, B b);
  }

  static public class ConceptTable<A extends Concept> {

    public JTable table;

    public Concepts concepts;

    public Class<A> conceptClass;

    public Set<String> dropFields;

    public IF1<A, Boolean> filter;

    public IF1<List<Map>, List<Map>> postProcess;

    public Runnable afterUpdate;

    public boolean latestFirst = false;

    public int idWidth = 50;

    public IF1<A, Map> renderer;

    public ConceptTable(Class<A> conceptClass) {
      this.conceptClass = conceptClass;
    }

    public JTable getTable() {
      init();
      return table;
    }

    public void init() {
      if (table != null)
        return;
      if (concepts == null)
        concepts = db_mainConcepts();
      if (renderer == null)
        renderer = defaultConceptRendererForTable(conceptClass);
      table = sexyTable();
      AutoCloseable __0 = tempSetTL(awtOnConceptChanges_concepts, concepts);
      try {
        awtOnConceptChanges(table, 1000, new Runnable() {

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

          public String toString() {
            return "update();";
          }
        });
      } finally {
        _close(__0);
      }
    }

    public Collection<A> list() {
      return main.list(concepts, conceptClass);
    }

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

        public void run() {
          try {
            List<Map> data = new ArrayList();
            for (A c : list()) if (filter == null || filter.get(c))
              addIfNotNull(data, (Map) renderer.get(c));
            if (latestFirst)
              reverseInPlace(data);
            data = (List) postProcess(postProcess, data);
            dataToTable_uneditable(data, table);
            pcallF(afterUpdate);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "new List<Map> data;\r\n    for (A c : list())\r\n      if (filter == null || filt...";
        }
      });
    }
  }

  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 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 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 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 void dbIndexing(Object... params) {
    db();
    for (int i = 0; i < l(params); i += 2) indexConceptField((Class) params[i], (String) params[i + 1]);
  }

  static public <A extends Concept> IF1<A, Map> defaultConceptRendererForTable(Class<A> c) {
    List<String> fields = concatLists(ll("id"), conceptFieldsInOrder(c));
    return (IF1<A, Map>) (cc -> mapKeyAndFunction_lhm(new F1<String, Object>() {

      public Object get(String field) {
        try {
          return renderForTable(cget(cc, field));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "renderForTable(cget(cc, field))";
      }
    }, fields));
  }

  static public <A, B> void transformValueInPlace(Object f, Map<A, B> map, A key) {
    if (f != null && map != null && map.containsKey(key))
      map.put(key, (B) callF(f, map.get(key)));
  }

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

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

  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 long elapsedMS_timestamp(long time) {
    ping();
    return now() - time;
  }

  static public <A extends JComponent> A awtEvery(A component, long delay, Object r) {
    swingEvery(component, delay, r);
    return component;
  }

  static public <A extends JComponent> A awtEvery(A component, long delay, long firstDelay, Object r) {
    swingEvery(component, delay, firstDelay, r);
    return component;
  }

  static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
    swingEvery(frame, delay, r);
  }

  static public <A extends JComponent> A awtEvery(A component, double delaySeconds, Object r) {
    return awtEvery(component, toMS(delaySeconds), r);
  }

  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 JPanel jCenteredSection(Component c) {
    return jCenteredSection("", c);
  }

  static public JPanel jCenteredSection(final String title, final 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 ThreadLocal<List<String>> showConceptsTable_dropFields = new ThreadLocal();

  static public ThreadLocal showConceptsTable_postProcess = new ThreadLocal();

  static public ThreadLocal showConceptsTable_afterUpdate = new ThreadLocal();

  static public ThreadLocal<Concepts> showConceptsTable_concepts = new ThreadLocal();

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

  static public int makeConceptsTable_idWidth = 50;

  static public JTable showConceptsTable(Class<? extends Concept> c) {
    JTable table = makeConceptsTable(c);
    showFrame(plural(shortClassName(c)), table);
    return table;
  }

  static public JTable makeConceptsTable(final Class<? extends Concept> c) {
    List<String> dropFields = getAndClearThreadLocal(showConceptsTable_dropFields);
    final Object pp = getAndClearThreadLocal(showConceptsTable_postProcess);
    final Object afterUpdate = optParam(showConceptsTable_afterUpdate);
    final Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts());
    final boolean latestFirst = boolParam(showConceptsTable_latestFirst);
    final List<String> fields = listMinusList(concatLists(ll("id"), conceptFieldsInOrder(c)), dropFields);
    final JTable table = sexyTable();
    tablePopupMenu(table, new VF2<JPopupMenu, Integer>() {

      public void get(JPopupMenu menu, final Integer row) {
        try {
          addMenuItem(menu, "Delete", new Runnable() {

            public void run() {
              try {
                final long id = toLong(getTableCell(table, row, 0));
                withDBLock(new Runnable() {

                  public void run() {
                    try {
                      deleteConcept(concepts, id);
                    } catch (Exception __e) {
                      throw rethrow(__e);
                    }
                  }

                  public String toString() {
                    return "deleteConcept(concepts, id)";
                  }
                });
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "final long id = toLong(getTableCell(table, row, 0));\r\n      withDBLock(r { de...";
            }
          });
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "addMenuItem(menu, \"Delete\", r {\r\n      final long id = toLong(getTableCell(ta...";
      }
    });
    AutoCloseable __0 = tempSetTL(awtOnConceptChanges_concepts, concepts);
    try {
      awtOnConceptChanges(table, new Runnable() {

        public void run() {
          try {
            List<List> data = new ArrayList();
            for (final Concept cc : list(concepts, c)) data.add(map(new F1<String, Object>() {

              public Object get(String field) {
                try {
                  return renderForTable(cget(cc, field));
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "renderForTable(cget(cc, field))";
              }
            }, fields));
            if (latestFirst)
              reverseInPlace(data);
            data = (List) postProcess(pp, data);
            fillTableWithData(table, data, map("humanizeFormLabel", fields));
            if (table.getColumnCount() > 0)
              table.getColumnModel().getColumn(0).setMaxWidth(makeConceptsTable_idWidth);
            pcallF(afterUpdate, table);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "//print(\"Updating concept table\");\r\n    new List<List> data;\r\n    for (final ...";
        }
      }, true);
      return table;
    } finally {
      _close(__0);
    }
  }

  static public <A extends Concept> JTable makeConceptsTable(final Class<A> cClass, final Object renderer) {
    if (renderer == null)
      return makeConceptsTable(cClass);
    final Object pp = optParam(showConceptsTable_postProcess);
    final Object afterUpdate = optParam(showConceptsTable_afterUpdate);
    final Concepts concepts = optParam(showConceptsTable_concepts, db_mainConcepts());
    final boolean latestFirst = boolParam(showConceptsTable_latestFirst);
    final JTable table = sexyTable();
    AutoCloseable __1 = tempSetTL(awtOnConceptChanges_concepts, concepts);
    try {
      awtOnConceptChanges(table, 1000, new Runnable() {

        public void run() {
          try {
            List<Map> data = new ArrayList();
            for (A c : list(concepts, cClass)) addIfNotNull(data, (Map) pcallF(renderer, c));
            if (latestFirst)
              reverseInPlace(data);
            data = (List) postProcess(pp, data);
            dataToTable_uneditable(data, table);
            pcallF(afterUpdate, table);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "new List<Map> data;\r\n    for (A c : list(concepts, cClass))\r\n      addIfNotNu...";
        }
      });
      return table;
    } finally {
      _close(__1);
    }
  }

  static public <A extends Concept> JTable showConceptsTable(final Class<A> c, final Object f) {
    JTable table = makeConceptsTable(c, f);
    showFrame(plural(shortClassName(c)), table);
    return table;
  }

  static public <A extends Concept> JTable showConceptsTable(String title, Class<A> cClass, Object f) {
    return setFrameTitle(title, showConceptsTable(cClass, f));
  }

  static public <A extends Concept> Collection<A> conceptsWhere(Class<A> c, Object... params) {
    return findConceptsWhere(c, params);
  }

  static public Collection<Concept> conceptsWhere(String c, Object... params) {
    return findConceptsWhere(c, params);
  }

  static public <A extends Concept> Collection<A> conceptsWhere(Concepts concepts, Class<A> c, Object... params) {
    return findConceptsWhere(concepts, c, params);
  }

  static public boolean sexyTable_drag = false;

  static public JTable sexyTable() {
    final JTable table = sexyTableWithoutDrag();
    if (sexyTable_drag)
      tableEnableTextDrag(table);
    return table;
  }

  static public <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
    return tempSetThreadLocal(tl, a);
  }

  static public int awtOnConceptChanges_defaultDelay = 1000;

  static public ThreadLocal<Concepts> awtOnConceptChanges_concepts = new ThreadLocal();

  static public void awtOnConceptChanges(Component component, Object runnable) {
    awtOnConceptChanges(componentToJComponent(component), runnable, true);
  }

  static public void awtOnConceptChanges(JComponent component, final Object runnable, boolean runOnFirstTime) {
    awtOnConceptChanges(component, awtOnConceptChanges_defaultDelay, 0, runnable, runOnFirstTime);
  }

  static public void awtOnConceptChanges(JComponent component, int delay, final Object runnable) {
    awtOnConceptChanges(component, delay, delay, runnable);
  }

  static public void awtOnConceptChanges(JComponent component, int delay, int firstDelay, Object runnable) {
    awtOnConceptChanges(component, delay, firstDelay, runnable, true);
  }

  static public boolean awtOnConceptChanges_debug = false;

  static public void awtOnConceptChanges(JComponent component, int delay, int firstDelay, final Object runnable, final boolean runOnFirstTime) {
    final Concepts concepts = or(awtOnConceptChanges_concepts.get(), db_mainConcepts());
    installTimer(component, delay, firstDelay, new Runnable() {

      public long c = runOnFirstTime ? -1 : concepts.changes;

      public void run() {
        long _c = concepts.changes;
        if (awtOnConceptChanges_debug)
          print("awtOnConceptChanges: " + _c + " / " + c);
        if (_c != c) {
          c = _c;
          call(runnable);
        }
      }
    });
  }

  static public <A extends Concept> List<A> list(Class<A> type) {
    return db_mainConcepts().list(type);
  }

  static public <A extends Concept> List<A> list(Concepts concepts, Class<A> type) {
    return concepts.list(type);
  }

  static public List<Concept> list(String type) {
    return db_mainConcepts().list(type);
  }

  static public List<Concept> list(Concepts concepts, String type) {
    return concepts.list(type);
  }

  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 <A> void addIfNotNull(Collection<A> l, A a) {
    if (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 <A> List<A> reverseInPlace(List<A> l) {
    return reverseList(l);
  }

  static public <A> A postProcess(Object f, A a) {
    return callPostProcessor(f, a);
  }

  static public JTable dataToTable_uneditable(Object data, final JTable table) {
    return dataToTable_uneditable(table, data);
  }

  static public JTable dataToTable_uneditable(final JTable table, final Object data) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            dataToTable(table, data, true);
            makeTableUneditable(table);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "dataToTable(table, data, true);\r\n    makeTableUneditable(table);";
        }
      });
    }
    return table;
  }

  static public JTable dataToTable_uneditable(final Object data) {
    return dataToTable_uneditable(showTable(), data);
  }

  static public JTable dataToTable_uneditable(Object data, String title) {
    return dataToTable_uneditable(showTable(title), data);
  }

  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 void db() {
    conceptsAndBot();
  }

  static public void db(Integer autoSaveInterval) {
    conceptsAndBot(autoSaveInterval);
  }

  static public void indexConceptField(Class<? extends Concept> c, String field) {
    indexConceptField(db_mainConcepts(), c, field);
  }

  static public void indexConceptField(Concepts concepts, Class<? extends Concept> c, String field) {
    if (!isConceptFieldIndexed(concepts, c, field))
      new ConceptFieldIndex(concepts, c, field);
  }

  static public List<String> conceptFieldsInOrder(Concept c) {
    return conceptFieldsInOrder(c.getClass());
  }

  static public List<String> conceptFieldsInOrder(Class<? extends Concept> c) {
    String order = toStringOpt(getOpt(c, "_fieldOrder"));
    Set<String> set = asTreeSet(conceptFields(c));
    if (order == null)
      return asList(set);
    List<String> fields = splitAtSpace(order);
    setAddAll(fields, set);
    return fields;
  }

  static public LinkedHashMap mapKeyAndFunction_lhm(Iterable l, Object f) {
    return mapKeyAndFunction_lhm(f, l);
  }

  static public LinkedHashMap mapKeyAndFunction_lhm(Object f, Iterable l) {
    LinkedHashMap map = new LinkedHashMap();
    if (l != null)
      for (Object o : l) map.put(o, callF(f, o));
    return map;
  }

  static public Object renderForTable(Object o) {
    {
      Object __1 = toBufferedImageOpt(o);
      if (__1 != null)
        return __1;
    }
    if (o instanceof String && containsNewLine((String) o))
      return escapeNewLines((String) o);
    return o;
  }

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

  static public String formatDouble(double d, int digits) {
    String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
    return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
  }

  static public void swingEvery(JComponent component, long delay, Object r) {
    installTimer(component, delay, r);
  }

  static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
    installTimer(component, r, delay, firstDelay);
  }

  static public void swingEvery(RootPaneContainer frame, long delay, Object r) {
    installTimer(frame, delay, r);
  }

  static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
    installTimer(frame, delay, firstDelay, r);
  }

  static public long toMS(double seconds) {
    return (long) (seconds * 1000);
  }

  static public JSplitPane setSplitPaneOnFirstShowing(final Component c, final double value) {
    final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
    if (sp != null)
      onFirstResize(sp, new Runnable() {

        public void run() {
          try {
            sp.setDividerLocation(value);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "sp.setDividerLocation(value);";
        }
      });
    return sp;
  }

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

  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
      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 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 jpanel(LayoutManager layout) {
    return swingNu(JPanel.class, layout);
  }

  static public JPanel jpanel() {
    return swingNu(JPanel.class);
  }

  static public JFrame showFrame() {
    return makeFrame();
  }

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

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

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

  static public JFrame showFrame(final JFrame f) {
    if (f != null) {
      swing(new Runnable() {

        public void run() {
          try {
            if (frameTooSmall(f))
              frameStandardSize(f);
            if (!f.isVisible())
              f.setVisible(true);
            if (f.getState() == Frame.ICONIFIED)
              f.setState(Frame.NORMAL);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (frameTooSmall(f)) frameStandardSize(f);\r\n    if (!f.isVisible()) f.setVis...";
        }
      });
    }
    return f;
  }

  static public JFrame showFrame(String title, Object content, JFrame frame) {
    if (frame == null)
      return showFrame(title, content);
    else {
      frame.setTitle(title);
      setFrameContents(frame, content);
      return frame;
    }
  }

  static public String plural(String s) {
    return getPlural(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 <A> A getAndClearThreadLocal(ThreadLocal<A> tl) {
    A a = tl.get();
    tl.set(null);
    return a;
  }

  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 boolean boolParam(ThreadLocal<Boolean> tl) {
    return boolOptParam(tl);
  }

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

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

  static public <A> List<A> listMinusList(Collection<A> l, Collection stuff) {
    if (empty(stuff) && l instanceof List)
      return (List) l;
    List<A> l2 = cloneList(l);
    for (Object o : stuff) l2.remove(o);
    return l2;
  }

  static public void addMenuItem(JPopupMenu menu, String text, Object action) {
    menu.add(jmenuItem(text, action));
  }

  static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
    menu.add(menuItem);
  }

  static public void addMenuItem(JMenu menu, String text, Object action) {
    menu.add(jmenuItem(text, action));
  }

  static public void addMenuItem(Menu menu, String text, Object action) {
    menu.add(menuItem(text, action));
  }

  static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
    menu.add(menuItem);
  }

  static public Object getTableCell(JTable tbl, int row, int col) {
    if (row >= 0 && row < tbl.getModel().getRowCount())
      return tbl.getModel().getValueAt(row, col);
    return null;
  }

  static public Object withDBLock(Object r) {
    Lock __0 = db_mainConcepts().lock;
    lock(__0);
    try {
      return callF(r);
    } finally {
      unlock(__0);
    }
  }

  static public <A> A withDBLock(F0<A> r) {
    return (A) withDBLock((Object) r);
  }

  static public Object withDBLock(Concepts concepts, Object r) {
    Lock __1 = concepts.lock;
    lock(__1);
    try {
      return callF(r);
    } finally {
      unlock(__1);
    }
  }

  static public <A> A withDBLock(Concepts concepts, F0<A> r) {
    return (A) withDBLock(concepts, (Object) r);
  }

  static public void deleteConcept(long id) {
    db_mainConcepts().deleteConcept(id);
  }

  static public void deleteConcept(Concepts concepts, long id) {
    concepts.deleteConcept(id);
  }

  static public void deleteConcept(Concept c) {
    if (c != null)
      c.delete();
  }

  static public void deleteConcept(Concept.Ref ref) {
    if (ref != null)
      deleteConcept(ref.get());
  }

  static public void fillTableWithData(final JTable table, List<List> rows, List<String> colNames) {
    fillTableWithData(table, rows, toStringArray(colNames));
  }

  static public void fillTableWithData(final JTable table, List<List> rows, String... colNames) {
    final DefaultTableModel model = fillTableWithData_makeModel(rows, colNames);
    setTableModel(table, model);
  }

  static public DefaultTableModel fillTableWithData_makeModel(List<List> rows, String... colNames) {
    Pair<Object[][], Object[]> p = fillTableWithData_makeData(rows, colNames);
    return new DefaultTableModel(p.a, p.b) {

      public Class getColumnClass(int column) {
        return or(_getClass(getValueAt(0, column)), String.class);
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
      }
    };
  }

  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 <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 <A extends Concept> Collection<A> findConceptsWhere(Class<A> c, Object... params) {
    return findConceptsWhere(db_mainConcepts(), c, params);
  }

  static public Collection<Concept> findConceptsWhere(String c, Object... params) {
    return findConceptsWhere(db_mainConcepts(), c, params);
  }

  static public <A extends Concept> Collection<A> findConceptsWhere(Concepts concepts, Class<A> c, Object... params) {
    params = expandParams(c, params);
    if (concepts.fieldIndices != null)
      for (int i = 0; i < l(params); i += 2) {
        IFieldIndex<A, Object> index = concepts.getFieldIndex(c, (String) params[i]);
        if (index != null) {
          Collection<A> rawList = index.getAll(params[i + 1]);
          params = dropEntryFromParams(params, i);
          if (params == null)
            return rawList;
          List<A> l = new ArrayList();
          for (A x : rawList) if (checkConceptFields(x, params))
            l.add(x);
          return l;
        }
      }
    return filterConcepts(concepts.list(c), params);
  }

  static public Collection<Concept> findConceptsWhere(Concepts concepts, String c, Object... params) {
    return filterConcepts(concepts.list(c), params);
  }

  static public void tableEnableTextDrag(final JTable table) {
    TransferHandler th = new TransferHandler() {

      @Override
      public int getSourceActions(JComponent c) {
        return COPY;
      }

      @Override
      public Transferable createTransferable(JComponent c) {
        Object o = selectedTableCell(table);
        return new StringSelection(str(o));
      }
    };
    tableEnableDrag(table, th);
  }

  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 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 __0 = tempActivity(r);
                try {
                  try {
                    if (!allPaused())
                      if (isFalse(callF(r)))
                        cancelTimer(timer.get());
                  } catch (Throwable __e) {
                    _handleException(__e);
                  }
                } finally {
                  _close(__0);
                }
              } 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 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 <A> List<A> reverseList(List<A> l) {
    Collections.reverse(l);
    return l;
  }

  static public <A> A callPostProcessor(Object f, A a) {
    return f == null ? a : (A) callF(f, a);
  }

  static public JTable dataToTable(Object data) {
    return dataToTable(showTable(), data);
  }

  static public JTable dataToTable(Object data, String title) {
    return dataToTable(showTable(title), data);
  }

  static public JTable dataToTable(JTable table, Object data) {
    return dataToTable(table, data, false);
  }

  static public JTable dataToTable(JTable table, Object data, boolean now) {
    List<List> rows = new ArrayList();
    List<String> cols = new ArrayList();
    if (data instanceof List) {
      for (Object x : (List) data) {
        try {
          rows.add(dataToTable_makeRow(x, cols));
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
    } else if (data instanceof Map) {
      Map map = (Map) data;
      for (Object key : map.keySet()) {
        Object value = map.get(key);
        rows.add(litlist(structureOrTextForUser(key), structureOrTextForUser(value)));
      }
    } else if (data != null)
      print("Unknown data type: " + data);
    fillTableWithData(table, rows, cols);
    return table;
  }

  static public void makeTableUneditable(JTable table) {
    for (int c = 0; c < table.getColumnCount(); c++) {
      Class<?> col_class = table.getColumnClass(c);
      table.setDefaultEditor(col_class, null);
    }
  }

  static public boolean showTable_searcher = true;

  static public JTable showTable(Object data) {
    return dataToTable_uneditable(data);
  }

  static public JTable showTable(String title, Object data) {
    return showTable(data, title);
  }

  static public JTable showTable(Object data, String title) {
    return dataToTable_uneditable(data, title);
  }

  static public JTable showTable(JTable table, Object data) {
    return showTable(table, data, autoFrameTitle());
  }

  static public JTable showTable(Object data, JTable table) {
    return showTable(table, data);
  }

  static public JTable showTable(JTable table, Object data, String title) {
    if (table == null)
      table = showTable(data, title);
    else {
      setFrameTitle(table, title);
      dataToTable_uneditable(table, data);
    }
    return table;
  }

  static public JTable showTable() {
    return showTable(new ArrayList<List<String>>(), new ArrayList<String>());
  }

  static public JTable showTable(String title) {
    return showTable(new ArrayList<List<String>>(), new ArrayList<String>(), title);
  }

  static public JTable showTable(List<List<String>> rows, List<String> cols) {
    return showTable(rows, cols, autoFrameTitle());
  }

  static public JTable showTable(List<List<String>> rows, List<String> cols, String title) {
    JTable tbl = sexyTable();
    fillTableWithStrings(tbl, rows, cols);
    showFrame(title, tbl);
    return tbl;
  }

  volatile static public boolean conceptsAndBot_running = false;

  static public boolean conceptsAndBot_thinOnStart = true;

  static public void conceptsAndBot() {
    conceptsAndBot(null);
  }

  static public void conceptsAndBot(Integer autoSaveInterval) {
    if (conceptsAndBot_running)
      return;
    conceptsAndBot_running = true;
    try {
      ensureDBNotRunning(dbBotStandardName());
    } catch (Throwable _e) {
      db_mainConcepts().dontSave = true;
      throw rethrow(_e);
    }
    db_mainConcepts().persist(autoSaveInterval);
    dbBot();
    if (conceptsAndBot_thinOnStart) {
      try {
        thinAProgramsBackups(getDBProgramID(), true);
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

  static public boolean isConceptFieldIndexed(Class<? extends Concept> c, String field) {
    return isConceptFieldIndexed(db_mainConcepts(), c, field);
  }

  static public boolean isConceptFieldIndexed(Concepts concepts, Class<? extends Concept> c, String field) {
    return concepts.getFieldIndex(c, field) != null;
  }

  static public String toStringOpt(Object o) {
    return o instanceof String ? ((String) o) : null;
  }

  static public TreeSet<String> asTreeSet(List l) {
    TreeSet set = new TreeSet();
    for (Object o : l) if (o != null)
      set.add(o);
    return set;
  }

  static public <A> TreeSet<A> asTreeSet(Set<A> set) {
    return set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
  }

  static public String[] conceptFields_drop = { "className", "fieldValues", "id", "created", "_modified", "refs", "backRefs", "_concepts" };

  static public Set<String> conceptFields(Concept c) {
    return setMinus(mergeSets(allNonStaticNonTransientFields(c), keys(c.fieldValues)), conceptFields_drop);
  }

  static public Set<String> conceptFields(Class<? extends Concept> c) {
    return setMinus(allNonStaticNonTransientFields(c), conceptFields_drop);
  }

  static public List<String> splitAtSpace(String s) {
    return empty(s) ? emptyList() : asList(s.split("\\s+"));
  }

  static public <A> void setAddAll(Collection<A> a, Collection<A> b) {
    for (A x : b) setAdd(a, x);
  }

  static public BufferedImage toBufferedImageOpt(Object o) {
    if (o instanceof BufferedImage)
      return (BufferedImage) o;
    if (o instanceof MakesBufferedImage)
      return ((MakesBufferedImage) o).getBufferedImage();
    if (o instanceof File)
      if (isImageFile(((File) o)))
        return loadImage2(((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 boolean containsNewLine(String s) {
    return contains(s, '\n');
  }

  static public String escapeNewLines(String s) {
    return s == null ? null : fixNewLines(s).replace("\n", " | ");
  }

  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 <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 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 <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 <A extends Component> A _recordNewSwingComponent(A c) {
    if (c != null)
      callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
    return 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 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 boolean frameTooSmall(JFrame frame) {
    return frame.getWidth() < 100 || frame.getHeight() < 50;
  }

  static public void frameStandardSize(JFrame frame) {
    frame.setBounds(300, 100, 500, 400);
  }

  static public void setFrameContents(final Component c, final Object contents) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            JFrame frame = getFrame(c);
            frame.getContentPane().removeAll();
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(wrap(contents));
            revalidate(frame);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "JFrame frame = getFrame(c);\r\n    frame.getContentPane().removeAll();\r\n    fra...";
        }
      });
    }
  }

  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 <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);
  }

  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 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 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 MenuItem menuItem(String text, final Object r) {
    MenuItem mi = new MenuItem(text);
    mi.addActionListener(actionListener(r));
    return mi;
  }

  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 Map<JTable, VF1<JTable>> setTableModel_after = weakHashMap();

  static public Map<JTable, VF2<JTable, RowSorter>> setTableModel_fixSorter = weakHashMap();

  static public void setTableModel(final JTable table, final TableModel model) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            Map<String, Integer> widths = tableColumnWidthsByName(table);
            int[] i = table.getSelectedRows();
            TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null;
            List<? extends RowSorter.SortKey> sortKeys = sorter == null ? null : sorter.getSortKeys();
            table.setModel(model);
            int n = model.getRowCount();
            ListSelectionModel sel = table.getSelectionModel();
            for (int j = 0; j < i.length; j++) if (i[j] < n)
              sel.addSelectionInterval(i[j], i[j]);
            tableSetColumnPreferredWidths(table, widths);
            if (sorter != null) {
              sorter.setModel(model);
              callF(setTableModel_fixSorter.get(table), table, sorter);
              if (sortKeys != null)
                sorter.setSortKeys(sortKeys);
            }
            table.setRowSorter(sorter);
            callF(setTableModel_after.get(table), table);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Map<String, Integer> widths = tableColumnWidthsByName(table);\r\n    int[] i = ...";
        }
      });
    }
  }

  static public Pair<Object[][], Object[]> fillTableWithData_makeData(List<List> rows, List<String> colNames) {
    return fillTableWithData_makeData(rows, asStringArray(colNames));
  }

  static public Pair<Object[][], Object[]> fillTableWithData_makeData(List<List> rows, String... colNames) {
    Object[][] data = new Object[rows.size()][];
    int w = 0;
    for (int i = 0; i < rows.size(); i++) {
      List l = rows.get(i);
      Object[] r = new Object[l.size()];
      for (int j = 0; j < l.size(); j++) {
        Object o = l.get(j);
        if (o instanceof BufferedImage)
          o = imageIcon((BufferedImage) o);
        if (o instanceof RGBImage)
          o = imageIcon((RGBImage) o);
        r[j] = o;
      }
      data[i] = r;
      w = Math.max(w, l.size());
    }
    Object[] columnNames = new Object[w];
    for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?";
    return pair(data, columnNames);
  }

  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 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 Object[] dropEntryFromParams(Object[] params, int i) {
    int n = l(params);
    if (i < 0 || i >= n)
      return params;
    if (n == 2)
      return null;
    Object[] p = new Object[n - 2];
    System.arraycopy(params, 0, p, 0, i);
    System.arraycopy(params, i + 2, p, i, n - i - 2);
    return p;
  }

  static public <A extends Concept> List<A> filterConcepts(List<A> list, Object... params) {
    if (empty(params))
      return list;
    List<A> l = new ArrayList();
    for (A x : list) if (checkConceptFields(x, params))
      l.add(x);
    return l;
  }

  static public Object selectedTableCell(JTable t, int col) {
    return getTableCell(t, selectedTableRow(t), col);
  }

  static public Object selectedTableCell(final JTable t) {
    return swing(new F0<Object>() {

      public Object get() {
        try {
          return selectedTableCell(t, t.getSelectedColumn());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret selectedTableCell(t, t.getSelectedColumn());";
      }
    });
  }

  static public Object selectedTableCell(final JTable t, final String colName) {
    return swing(new F0<Object>() {

      public Object get() {
        try {
          return selectedTableCell(t, tableColumnViewIndex(t, colName));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret selectedTableCell(t, tableColumnViewIndex(t, colName));";
      }
    });
  }

  static public void tableEnableDrag(final JTable table, TransferHandler th) {
    if (table.getDragEnabled()) {
      print("Table drag already enabled");
      return;
    }
    table.setDragEnabled(true);
    table.setTransferHandler(th);
    table.addMouseListener(new MouseAdapter() {

      @Override
      public void mousePressed(MouseEvent e) {
        if (e.getButton() == 1 && e.getClickCount() == 1)
          table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY);
      }
    });
  }

  static public AutoCloseable tempActivity(Object r) {
    return null;
  }

  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) {
        _handleException(__e);
      }
    }
  }

  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 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 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 void dataToTable_dynSet(List l, int i, Object s) {
    while (i >= l.size()) l.add("");
    l.set(i, s);
  }

  static public List dataToTable_makeRow(Object x, List<String> cols) {
    if (instanceOf(x, "DynamicObject"))
      x = get_raw(x, "fieldValues");
    if (x instanceof Map) {
      Map m = (Map) x;
      List row = new ArrayList();
      for (Object _field : keysWithoutHidden(m)) {
        String field = (String) _field;
        Object value = m.get(field);
        int col = cols.indexOf(field);
        if (col < 0) {
          cols.add(field);
          col = cols.size() - 1;
        }
        dataToTable_dynSet(row, col, dataToTable_wrapValue(value));
      }
      return row;
    }
    return litlist(structureOrText(x));
  }

  static public Object dataToTable_wrapValue(Object o) {
    if (o instanceof BufferedImage)
      return o;
    if (o instanceof MakesBufferedImage)
      return ((MakesBufferedImage) o).getBufferedImage();
    if (o instanceof RGBImage)
      return o;
    if (o instanceof Boolean)
      return o;
    return structureOrTextForUser(o);
  }

  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 structureOrTextForUser(Object o) {
    return o == null ? "" : o instanceof String ? (String) o : structureForUser(o);
  }

  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 fillTableWithStrings(final JTable table, List<List<String>> rows, List<String> colNames) {
    fillTableWithStrings(table, rows, toStringArray(colNames));
  }

  static public void fillTableWithStrings(final JTable table, List<List<String>> rows, String... colNames) {
    final DefaultTableModel model = fillTableWithStrings_makeModel(rows, colNames);
    swingNowOrLater(new Runnable() {

      public void run() {
        try {
          setTableModel(table, model);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setTableModel(table, model);";
      }
    });
  }

  static public DefaultTableModel fillTableWithStrings_makeModel(List<List<String>> rows, String... colNames) {
    Object[][] data = new Object[rows.size()][];
    int w = 0;
    for (int i = 0; i < rows.size(); i++) {
      List<String> l = rows.get(i);
      Object[] r = new Object[l.size()];
      for (int j = 0; j < l.size(); j++) r[j] = l.get(j);
      data[i] = r;
      w = Math.max(w, l.size());
    }
    Object[] columnNames = new Object[w];
    for (int i = 0; i < w; i++) columnNames[i] = i < l(colNames) ? colNames[i] : "?";
    return new DefaultTableModel(data, columnNames);
  }

  static public void ensureDBNotRunning(String name) {
    if (hasBot(name)) {
      try {
        String framesBot = dropSuffix(".", name) + " Frames";
        print("Trying to activate frames of running DB: " + framesBot);
        if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram())
          cleanKill();
      } catch (Throwable __e) {
        _handleException(__e);
      }
      throw fail("Already running: " + name);
    }
  }

  static public void ensureDBNotRunning() {
    ensureDBNotRunning(dbBotStandardName());
  }

  static public String dbBotStandardName() {
    String home = userHome();
    String name = dbBotName(getDBProgramID());
    if (neq(home, actualUserHome()))
      name += " " + quote(home);
    return name + ".";
  }

  static volatile public Android3 dbBot_instance;

  static public Android3 dbBot() {
    return dbBot(dbBotStandardName());
  }

  static public Android3 dbBot(String name) {
    ensureDBNotRunning(name);
    return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock);
  }

  static public void thinAProgramsBackups(String progID, boolean doIt) {
    List<File> files = new ArrayList();
    Map<File, Double> ageMap = new HashMap();
    java.util.regex.Pattern pat = regexp("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)$");
    File dir = programDir(progID);
    for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) {
      String s = f.getName();
      java.util.regex.Matcher matcher = pat.matcher(s);
      {
        if (!(matcher.find()))
          continue;
      }
      String originalName = matcher.group(1);
      {
        if (!(eq(originalName, "concepts.structure.gz")))
          continue;
      }
      int year = matcherInt(matcher, 2);
      int month = matcherInt(matcher, 3);
      int day = matcherInt(matcher, 4);
      int hour = matcherInt(matcher, 5);
      long time = timestampFromYMDH(year, month, day, hour);
      double age = ((now() - time) / 1000.0 / 60 / 60 / 24);
      ageMap.put(f, age);
      files.add(f);
    }
    int numDeleted = 0;
    sortByMap_inPlace(files, ageMap);
    double lastAge = -1;
    for (File f : files) {
      double age = ageMap.get(f);
      if (!thinAProgramsBackups_shouldKeep(age, lastAge)) {
        ++numDeleted;
        if (doIt) {
          print("Deleting: " + f);
          f.delete();
        }
      } else {
        lastAge = age;
      }
    }
    if (numDeleted != 0)
      print((doIt ? "Deleted: " : "Would delete: ") + n(numDeleted, "file"));
  }

  static public boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) {
    return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge);
  }

  static public <A> Set<A> setMinus(Set<A> set, Object... stuff) {
    Set s2 = cloneSet(set);
    for (Object o : stuff) s2.remove(o);
    return s2;
  }

  static public <A> Set<A> mergeSets(Set<A>... l) {
    return joinSets(l);
  }

  static public Set<String> allNonStaticNonTransientFields(Object o) {
    TreeSet<String> fields = new TreeSet();
    Class _c = _getClass(o);
    do {
      for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)
        fields.add(f.getName());
      _c = _c.getSuperclass();
    } while (_c != null);
    return fields;
  }

  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(MultiSetMap<A, B> mm) {
    return mm.keySet();
  }

  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 boolean isImageFile(File f) {
    return isImageFileName(fileName(f));
  }

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

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

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

  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 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 <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 Object vm_generalMap_get(Object key) {
    return vm_generalMap().get(key);
  }

  static public String programTitle() {
    return getProgramName();
  }

  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 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 void _initFrame(JFrame f) {
    myFrames_list.put(f, Boolean.TRUE);
    standardTitlePopupMenu(f);
  }

  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 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 <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 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 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 String dropPrefix(String prefix, String s) {
    return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
  }

  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 __0 = holdInstance(instanceToHold);
                try {
                  callF(runnable);
                } finally {
                  _close(__0);
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "AutoCloseable __0 = holdInstance(instanceToHold); try {\r\n      callF(runnable...";
            }
          });
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  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 __0 = holdInstance(instanceToHold);
          try {
            callF(runnable);
          } finally {
            _close(__0);
          }
        } catch (Throwable __e) {
          messageBox(__e);
        }
      }
    };
  }

  static public <A, B> Map<A, B> weakHashMap() {
    return newWeakHashMap();
  }

  static public Map<String, Integer> tableColumnWidthsByName(JTable table) {
    TableColumnModel tcm = table.getColumnModel();
    if (tcm == null)
      return null;
    int n = tcm.getColumnCount();
    TreeMap<String, Integer> map = new TreeMap();
    for (int i = 0; i < n; i++) {
      TableColumn tc = tcm.getColumn(i);
      map.put(str(tc.getHeaderValue()), tc.getWidth());
    }
    return map;
  }

  static public int tableColumnCount(JTable table) {
    return tableNumColumns(table);
  }

  static public boolean tableSetColumnPreferredWidths_debug = false;

  static public void tableSetColumnPreferredWidths(final JTable table, final Map<String, Integer> widths) {
    if (table == null || widths == null)
      return;
    {
      swing(new Runnable() {

        public void run() {
          try {
            try {
              TableColumnModel tcm = table.getColumnModel();
              int n = tcm.getColumnCount();
              for (int i = 0; i < n; i++) {
                TableColumn tc = tcm.getColumn(i);
                Integer w = widths.get(str(tc.getHeaderValue()));
                if (w != null) {
                  tc.setPreferredWidth(w);
                  if (tableSetColumnPreferredWidths_debug)
                    print("Setting preferred width of column " + i + " to " + w);
                }
              }
            } catch (Throwable __e) {
              _handleException(__e);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "pcall {\r\n    TableColumnModel tcm = table.getColumnModel();\r\n    int n = tcm....";
        }
      });
    }
  }

  static public void tableSetColumnPreferredWidths(JTable table, Object... widths) {
    tableSetColumnPreferredWidths(table, litorderedmap(widths));
  }

  static public String[] asStringArray(Collection<String> c) {
    return toStringArray(c);
  }

  static public String[] asStringArray(Object o) {
    return toStringArray(o);
  }

  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 <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 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 List<AbstractButton> buttonsInGroup(ButtonGroup g) {
    if (g == null)
      return ll();
    return asList(g.getElements());
  }

  static public int selectedTableRow(final JTable t) {
    return t == null ? -1 : swing(new F0<Integer>() {

      public Integer get() {
        try {
          return t.getSelectedRow();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret t.getSelectedRow();";
      }
    });
  }

  static public int tableColumnViewIndex(final JTable t, final String colName) {
    return swing(new F0<Integer>() {

      public Integer get() {
        try {
          return t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret t.convertColumnIndexToView(t.getColumn(colName).getModelIndex());";
      }
    });
  }

  static public boolean headless() {
    return isHeadless();
  }

  static public Runnable asRunnable(Object o) {
    return toRunnable(o);
  }

  static public void _inheritThreadInfo(Object info) {
    _threadInheritInfo(info);
  }

  static public boolean instanceOf(Object o, String className) {
    if (o == null)
      return false;
    String c = o.getClass().getName();
    return eq(c, className) || eq(c, "main$" + className);
  }

  static public boolean instanceOf(Object o, Class c) {
    if (c == null)
      return false;
    return c.isInstance(o);
  }

  static public <A, B> List<A> keysWithoutHidden(Map<A, B> map) {
    return filter(keys(map), new F1<Object, Boolean>() {

      public Boolean get(Object o) {
        try {
          return !eq(o, "[hidden]") && !isStringStartingWith(o, "[hidden] ");
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "!eq(o, \"[hidden]\") && !isStringStartingWith(o, \"[hidden] \")";
      }
    });
  }

  static public String structureOrText(Object o) {
    return o instanceof String ? (String) o : structure(o);
  }

  static public String structureForUser(Object o) {
    return beautifyStructure(struct_noStringSharing(o));
  }

  static public String getProgramTitle() {
    return getProgramName();
  }

  static public void swingNowOrLater(Runnable r) {
    if (isAWTThread())
      r.run();
    else
      swingLater(r);
  }

  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 boolean hasBot(String searchPattern) {
    try {
      DialogIO io = findBot(searchPattern);
      if (io != null) {
        io.close();
        return true;
      } else
        return false;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isOK(String s) {
    s = trim(s);
    return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s);
  }

  static public String sendOpt(String bot, String text, Object... args) {
    return sendToLocalBotOpt(bot, text, args);
  }

  static public boolean isMainProgram() {
    return creator() == null;
  }

  static public void cleanKill() {
    cleanKillVM();
  }

  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 String dbBotName(String progIDWithCase) {
    return fsI_flex(progIDWithCase) + " Concepts";
  }

  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 Android3 methodsBot2(String name, final Object receiver, final List<String> exposedMethods) {
    return methodsBot2(name, receiver, exposedMethods, null);
  }

  static public Android3 methodsBot2(String name, final Object receiver, final List<String> exposedMethods, final Lock lock) {
    Android3 android = new Android3();
    android.greeting = name;
    android.console = false;
    android.responder = new Responder() {

      public String answer(String s, List<String> history) {
        return exposeMethods2(receiver, s, exposedMethods, lock);
      }
    };
    return makeBot(android);
  }

  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 List<String> db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount");

  static public List<String> db_standardExposedMethods() {
    return db_standardExposedMethods_list;
  }

  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 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 List<File> listFilesNotDirs(String dir) {
    return listFilesOnly(dir);
  }

  static public List<File> listFilesNotDirs(File... dirs) {
    return listFilesOnly(dirs);
  }

  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 int matcherInt(Matcher m, int i) {
    return parseInt(m.group(i));
  }

  static public long timestampFromYMDH(int y, int m, int d, int h) {
    return new GregorianCalendar(y, m - 1, d, h, 0).getTimeInMillis();
  }

  static public <A> List<A> sortByMap_inPlace(List<A> l, Map<A, ?> map) {
    sort(l, mapComparator(map));
    return l;
  }

  static public boolean defaultAgeBasedBackupRetentionStrategy_shouldKeep(double age, double lastAge) {
    if (age <= 0.5)
      return true;
    if (age <= 7 && age >= lastAge + 1)
      return true;
    if (age >= lastAge + 7)
      return true;
    return false;
  }

  static public <A> Set<A> cloneSet(Set<A> set) {
    if (set == null)
      return new HashSet();
    synchronized (collectionMutex(set)) {
      Set<A> s = similarEmptySet(set);
      s.addAll(set);
      return s;
    }
  }

  static public <A> Set<A> joinSets(Set<A>... l) {
    TreeSet set = new TreeSet();
    for (Set o : l) if (o != null)
      set.addAll(o);
    return set;
  }

  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 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) {
    try {
      return file.isFile() ? ImageIO.read(file) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 Thread startThread(Object runnable) {
    return startThread(defaultThreadName(), runnable);
  }

  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 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 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 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 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(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(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 JFrame consoleFrame() {
    return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
  }

  static public void autoVMExit() {
    call(getJavaX(), "autoVMExit");
  }

  static public boolean isLetterOrDigit(char c) {
    return Character.isLetterOrDigit(c);
  }

  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 int tableNumColumns(final JTable table) {
    return swing(new F0<Integer>() {

      public Integer get() {
        try {
          return table.getColumnCount();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret table.getColumnCount();";
      }
    });
  }

  static public LinkedHashMap litorderedmap(Object... x) {
    LinkedHashMap map = new LinkedHashMap();
    litmap_impl(map, x);
    return map;
  }

  static public String fsI(String id) {
    return formatSnippetID(id);
  }

  static public String fsI(long id) {
    return formatSnippetID(id);
  }

  static public File loadBinarySnippet(String snippetID) {
    try {
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(snippetID);
      long id = parseSnippetID(snippetID);
      if (isImageServerSnippet(id))
        return loadImageAsFile(snippetID);
      File f = DiskSnippetCache_getLibrary(id);
      if (fileSize(f) == 0)
        f = loadDataSnippetToFile(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 boolean isAllUpperCase(String s) {
    return hasLettersAllUpperCase(s);
  }

  static public boolean isUpperCaseLetter(char c) {
    return Character.isUpperCase(c);
  }

  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 <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 boolean isStringStartingWith(Object o, String prefix) {
    return o instanceof String && ((String) o).startsWith(prefix);
  }

  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 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, 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 Map<String, Integer> findBot_cache = synchroHashMap();

  static public int findBot_timeout = 5000;

  static public DialogIO findBot(String searchPattern) {
    String subBot = null;
    int i = searchPattern.indexOf('/');
    if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) {
      subBot = searchPattern.substring(i + 1);
      searchPattern = searchPattern.substring(0, i);
      if (!isInteger(searchPattern))
        searchPattern = "Multi-Port at " + searchPattern + ".";
    }
    if (isInteger(searchPattern))
      return talkToSubBot(subBot, talkTo(parseInt(searchPattern)));
    if (eq(searchPattern, "remote"))
      return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999));
    Integer port = findBot_cache.get(searchPattern);
    if (port != null)
      try {
        DialogIO io = talkTo("localhost", port);
        io.waitForLine();
        String line = io.readLineNoBlock();
        if (indexOfIgnoreCase(line, searchPattern) == 0) {
          call(io, "pushback", line);
          return talkToSubBot(subBot, io);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    List<ProgramScan.Program> bots = quickBotScan();
    for (ProgramScan.Program p : bots) {
      if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) {
        findBot_cache.put(searchPattern, p.port);
        return talkToSubBot(subBot, talkTo("localhost", p.port));
      }
    }
    for (ProgramScan.Program p : bots) {
      String botName = firstPartOfHelloString(p.helloString);
      boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM.");
      boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM;
      if (shouldRecurse)
        try {
          Map<Number, String> subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots"));
          for (Number vport : subBots.keySet()) {
            String name = subBots.get(vport);
            if (startsWithIgnoreCase(name, searchPattern))
              return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
          }
        } catch (Throwable __e) {
          print(exceptionToStringShort(__e));
        }
    }
    return null;
  }

  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 matchStart(String pat, String s) {
    return matchStart(pat, s, null);
  }

  static public boolean matchStart(String pat, String s, Matches matches) {
    if (s == null)
      return false;
    return matchStart(pat, parse3_cachedInput(s), matches);
  }

  static public boolean matchStart(String pat, List<String> toks, Matches matches) {
    if (toks == null)
      return false;
    List<String> tokpat = parse3_cachedPattern(pat);
    if (toks.size() < tokpat.size())
      return false;
    String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
    if (m == null)
      return false;
    if (matches != null) {
      matches.m = new String[m.length + 1];
      arraycopy(m, matches.m);
      matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size());
    }
    return true;
  }

  static public String sendToLocalBotOpt(String bot, String text, Object... args) {
    if (bot == null)
      return null;
    text = format(text, args);
    DialogIO channel = findBot(bot);
    try {
      if (channel == null) {
        print(quote(bot) + " not found, skipping send: " + quote(text));
        return null;
      }
      try {
        channel.readLine();
        print(shorten(bot + "> " + text, 200));
        channel.sendLine(text);
        String s = channel.readLine();
        print(shorten(bot + "< " + s, 200));
        return s;
      } catch (Throwable e) {
        e.printStackTrace();
        return null;
      }
    } finally {
      _close(channel);
    }
  }

  static public WeakReference<Object> creator_class;

  static public Object creator() {
    return creator_class == null ? null : creator_class.get();
  }

  static public void cleanKillVM() {
    try {
      ping();
      assertNotOnAWTThread();
      cleanKillVM_noSleep();
      Object o = new Object();
      synchronized (o) {
        o.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void cleanKillVM_noSleep() {
    call(getJavaX(), "cleanKill");
  }

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

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

  static public String fsI_flex(String s) {
    return startsWithDigit(s) ? "#" + s : s;
  }

  static public boolean exposeMethods2_debug = false;

  static public String exposeMethods2(Object receiver, String s, List<String> methodNames) {
    return exposeMethods2(receiver, s, methodNames, null);
  }

  static public String exposeMethods2(Object receiver, String s, List<String> methodNames, Lock lock) {
    Matches m = new Matches();
    if (exposeMethods2_debug)
      print("Received: " + s);
    if (match("call *", s, m)) {
      List l;
      if (isIdentifier(m.unq(0)))
        l = ll(m.unq(0));
      else
        l = (List) unstructure(m.unq(0));
      String method = getString(l, 0);
      if (!contains(methodNames, method))
        throw fail("Method not allowed: " + method);
      if (lock != null)
        lock.lock();
      try {
        if (exposeMethods2_debug)
          print("Calling: " + method);
        Object o = call(receiver, method, asObjectArray(subList(l, 1)));
        if (exposeMethods2_debug)
          print("Got: " + getClassName(o));
        return ok2(structure(o));
      } finally {
        if (lock != null)
          lock.unlock();
      }
    }
    if (match("list methods", s))
      return ok2(structure(methodNames));
    return null;
  }

  static public int makeBot(String greeting) {
    return makeAndroid3(greeting).port;
  }

  static public Android3 makeBot(Android3 a) {
    makeAndroid3(a);
    return a;
  }

  static public Android3 makeBot(String greeting, Object responder) {
    Android3 a = new Android3(greeting);
    a.responder = makeResponder(responder);
    makeBot(a);
    return a;
  }

  static public Android3 makeBot() {
    return makeAndroid3(defaultBotName());
  }

  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 boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  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 List<File> listFilesOnly(String dir) {
    return listFilesOnly(new File(dir));
  }

  static public List<File> listFilesOnly(File... dirs) {
    return concatMap(rcurry("listFilesWithSuffix", ""), dirs);
  }

  static public <T> void sort(T[] a, Comparator<? super T> c) {
    Arrays.sort(a, c);
  }

  static public <T> void sort(T[] a) {
    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) {
    Collections.sort(a, c);
  }

  static public void sort(List a) {
    Collections.sort(a);
  }

  static public <A, B> Comparator<A> mapComparator(final Map<A, B> map) {
    return new Comparator<A>() {

      public int compare(A a, A b) {
        return cmp(map.get(a), map.get(b));
      }
    };
  }

  static public Set similarEmptySet(Collection m) {
    if (m instanceof TreeSet)
      return new TreeSet(((TreeSet) m).comparator());
    if (m instanceof LinkedHashSet)
      return new LinkedHashSet();
    return new HashSet();
  }

  static public boolean eqicOneOf(String s, String... l) {
    for (String x : l) if (eqic(s, x))
      return true;
    return false;
  }

  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 boolean isURL(String s) {
    return startsWithOneOf(s, "http://", "https://", "file:");
  }

  static public BufferedImage imageIO_readURL(String url) {
    try {
      if (startsWith(url, "https:"))
        disableCertificateValidation();
      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 Lock downloadLock_lock = fairLock();

  static public Lock downloadLock() {
    return downloadLock_lock;
  }

  static public String getSnippetTitleOpt(String s) {
    return isSnippetID(s) ? getSnippetTitle(s) : 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) {
    return toRunnable(r);
  }

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

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

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

  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 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 JCheckBoxMenuItem jCheckBoxMenuItem(String text, boolean checked, final Object r) {
    final JCheckBoxMenuItem mi = 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 void toggleAlwaysOnTop(JFrame frame) {
    frame.setAlwaysOnTop(!frame.isAlwaysOnTop());
  }

  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> 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 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 long fileSize(String path) {
    return getFileSize(path);
  }

  static public long fileSize(File f) {
    return getFileSize(f);
  }

  static public File loadDataSnippetToFile(String snippetID) {
    try {
      snippetID = fsI(snippetID);
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.loadLibrary(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("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 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 <A> void setVar(IVar<A> v, A value) {
    if (v != null)
      v.set(value);
  }

  static public boolean hasLettersAllUpperCase(String s) {
    return hasLetters(s) && !containsLowerCase(s);
  }

  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 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 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> ArrayList<A> cloneListSynchronizingOn(Collection<A> l, Object mutex) {
    if (l == null)
      return new ArrayList();
    synchronized (mutex) {
      return new ArrayList<A>(l);
    }
  }

  static public DialogIO talkToSubBot(final long vport, final DialogIO io) {
    return talkToSubBot(String.valueOf(vport), io);
  }

  static public DialogIO talkToSubBot(final String subBot, final DialogIO io) {
    if (subBot == null)
      return io;
    return new talkToSubBot_IO(subBot, io);
  }

  static public class talkToSubBot_IO extends DialogIO {

    public String subBot;

    public DialogIO io;

    public talkToSubBot_IO(String subBot, DialogIO io) {
      this.io = io;
      this.subBot = subBot;
    }

    public boolean isStillConnected() {
      return io.isStillConnected();
    }

    public String readLineImpl() {
      return io.readLineImpl();
    }

    public boolean isLocalConnection() {
      return io.isLocalConnection();
    }

    public Socket getSocket() {
      return io.getSocket();
    }

    public void close() {
      try {
        io.close();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void sendLine(String line) {
      io.sendLine(format3("please forward to bot *: *", subBot, line));
    }
  }

  static public DialogIO talkTo(int port) {
    return talkTo("localhost", port);
  }

  static public int talkTo_defaultTimeout = 10000;

  static public int talkTo_timeoutForReads = 0;

  static public ThreadLocal<Map<String, DialogIO>> talkTo_byThread = new ThreadLocal();

  static public DialogIO talkTo(String ip, int port) {
    try {
      String full = ip + ":" + port;
      Map<String, DialogIO> map = talkTo_byThread.get();
      if (map != null && map.containsKey(full))
        return map.get(full);
      if (isLocalhost(ip) && port == vmPort())
        return talkToThisVM();
      return new talkTo_IO(ip, port);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public class talkTo_IO extends DialogIO {

    public String ip;

    public int port;

    public Socket s;

    public Writer w;

    public BufferedReader in;

    public talkTo_IO(String ip, int port) {
      this.port = port;
      this.ip = ip;
      try {
        s = new Socket();
        try {
          if (talkTo_timeoutForReads != 0)
            s.setSoTimeout(talkTo_timeoutForReads);
          s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
        } catch (Throwable e) {
          throw fail("Tried talking to " + ip + ":" + port, e);
        }
        w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
        in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public boolean isLocalConnection() {
      return s.getInetAddress().isLoopbackAddress();
    }

    public boolean isStillConnected() {
      return !(eos || s.isClosed());
    }

    public void sendLine(String line) {
      try {
        Lock __0 = lock;
        lock(__0);
        try {
          w.write(line + "\n");
          w.flush();
        } finally {
          unlock(__0);
        }
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String readLineImpl() {
      try {
        return in.readLine();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void close() {
      try {
        if (!noClose)
          s.close();
      } catch (IOException e) {
      }
    }

    public Socket getSocket() {
      return s;
    }
  }

  static public List<ProgramScan.Program> quickBotScan() {
    return ProgramScan.quickBotScan();
  }

  static public List<ProgramScan.Program> quickBotScan(int[] preferredPorts) {
    return ProgramScan.quickBotScan(preferredPorts);
  }

  static public List<ProgramScan.Program> quickBotScan(String searchPattern) {
    List<ProgramScan.Program> l = new ArrayList<ProgramScan.Program>();
    for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
      l.add(p);
    return l;
  }

  static public String firstPartOfHelloString(String s) {
    int i = s.lastIndexOf('/');
    return i < 0 ? s : rtrim(s.substring(0, i));
  }

  static public boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  static public Object unstructure(String text) {
    return unstructure(text, false);
  }

  static public Object unstructure(String text, final boolean allDynamic) {
    return unstructure(text, allDynamic, null);
  }

  static public int structure_internStringsLongerThan = 50;

  static public int unstructure_unquoteBufSize = 100;

  static public int unstructure_tokrefs;

  abstract static public class unstructure_Receiver {

    abstract public void set(Object o);
  }

  static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
    if (text == null)
      return null;
    return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
  }

  static public Object unstructure_reader(BufferedReader reader) {
    return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
  }

  static public Object unstructure_tok(final Producer<String> tok, final boolean allDynamic, final Object _classFinder) {
    final boolean debug = unstructure_debug;
    final class X {

      public int i = -1;

      final public Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();

      public HashMap<Integer, Object> refs = new HashMap();

      public HashMap<Integer, Object> tokrefs = new HashMap();

      public HashSet<String> concepts = new HashSet();

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

      public List<Runnable> stack = new ArrayList();

      public String curT;

      public char[] unquoteBuf = new char[unstructure_unquoteBufSize];

      public String unquote(String s) {
        return unquoteUsingCharArray(s, unquoteBuf);
      }

      public String t() {
        return curT;
      }

      public String tpp() {
        String t = curT;
        consume();
        return t;
      }

      public void parse(final unstructure_Receiver out) {
        String t = t();
        int refID = 0;
        if (structure_isMarker(t, 0, l(t))) {
          refID = parseInt(t.substring(1));
          consume();
        }
        final int _refID = refID;
        final int tokIndex = i;
        parse_inner(refID, tokIndex, new unstructure_Receiver() {

          public void set(Object o) {
            if (_refID != 0)
              refs.put(_refID, o);
            if (o != null)
              tokrefs.put(tokIndex, o);
            out.set(o);
          }
        });
      }

      public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
        String t = t();
        Class c = classesMap.get(t);
        if (c == null) {
          if (t.startsWith("\"")) {
            String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
            out.set(s);
            return;
          }
          if (t.startsWith("'")) {
            out.set(unquoteCharacter(tpp()));
            return;
          }
          if (t.equals("bigint")) {
            out.set(parseBigInt());
            return;
          }
          if (t.equals("d")) {
            out.set(parseDouble());
            return;
          }
          if (t.equals("fl")) {
            out.set(parseFloat());
            return;
          }
          if (t.equals("sh")) {
            consume();
            t = tpp();
            if (t.equals("-")) {
              t = tpp();
              out.set((short) (-parseInt(t)));
              return;
            }
            out.set((short) parseInt(t));
            return;
          }
          if (t.equals("-")) {
            consume();
            t = tpp();
            out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
            return;
          }
          if (isInteger(t) || isLongConstant(t)) {
            consume();
            if (isLongConstant(t)) {
              out.set(parseLong(t));
              return;
            }
            long l = parseLong(t);
            boolean isInt = l == (int) l;
            out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
            return;
          }
          if (t.equals("false") || t.equals("f")) {
            consume();
            out.set(false);
            return;
          }
          if (t.equals("true") || t.equals("t")) {
            consume();
            out.set(true);
            return;
          }
          if (t.equals("-")) {
            consume();
            t = tpp();
            out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
            return;
          }
          if (isInteger(t) || isLongConstant(t)) {
            consume();
            if (isLongConstant(t)) {
              out.set(parseLong(t));
              return;
            }
            long l = parseLong(t);
            boolean isInt = l == (int) l;
            out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
            return;
          }
          if (t.equals("File")) {
            consume();
            File f = new File(unquote(tpp()));
            out.set(f);
            return;
          }
          if (t.startsWith("r") && isInteger(t.substring(1))) {
            consume();
            int ref = Integer.parseInt(t.substring(1));
            Object o = refs.get(ref);
            if (o == null)
              throw fail("unsatisfied back reference " + ref);
            out.set(o);
            return;
          }
          if (t.startsWith("t") && isInteger(t.substring(1))) {
            consume();
            int ref = Integer.parseInt(t.substring(1));
            Object o = tokrefs.get(ref);
            if (o == null)
              throw fail("unsatisfied token reference " + ref + " at " + tokIndex);
            out.set(o);
            return;
          }
          if (t.equals("hashset")) {
            parseHashSet(out);
            return;
          }
          if (t.equals("lhs")) {
            parseLinkedHashSet(out);
            return;
          }
          if (t.equals("treeset")) {
            parseTreeSet(out);
            return;
          }
          if (t.equals("ciset")) {
            parseCISet(out);
            return;
          }
          if (eqOneOf(t, "hashmap", "hm")) {
            consume();
            parseMap(new HashMap(), out);
            return;
          }
          if (t.equals("lhm")) {
            consume();
            parseMap(new LinkedHashMap(), out);
            return;
          }
          if (t.equals("tm")) {
            consume();
            parseMap(new TreeMap(), out);
            return;
          }
          if (t.equals("cimap")) {
            consume();
            parseMap(ciMap(), out);
            return;
          }
          if (t.equals("ll")) {
            consume();
            {
              parseList(new LinkedList(), out);
              return;
            }
          }
          if (t.equals("syncLL")) {
            consume();
            {
              parseList(synchroLinkedList(), out);
              return;
            }
          }
          if (t.equals("sync")) {
            consume();
            {
              parse(new unstructure_Receiver() {

                public void set(Object value) {
                  if (value instanceof Map) {
                    if (value instanceof NavigableMap) {
                      out.set(Collections.synchronizedNavigableMap((NavigableMap) value));
                      return;
                    }
                    if (value instanceof SortedMap) {
                      out.set(Collections.synchronizedSortedMap((SortedMap) value));
                      return;
                    }
                    {
                      out.set(Collections.synchronizedMap((Map) value));
                      return;
                    }
                  } else {
                    out.set(Collections.synchronizedList((List) value));
                    return;
                  }
                }
              });
              return;
            }
          }
          if (t.equals("{")) {
            parseMap(out);
            return;
          }
          if (t.equals("[")) {
            this.parseList(new ArrayList(), out);
            return;
          }
          if (t.equals("bitset")) {
            parseBitSet(out);
            return;
          }
          if (t.equals("array") || t.equals("intarray")) {
            parseArray(out);
            return;
          }
          if (t.equals("ba")) {
            consume();
            String hex = unquote(tpp());
            out.set(hexToBytes(hex));
            return;
          }
          if (t.equals("boolarray")) {
            consume();
            int n = parseInt(tpp());
            String hex = unquote(tpp());
            out.set(boolArrayFromBytes(hexToBytes(hex), n));
            return;
          }
          if (t.equals("class")) {
            out.set(parseClass());
            return;
          }
          if (t.equals("l")) {
            parseLisp(out);
            return;
          }
          if (t.equals("null")) {
            consume();
            out.set(null);
            return;
          }
          if (eq(t, "c")) {
            consume();
            t = t();
            assertTrue(isJavaIdentifier(t));
            concepts.add(t);
          }
          if (eq(t, "cu")) {
            consume();
            t = tpp();
            assertTrue(isJavaIdentifier(t));
            String fullClassName = "main$" + t;
            Class _c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
            if (_c == null)
              throw fail("Class not found: " + fullClassName);
            parse(new unstructure_Receiver() {

              public void set(Object value) {
                out.set(call(_c, "_deserialize", value));
              }
            });
            return;
          }
        }
        if (eq(t, "j")) {
          consume("j");
          out.set(parseJava());
          return;
        }
        if (c == null && !isJavaIdentifier(t))
          throw new RuntimeException("Unknown token " + (i + 1) + ": " + t);
        consume();
        String className, fullClassName;
        if (eq(t(), ".")) {
          consume();
          className = fullClassName = t + "." + assertIdentifier(tpp());
        } else {
          className = t;
          fullClassName = "main$" + t;
        }
        if (c == null) {
          if (allDynamic)
            c = null;
          else
            c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
          if (c != null)
            classesMap.put(className, c);
        }
        boolean hasBracket = eq(t(), "(");
        if (hasBracket)
          consume();
        boolean hasOuter = hasBracket && eq(t(), "this$1");
        DynamicObject dO = null;
        Object o = null;
        final String thingName = t;
        if (c != null) {
          o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
          if (o instanceof DynamicObject)
            dO = (DynamicObject) o;
        } else {
          if (concepts.contains(t) && (c = findClass("Concept")) != null)
            o = dO = (DynamicObject) nuEmptyObject(c);
          else
            dO = new DynamicObject();
          dO.className = className;
        }
        if (refID != 0)
          refs.put(refID, o != null ? o : dO);
        tokrefs.put(tokIndex, o != null ? o : dO);
        final LinkedHashMap<String, Object> fields = new LinkedHashMap();
        final Object _o = o;
        final DynamicObject _dO = dO;
        if (hasBracket) {
          stack.add(new Runnable() {

            public void run() {
              try {
                if (eq(t(), ","))
                  consume();
                if (eq(t(), ")")) {
                  consume(")");
                  objRead(_o, _dO, fields, hasOuter);
                  out.set(_o != null ? _o : _dO);
                } else {
                  final String key = unquote(tpp());
                  String t = tpp();
                  if (!eq(t, "="))
                    throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
                  stack.add(this);
                  parse(new unstructure_Receiver() {

                    public void set(Object value) {
                      fields.put(key, value);
                    }
                  });
                }
              } catch (Exception __e) {
                throw rethrow(__e);
              }
            }

            public String toString() {
              return "ifdef unstructure_debug\r\n            print(\"in object values, token: \" + t())...";
            }
          });
        } else {
          objRead(o, dO, fields, hasOuter);
          out.set(o != null ? o : dO);
        }
      }

      public void objRead(Object o, DynamicObject dO, Map<String, Object> fields, boolean hasOuter) {
        if (o != null) {
          if (dO != null) {
            setOptAllDyn(dO, fields);
          } else {
            setOptAll_pcall(o, fields);
          }
          if (hasOuter)
            fixOuterRefs(o);
        } else
          for (Map.Entry<String, Object> e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
        if (o != null)
          pcallOpt_noArgs(o, "_doneLoading");
      }

      public void parseSet(final Set set, final unstructure_Receiver out) {
        this.parseList(new ArrayList(), new unstructure_Receiver() {

          public void set(Object o) {
            set.addAll((List) o);
            out.set(set);
          }
        });
      }

      public void parseLisp(final unstructure_Receiver out) {
        throw fail("class Lisp not included");
      }

      public void parseBitSet(final unstructure_Receiver out) {
        consume("bitset");
        consume("{");
        final BitSet bs = new BitSet();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(bs);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    bs.set((Integer) o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(bs);\r\n       ...";
          }
        });
      }

      public void parseList(final List list, final unstructure_Receiver out) {
        tokrefs.put(i, list);
        consume("[");
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "]")) {
                consume();
                out.set(list);
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"]\")) {\r\n          consume();\r\n          ifdef unstructure_debug\r...";
          }
        });
      }

      public void parseArray(final unstructure_Receiver out) {
        final String type = tpp();
        consume("{");
        final List list = new ArrayList();
        stack.add(new Runnable() {

          public void run() {
            try {
              if (eq(t(), "}")) {
                consume("}");
                out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
              } else {
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    list.add(o);
                    if (eq(t(), ","))
                      consume();
                  }
                });
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (eq(t(), \"}\")) {\r\n          consume(\"}\");\r\n          out.set(type.equals(\"...";
          }
        });
      }

      public Object parseClass() {
        consume("class");
        consume("(");
        String name = unquote(tpp());
        consume(")");
        Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
        if (c != null)
          return c;
        DynamicObject dO = new DynamicObject();
        dO.className = "java.lang.Class";
        name = dropPrefix("main$", name);
        dO.fieldValues.put("name", name);
        return dO;
      }

      public Object parseBigInt() {
        consume("bigint");
        consume("(");
        String val = tpp();
        if (eq(val, "-"))
          val = "-" + tpp();
        consume(")");
        return new BigInteger(val);
      }

      public Object parseDouble() {
        consume("d");
        consume("(");
        String val = unquote(tpp());
        consume(")");
        return Double.parseDouble(val);
      }

      public Object parseFloat() {
        consume("fl");
        String val;
        if (eq(t(), "(")) {
          consume("(");
          val = unquote(tpp());
          consume(")");
        } else {
          val = unquote(tpp());
        }
        return Float.parseFloat(val);
      }

      public void parseHashSet(unstructure_Receiver out) {
        consume("hashset");
        parseSet(new HashSet(), out);
      }

      public void parseLinkedHashSet(unstructure_Receiver out) {
        consume("lhs");
        parseSet(new LinkedHashSet(), out);
      }

      public void parseTreeSet(unstructure_Receiver out) {
        consume("treeset");
        parseSet(new TreeSet(), out);
      }

      public void parseCISet(unstructure_Receiver out) {
        consume("ciset");
        parseSet(ciSet(), out);
      }

      public void parseMap(unstructure_Receiver out) {
        parseMap(new TreeMap(), out);
      }

      public Object parseJava() {
        String j = unquote(tpp());
        Matches m = new Matches();
        if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
          return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
        else {
          warn("Unknown Java object: " + j);
          return null;
        }
      }

      public void parseMap(final Map map, final unstructure_Receiver out) {
        consume("{");
        stack.add(new Runnable() {

          public boolean v = false;

          public Object key;

          public void run() {
            if (v) {
              v = false;
              stack.add(this);
              if (!eq(tpp(), "="))
                throw fail("= expected, got " + t() + " in map of size " + l(map));
              parse(new unstructure_Receiver() {

                public void set(Object value) {
                  map.put(key, value);
                  if (eq(t(), ","))
                    consume();
                }
              });
            } else {
              if (eq(t(), "}")) {
                consume("}");
                out.set(map);
              } else {
                v = true;
                stack.add(this);
                parse(new unstructure_Receiver() {

                  public void set(Object o) {
                    key = o;
                  }
                });
              }
            }
          }
        });
      }

      public void consume() {
        curT = tok.next();
        ++i;
      }

      public void consume(String s) {
        if (!eq(t(), s)) {
          throw fail(quote(s) + " expected, got " + quote(t()));
        }
        consume();
      }

      public void parse_initial(unstructure_Receiver out) {
        consume();
        parse(out);
        while (nempty(stack)) popLast(stack).run();
      }
    }
    Boolean b = DynamicObject_loading.get();
    DynamicObject_loading.set(true);
    try {
      final Var v = new Var();
      X x = new X();
      x.parse_initial(new unstructure_Receiver() {

        public void set(Object o) {
          v.set(o);
        }
      });
      unstructure_tokrefs = x.tokrefs.size();
      return v.get();
    } finally {
      DynamicObject_loading.set(b);
    }
  }

  static public boolean unstructure_debug = false;

  static public String sendToLocalBotQuietly(String bot, String text, Object... args) {
    text = format3(text, args);
    DialogIO channel = newFindBot2(bot);
    try {
      if (channel == null)
        throw fail(quote(bot) + " not found");
      try {
        channel.readLine();
        channel.sendLine(text);
        String s = channel.readLine();
        return s;
      } catch (Throwable e) {
        e.printStackTrace();
        return null;
      }
    } finally {
      _close(channel);
    }
  }

  static public String sendToLocalBotQuietly(int port, String text, Object... args) {
    text = format3(text, args);
    DialogIO channel = talkTo(port);
    try {
      try {
        channel.readLine();
        channel.sendLine(text);
        String s = channel.readLine();
        return s;
      } catch (Throwable e) {
        e.printStackTrace();
        return null;
      }
    } finally {
      _close(channel);
    }
  }

  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 Map<String, List<String>> parse3_cachedInput_cache = synchronizedMRUCache(1000);

  static public List<String> parse3_cachedInput(String s) {
    List<String> tok = parse3_cachedInput_cache.get(s);
    if (tok == null)
      parse3_cachedInput_cache.put(s, tok = parse3(s));
    return tok;
  }

  static public Map<String, List<String>> parse3_cachedPattern_cache = synchronizedMRUCache(1000);

  static synchronized public List<String> parse3_cachedPattern(String s) {
    List<String> tok = parse3_cachedPattern_cache.get(s);
    if (tok == null)
      parse3_cachedPattern_cache.put(s, tok = parse3(s));
    return tok;
  }

  static public String[] match2(List<String> pat, List<String> tok) {
    int i = pat.indexOf("...");
    if (i < 0)
      return match2_match(pat, tok);
    pat = new ArrayList<String>(pat);
    pat.set(i, "*");
    while (pat.size() < tok.size()) {
      pat.add(i, "*");
      pat.add(i + 1, "");
    }
    return match2_match(pat, tok);
  }

  static public String[] match2_match(List<String> pat, List<String> tok) {
    List<String> result = new ArrayList<String>();
    if (pat.size() != tok.size()) {
      return null;
    }
    for (int i = 1; i < pat.size(); i += 2) {
      String p = pat.get(i), t = tok.get(i);
      if (eq(p, "*"))
        result.add(t);
      else if (!equalsIgnoreCase(unquote(p), unquote(t)))
        return null;
    }
    return result.toArray(new String[result.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 format(String pat, Object... args) {
    return format3(pat, args);
  }

  static public int shorten_default = 100;

  static public String shorten(String s) {
    return shorten(s, shorten_default);
  }

  static public String shorten(String s, int max) {
    return shorten(s, max, "...");
  }

  static public String shorten(String s, int max, String shortener) {
    if (s == null)
      return "";
    if (max < 0)
      return s;
    return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
  }

  static public String shorten(int max, String s) {
    return shorten(s, max);
  }

  static public void assertNotOnAWTThread() {
    assertFalse("Can't do this in AWT thread", isAWTThread());
  }

  static public boolean startsWithDigit(String s) {
    return nempty(s) && isDigit(s.charAt(0));
  }

  static public boolean isIdentifier(String s) {
    return isJavaIdentifier(s);
  }

  static public Object[] asObjectArray(Collection l) {
    return toObjectArray(l);
  }

  static public String ok2(String s) {
    return "ok " + s;
  }

  static public boolean makeAndroid3_disable = false;

  static public class Android3 {

    public String greeting;

    public boolean publicOverride = false;

    public int startPort = 5000;

    public Responder responder;

    public boolean console = true;

    public boolean quiet = false;

    public boolean daemon = false;

    public boolean incomingSilent = false;

    public int incomingPrintLimit = 200;

    public boolean useMultiPort = true;

    public boolean recordHistory = false;

    public boolean verbose = false;

    public int answerPrintLimit = 500;

    public boolean newLineAboveAnswer, newLineBelowAnswer;

    public int port;

    public long vport;

    public DialogHandler handler;

    public ServerSocket server;

    public Android3(String greeting) {
      this.greeting = greeting;
    }

    public Android3() {
    }

    synchronized public void dispose() {
      if (server != null) {
        try {
          server.close();
        } catch (IOException e) {
          print("[internal] " + e);
        }
        server = null;
      }
      if (vport != 0) {
        try {
          print("Disposing " + this);
          removeFromMultiPort(vport);
          vport = 0;
        } catch (Throwable __e) {
          _handleException(__e);
        }
      }
    }

    public String toString() {
      return "Bot: " + greeting + " [vport " + vport + "]";
    }
  }

  static abstract public class Responder {

    abstract public String answer(String s, List<String> history);
  }

  static public Android3 makeAndroid3(final String greeting) {
    return makeAndroid3(new Android3(greeting));
  }

  static public Android3 makeAndroid3(final String greeting, Responder responder) {
    Android3 android = new Android3(greeting);
    android.responder = responder;
    return makeAndroid3(android);
  }

  static public Android3 makeAndroid3(final Android3 a) {
    if (makeAndroid3_disable)
      return a;
    if (a.responder == null)
      a.responder = new Responder() {

        public String answer(String s, List<String> history) {
          return callStaticAnswerMethod(s, history);
        }
      };
    if (!a.quiet)
      print("[bot] " + a.greeting);
    if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse()))
      a.console = false;
    record(a);
    if (a.useMultiPort)
      a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a));
    if (a.console)
      makeAndroid3_handleConsole(a);
    if (a.useMultiPort)
      return a;
    a.handler = makeAndroid3_makeDialogHandler(a);
    if (a.quiet)
      startDialogServer_quiet.set(true);
    try {
      a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler);
    } finally {
      startDialogServer_quiet.set(null);
    }
    a.server = startDialogServer_serverSocket;
    return a;
  }

  static public void makeAndroid3_handleConsole(final Android3 a) {
    if (!a.quiet)
      print("You may also type on this console.");
    {
      startThread(new Runnable() {

        public void run() {
          try {
            List<String> history = new ArrayList();
            while (licensed()) {
              String line;
              try {
                line = readLine();
              } catch (Throwable e) {
                print(getInnerMessage(e));
                break;
              }
              if (line == null)
                break;
              {
                history.add(line);
                history.add(makeAndroid3_getAnswer(line, history, a));
              }
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "List<String> history = new ArrayList();\r\n    while (licensed()) {\r\n      Stri...";
        }
      });
    }
  }

  static public DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
    return new DialogHandler() {

      public void run(final DialogIO io) {
        if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
          io.sendLine("Sorry, not allowed");
          return;
        }
        String dialogID = randomID(8);
        io.sendLine(a.greeting + " / Your ID: " + dialogID);
        List<String> history = new ArrayList();
        while (io.isStillConnected()) {
          if (io.waitForLine()) {
            final String line = io.readLineNoBlock();
            String s = dialogID + " at " + now() + ": " + quote(line);
            if (!a.incomingSilent)
              print(shorten(s, a.incomingPrintLimit));
            if (eq(line, "bye")) {
              io.sendLine("bye stranger");
              return;
            }
            Matches m = new Matches();
            if (a.recordHistory)
              history.add(line);
            String answer;
            if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) {
              dialogID = unquote(m.m[0]);
              answer = "ok";
            } else
              try {
                makeAndroid3_io.set(io);
                answer = makeAndroid3_getAnswer(line, history, a);
              } finally {
                makeAndroid3_io.set(null);
              }
            if (a.recordHistory)
              history.add(answer);
            io.sendLine(answer);
          }
        }
      }
    };
  }

  static public String makeAndroid3_getAnswer(String line, List<String> history, Android3 a) {
    String answer, originalAnswer;
    try {
      originalAnswer = a.responder.answer(line, history);
      answer = makeAndroid3_fallback(line, history, originalAnswer);
    } catch (Throwable e) {
      e = getInnerException(e);
      printStackTrace(e);
      originalAnswer = answer = e.toString();
    }
    if (!a.incomingSilent) {
      if (originalAnswer == null)
        originalAnswer = "?";
      if (a.newLineAboveAnswer)
        print();
      print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
      if (a.newLineBelowAnswer)
        print();
    }
    return answer;
  }

  static public String makeAndroid3_fallback(String s, List<String> history, String answer) {
    if (answer == null && match3("what is your pid", s))
      return getPID();
    if (answer == null && match3("what is your program id", s))
      return getProgramID();
    if (match3("get injection id", s))
      return getInjectionID();
    if (answer == null)
      answer = "?";
    if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
      answer = quote(answer);
    return answer;
  }

  static public boolean makeAndroid3_consoleInUse() {
    if (isTrue(vm_generalMap_get("consoleInUse")))
      return true;
    for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console)
      return true;
    return false;
  }

  static public Responder makeAndroid3_verboseResponder(final Android3 a) {
    return new Responder() {

      public String answer(String s, List<String> history) {
        if (a.verbose)
          print("> " + shorten(s, a.incomingPrintLimit));
        String answer = a.responder.answer(s, history);
        if (a.verbose)
          print("< " + shorten(answer, a.incomingPrintLimit));
        return answer;
      }
    };
  }

  static public ThreadLocal<DialogIO> makeAndroid3_io = new ThreadLocal();

  static public Android3 makeAndroid3() {
    return makeAndroid3(getProgramTitle() + ".");
  }

  static public String makeResponder_callAnswerMethod(Object bot, String s, List<String> history) {
    String answer = (String) callOpt(bot, "answer", s, history);
    if (answer == null)
      answer = (String) callOpt(bot, "answer", s);
    return answer;
  }

  static public Responder makeResponder(final Object bot) {
    if (bot instanceof Responder)
      return (Responder) bot;
    if (bot instanceof String) {
      String f = (String) bot;
      return new Responder() {

        public String answer(String s, List<String> history) {
          String answer = (String) callOptMC((String) bot, s, history);
          if (answer == null)
            answer = (String) callOptMC((String) bot, s);
          return answer;
        }
      };
    }
    return new Responder() {

      public String answer(String s, List<String> history) {
        return makeResponder_callAnswerMethod(bot, s, history);
      }
    };
  }

  static public String defaultBotName() {
    return getProgramTitle() + ".";
  }

  static public <A, B> Map<A, B> syncMRUCache(int size) {
    return synchroMap(new MRUCache(size));
  }

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

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

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

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

  static public <A, B, C extends Collection<B>> List<B> concatMap(Iterable<A> l, IF1<A, C> f) {
    return concatMap(l, (Object) f);
  }

  static public Object rcurry(final Object f, final Object arg) {
    int n = numberOfFunctionArguments(f);
    if (n == 0)
      throw fail("function takes no arguments");
    if (n == 1)
      return new F0() {

        public Object get() {
          return callF(f, arg);
        }
      };
    if (n == 2)
      return new F1() {

        public Object get(Object a) {
          return callF(f, a, arg);
        }
      };
    throw todo("currying a function with " + n + "arguments");
  }

  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(Object a, Object b) {
    if (a == null)
      return b == null ? 0 : -1;
    if (b == null)
      return 1;
    return ((Comparable) a).compareTo(b);
  }

  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 volatile public boolean disableCertificateValidation_attempted = false;

  static public void disableCertificateValidation() {
    try {
      if (disableCertificateValidation_attempted)
        return;
      disableCertificateValidation_attempted = true;
      try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

          public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {
          }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {
          }
        } };
        HostnameVerifier hv = new HostnameVerifier() {

          public boolean verify(String hostname, SSLSession session) {
            return true;
          }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
      } catch (Throwable __e) {
        _handleException(__e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 InvocationHandler() {

      public Object invoke(Object proxy, Method method, Object[] args) {
        return call(target, method.getName(), unnull(args));
      }
    });
  }

  static public <A> A proxy(Object target, Class<A> intrface) {
    return proxy(intrface, target);
  }

  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 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 (isURL(snippetID))
      return snippetID;
    long id = parseSnippetID(snippetID);
    String url;
    if (isImageServerSnippet(id))
      url = imageServerLink(id);
    else
      url = "https://www.botcompany.de:8443/img/" + id;
    return url;
  }

  static public String getSnippetTitle(String id) {
    try {
      if (id == null)
        return null;
      if (!isSnippetID(id))
        return "?";
      IResourceLoader rl = vm_getResourceLoader();
      if (rl != null)
        return rl.getSnippetTitle(id);
      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 Runnable _topLevelErrorHandling(final Runnable runnable) {
    final Object info = _threadInfo();
    return new Runnable() {

      public void run() {
        try {
          try {
            _threadInheritInfo(info);
            runnable.run();
          } catch (Throwable __e) {
            _handleException(__e);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }";
      }
    };
  }

  static public <A> WeakReference<A> weakRef(A a) {
    return newWeakReference(a);
  }

  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 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(final 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(final 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 <A> A listGet(List<A> l, int idx) {
    return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
  }

  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 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 "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw;
    }
    return fileServerURL() + "/" + id;
  }

  static public String tb_mainServer_default = "http://code.botcompany.de:8081";

  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 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 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 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 byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

  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 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 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 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, 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 == '\'' && 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 + 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));
      ++n;
      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 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;
    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) {
    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 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 Class hotwireOnce(String programID) {
    return hotwireCached(programID, false);
  }

  static public boolean isQuoted(String s) {
    if (isNormalQuoted(s))
      return true;
    return isMultilineQuoted(s);
  }

  static public boolean isLocalhost(String ip) {
    return isLoopbackIP(ip) || eqic(ip, "localhost");
  }

  static public int vmPort() {
    return myVMPort();
  }

  static public DialogIO talkToThisVM() {
    return new talkToThisVM_IO();
  }

  static public class talkToThisVM_IO extends DialogIO {

    public List<String> answers = ll(thisVMGreeting());

    public boolean isLocalConnection() {
      return true;
    }

    public boolean isStillConnected() {
      return true;
    }

    public int getPort() {
      return vmPort();
    }

    public void sendLine(String line) {
      answers.add(or2(sendToThisVM_newThread(line), "?"));
    }

    public String readLineImpl() {
      try {
        return popFirst(answers);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void close() {
    }

    public Socket getSocket() {
      return null;
    }
  }

  public static String rtrim(String s) {
    if (s == null)
      return null;
    int i = s.length();
    while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
    return i < s.length() ? s.substring(0, i) : s;
  }

  static public Producer<String> javaTokC_noMLS_iterator(final String s) {
    return javaTokC_noMLS_iterator(s, 0);
  }

  static public Producer<String> javaTokC_noMLS_iterator(final String s, final int startIndex) {
    return new Producer<String>() {

      final public int l = s.length();

      public int i = startIndex;

      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)));
        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;
        String t = quickSubstring(s, i, j);
        i = j;
        return t;
      }
    };
  }

  static public Producer<String> javaTokC_noMLS_onReader(final BufferedReader r) {
    final class X implements Producer<String> {

      public StringBuilder buf = new StringBuilder();

      public char c, d, e = 'x';

      public X() {
        nc();
        nc();
        nc();
      }

      public void nc() {
        try {
          c = d;
          d = e;
          if (e == '\0')
            return;
          int i = r.read();
          e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public void ncSave() {
        if (c != '\0') {
          buf.append(c);
          nc();
        }
      }

      public String next() {
        while (c != '\0') {
          if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
            nc();
          else if (c == '/' && d == '*') {
            do nc(); while (c != '\0' && !(c == '*' && d == '/'));
            nc();
            nc();
          } else if (c == '/' && d == '/') {
            do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
          } else
            break;
        }
        if (c == '\0')
          return null;
        if (c == '\'' || c == '"') {
          char opener = c;
          ncSave();
          while (c != '\0') {
            if (c == opener || c == '\n') {
              ncSave();
              break;
            } else if (c == '\\') {
              ncSave();
              ncSave();
            } else
              ncSave();
          }
        } else if (Character.isJavaIdentifierStart(c))
          do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
        else if (Character.isDigit(c)) {
          do ncSave(); while (Character.isDigit(c));
          if (c == 'L')
            ncSave();
        } else
          ncSave();
        String t = buf.toString();
        buf.setLength(0);
        return t;
      }
    }
    return new X();
  }

  static public String unquoteUsingCharArray(String s, char[] buf) {
    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();
        if (l > buf.length)
          return unquote(s);
        int n = 0;
        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++;
                }
              }
              buf[n++] = (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);
                char[] x = Character.toChars(code);
                int lx = x.length;
                for (int j = 0; j < lx; j++) buf[n++] = x[j];
                i += 5;
                continue;
              default:
                ch = nextChar;
            }
            i++;
          }
          buf[n++] = ch;
        }
        return new String(buf, 0, n);
      }
    }
    return s;
  }

  static public boolean structure_isMarker(String s, int i, int j) {
    if (i >= j)
      return false;
    if (s.charAt(i) != 'm')
      return false;
    ++i;
    while (i < j) {
      char c = s.charAt(i);
      if (c < '0' || c > '9')
        return false;
      ++i;
    }
    return true;
  }

  static public String internIfLongerThan(String s, int l) {
    return s == null ? null : l(s) >= l ? intern(s) : s;
  }

  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 char unquoteCharacter(String s) {
    assertTrue(s.startsWith("'") && s.length() > 1);
    return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0);
  }

  static public BigInteger parseBigInt(String s) {
    return new BigInteger(s);
  }

  static public double parseDouble(String s) {
    return Double.parseDouble(s);
  }

  static public float parseFloat(String s) {
    return Float.parseFloat(s);
  }

  static public boolean isLongConstant(String s) {
    if (!s.endsWith("L"))
      return false;
    s = s.substring(0, l(s) - 1);
    return isInteger(s);
  }

  static public <A> TreeMap<String, A> ciMap() {
    return caseInsensitiveMap();
  }

  static public List parseList(String s) {
    return (List) safeUnstructure(s);
  }

  static public <A> List<A> synchroLinkedList() {
    return Collections.synchronizedList(new LinkedList<A>());
  }

  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 boolean[] boolArrayFromBytes(byte[] a, int n) {
    boolean[] b = new boolean[n];
    int m = min(n, l(a) * 8);
    for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0;
    return b;
  }

  static public String assertIdentifier(String s) {
    return assertIsIdentifier(s);
  }

  static public String assertIdentifier(String msg, String s) {
    return assertIsIdentifier(msg, s);
  }

  static public <A> A nuStubInnerObject(Class<A> c) {
    return nuStubInnerObject(c, null);
  }

  static public <A> A nuStubInnerObject(Class<A> c, Object classFinder) {
    try {
      Class outerType = getOuterClass(c, classFinder);
      Constructor m = c.getDeclaredConstructor(outerType);
      makeAccessible(m);
      return (A) m.newInstance(new Object[] { null });
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, Constructor> nuEmptyObject_cache = newDangerousWeakHashMap();

  static public <A> A nuEmptyObject(Class<A> c) {
    try {
      Constructor ctr;
      synchronized (nuEmptyObject_cache) {
        ctr = nuEmptyObject_cache.get(c);
        if (ctr == null) {
          nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
          makeAccessible(ctr);
        }
      }
      try {
        return (A) ctr.newInstance();
      } catch (InstantiationException e) {
        if (empty(e.getMessage()))
          if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
            throw fail("Can't instantiate abstract class " + className(c), e);
          else
            throw fail("Can't instantiate " + className(c), e);
        else
          throw rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Constructor nuEmptyObject_findConstructor(Class c) {
    for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0)
      return m;
    throw fail("No default constructor declared in " + c.getName());
  }

  static public void setOptAllDyn(DynamicObject o, Map<String, Object> fields) {
    if (fields == null)
      return;
    HashMap<String, Field> fieldMap = instanceFieldsMap(o);
    for (Map.Entry<String, Object> e : fields.entrySet()) {
      String field = e.getKey();
      Object val = e.getValue();
      boolean has = fieldMap.containsKey(field);
      if (has)
        setOpt(o, field, val);
      else {
        o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, intern(field), val);
      }
    }
  }

  static public void setOptAll_pcall(Object o, Map<String, Object> fields) {
    if (fields == null)
      return;
    for (String field : keys(fields)) try {
      setOpt(o, field, fields.get(field));
    } catch (Throwable __e) {
      print(exceptionToStringShort(__e));
    }
  }

  static public void setOptAll_pcall(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];
      try {
        setOpt(o, field, value);
      } catch (Throwable __e) {
        print(exceptionToStringShort(__e));
      }
    }
  }

  static public void fixOuterRefs(Object o) {
    try {
      if (o == null)
        return;
      Field[] l = thisDollarOneFields(o.getClass());
      if (l.length <= 1)
        return;
      Object father = null;
      for (Field f : l) {
        father = f.get(o);
        if (father != null)
          break;
      }
      if (father == null)
        return;
      for (Field f : l) f.set(o, father);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void setDynObjectValue(DynamicObject o, String field, Object value) {
    o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, field, value);
  }

  static public String intern(String s) {
    return fastIntern(s);
  }

  static public void pcallOpt_noArgs(Object o, String method) {
    try {
      callOpt_noArgs(o, method);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

  static public int[] toIntArray(Collection<Integer> l) {
    int[] a = new int[l(l)];
    int i = 0;
    if (a.length != 0)
      for (int x : l) a[i++] = x;
    return a;
  }

  static public TreeSet<String> ciSet() {
    return caseInsensitiveSet();
  }

  static public boolean jmatch(String pat, String s) {
    return jmatch(pat, s, null);
  }

  static public boolean jmatch(String pat, String s, Matches matches) {
    if (s == null)
      return false;
    return jmatch(pat, javaTok(s), matches);
  }

  static public boolean jmatch(String pat, List<String> toks) {
    return jmatch(pat, toks, null);
  }

  static public boolean jmatch(String pat, List<String> toks, Matches matches) {
    List<String> tokpat = javaTok(pat);
    String[] m = match2(tokpat, toks);
    if (m == null)
      return false;
    else {
      if (matches != null)
        matches.m = m;
      return true;
    }
  }

  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);
  }

  static public Map<String, Integer> newFindBot2_cache = synchroHashMap();

  static public boolean newFindBot2_verbose = false;

  static public DialogIO newFindBot2(String name) {
    Integer port = newFindBot2_cache.get(name);
    if (port != null) {
      if (newFindBot2_verbose)
        print("newFindBot2: testing " + name + " => " + port);
      DialogIO io = talkTo(port);
      String q = format("has bot *", name);
      String s = io.ask(q);
      if (match("yes", s)) {
        io = talkToSubBot(name, io);
        call(io, "pushback", "?");
        return io;
      }
      newFindBot2_cache.remove(name);
      if (newFindBot2_verbose)
        print("newFindBot2: dropping " + name + " => " + port);
    }
    DialogIO io = findBot(name);
    if (io != null) {
      newFindBot2_cache.put(name, io.getPort());
      if (newFindBot2_verbose)
        print("newFindBot2: remembering " + name + " => " + port);
    }
    return io;
  }

  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) ? s : prefix + s;
  }

  static public <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
    return synchroMap(new MRUCache(maxSize));
  }

  static public List<String> parse3(String s) {
    return dropPunctuation(javaTokPlusPeriod(s));
  }

  static public boolean equalsIgnoreCase(String a, String b) {
    return eqic(a, b);
  }

  static public boolean equalsIgnoreCase(char a, char b) {
    return eqic(a, b);
  }

  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 boolean isDigit(char c) {
    return Character.isDigit(c);
  }

  static public Object[] toObjectArray(Collection c) {
    List l = asList(c);
    return l.toArray(new Object[l.size()]);
  }

  static public void removeFromMultiPort(long vport) {
    if (vport == 0)
      return;
    for (Object port : getMultiPorts()) call(port, "removePort", vport);
  }

  static public String callStaticAnswerMethod(List bots, String s) {
    for (Object c : bots) try {
      String answer = callStaticAnswerMethod(c, s);
      if (!empty(answer))
        return answer;
    } catch (Throwable e) {
      print("Error calling " + getProgramID(c));
      e.printStackTrace();
    }
    return null;
  }

  static public String callStaticAnswerMethod(Object c, String s) {
    String answer = (String) callOpt(c, "answer", s, litlist(s));
    if (answer == null)
      answer = (String) callOpt(c, "answer", s);
    return emptyToNull(answer);
  }

  static public String callStaticAnswerMethod(String s) {
    return callStaticAnswerMethod(mc(), s);
  }

  static public String callStaticAnswerMethod(String s, List<String> history) {
    return callStaticAnswerMethod(mc(), s, history);
  }

  static public String callStaticAnswerMethod(Object c, String s, List<String> history) {
    String answer = (String) callOpt(c, "answer", s, history);
    if (answer == null)
      answer = (String) callOpt(c, "answer", s);
    return emptyToNull(answer);
  }

  static public List<Object> record_list = synchroList();

  static public void record(Object o) {
    record_list.add(o);
  }

  static public Object addToMultiPort_responder;

  static public long addToMultiPort(final String botName) {
    return addToMultiPort(botName, new Object() {

      public String answer(String s, List<String> history) {
        String answer = (String) (callOpt(getMainClass(), "answer", s, history));
        if (answer != null)
          return answer;
        answer = (String) callOpt(getMainClass(), "answer", s);
        if (answer != null)
          return answer;
        if (match3("get injection id", s))
          return getInjectionID();
        return null;
      }
    });
  }

  static public long addToMultiPort(final String botName, final Object responder) {
    addToMultiPort_responder = responder;
    startMultiPort();
    List ports = getMultiPorts();
    if (ports == null)
      return 0;
    if (ports.isEmpty())
      throw fail("No multiports!");
    if (ports.size() > 1)
      print("Multiple multi-ports. Using last one.");
    Object port = last(ports);
    Object responder2 = new Object() {

      public String answer(String s, List<String> history) {
        if (match3("get injection id", s))
          return getInjectionID();
        if (match3("your name", s))
          return botName;
        return (String) call(responder, "answer", s, history);
      }
    };
    record(responder2);
    return (Long) call(port, "addResponder", botName, responder2);
  }

  static public AtomicInteger dialogServer_clients = new AtomicInteger();

  static public boolean dialogServer_printConnects = false;

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

  static public Set<String> dialogServer_knownClients = synchroTreeSet();

  static public int startDialogServerOnPortAbove(int port, DialogHandler handler) {
    while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port;
    return port;
  }

  static public int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
    while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port;
    return port;
  }

  static public void startDialogServer(int port, DialogHandler handler) {
    if (!startDialogServerIfPortAvailable(port, handler))
      throw fail("Can't start dialog server on port " + port);
  }

  static public boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
    return startDialogServerIfPortAvailable(port, handler, false);
  }

  static public ServerSocket startDialogServer_serverSocket;

  static public boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port);
    } catch (IOException e) {
      return false;
    }
    final ServerSocket _serverSocket = serverSocket;
    startDialogServer_serverSocket = serverSocket;
    Thread thread = new Thread("Socket accept port " + port) {

      public void run() {
        try {
          while (true) {
            try {
              final Socket s = _serverSocket.accept();
              String client = s.getInetAddress().toString();
              if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
                print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
                dialogServer_knownClients.add(client);
              }
              String threadName = "Handling client " + s.getInetAddress();
              Thread t2 = new Thread(threadName) {

                public void run() {
                  try {
                    final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
                    final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
                    DialogIO io = new DialogIO() {

                      public boolean isLocalConnection() {
                        return s.getInetAddress().isLoopbackAddress();
                      }

                      public boolean isStillConnected() {
                        return !(eos || s.isClosed());
                      }

                      public void sendLine(String line) {
                        try {
                          w.write(line + "\n");
                          w.flush();
                        } catch (Exception __e) {
                          throw rethrow(__e);
                        }
                      }

                      public String readLineImpl() {
                        try {
                          return in.readLine();
                        } catch (Exception __e) {
                          throw rethrow(__e);
                        }
                      }

                      public void close() {
                        try {
                          s.close();
                        } catch (IOException e) {
                        }
                      }

                      public Socket getSocket() {
                        return s;
                      }
                    };
                    try {
                      handler.run(io);
                    } finally {
                      if (!io.noClose)
                        s.close();
                    }
                  } catch (IOException e) {
                    print("[internal] " + e);
                  } finally {
                  }
                }
              };
              t2.setDaemon(true);
              t2.start();
            } catch (SocketTimeoutException e) {
            }
          }
        } catch (IOException e) {
          print("[internal] " + e);
        }
      }
    };
    if (daemon)
      thread.setDaemon(true);
    thread.start();
    if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
      print("Dialog server on port " + port + " started.");
    return true;
  }

  static volatile public boolean readLine_noReadLine = false;

  static public String readLine_lastInput;

  static public String readLine_prefix = "[] ";

  static public String readLine() {
    if (readLine_noReadLine)
      return null;
    String s = readLineHidden();
    if (s != null) {
      readLine_lastInput = s;
      print(readLine_prefix + s);
    }
    return s;
  }

  static public String getInnerMessage(Throwable e) {
    if (e == null)
      return null;
    return getInnerException(e).getMessage();
  }

  static public boolean publicCommOn() {
    return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
  }

  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 boolean match3(String pat, String s) {
    return match3(pat, s, null);
  }

  static public boolean match3(String pat, String s, Matches matches) {
    if (pat == null || s == null)
      return false;
    return match3(pat, parse3_cachedInput(s), matches);
  }

  static public boolean match3(String pat, List<String> toks, Matches matches) {
    List<String> tokpat = parse3_cachedPattern(pat);
    return match3(tokpat, toks, matches);
  }

  static public boolean match3(List<String> tokpat, List<String> toks, Matches matches) {
    String[] m = match2(tokpat, toks);
    if (m == null)
      return false;
    if (matches != null)
      matches.m = m;
    return true;
  }

  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 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 String processID_cached;

  static public String getPID() {
    if (processID_cached == null) {
      String name = ManagementFactory.getRuntimeMXBean().getName();
      processID_cached = name.replaceAll("@.*", "");
    }
    return processID_cached;
  }

  static public String getInjectionID() {
    return (String) call(getJavaX(), "getInjectionID", getMainClass());
  }

  static public Object callOptMC(String method, Object... args) {
    return callOpt(mc(), method, args);
  }

  static public Map synchroMap() {
    return synchroHashMap();
  }

  static public <A, B> Map<A, B> synchroMap(Map<A, B> map) {
    return Collections.synchronizedMap(map);
  }

  static public int numberOfFunctionArguments(Object f) {
    if (f instanceof F0)
      return 0;
    if (f instanceof F1)
      return 1;
    if (f instanceof F2)
      return 2;
    if (f instanceof VF1)
      return 1;
    if (f instanceof VF2)
      return 2;
    if (f instanceof VF3)
      return 3;
    if (f instanceof String)
      return numberOfMethodArguments(mc(), (String) f);
    return numberOfMethodArguments(f, "get");
  }

  static public RuntimeException todo() {
    throw new RuntimeException("TODO");
  }

  static public RuntimeException todo(Object msg) {
    throw new RuntimeException("TODO: " + msg);
  }

  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 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 imageServerURL() {
    return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
  }

  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 <A> WeakReference<A> newWeakReference(A a) {
    return a == null ? null : new WeakReference(a);
  }

  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 Window getWindow(Object o) {
    if (!(o instanceof Component))
      return null;
    Component c = (Component) o;
    while (c != null) {
      if (c instanceof Window)
        return (Window) c;
      c = c.getParent();
    }
    return null;
  }

  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 <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 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 (url.getProtocol().equals("https"))
        disableCertificateValidation();
      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 (loadPageThroughProxy_enabled) {
          print("Trying proxy because of: " + e);
          try {
            return loadPageThroughProxy(str(url));
          } catch (Throwable e2) {
            print("  " + exceptionToStringShort(e2));
          }
        } else 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 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 <A> A println(A a) {
    return print(a);
  }

  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;
  }

  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 loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(File f, String defaultContents) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      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 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);
  }

  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(total, 100000))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void renameFile_assertTrue(File a, File b) {
    try {
      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));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 boolean isLowerCase(char c) {
    return Character.isLowerCase(c);
  }

  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 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, 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 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();
    dest.addAll(src);
  }

  static public void replaceListPart(List l, int i, int j, List l2) {
    replaceSublist(l, i, j, l2);
  }

  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 boolean isLoopbackIP(String ip) {
    return eq(ip, "127.0.0.1");
  }

  static public int myVMPort() {
    List records = (List) (get(getJavaX(), "record_list"));
    Object android = last(records);
    return or0((Integer) get(android, "port"));
  }

  static public String thisVMGreeting() {
    List record_list = (List) (get(getJavaX(), "record_list"));
    Object android = first(record_list);
    return getString(android, "greeting");
  }

  static public String sendToThisVM_newThread(String s, Object... args) {
    final String _s = format(s, args);
    try {
      return (String) evalInNewThread(new F0<Object>() {

        public Object get() {
          try {
            return callStaticAnswerMethod(getJavaX(), _s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ret callStaticAnswerMethod(getJavaX(), _s);";
        }
      });
    } catch (Throwable e) {
      e = getInnerException(e);
      printStackTrace(e);
      return str(e);
    }
  }

  static public <A> A popFirst(List<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(0);
    return a;
  }

  static public <A> A popFirst(Collection<A> l) {
    if (empty(l))
      return null;
    A a = first(l);
    l.remove(a);
    return a;
  }

  static public <A> List<A> popFirst(int n, List<A> l) {
    List<A> part = cloneSubList(l, 0, n);
    removeSubList(l, 0, n);
    return part;
  }

  static public String quickSubstring(String s, int i, int j) {
    if (i == j)
      return "";
    return s.substring(i, j);
  }

  static public <A> TreeMap<String, A> caseInsensitiveMap() {
    return new TreeMap(caseInsensitiveComparator());
  }

  static public Object safeUnstructure(String s) {
    return unstructure(s, true);
  }

  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 String assertIsIdentifier(String s) {
    if (!isIdentifier(s))
      throw fail("Not an identifier: " + quote(s));
    return s;
  }

  static public String assertIsIdentifier(String msg, String s) {
    if (!isIdentifier(s))
      throw fail(msg + " - Not an identifier: " + quote(s));
    return s;
  }

  static public Class getOuterClass(Class c) {
    return getOuterClass(c, null);
  }

  static public Class getOuterClass(Class c, Object classFinder) {
    try {
      String s = c.getName();
      int i = s.lastIndexOf('$');
      String name = substring(s, 0, i);
      if (classFinder != null)
        return (Class) callF(classFinder, name);
      return Class.forName(name);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Field> instanceFieldsMap(Object o) {
    Class c = o.getClass();
    HashMap<String, Field> map;
    synchronized (getOpt_cache) {
      map = getOpt_cache.get(c);
      if (map == null)
        map = getOpt_makeCache(c);
    }
    return map;
  }

  static public <A, B> LinkedHashMap<A, B> syncMapPut2_createLinkedHashMap(LinkedHashMap<A, B> map, A key, B value) {
    if (key != null)
      if (value != null) {
        if (map == null)
          map = new LinkedHashMap();
        synchronized (collectionMutex(map)) {
          map.put(key, value);
        }
      } else if (map != null)
        synchronized (collectionMutex(map)) {
          map.remove(key);
        }
    return map;
  }

  static public Map<Class, Field[]> thisDollarOneFields_cache = newDangerousWeakHashMap();

  static public Field[] thisDollarOneFields(Class c) {
    synchronized (thisDollarOneFields_cache) {
      Field[] l = thisDollarOneFields_cache.get(c);
      if (l == null)
        thisDollarOneFields_cache.put(c, l = thisDollarOneFields_uncached(c));
      return l;
    }
  }

  static public Field[] thisDollarOneFields_uncached(Class c) {
    List<Field> fields = new ArrayList();
    do {
      for (Field f : c.getDeclaredFields()) if (f.getName().equals("this$1"))
        fields.add(makeAccessible(f));
      c = c.getSuperclass();
    } while (c != null);
    return toArray(new Field[l(fields)], fields);
  }

  static public Method fastIntern_method;

  static public String fastIntern(String s) {
    try {
      if (s == null)
        return null;
      if (fastIntern_method == null) {
        fastIntern_method = findMethodNamed(javax(), "internPerProgram");
        if (fastIntern_method == null)
          upgradeJavaXAndRestart();
      }
      return (String) fastIntern_method.invoke(null, s);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Map<Class, HashMap<String, Method>> callOpt_noArgs_cache = newDangerousWeakHashMap();

  static public Object callOpt_noArgs(Object o, String method) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class)
        return callOpt(o, method);
      Class c = o.getClass();
      HashMap<String, Method> map;
      synchronized (callOpt_noArgs_cache) {
        map = callOpt_noArgs_cache.get(c);
        if (map == null)
          map = callOpt_noArgs_makeCache(c);
      }
      Method m = map.get(method);
      return m != null ? m.invoke(o) : null;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public HashMap<String, Method> callOpt_noArgs_makeCache(Class c) {
    HashMap<String, Method> map = new HashMap();
    Class _c = c;
    do {
      for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) {
        makeAccessible(m);
        String name = m.getName();
        if (!map.containsKey(name))
          map.put(name, m);
      }
      _c = _c.getSuperclass();
    } while (_c != null);
    callOpt_noArgs_cache.put(c, map);
    return map;
  }

  static public TreeSet<String> caseInsensitiveSet() {
    return caseInsensitiveSet_treeSet();
  }

  static public TreeSet<String> caseInsensitiveSet(Collection<String> c) {
    return caseInsensitiveSet_treeSet(c);
  }

  static public <A> boolean addToCollection(Collection<A> c, A a) {
    return c != null && c.add(a);
  }

  static public List<String> dropPunctuation_keep = ll("*", "<", ">");

  static public List<String> dropPunctuation(List<String> tok) {
    tok = new ArrayList<String>(tok);
    for (int i = 1; i < tok.size(); i += 2) {
      String t = tok.get(i);
      if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
        tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1));
        tok.remove(i);
        tok.remove(i);
        i -= 2;
      }
    }
    return tok;
  }

  static public String dropPunctuation(String s) {
    return join(dropPunctuation(nlTok(s)));
  }

  static public List<String> javaTokPlusPeriod(String s) {
    List<String> tok = new ArrayList<String>();
    if (s == null)
      return tok;
    int l = s.length();
    int i = 0;
    while (i < l) {
      int j = i;
      char c;
      String cc;
      while (j < l) {
        c = s.charAt(j);
        cc = s.substring(j, Math.min(j + 2, l));
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
          ++j;
        else if (cc.equals("/*")) {
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
          j = Math.min(j + 2, l);
        } else if (cc.equals("//")) {
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
        } else
          break;
      }
      tok.add(s.substring(i, j));
      i = j;
      if (i >= l)
        break;
      c = s.charAt(i);
      cc = s.substring(i, Math.min(i + 2, l));
      if (c == (char) 0x201C || c == (char) 0x201D)
        c = '"';
      if (c == '\'' || c == '"') {
        char opener = c;
        ++j;
        while (j < l) {
          char _c = s.charAt(j);
          if (_c == (char) 0x201C || _c == (char) 0x201D)
            _c = '"';
          if (_c == opener) {
            ++j;
            break;
          } else if (s.charAt(j) == '\\' && j + 1 < l)
            j += 2;
          else
            ++j;
        }
        if (j - 1 >= i + 1) {
          tok.add(opener + s.substring(i + 1, j - 1) + opener);
          i = j;
          continue;
        }
      } 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)));
      else if (cc.equals("[[")) {
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
        j = Math.min(j + 2, l);
      } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j + 3, l)).equals("..."))
        j += 3;
      else if (c == '$' || c == '#')
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
      else
        ++j;
      tok.add(s.substring(i, j));
      i = j;
    }
    if ((tok.size() % 2) == 0)
      tok.add("");
    return tok;
  }

  static public List<Object> getMultiPorts() {
    return (List) callOpt(getJavaX(), "getMultiPorts");
  }

  static public String emptyToNull(String s) {
    return eq(s, "") ? null : s;
  }

  static public <A, B> Map<A, B> emptyToNull(Map<A, B> map) {
    return empty(map) ? null : map;
  }

  static public void startMultiPort() {
    List mp = getMultiPorts();
    if (mp != null && mp.isEmpty()) {
      nohupJavax("#1001639");
      throw fail("Upgrading JavaX, please restart this program afterwards.");
    }
  }

  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 <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(SortedSet<A> l) {
    return l == null ? null : l.last();
  }

  static public <A> Set<A> synchroTreeSet() {
    return Collections.synchronizedSet(new TreeSet<A>());
  }

  static public boolean forbiddenPort(int port) {
    return port == 5037;
  }

  static public String readLineHidden() {
    try {
      if (get(javax(), "readLine_reader") == null)
        set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8")));
      try {
        return ((BufferedReader) get(javax(), "readLine_reader")).readLine();
      } finally {
        consoleClearInput();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 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 int numberOfMethodArguments(Object o, String method) {
    Class c;
    boolean mustBeStatic = false;
    if (o instanceof Class) {
      c = (Class) o;
      mustBeStatic = true;
    } else
      c = o.getClass();
    Class _c = c;
    int n = -1;
    while (c != null) {
      for (Method m : c.getDeclaredMethods()) {
        if (!m.getName().equals(method))
          continue;
        if (mustBeStatic && !methodIsStatic(m))
          continue;
        int nn = l(m.getParameterTypes());
        if (n == -1)
          n = nn;
        else if (n != nn)
          throw fail("Variable number of method arguments: " + _c + "." + method);
      }
      c = c.getSuperclass();
    }
    if (n == -1)
      throw fail("Method not found: " + _c + "." + method);
    return n;
  }

  static public boolean possibleMD5(String s) {
    return isMD5(s);
  }

  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 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> 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 boolean networkAllowanceTest(String url) {
    return isAllowed("networkAllowanceTest", url);
  }

  static final public boolean loadPageThroughProxy_enabled = false;

  static public String loadPageThroughProxy(String url) {
    return null;
  }

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

  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 (get(javax(), "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 {
    UnknownHostException lastException = null;
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      try {
        if (con instanceof HttpURLConnection)
          if (((HttpURLConnection) con).getResponseCode() == 500)
            throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con))));
        return con.getInputStream();
      } catch (UnknownHostException e) {
        lastException = e;
        print("Retrying because of: " + e);
        continue;
      }
    }
    throw lastException;
  }

  static public GZIPInputStream newGZIPInputStream(File f) {
    return gzInputStream(f);
  }

  static public GZIPInputStream newGZIPInputStream(InputStream in) {
    return gzInputStream(in);
  }

  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 String getComputerID_quick() {
    return computerID();
  }

  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 void _registerIO(Object object, String path, boolean opened) {
  }

  static public File muricaPasswordFile() {
    return new File(javaxSecretDir(), "murica/muricaPasswordFile");
  }

  static public ThreadLocal<VF1<File>> checkFileNotTooBigToRead_tl = new ThreadLocal();

  static public void checkFileNotTooBigToRead(File f) {
    callF(checkFileNotTooBigToRead_tl.get(), f);
  }

  static public File getProgramDir() {
    return programDir();
  }

  static public File getProgramDir(String snippetID) {
    return programDir(snippetID);
  }

  static public int roundDownTo(int x, int n) {
    return x / n * n;
  }

  static public long roundDownTo(long x, long n) {
    return x / n * n;
  }

  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 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 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 Object getOpt_cached(Object o, String field) {
    try {
      if (o == null)
        return null;
      Class c = o.getClass();
      HashMap<String, Field> map;
      synchronized (getOpt_cache) {
        map = getOpt_cache.get(c);
        if (map == null)
          map = getOpt_makeCache(c);
      }
      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 mapGet2(((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 Class<?> hotwire(String src) {
    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 int or0(Integer i) {
    return i == null ? 0 : i;
  }

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

  static public double or0(Double d) {
    return d == null ? 0.0 : d;
  }

  static public Object evalInNewThread(final Object f) {
    final Flag flag = new Flag();
    final Var var = new Var();
    final Var<Throwable> exception = new Var();
    {
      startThread(new Runnable() {

        public void run() {
          try {
            try {
              var.set(callF(f));
            } catch (Throwable e) {
              exception.set(e);
            }
            flag.raise();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "try {\r\n      var.set(callF(f));\r\n    } catch (Throwable e) {\r\n      exception...";
        }
      });
    }
    flag.waitUntilUp();
    if (exception.has())
      throw rethrow(exception.get());
    return var.get();
  }

  static public Comparator<String> caseInsensitiveComparator() {
    return betterCIComparator();
  }

  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 Object[] toArray(Collection c) {
    return toObjectArray(c);
  }

  static public <A> A[] toArray(Collection c, Class<A> type) {
    A[] a = arrayOfType(l(c), type);
    if (a.length == 0)
      return a;
    asList(c).toArray(a);
    return a;
  }

  static public <A> A[] toArray(A[] array, Collection c) {
    if (array == null || c == null)
      return null;
    asList(c).toArray(array);
    return array;
  }

  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 void upgradeJavaXAndRestart() {
    run("#1001639");
    restart();
    sleep();
  }

  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 List<String> nlTok(String s) {
    return javaTokPlusPeriod(s);
  }

  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 consoleClearInput() {
    consoleSetInput("");
  }

  static public Random defaultRandomGenerator() {
    return ThreadLocalRandom.current();
  }

  static public boolean isMD5(String s) {
    return l(s) == 32 && isLowerHexString(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 File fileInSameDir(File f, String newName) {
    return newFile(parentFile(f), newName);
  }

  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 <A> List<A> takeFirst(int n, Iterable<A> i) {
    List l = new ArrayList();
    Iterator<A> it = i.iterator();
    for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
      if (it.hasNext())
        l.add(it.next());
      else
        break;
    }
    return l;
  }

  static public String makePostData(Map<Object, Object> map) {
    StringBuilder buf = new StringBuilder();
    for (Map.Entry<Object, Object> e : 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 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 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 String getSelectedItem(JList l) {
    return (String) l.getSelectedValue();
  }

  static public String getSelectedItem(JComboBox cb) {
    return strOrNull(cb.getSelectedItem());
  }

  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 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 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 hmsWithColons() {
    return hmsWithColons(now());
  }

  static public String hmsWithColons(long time) {
    return new SimpleDateFormat("HH:mm:ss").format(time);
  }

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

  static public String joinNemptiesWithColonSpace(String... strings) {
    return joinNempties(": ", strings);
  }

  static public String joinNemptiesWithColonSpace(Collection<String> strings) {
    return joinNempties(": ", strings);
  }

  static public String tryToReadErrorStreamFromURLConnection(URLConnection conn) {
    try {
      if (conn instanceof HttpURLConnection)
        return stream2string(((HttpURLConnection) conn).getErrorStream());
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  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("UTF-8");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  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 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 <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 void clear(Collection c) {
    if (c != null)
      c.clear();
  }

  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 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 mapGet2(Map<A, B> map, A a) {
    return map == null ? null : map.get(a);
  }

  static public <A, B> B mapGet2(A a, Map<A, B> map) {
    return map == null ? null : map.get(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 _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 betterCIComparator_C betterCIComparator_instance;

  static public betterCIComparator_C betterCIComparator() {
    if (betterCIComparator_instance == null)
      betterCIComparator_instance = new betterCIComparator_C();
    return betterCIComparator_instance;
  }

  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 char stringToChar(String s) {
    if (l(s) != 1)
      throw fail("bad stringToChar: " + s);
    return firstChar(s);
  }

  static public Class run(String progID, String... args) {
    Class main = hotwire(progID);
    callMain(main, args);
    return main;
  }

  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 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)
        value = ((Long) value).intValue();
      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 void consoleSetInput(final String text) {
    if (headless())
      return;
    setTextAndSelectAll(consoleInputField(), text);
    focusConsole();
  }

  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 File associatedInfosFile(File f) {
    return replaceExtension(f, ".infos");
  }

  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 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 File parentFile(File f) {
    return dirOfFile(f);
  }

  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 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) {
    if (files != null)
      for (File f : files) if (fileExists(f))
        return f;
    return null;
  }

  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) {
          _handleException(__e);
        }
      }
      sleepInCleanUp(10);
    }
  }

  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 strOrNull(Object o) {
    return o == null ? null : str(o);
  }

  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 <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 String joinNempties(String sep, String... strings) {
    return joinStrings(sep, strings);
  }

  static public String joinNempties(String sep, Collection<String> strings) {
    return joinStrings(sep, strings);
  }

  static public String stream2string(InputStream in) {
    return utf8streamToString(in);
  }

  static public <A> A _registerIOWrap(A wrapper, Object wrapped) {
    return wrapper;
  }

  static public File computerIDFile() {
    return javaxDataDir("Basic Info/computer-id.txt");
  }

  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 <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 char firstChar(String s) {
    return s.charAt(0);
  }

  static public boolean isCISet(Iterable<String> l) {
    return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
  }

  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 && 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)
      a.putAll(b);
    return a;
  }

  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 JTextField setTextAndSelectAll(final JTextField tf, final String text) {
    if (tf != null) {
      swing(new Runnable() {

        public void run() {
          try {
            tf.setText(text);
            tf.selectAll();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "tf.setText(text);\r\n    tf.selectAll();";
        }
      });
    }
    return tf;
  }

  static public JTextField consoleInputField() {
    Object console = get(getJavaX(), "console");
    return (JTextField) getOpt(console, "tfInput");
  }

  static public void focusConsole(String s) {
    setConsoleInput(s);
    focusConsole();
  }

  static public void focusConsole() {
    JComponent tf = consoleInputFieldOrComboBox();
    if (tf != null) {
      tf.requestFocus();
    }
  }

  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 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) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }

  static public File dirOfFile(File f) {
    return f == null ? null : f.getParentFile();
  }

  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 String n2(long l) {
    return formatWithThousands(l);
  }

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

  static public String n2(double l, String singular) {
    return 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 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(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 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 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 joinStrings(String sep, String... strings) {
    return joinStrings(sep, Arrays.asList(strings));
  }

  static public String joinStrings(String sep, Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String s : unnull(strings)) if (nempty(s)) {
      if (nempty(buf))
        buf.append(sep);
      buf.append(s);
    }
    return str(buf);
  }

  static public String utf8streamToString(InputStream in) {
    return readerToString(utf8bufferedReader(in));
  }

  static public void setConsoleInput(String text) {
    consoleSetInput(text);
  }

  static public JComponent consoleInputFieldOrComboBox() {
    Object console = get(getJavaX(), "console");
    JComboBox cb = (JComboBox) (getOpt(console, "cbInput"));
    if (cb != null)
      return cb;
    return (JTextField) getOpt(console, "tfInput");
  }

  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 CloseableIterableIterator<String> linesFromFile(File f) {
    try {
      if (!f.exists())
        return emptyCloseableIterableIterator();
      if (ewic(f.getName(), ".gz"))
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
      return linesFromReader(utf8bufferedReader(f));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public CloseableIterableIterator<String> linesFromFile(String path) {
    return linesFromFile(newFile(path));
  }

  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 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 String readerToString(Reader r) {
    try {
      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 BufferedReader utf8bufferedReader(InputStream in) {
    try {
      return 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 String addPrefixIfNotEmpty2(String prefix, String s) {
    return empty(s) ? "" : addPrefix(prefix, s);
  }

  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) {
    final BufferedReader br = bufferedReader(r);
    return 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 String formatWithThousandsSeparator(long l) {
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
  }

  static public BufferedReader bufferedReader(Reader r) {
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
  }

  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 String addPrefix(String prefix, String s) {
    return s.startsWith(prefix) ? s : prefix + s;
  }

  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 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 ProgramScan {

    static public int threads = isWindows() ? 500 : 10;

    static public int timeout = 5000;

    static public String ip = "127.0.0.1";

    static public int quickScanFrom = 10000, quickScanTo = 10999;

    static public int maxNumberOfVMs_android = 4;

    static public int maxNumberOfVMs_nonAndroid = 50;

    static public int maxNumberOfVMs;

    static public boolean verbose = false;

    static public class Program {

      public int port;

      public String helloString;

      public Program(int port, String helloString) {
        this.helloString = helloString;
        this.port = port;
      }
    }

    static public List<Program> scan() {
      try {
        return scan(1, 65535);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    static public List<Program> scan(int fromPort, int toPort) {
      return scan(fromPort, toPort, new int[0]);
    }

    static public List<Program> scan(int fromPort, int toPort, int[] preferredPorts) {
      try {
        Set<Integer> preferredPortsSet = new HashSet<Integer>(asList(preferredPorts));
        int scanSize = toPort - fromPort + 1;
        String name = toPort < 10000 ? "bot" : "program";
        int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10);
        final ExecutorService es = Executors.newFixedThreadPool(threads);
        if (verbose)
          print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads.");
        startTiming();
        List<Future<Program>> futures = new ArrayList();
        List<Integer> ports = new ArrayList();
        for (int port : preferredPorts) {
          futures.add(checkPort(es, ip, port, timeout));
          ports.add(port);
        }
        for (int port = fromPort; port <= toPort; port++) if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) {
          futures.add(checkPort(es, ip, port, timeout));
          ports.add(port);
        }
        es.shutdown();
        List<Program> programs = new ArrayList();
        long time = now();
        int i = 0;
        for (final Future<Program> f : futures) {
          if (verbose)
            print("Waiting for port " + get(ports, i++) + " at time " + (now() - time));
          Program p = f.get();
          if (p != null)
            programs.add(p);
        }
        if (verbose)
          print("Found " + programs.size() + " " + name + "(s) on " + ip);
        return programs;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    static public Future<Program> checkPort(final ExecutorService es, final String ip, final int port, final int timeout) {
      return es.submit(new Callable<Program>() {

        @Override
        public Program call() {
          try {
            Socket socket = new Socket();
            try {
              socket.setSoTimeout(timeout);
              socket.connect(new InetSocketAddress(ip, port), timeout);
              BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
              String hello = or(in.readLine(), "?");
              return new Program(port, hello);
            } finally {
              socket.close();
            }
          } catch (Exception ex) {
            return null;
          }
        }
      });
    }

    static public List<Program> quickScan() {
      return scan(quickScanFrom, quickScanTo);
    }

    static public List<Program> quickBotScan() {
      return quickBotScan(new int[0]);
    }

    static public List<Program> quickBotScan(int[] preferredPorts) {
      if (maxNumberOfVMs == 0)
        maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid;
      return scan(4999, 5000 + maxNumberOfVMs - 1, preferredPorts);
    }
  }

  static abstract public class DialogIO implements AutoCloseable {

    public String line;

    public boolean eos, loud, noClose;

    public Lock lock = lock();

    abstract public String readLineImpl();

    abstract public boolean isStillConnected();

    abstract public void sendLine(String line);

    abstract public boolean isLocalConnection();

    abstract public Socket getSocket();

    public int getPort() {
      Socket s = getSocket();
      return s == null ? 0 : s.getPort();
    }

    public boolean helloRead = false;

    public int shortenOutputTo = 500;

    public String readLineNoBlock() {
      String l = line;
      line = null;
      return l;
    }

    public boolean waitForLine() {
      try {
        ping();
        if (line != null)
          return true;
        line = readLineImpl();
        if (line == null)
          eos = true;
        return line != null;
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public String readLine() {
      waitForLine();
      helloRead = true;
      return readLineNoBlock();
    }

    public String ask(String s, Object... args) {
      if (loud)
        return askLoudly(s, args);
      if (!helloRead)
        readLine();
      if (args.length != 0)
        s = format3(s, args);
      sendLine(s);
      return readLine();
    }

    public String askLoudly(String s, Object... args) {
      if (!helloRead)
        readLine();
      if (args.length != 0)
        s = format3(s, args);
      print("> " + shorten(s, shortenOutputTo));
      sendLine(s);
      String answer = readLine();
      print("< " + shorten(answer, shortenOutputTo));
      return answer;
    }

    public void pushback(String l) {
      if (line != null)
        throw fail();
      line = l;
      helloRead = false;
    }
  }

  static abstract public class DialogHandler {

    abstract public void run(DialogIO io);
  }

  static public class ConceptFieldIndex<A extends Concept, Val> implements IConceptIndex, IFieldIndex<A, Val>, IConceptCounter {

    public Class<A> cc;

    public String field;

    public HashMap<A, Val> objectToValue = new HashMap();

    public MultiSetMap<Val, A> valueToObject = new MultiSetMap();

    public ConceptFieldIndex() {
    }

    public ConceptFieldIndex(Class<A> cc, String field) {
      this(mainConcepts, cc, field);
    }

    public ConceptFieldIndex(Concepts concepts, Class<A> cc, String field) {
      this.field = field;
      this.cc = cc;
      concepts.addConceptIndex(this);
      for (A c : list(concepts, cc)) updateImpl(c);
      concepts.addFieldIndex(cc, field, this);
    }

    public void update(Concept c) {
      if (!isInstance(cc, c))
        return;
      updateImpl(c);
    }

    synchronized public void updateImpl(Concept c) {
      Val newValue = (Val) (cget(c, field));
      Val oldValue = objectToValue.get(c);
      if (newValue == null || newValue != oldValue) {
        valueToObject.remove(oldValue, (A) c);
        valueToObject.put(newValue, (A) c);
        objectToValue.put((A) c, newValue);
      }
    }

    public synchronized void remove(Concept c) {
      if (!isInstance(cc, c))
        return;
      Val value = (Val) (cget(c, field));
      objectToValue.remove(c);
      valueToObject.remove(value, (A) c);
    }

    synchronized public A get(Val value) {
      return valueToObject.getFirst(value);
    }

    public synchronized Collection<A> getAll(Val value) {
      return valueToObject.get(value);
    }

    public synchronized List<Val> allValues() {
      return cloneKeys_noSync(valueToObject.data);
    }

    public synchronized MultiSet<Val> allValues_multiSet() {
      return multiSetMapToMultiSet(valueToObject);
    }

    public Class<? extends Concept> conceptClass() {
      return cc;
    }

    public int countConcepts() {
      return l(objectToValue);
    }

    public Collection<Concept> allConcepts() {
      return (Collection) keys(objectToValue);
    }
  }

  static public class Var<A> implements IVar<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 synchronized void clear() {
      v = null;
    }

    public String toString() {
      return str(get());
    }
  }

  static abstract public class TokCondition {

    abstract public boolean get(List<String> tok, int i);
  }

  static abstract public class IterableIterator<A> implements Iterator<A>, Iterable<A> {

    public Iterator<A> iterator() {
      return this;
    }

    public void remove() {
      unsupportedOperation();
    }
  }

  static public class Flag implements Runnable {

    public boolean up = false;

    public synchronized boolean raise() {
      if (!up) {
        up = true;
        notifyAll();
        return true;
      } else
        return false;
    }

    public synchronized void waitUntilUp() {
      while (!up) {
        try {
          wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    public synchronized void waitUntilUp(long timeout) {
      if (!up) {
        try {
          wait(timeout);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    public synchronized boolean isUp() {
      return up;
    }

    public boolean get() {
      return isUp();
    }

    public String toString() {
      return isUp() ? "up" : "down";
    }

    public void waitForThisOr(Flag otherFlag) {
      try {
        while (!isUp() && !otherFlag.isUp()) Thread.sleep(50);
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void run() {
      raise();
    }
  }

  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 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 Producer<A> {

    public A next();
  }

  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);

    public File pathToJavaXJar();

    public File getSnippetJar(String snippetID, String transpiledSrc);
  }

  static public interface IVar<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

  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 class MultiSetMap<A, B> {

    public Map<A, Set<B>> data = new HashMap<A, Set<B>>();

    public MultiSetMap() {
    }

    public MultiSetMap(boolean useTreeMap) {
      if (useTreeMap)
        data = new TreeMap();
    }

    public MultiSetMap(MultiSetMap<A, B> map) {
      putAll(map);
    }

    public MultiSetMap(Map<A, Set<B>> data) {
      this.data = data;
    }

    public void put(A key, B value) {
      synchronized (data) {
        Set<B> set = data.get(key);
        if (set == null)
          data.put(key, set = _makeEmptySet());
        set.add(value);
      }
    }

    public void add(A key, B value) {
      put(key, value);
    }

    public void addAll(A key, Collection<B> values) {
      synchronized (data) {
        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(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) put(key, value);
      }
    }

    public void removeAll(A key, Collection<B> values) {
      synchronized (data) {
        for (B value : values) remove(key, value);
      }
    }

    public Set<B> get(A key) {
      synchronized (data) {
        Set<B> set = data.get(key);
        return set == null ? Collections.<B>emptySet() : set;
      }
    }

    public Set<B> getActual(A key) {
      synchronized (data) {
        Set<B> set = data.get(key);
        if (set == null)
          data.put(key, set = _makeEmptySet());
        return set;
      }
    }

    public void clean(A key) {
      synchronized (data) {
        Set<B> list = data.get(key);
        if (list != null && list.isEmpty())
          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) {
        data.remove(key);
      }
    }

    public void remove(A key, B value) {
      synchronized (data) {
        Set<B> set = data.get(key);
        if (set != null) {
          set.remove(value);
          if (set.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) {
        return first(get(key));
      }
    }

    public void addAll(MultiSetMap<A, B> map) {
      putAll(map);
    }

    public void putAll(MultiSetMap<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());
      }
    }

    public int keysSize() {
      synchronized (data) {
        return l(data);
      }
    }

    public int size() {
      synchronized (data) {
        int n = 0;
        for (Set l : data.values()) n += l(l);
        return n;
      }
    }

    public Set<A> reverseGet(B b) {
      synchronized (data) {
        Set<A> l = new HashSet();
        for (A key : data.keySet()) if (data.get(key).contains(b))
          l.add(key);
        return l;
      }
    }

    public Map<A, Set<B>> asMap() {
      synchronized (data) {
        return cloneMap(data);
      }
    }

    public boolean isEmpty() {
      synchronized (data) {
        return data.isEmpty();
      }
    }

    public Set<B> _makeEmptySet() {
      return new HashSet();
    }

    public Collection<Set<B>> allLists() {
      synchronized (data) {
        return new HashSet(data.values());
      }
    }

    public List<B> allValues() {
      return concatLists(values(data));
    }

    public Object mutex() {
      return data;
    }

    public String toString() {
      return "mm" + str(data);
    }
  }

  static public interface IConceptCounter {

    public Class<? extends Concept> conceptClass();

    public int countConcepts();

    public Collection<Concept> allConcepts();
  }

  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 <A> A highestByField(String field, Collection<A> l) {
    A best = null;
    Object bestValue = null;
    if (l != null)
      for (A a : l) {
        Object val = getOpt(a, field);
        if (val != null && (bestValue == null || cmp(val, bestValue) > 0)) {
          best = a;
          bestValue = val;
        }
      }
    return best;
  }

  static public <A> A highestByField(Collection<A> l, String field) {
    return highestByField(field, l);
  }

  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();";
      }
    });
  }

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

  static public long stopTiming_defaultMin = 10;

  static public long startTiming_startTime;

  static public void startTiming() {
    startTiming_startTime = now();
  }

  static public void stopTiming() {
    stopTiming(null);
  }

  static public void stopTiming(String text) {
    stopTiming(text, stopTiming_defaultMin);
  }

  static public void stopTiming(String text, long minToPrint) {
    long time = now() - startTiming_startTime;
    if (time >= minToPrint) {
      text = or2(text, "Time: ");
      print(text + time + " ms");
    }
  }

  static public <A, B> List<B> getAll(Map<A, B> map, Collection<A> l) {
    return lookupAllOpt(map, l);
  }

  static public <A, B> List<B> getAll(Collection<A> l, Map<A, B> map) {
    return lookupAllOpt(map, l);
  }

  static public <A, B> List<A> cloneKeys_noSync(Map<A, B> map) {
    return cloneList_noSync(keys(map));
  }

  static public <A, B> MultiSet<A> multiSetMapToMultiSet(MultiSetMap<A, B> mm) {
    MultiSet<A> ms = new MultiSet();
    for (A a : keys(mm)) ms.add(a, l(mm.get(a)));
    return ms;
  }

  static public Collection<Concept> allConcepts() {
    return db_mainConcepts().allConcepts();
  }

  static public Collection<Concept> allConcepts(Concepts concepts) {
    return concepts.allConcepts();
  }

  static public UnsupportedOperationException unsupportedOperation() {
    throw new UnsupportedOperationException();
  }

  static public <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
    return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
  }

  static public File loadLibrary(String snippetID) {
    return loadBinarySnippet(snippetID);
  }

  static public int hashCodeFor(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  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> 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 Set emptySet() {
    return new HashSet();
  }

  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> 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, 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> Collection<B> values(Map<A, B> map) {
    return map == null ? emptyList() : map.values();
  }

  static public <A, B> List<B> lookupAllOpt(Map<A, B> map, Collection<A> l) {
    List<B> out = new ArrayList();
    if (l != null)
      for (A a : l) addIfNotNull(out, map.get(a));
    return out;
  }

  static public <A, B> List<B> lookupAllOpt(Collection<A> l, Map<A, B> map) {
    return lookupAllOpt(map, l);
  }

  static public <A> ArrayList<A> cloneList_noSync(Iterable<A> l) {
    return l instanceof Collection ? cloneList_noSync((Collection) l) : asList(l);
  }

  static public <A> ArrayList<A> cloneList_noSync(Collection<A> l) {
    if (l == null)
      return new ArrayList();
    return new ArrayList<A>(l);
  }
}