Warning : session_start(): open(/var/lib/php/sessions/sess_1ajb05k0os5rh5oitig21qrm78, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
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 java.awt.datatransfer.*;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;
import java.text.NumberFormat;
import java.text.*;
import javax.swing.undo.UndoManager;
import java.util.TimeZone;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.geom.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
class main {
static class ModuleInfo {
String name;
long code, data;
}
static class ModuleRAMSizes extends DynObjectTable {
void start() { try { super.start();
itemToMap = new F1() { public Map get(ModuleInfo m) { try {
return litorderedmap(
"Name" , m.name,
"Code (+submodules)" , str_toK_questionMarkIfZero(m.code),
"Data" , str_toK_questionMarkIfZero(m.data),
"Sum" , str_toK_questionMarkIfZero(m.code + m.data));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "litorderedmap(\r\n Name := m.name,\r\n \"Code (+submodules)\" := str_..."; }};
doEvery(dm_osStarting() ? 10.0 : 0.0, 60.0, new Runnable() { public void run() { try { calcIt();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "calcIt();"; }});
} catch (Exception __e) { throw rethrow(__e); } }
void calcIt() {
AutoCloseable __2 = enter(); try {
List l = new ArrayList();
long _startTime_0 = sysNow();
for (Object mod : dm_listModules()) {
long code = 0, data = 0;
try { code = dm_moduleCodeSizeWithSubModules(mod); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
try { data = dm_moduleSize(mod); } catch (Throwable __e) { print(exceptionToStringShort(__e)); }
l.add(nu(ModuleInfo.class,
"name" , dm_moduleName(mod),
"code", code,
"data", data));
}
done2_always("Calculate Module Sizes", _startTime_0);
setData(sortedByCalculatedFieldDesc(new F1() { public Object get(ModuleInfo m) { try { return m.code+m.data; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "m.code+m.data"; }}, l));
} finally { _close(__2); }}
}
static boolean _moduleClass_ModuleRAMSizes = true;
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_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 Field get_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 Object get(String field, Object o) {
return get(o, field);
}
static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static String str_toK_questionMarkIfZero(long l) {
return l == 0 ? "?" : toK(l) + " K";
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
// firstDelay = delay
static FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
// reversed argument order for fun
static FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static boolean dm_osStarting() {
return dm_osLoading();
}
static long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static List dm_listModules() {
return (List) dm_callOS("listModules");
}
static long dm_moduleCodeSizeWithSubModules(Object mod) {
Class mc = getMainClass(dm_getModule(mod));
if (mc == dm_os()) return 0;
return loadedCodeSizeOfProgramAndSubModules(mc);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static volatile Object print_preprocess;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping_okInCleanUp();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
print_raw(s);
}
static 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 void print_autoRotate() {
}
static 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 long dm_moduleSize(Object mod) {
return dm_moduleSize(mod, new guessDeepObjectSize_recursive_Data());
}
static long dm_moduleSize(Object mod, guessDeepObjectSize_recursive_Data data) {
data.realmsToIgnore = lithashset(getRealm(dm_os()));
return guessDeepObjectSize_recursive(data, dm_getModule(mod));
}
static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static String dm_moduleName() {
return dm_moduleName(assertNotNull(dm_current_generic()));
}
static String dm_moduleName(Object module) {
return (String) callOpt(dm_getStem(module), "moduleName");
}
static long done2_always(long startTime, String desc) {
long time = sysNow()-startTime;
// BREAKING CHANGE: Now stores result for lastTiming()
saveTiming_noPrint(time);
print(desc + " [" + time + " ms]");
return time;
}
static long done2_always(String desc, long startTime) {
return done2_always(startTime, desc);
}
static long done2_always(long startTime) {
return done2_always(startTime, "");
}
// f: A -> Comparable
static List sortedByCalculatedFieldDesc(Collection c, final Object f) {
return sortByCalculatedFieldDesc(c, f);
}
static List sortedByCalculatedFieldDesc(Object f, Collection c) {
return sortByCalculatedFieldDesc(f, c);
}
static List sortedByCalculatedFieldDesc(Iterable c, IF1 f) {
return sortByCalculatedFieldDesc(c, f);
}
static List sortedByCalculatedFieldDesc(IF1 f, Iterable c) {
return sortByCalculatedFieldDesc(f, c);
}
static void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); }
static Field getOpt_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);
return null;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error",e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, c);
}
return c;
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static 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 long toK(long l) {
return (l+1023)/1024;
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
static String shorten(String s, int max) {
return shorten(s, max, "...");
}
static 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 String shorten(int max, String s) { return shorten(s, max); }
static String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
// r may return false to cancel timer
static TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static class SmartTimerTask extends TimerTask implements IFieldsToList{
Object r;
java.util.Timer timer;
long delay;
Object threadInfo;
SmartTimerTask() {}
SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;}
public String toString() { return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")"; }public Object[] _fieldsToList() { return new Object[] {r, timer, delay, threadInfo}; }
long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r); try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay*0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally { _close(__1); }}
}
}
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt(((String) o));
if (o instanceof Boolean)
return boolToInt(((Boolean) o));
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted",timer, costCenter());
return timer;
}
static long toMS(double seconds) {
return (long) (seconds*1000);
}
static boolean dm_osLoading() {
return isTrue(dm_callOS("isLoading"));
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
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 Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
static Class getMainClass() {
return mc();
}
static 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 Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, "")) return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static Object dm_os() {
{ Object __1= vm_generalMap_get("stefansOS"); if (__1 != null) return __1; }
return creator();
}
static long loadedCodeSizeOfProgramAndSubModules(Object program) {
return intSumAsLong(map("classSizeInBytes",loadedClassesOfProgramAndSubModules(program)));
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
// this syntax should be removed...
static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static 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 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); } }
// PersistableThrowable doesn't hold GC-disturbing class references in backtrace
static volatile PersistableThrowable lastException_lastException;
static PersistableThrowable lastException() {
return lastException_lastException;
}
static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static Throwable getInnerException(Throwable e) {
if (e == null) return null;
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url))) return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.')+1);
}
static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static String getRealm(Object o) {
if (o == null) return null;
Object classLoader = getClass(o).getClassLoader();
return (String) getOpt(classLoader, "progID");
}
static class guessDeepObjectSize_recursive_Data {
long size;
List stack = new ArrayList();
Set seen = identityHashSet(); // add objects here to ignore them
Set fieldsToIgnore;
Set realmsToIgnore;
VF1 onNewObject;
}
static long guessDeepObjectSize_recursive(Object o) {
if (o == null) return 0;
return guessDeepObjectSize_recursive(new guessDeepObjectSize_recursive_Data(), o);
}
static long guessDeepObjectSize_recursive(guessDeepObjectSize_recursive_Data data, Object o) {
if (o == null) return 0;
data.stack.add(o);
while (nempty(data.stack)) { ping();
/*ifdef guessDeepObjectSize_recursive_debug
print("gos stack size: " + l(data.stack));
endifdef*/
guessDeepObjectSize_recursive_step(data, popLast(data.stack));
}
return data.size;
}
static void guessDeepObjectSize_recursive_step(guessDeepObjectSize_recursive_Data data, Object o) {
if (!data.seen.add(o)) return;
if (guessDeepObjectSize_shouldIgnoreObject(o)) return;
callF(data.onNewObject, o);
if (data.realmsToIgnore != null && contains(data.realmsToIgnore, getRealm(o))) return;
if (o instanceof Class) return;
if (isArray(o)) {
int len;
if (o instanceof Object[]) {
// len is computed correctly by unsafe_sizeOf
len = unsafe_sizeOf(o);
for (Object x : (Object[]) o)
if (x != null && !data.seen.contains(x)) data.stack.add(x);
} else
len = inMemorySizeOfPrimitiveArray(o);
data.size += len;
return;
}
data.size += unsafe_sizeOf(o);
if (sizeCalculation_shouldSkipObject(o)) return;
for (Field f : nonStaticNonPrimitiveFieldObjects(o)) {
if (contains(data.fieldsToIgnore, f)) continue;
Object x;
try {
x = f.get(o);
} catch (Throwable e) {
print("Error trying to access " + f + ": " + e);
continue;
}
if (x != null && !data.seen.contains(x)) {
data.stack.add(x);
}
}
//fail("can't handle object type: " + className(o));
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static 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 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 A setAll(A o, Map fields) {
if (fields == null) return o;
for (String field : keys(fields))
set(o, field, fields.get(field));
return o;
}
static A setAll(A o, Object... values) {
//values = expandParams(c.getClass(), values);
failIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
set(o, field, value);
}
return o;
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
// named like this for historic reasons
static InheritableThreadLocal dm_currentModule_value = new InheritableThreadLocal();
static Object dm_current_generic() {
return getWeakRef(dm_currentModule_value.get());
}
// prevent memory leak
static void cleanMeUp_dm_current_generic() {
dm_currentModule_value = new InheritableThreadLocal();
}
static Object callOpt(Object o) {
return callF(o);
}
static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
static Object dm_getStem(Object moduleOrID) {
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
moduleOrID = dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static ThreadLocal saveTiming_last = new ThreadLocal();
static void saveTiming(long ms) {
print(ms + " ms");
saveTiming_noPrint(ms);
}
static void saveTiming_noPrint(long ms) {
saveTiming_last.set(ms);
}
// f: A -> Comparable
static List sortByCalculatedFieldDesc(Collection c, final Object f) {
return sortByCalculatedFieldDesc_inPlace(cloneList(c), f);
}
static List sortByCalculatedFieldDesc(Object f, Collection c) {
return sortByCalculatedFieldDesc(c, f);
}
static List sortByCalculatedFieldDesc(Iterable c, IF1 f) {
List l = cloneList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return stdcompare(f.get(b), f.get(a));
}
});
return l;
}
static List sortByCalculatedFieldDesc(IF1 f, Iterable c) {
return sortByCalculatedFieldDesc(c, f);
}
static ThreadLocal print_byThread() {
synchronized(print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
// f can return false to suppress regular printing
// call print_raw within f to actually print something
static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static 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 void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static Class javax() {
return getJavaX();
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static 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);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static List> _threadInfo_makers = synchroList();
static Object _threadInfo() {
if (empty(_threadInfo_makers)) return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static 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 volatile boolean licensed_yes = true;
static boolean licensed() {
if (!licensed_yes) return false;
ping_okInCleanUp();
return true;
}
static void licensed_off() {
licensed_yes = false;
}
static List> _threadInheritInfo_retrievers = synchroList();
static void _threadInheritInfo(Object info) {
if (info == null) return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static AutoCloseable tempActivity(Object r) {
return null;
}
static long fixTimestamp(long timestamp) {
return timestamp > now() ? 0 : timestamp;
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static void pcallF(VF1 f, A a) {
try {
if (f != null) f.get(a);
} catch (Throwable __e) { _handleException(__e); }
}
static int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static int boolToInt(boolean b) {
return b ? 1 : 0;
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object costCenter() { return mc(); }
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Thread currentThread() {
return Thread.currentThread();
}
static Class mc() {
return main.class;
}
static boolean isString(Object o) {
return o instanceof String;
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static WeakReference creator_class;
static Object creator() {
return creator_class == null ? null : creator_class.get();
}
static long intSumAsLong(Iterable l) {
long sum = 0;
for (Integer i : unnull(l))
if (i != null) sum += i;
return sum;
}
static List map(Iterable l, Object f) { return map(f, l); }
static 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 List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(callF(f, o));
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
x.add(f.get(o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static 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 List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static Map classSizeInBytes_cache = weakHashMap();
static int classSizeInBytes(Class c) {
Integer size = classSizeInBytes_cache.get(c);
if (size == null)
classSizeInBytes_cache.put(c, size = classSizeInBytes_uncached(c));
return size;
}
static int classSizeInBytes_uncached(Class c) { try {
List files = (List) (get(getClassLoader(c), "files"));
String name = c.getName().replace('.', '/') + ".class";
for (File location : files)
if (location.isDirectory()) {
File f = new File(location, name);
if (f.exists()) return toInt_checked(fileSize(f));
} else if (location.isFile()) { try {
ZipFile zip = new ZipFile(location); try {
ZipEntry entry = zip.getEntry(name);
if (entry != null) return toInt_checked(entry.getSize());
} finally { _close(zip); }} catch (Throwable __e) { _handleException(__e); }}
print(name + " not found in: " + files);
return -1;
} catch (Exception __e) { throw rethrow(__e); } }
static List loadedClassesOfProgramAndSubModules(Object program) {
return concatMap(__20 -> loadedClassesOfProgram(__20),listPlus(dependentClassesOfProgram(program), (Class) program));
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) { try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) { try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) { throw rethrow(__e); } }
static Field getOpt_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);
return null;
}
static A or(A a, A b) {
return a != null ? a : b;
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
static 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 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 int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
int n = l(l);
for (int i = startIndex; i < n; i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++)
if (eq(x[i], a))
return i;
return -1;
}
static 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 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 PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m)) return true; return false;
}
static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static String hostNameFromURL(String url) { try {
return new URL(url).getHost();
} catch (Exception __e) { throw rethrow(__e); } }
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static Map emptyMap() {
return new HashMap();
}
static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static 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 boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(double[] a) { return a == null || a.length == 0; }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); }
static boolean empty(File f) { return getFileSize(f) == 0; }
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static 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 Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static A popLast(List l) {
return liftLast(l);
}
static List popLast(int n, List l) {
return liftLast(n, l);
}
static boolean guessDeepObjectSize_shouldIgnoreObject(Object o) {
return o instanceof Component // skipping AWT for now
|| o instanceof Thread || o instanceof ThreadLocal
|| startsWith(className(o), "sun.");
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static boolean contains(Producer p, A a) {
if (p != null && a != null) while (true) {
A x = p.next();
if (x == null) break;
if (eq(x, a)) return true;
}
return false;
}
static boolean isArray(Object o) {
return o != null && o.getClass().isArray();
}
static Map unsafe_sizeOf_cache = weakHashMap();
static int unsafe_sizeOf(Object o) {
Class c = _getClass(o);
if (o instanceof Object[])
return unsafe_sizeOf_uncached(o, c); // can't cache
Integer l = unsafe_sizeOf_cache.get(c);
if (l == null)
unsafe_sizeOf_cache.put(c, l = unsafe_sizeOf_uncached(o, c));
return l;
}
static int unsafe_sizeOf_uncached(Object o, Class src) {
int WORD = javaDataModelWordSize();
int MIN_SIZE = 16;
List instanceFields = new ArrayList();
while (src != null && src != Object.class && empty(instanceFields)) {
for (Field f : src.getDeclaredFields())
if ((f.getModifiers() & Modifier.STATIC) == 0)
instanceFields.add(f);
src = src.getSuperclass();
}
long maxOffset = MIN_SIZE;
if (o instanceof Object[]) {
int n = l((Object[]) o);
maxOffset = lowestValue(unsafe_allFieldOffsets(Pair.class)) + 4 + java_pointerSize()*(n-1);
} else // TODO: add primitive arrays
for (Field f : instanceFields) {
long offset = (long) (call(theUnsafe_gen(), "objectFieldOffset", f));
if (offset > maxOffset) maxOffset = offset;
}
return (((int) maxOffset/WORD) + 1)*WORD;
}
static int inMemorySizeOfPrimitiveArray(Object o) {
return roundUpTo(javaDataModelWordSize(),
unsafe_sizeOf(_SimulatedArrayStub.class) + primitiveTypeSize(arrayElementType(o))*l(o));
}
static TreeSet sizeCalculation_shouldSkipObject_set = asTreeSet(tlft("\r\n java.io.\r\n java.lang.reflect.\r\n java.awt.\r\n javax.swing.\r\n"));
static boolean sizeCalculation_shouldSkipObject(Object o) {
if (o instanceof Reference) return true;
return startsWithOneOf_treeSet(className(o), sizeCalculation_shouldSkipObject_set);
}
static final Map> nonStaticNonPrimitiveFieldObjects_cache = dangerousWeakMap();
static List nonStaticNonPrimitiveFieldObjects(Object o) {
Class c = o.getClass();
List fields;
synchronized(nonStaticNonPrimitiveFieldObjects_cache) {
fields = nonStaticNonPrimitiveFieldObjects_cache.get(c);
if (fields == null)
nonStaticNonPrimitiveFieldObjects_cache.put(c, fields = nonStaticNonPrimitiveFieldObjects_uncached(c));
}
return fields;
}
static Map classForName_cache = synchroHashMap();
static Class classForName(String name) { try {
if (classForName_cache == null) return Class.forName(name); // in class init
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 Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
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 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 List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static 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 Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiSet ms) {
return ms.keySet();
}
static 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 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 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 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 void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
static void assertTrue(Object o) {
if (!(eq(o, true) /*|| isTrue(pcallF(o))*/))
throw fail(str(o));
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static A getWeakRef(Reference ref) {
return ref == null ? null : ref.get();
}
static Object callOpt_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
// TODO: varargs
return null;
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
// f: A -> Comparable
static List sortByCalculatedFieldDesc_inPlace(List l, final Object f) {
sort(l, new Comparator () {
public int compare(A b, A a) {
return stdcompare((Object) callF(f, a), (Object) callF(f, b));
}
});
return l;
}
static List sortByCalculatedFieldDesc_inPlace(Object f, List c) {
return sortByCalculatedFieldDesc_inPlace(c, f);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static void sort(int[] a) { if (a != null) Arrays.sort(a); }
static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static void sort(List a) {
Collections.sort(a);
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal 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 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);
// try varargs
List 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);
// try varargs
List 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 Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null
: l(args) == 1 ? args[0]
: args;
}
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static Set vm_busListeners_live_cache;
static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; }
static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static Map vm_busListenersByMessage_live_cache;
static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; }
static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static int strL(String s) {
return s == null ? 0 : s.length();
}
static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static 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 Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static 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); // not using pcall here - it could lead to endless loops
}
}
static boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static List _registerWeakMap_preList;
static A _registerWeakMap(A map) {
if (javax() == null) {
// We're in class init
if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null) return;
for (Object o : _registerWeakMap_preList)
_registerWeakMap(o);
_registerWeakMap_preList = null;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static 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 Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{ Object __1= pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__1 != null) return __1; }
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static Map weakHashMap() {
return newWeakHashMap();
}
static ClassLoader getClassLoader(Object o) {
return o == null ? null : _getClass(o).getClassLoader();
}
static int toInt_checked(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
// f must return a list
static List concatMap(Object f, Iterable l) {
return concatLists(map(f, l));
}
static List concatMap(Iterable l, Object f) {
return concatMap(f, l);
}
static List concatMap(Object f, Object[] l) {
return concatLists(map(f, l));
}
static List concatMap(Object[] l, Object f) {
return concatMap(f, l);
}
static > List concatMap(Iterable l, IF1 f) {
return concatMap(l, (Object) f);
}
static > List concatMap(IF1 f, Iterable l) {
return concatMap(l, f);
}
static List loadedClassesOfProgram(Object program) {
return cloneListOrNull((Collection) getOpt(getClassLoader(program), "loadedClasses"));
}
static List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
static List dependentClassesOfProgram(Object program) {
return getWeakReferencesList((List>) getOpt(program, "hotwire_classes"));
}
//static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init);
static class getOpt_Map extends WeakHashMap {
getOpt_Map() {
if (getOpt_special == null) getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
//print("getOpt clear");
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
//static final Map> getOpt_cache = _registerWeakMap(synchroMap(new getOpt_Map));
static HashMap getOpt_special; // just a marker
/*static void getOpt_special_init(Map map) {
map.put(Class.class, getOpt_special);
map.put(S.class, getOpt_special);
}*/
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap 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 S)
ret getOpt(getBot((S) 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); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap 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 List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() { 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) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static String joinWithSpace(Iterable c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static 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 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 boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static String theAGIBlueDomain() {
return "agi.blue";
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static 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 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 byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static A liftLast(List l) {
if (empty(l)) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
static List liftLast(int n, List l) {
int i = l(l)-n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static String className(Object o) {
return getClassName(o);
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static int javaDataModelWordSize_value;
static int javaDataModelWordSize() {
if (javaDataModelWordSize_value == 0)
javaDataModelWordSize_value = Integer.valueOf(System.getProperty("sun.arch.data.model"))/8;
return javaDataModelWordSize_value;
}
static B lowestValue(Map map) {
B best = null;
for (B b : values(map))
if (best == null || cmp(b, best) < 0)
best = b;
return best;
}
static Map unsafe_allFieldOffsets(Object o){
Class src = _getClass(o);
Map map = new HashMap();
while (src != null && src != Object.class) {
for (Field f : src.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) == 0) {
long offset = (long) (call(theUnsafe_gen(), "objectFieldOffset", f));
String name = f.getName();
if (map.containsKey(name)) name = lightlyShortClassName(src) + "." + name;
map.put(name, offset);
}
}
src = src.getSuperclass();
}
return orderMapByValue(map);
}
static int java_pointerSize() {
boolean c = compressedOOPSEnabled();
return compressedOOPSEnabled_is64bitHotSpot && !c ? 8 : 4;
}
static Object theUnsafe_gen_theUnsafe;
static Object theUnsafe_gen() {
if (theUnsafe_gen_theUnsafe == null)
theUnsafe_gen_theUnsafe = get(classForName("sun.misc.Unsafe"), "theUnsafe");
return theUnsafe_gen_theUnsafe;
}
static int roundUpTo(int n, int x) {
return (x+n-1)/n*n;
}
static long roundUpTo(long n, long x) {
return (x+n-1)/n*n;
}
static int primitiveTypeSize(Class c) {
if (c == byte.class || c == boolean.class) return 1;
if (c == short.class || c == char.class) return 2;
if (c == int.class || c == float.class) return 4;
if (c == long.class || c == double.class) return 8;
return 0;
}
static Class arrayElementType(Object o) {
return _getClass(o).getComponentType();
}
static TreeSet asTreeSet(Collection set) {
return set == null ? null : set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}
static List tlft(String s) { return toLinesFullTrim(s); }
static List tlft(File f) { return toLinesFullTrim(f); }
static boolean startsWithOneOf_treeSet(String s, TreeSet set) {
if (set == null || s == null) return false;
while (licensed()) {
String key = set.floor(s);
if (key == null) return false; // s is in front of whole set => no prefix in there
int n = lCommonPrefix(key, s);
if (n == l(key)) return true; // found!
s = takeFirst(s, n); // shorten and try again
}
return false; // dummy
}
static Map dangerousWeakMap() {
return newDangerousWeakHashMap();
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map dangerousWeakMap(Object initFunction) {
return newDangerousWeakHashMap(initFunction);
}
static List nonStaticNonPrimitiveFieldObjects_uncached(Object o) {
List fields = new ArrayList();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields())
if ((f.getModifiers() & Modifier.STATIC) == 0 && !isPrimitiveType(f.getType()))
fields.add(makeAccessible(f));
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
// take care of common case (long to int)
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 boolean odd(int i) {
return (i & 1) != 0;
}
static boolean odd(long i) {
return (i & 1) != 0;
}
static boolean odd(BigInteger i) { return odd(toInt(i)); }
static final Map callOpt_cache = newDangerousWeakHashMap();
static 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);
// TODO: (super-rare) case where method exists static and non-static
// with different args
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 _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 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 Object collectionMutex(List l) {
return l;
}
static 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 int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static 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 Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static Set vm_generalIdentityHashSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static Map vm_generalHashMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
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 int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
// starts searching from i-1
static int lastIndexOf(List l, int i, A a) {
if (l == null) return -1;
for (i = min(l(l), i)-1; i >= 0; i--)
if (eq(l.get(i), a))
return i;
return -1;
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l))
{ Object __1= pcallF(f, args); if (__1 != null) return __1; }
return null;
}
static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext())
{ Object __2= pcallF(it.next(), args); if (__2 != null) return __2; }
return null;
}
static String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
static List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null) for (Iterable list : lists)
addAll(l, list);
return l;
}
static ArrayList cloneListOrNull(Iterable l) {
return l == null ? null : cloneList(l);
}
static ArrayList cloneListOrNull(Collection l) {
return l == null ? null : cloneList(l);
}
static List getWeakReferencesList(List> l) {
List out = new ArrayList();
for (WeakReference ref : unnull(l))
addIfNotNull(out, ref.get());
return out;
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void clear(Map map) {
if (map != null) map.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l)) l.set(i, a);
}
static B mapGet2(Map map, A a) {
return map == null ? null : map.get(a);
}
static B mapGet2(A a, Map map) {
return map == null ? null : map.get(a);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Set reflection_classesNotToScan_value = litset(
"jdk.internal.loader.URLClassPath"
);
static Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with arguments (" + joinWithComma(getClasses(args)) + ") found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(m);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1) return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator 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 String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null) for (Object o : l)
out.add(o == null ? null : getClassName(o));
return out;
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static 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 boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static void removeSubList(List l, int from, int to) {
if (l != null) subList(l, from, to).clear();
}
static void removeSubList(List l, int from) {
if (l != null) subList(l, from).clear();
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
// convenience shortcut for values_gen
static Collection values(Object map) {
return values((Map) map);
}
static String lightlyShortClassName(Object o) {
if (o == null) return null;
return lightlyShortenClassName(className(o));
}
static LinkedHashMap orderMapByValue(final Map map) {
List l = new ArrayList(map.keySet());
sort(l, mapComparator(map));
LinkedHashMap map2 = litorderedmap();
for (A a : l)
map2.put(a, map.get(a));
return map2;
}
static boolean compressedOOPSEnabled_is64bitHotSpot = false;
static boolean compressedOOPSEnabled_compressedOOPS = false;
static boolean compressedOOPSEnabled_checked = false;
static boolean compressedOOPSEnabled() {
if (compressedOOPSEnabled_checked) return compressedOOPSEnabled_compressedOOPS;
String OS_ARCH = System.getProperty("os.arch");
String MANAGEMENT_FACTORY_CLASS = "java.lang.management.ManagementFactory";
String HOTSPOT_BEAN_CLASS = "com.sun.management.HotSpotDiagnosticMXBean";
String x = System.getProperty("sun.arch.data.model");
boolean is64Bit = contains(or(x, OS_ARCH), "64");
if (is64Bit) {
try {
final Class> beanClazz = Class.forName(HOTSPOT_BEAN_CLASS);
final Object hotSpotBean = Class.forName(MANAGEMENT_FACTORY_CLASS).getMethod("getPlatformMXBean", Class.class)
.invoke(null, beanClazz);
if (hotSpotBean != null) {
compressedOOPSEnabled_is64bitHotSpot = true;
final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
try {
final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "UseCompressedOops");
compressedOOPSEnabled_compressedOOPS = Boolean.parseBoolean(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
} catch (ReflectiveOperationException | RuntimeException e) {
compressedOOPSEnabled_is64bitHotSpot = false;
}
}
} catch (ReflectiveOperationException | RuntimeException e) {
compressedOOPSEnabled_is64bitHotSpot = false;
}
}
compressedOOPSEnabled_checked = true;
return compressedOOPSEnabled_compressedOOPS;
}
static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line);
return l;
}
static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line);
return l;
}
static int lCommonPrefix(String a, String b) {
int i = 0, n = min(l(a), l(b));
while (i < n && a.charAt(i) == b.charAt(i))
++i;
return i;
}
static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static String takeFirst(int n, String s) { return substring(s, 0, n); }
static String takeFirst(String s, int n) { return substring(s, 0, n); }
static List takeFirst(int n, Iterable i) {
if (i == null) return null;
List l = new ArrayList();
Iterator 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 boolean isPrimitiveType(Class c) {
return c != null && c.isPrimitive();
}
static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap) return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null) synchronized(collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static 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 A printStackTrace(A e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static 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 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 void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static Map addAll(Map a, Map extends A,? extends B> b) {
if (a != null) a.putAll(b);
return a;
}
static boolean addIfNotNull(Collection l, A a) {
return a != null && l != null & l.add(a);
}
static void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null) ms.add(a);
}
static HashSet litset(A... items) {
return lithashset(items);
}
static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(IterableIterator i) {
return first((Iterator ) i);
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static 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 List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static List subList(List 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 String lightlyShortenClassName(String name) {
if (name == null) return null;
int i = indexOf(name, "$");
if (i < 0) i = indexOf(name, ".");
return i < 0 ? name : substring(name, i+1);
}
static Comparator mapComparator(final Map map) {
return new Comparator () {
public int compare(A a, A b) {
return cmp(map.get(a), map.get(b));
}
};
}
static IterableIterator toLines(File f) {
return linesFromFile(f);
}
static List toLines(String s) {
List lines = new ArrayList();
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 int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static CloseableIterableIterator 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 CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static List newSubListOrSame(List 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 A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static 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 String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
static B mapPutOrRemove(Map 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 Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static long parseLong(String s) {
if (empty(s)) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() { throw fail(); }
public boolean hasNext() { return false; }
};
static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r));
}
static BufferedReader utf8bufferedReader(InputStream in) { try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedReader utf8bufferedReader(File f) { try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static File newFile(String name) {
return name == null ? null : new File(name);
}
static File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
A a;
boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done) throw fail();
A _a = a;
a = null;
return _a;
}
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 String readLineFromReaderWithClose(BufferedReader r) { try {
String s = r.readLine();
if (s == null) r.close();
return s;
} catch (Exception __e) { throw rethrow(__e); } }
static 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 A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
static FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
static int gzInputStream_defaultBufferSize = 65536;
static GZIPInputStream gzInputStream(File f) { try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(File f, int bufferSize) { try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) { throw rethrow(__e); } }
static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) { throw rethrow(__e); } }
static void _registerIO(Object object, String path, boolean opened) {
}
// immutable, has strong refs
final static class _MethodCache {
final Class c;
final HashMap> cache = new HashMap();
_MethodCache(Class c) {
this.c = c; _init(); }
void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods())
if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
// add default methods - this might lead to a duplication
// because the overridden method is also added, but it's not
// a problem except for minimal performance loss.
for (Class intf : allInterfacesImplementedBy(c))
for (Method m : intf.getDeclaredMethods())
if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
// Returns only matching methods
Method findMethod(String method, Object[] args) { try {
List 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); } }
Method findStaticMethod(String method, Object[] args) { try {
List 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 abstract class VF1 implements IVF1 {
public abstract void get(A a);
}abstract static class DynObjectTable extends DynModule {
List data = new ArrayList();
transient JTable table;
transient F1 itemToMap;
transient VF1 defaultAction;
transient boolean debug, fieldsInOrder = true, withSearcher;
transient TableSearcher searcher;
transient List onListChanged;
transient Set hideFields;
transient boolean useStruct = false; // possible breaking change for older modules
void start() { try { super.start();
itemToMap = new F1() { public Map get(A a) { try {
if (a instanceof String) return litorderedmap("" , (String) a);
Map map = humanizeKeys(fieldsInOrder ? objectToMap_inOrder_withoutFields(a, hideFields) : objectToMap(a));
if (!useStruct) map = mapValues(__38 -> strOrEmpty(__38),map);
return map;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (a instanceof S) ret litorderedmap(\"\" := (S) a);\r\n Map map = humanize..."; }};
onChange(new Runnable() { public void run() { try { updateTable();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateTable();"; }});
} catch (Exception __e) { throw rethrow(__e); } }
void onListChanged(Runnable r) {
if (r == null) return;
onListChanged = addDyn_sync(onListChanged, r);
}
void onListChangedAndNow(Runnable r) {
if (r == null) return;
onListChanged(r);
r.run();
}
void addCountToName() {
onListChangedAndNow(new Runnable() { public void run() { try { addCountToNameNow();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addCountToNameNow();"; }});
}
void addCountToNameNow() { AutoCloseable __1 = enter(); try {
setModuleName(programTitle() + " (" + count() + ")");
} finally { _close(__1); }}
public JComponent visualize() {
List l = map(itemToMap, data);
table = dataToTable_uneditable(sexyTable(), l);
onDoubleClickOrEnter(table, new VF1() { public void get(Integer row) { try {
AutoCloseable __2 = enter(); try {
A a = _get(data, row);
if (a != null) onDoubleClick(a);
} finally { _close(__2); }} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "temp enter();\r\n A a = _get(data, row);\r\n if (a != null) onDoubleCli..."; }});
if (withSearcher)
return (searcher = tableWithSearcher2(table)).panel;
return table;
}
void unvisualize() { super.unvisualize(); searcher = null; }
void onDoubleClick(A line) { callF(defaultAction, line); }
void updateTable() { AutoCloseable __3 = enter(); try {
if (table != null) { swing(new Runnable() { public void run() { try {
Point scrollPosition = enclosingViewPosition(table);
if (debug) print("Scroll position: " + scrollPosition);
dataToTable_uneditable(table, map(itemToMap, data));
setEnclosingViewPosition(table, scrollPosition);
if (searcher != null) searcher.rowIndices = null;
if (debug) print("dataToTable done, alerting " + n2(onListChanged, "listener"));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Point scrollPosition = enclosingViewPosition(table);\r\n if (debug) print(..."; }}); }
pcallFAll(onListChanged);
} finally { _close(__3); }}
/*TODO void itemChanged(int row, A entry) {
if (getRow(row) != entry) {
fireDataChanged();
warn("Item index mismatch, recreating table");
}
rows.add(dataToTable_makeRow(x, cols));
}*/
void dontPersist() { _persistenceInfo = mapPlus(_persistenceInfo, "data" , false); }
void clear() { syncClear(data); fireDataChanged(); }
void add(A a) { syncAdd(data, a); fireDataChanged(); }
A addAndReturn(A a) { add(a); return a; }
void add(int idx, A a) { syncAdd(data, idx, a); fireDataChanged(); }
void addAll(Collection l) { if (empty(l)) return; syncAddAll(data, l); fireDataChanged(); }
void addAndScrollDown(A a) { add(a); scrollDown(); }
void remove(A a) { syncRemove(data, a); fireDataChanged(); }
void removeAll(List a) { syncRemoveAll(data, a); fireDataChanged(); }
void setList(Iterable data) { setData(data); }
void removeSelected() { removeAll(allSelected()); }
// rare legacy binary compatibility workaround
void setData(Collection data) { setData((Iterable) data); }
void setData(Iterable data) {
setData(data, false);
}
void setData(Iterable data, boolean force) {
// ATTN: new logic. test if it works in all cases
{ swing(new Runnable() { public void run() { try {
//int selection = selectedIndex();
int[] selection = selectedTableRows_array(table);
List cloned = cloneList(data);
if (setField("data" , cloned) || force) {
updateTable();
dm_vmBus_send("listChanged",module(), cloned);
}
if (force) change();
//selectRow(table, selection);
selectTableRows(table, selection);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "//int selection = selectedIndex();\r\n int[] selection = selectedTableRows..."; }}); }
}
int count() { return syncL(data); }
void setData_force(Collection data) {
setData(data, true);
}
// tries to keep selection
void fireDataChanged() {
setData_force(data);
}
int rowFromSearcher(int i) {
return searcher == null || searcher.rowIndices == null ? i : or(get(searcher.rowIndices, i), -1);
}
A selected() { return syncGet(data, rowFromSearcher(selectedTableRowInModel(table))); }
List allSelected() { return syncListGetMulti(data, selectedIndices()); }
int selectedIndex() { return selectedTableRow(table); }
List selectedIndices() { return map(i -> rowFromSearcher(i), selectedTableRowsInModel(table)); }
boolean selectItem(A a) { int i = indexOf(data, a); selectRow(table, i); return i >= 0; } // true if item exists
void doubleClickItem(A a) { if (selectItem(a)) onDoubleClick(a); }
// r : Runnable or VF1
// run only in visualize()!
void popupMenuItem(String text, Object r) {
tablePopupMenuItemsThreaded(table, text, _convertRunnable(r));
}
void popupMenuItem_top(String text, Object r) {
tablePopupMenuItemsThreaded_top(table, text, _convertRunnable(r));
}
// row index => element
Object _convertRunnable(final Object r) {
if (r == null || r instanceof Runnable) return r;
return new VF1() { public void get(Integer idx) { try { callF(r, syncGet(data, idx)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(r, syncGet(data, idx))"; }};
}
JTable table() { return table; }
void hideFields(String... fields) {
if (hideFields == null) hideFields = new HashSet();
_addAll(hideFields, fields);
}
A getRow(int row) { return get(data, row); }
void scrollDown() { scrollTableDownNow(table); }
// API
List getData() { return data; } // data is usually immutable
List data() { return getData(); }
List list() { return getData(); }
List getList() { return getData(); }
List clonedList() { return cloneList(data); }
// log list (and whole module) contents somewhere
File quickBackup() {
File f = programFile("backup-" + ymd_minus_hms_minus_millis() + ".gz");
saveGZStructToFile(f, module());
printFileInfo(f);
return f;
}
}
static class Matches {
String[] m;
Matches() {}
Matches(String... m) {
this.m = m;}
String get(int i) { return i < m.length ? m[i] : null; }
String unq(int i) { return unquote(get(i)); }
String tlc(int i) { return unq(i).toLowerCase(); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
int psi(int i) { return Integer.parseInt(unq(i)); }
public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; }
public int hashCode() { return _hashCode(toList(m)); }
public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); }
}
static abstract class F0 {
abstract A get();
}static abstract class F1 {
abstract B get(A a);
}// you still need to implement hasNext() and next()
static abstract class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}static abstract class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {}
}static interface IFieldsToList {
Object[] _fieldsToList();
}static interface IF2 {
C get(A a, B b);
}static interface IF1 {
B get(A a);
}static class PersistableThrowable {
String className;
String msg;
String stacktrace;
PersistableThrowable() {}
PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}static class FixedRateTimer extends java.util.Timer {
FixedRateTimer() { this(false); }
FixedRateTimer(boolean daemon) { this(defaultTimerName(), daemon); }
FixedRateTimer(String name) { this(name, false); }
FixedRateTimer(String name, boolean daemon) {
super(name, daemon);
_registerTimer(this);
}
List entries = synchroList();
static class Entry implements IFieldsToList{
TimerTask task;
long firstTime;
long period;
Entry() {}
Entry(TimerTask task, long firstTime, long period) {
this.period = period;
this.firstTime = firstTime;
this.task = task;}
public String toString() { return shortClassName(this) + "(" + task + ", " + firstTime + ", " + period + ")"; }public Object[] _fieldsToList() { return new Object[] {task, firstTime, period}; }
}
// Note: not all methods overridden; only use these ones
public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
entries.add(new Entry(task, now()+delay, period));
super.scheduleAtFixedRate(task, delay, period);
}
public void cancel() {
entries.clear();
super.cancel();
}
public int purge() {
entries.clear();
return super.purge();
}
FixedRateTimer changeRate(int newPeriod) {
Object r = ((SmartTimerTask) first(entries).task).r;
cancel();
return doEvery(newPeriod, r);
}
}static class _SimulatedArrayStub {
int len;
}static class Pair implements Comparable> {
A a;
B b;
Pair() {}
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 p) {
if (p == null) return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0) return i;
return ((Comparable) b).compareTo(p.b);
}
}
static interface IVF1 {
void get(A a);
}static abstract class DynModule {
// we really shouldn't have used up these variable names
// (subclasses can't overload them due to how the persistence works)
String name, toolTip; // module name, module tool tip in task bar
PersistableThrowable _error;
Map> mechLists;
Map _persistenceInfo;
transient Object _host;
transient Map timers = newWeakHashMap(); // all kinds of resources actually; value is closer helper
transient Set _resources = synchroHashSet();
transient Lock lock; // set by stem
transient boolean persistOnChangedField = true;
transient int changeCount;
transient Object changeCountSync = new Object();
transient List onChange;
transient List onTransientChange;
transient boolean verboseTimers = false;
transient ReliableSingleThread rstUpdate;
transient Set componentFieldsToKeep;
transient Map transientGeneralMap = synchroHashMap();
transient Q q; // module command queue
transient List onFieldChange; // also for non-persistent fields. L
transient boolean _hasPreviousBounds = false;
transient StringBuffer _printLog = new StringBuffer();
transient boolean deleted = false;
DynModule() {
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
boolean isVisible() { return isTrue(getOpt(_host, "visible")); }
String moduleName() { return name; }
void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
setField("name", name);
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
A ownTimer(A timer) {
if (timer instanceof AutoCloseable) ownResource((AutoCloseable) timer);
ownTimer(timer, "cancelTimerOrInterruptThread");
return timer;
}
void ownTimer(Object timer, Object closerHelper) {
timers.put(timer, closerHelper);
}
void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try { resource.close(); } catch (Throwable __e) { _handleException(__e); }
}
{ final Map __0 = getAndClearMap(timers); for (Object timer : keys( __0)) { Object closerHelper = __0.get(timer);
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallFInRealOrMyMC(this, closerHelper, timer);
}}
}
boolean isDeleted() { return deleted; }
void cleanMeUp_dynModule() {
deleted = true;
stopAllTimers();
}
void persistMe() {
synchronized(changeCountSync) { ++changeCount; }
pcallFAll(onChange); callOpt(_host, "_change");
updateMe();
}
void fireChangeWithoutPersisting() {
pcallFAll(onChange);
}
void fireTransientChange() {
pcallFAll(onTransientChange);
}
void _change() { persistMe(); }
void change() { persistMe(); }
void updateMe() {
rstUpdate().trigger();
}
void changeAndUpdate() { _change(); updateMe(); }
boolean setField(String name, Object value) { AutoCloseable __5 = enter(); try {
{
// lock lock; // this leads to too many problems
try { // some really weird classes fail on equals() (BCEL JavaClass, I'm looking at you)
if (eq(get(this, name), value)) return false;
} catch (Throwable __e) { _handleException(__e); }
set(this, name, value);
} // releasing lock before calling _change()!
pcallFAll(onFieldChange, name);
if (persistOnChangedField
//&& !isTransientField(this, name)
&& !isFalse(mapGet(_persistenceInfo, name)))
_change();
return true;
} finally { _close(__5); }}
A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2)
if (setField((String) params[i], params[i+1])) change = true;
return change;
}
void start() {
_hasPreviousBounds = dm_getBounds() != null;
if (hasMethod_onTypes(this, "onTopInput", String.class))
dm_onTopInput_q(new VF1() { public void get(String s) { try { call(module(), "onTopInput", s) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "call(module(), 'onTopInput, s)"; }});
}
void revisualize() {
call(creator(), "revisualizeModule", _host);
}
AutoCloseable enter() {
AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
final Object realMC = getMainClass(this);
if (printToModule())
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor()));
if (realMC != mc()) {
if (printToModule())
c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor()));
else
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() { public Boolean get(String s) { try {
{ call(realMC, "print", s); return false; }
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret false with call(realMC, 'print, s);"; }}));
c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC));
}
return c;
}
F1 _printToModuleInterceptor() {
return new F1() { public Boolean get(String s) { try {
if (print_preprocess != null) s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = _printLog;
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);
return false;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ..."; }};
}
boolean printToModule() { return true; } // on by default now
AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
boolean setError(Throwable e) {
setField("_error" , persistableThrowable(e));
return true;
}
void clearError() {
setField("_error" , null);
}
void onChange(Runnable r) {
Lock __1 = lock; lock(__1); try {
if (onChange == null) onChange = synchroList();
addIfNotThere(onChange, r);
} finally { unlock(__1); } }
void onFieldChange(VF1 r) {
Lock __2 = lock; lock(__2); try {
if (onFieldChange == null) onFieldChange = synchroList();
addIfNotThere(onFieldChange, r);
} finally { unlock(__2); } }
void onChangeAndNow(Runnable r) {
onChange(r);
callF(r);
}
// forward to main class
void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
/*static*/ A onChange(A tc, Object r) {
onUpdate(tc, r);
return tc;
}
void update() {}
void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
// return L (legacy)
// or litobjectarray(text, Runnable, text, Runnable, ...)
Object menuItems() {
return null;
}
void enhanceFrame(Container f) {
Object items = menuItems();
if (items instanceof Object[])
items = paramsToAbstractActions((Object[]) items);
internalFramePopupMenuFromActions_threaded(f, (List) items);
String switchableFields = (String) (callOpt(this, "switchableFields"));
Set set = asLinkedHashSet(splitAtSpace(switchableFields));
Matches m = new Matches();
for (String field : allFields(this))
if (startsWith(field, "_switchableField_", m))
set.add(m.rest());
for (String field : set) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
else if (eq(String.class, type))
dm_stringFieldMenuItem(f, field);
}
}
// assume this is called in start(), so no locking
ReliableSingleThread rstUpdate() {
if (rstUpdate == null) rstUpdate = dm_rst(this, new Runnable() { public void run() { try { AutoCloseable __6 = enter(); try { update();
} finally { _close(__6); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp enter(); update();"; }});
return rstUpdate;
}
Q q() { AutoCloseable __7 = enter(); try {
if (q == null) {
Lock __3 = lock; lock(__3); try {
if (q == null) q = dm_startQ();
} finally { unlock(__3); } }
return q;
} finally { _close(__7); }}
A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
DynModule module() { return this; }
DynModule me() { return this; }
JComponent visualize() {
return dm_noVisualisation();
}
String programTitle_cache;
String programTitle() {
if (programTitle_cache == null)
programTitle_cache = snippetTitle(programID(mainClass(this)));
return programTitle_cache;
}
// field must be non-transient
void doPersist(String field) {
_persistenceInfo = mapMinus(_persistenceInfo, field);
}
void dontPersist(String field) {
_persistenceInfo = mapPlus(_persistenceInfo, "field" , false);
}
Appendable _actualPrintLog() { return printToModule() ? _printLog : print_log; }
}
static void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
dm_currentModule().ownTimer(timer);
}
/*
TODO: thread {} should enter the module
svoid _onLoad_moduleThreadInfo {
_threadInfo_addMakerAndRetriever(
voidfunc(Map map) { mapPut(map, dm_current := dm_currentModule()) },
voidfunc(Map map) { dm_enter((S) map.get('dm_current)) });
}
*/
static class Q implements AutoCloseable {
String name = "Unnamed Queue";
List q = synchroLinkedList();
ReliableSingleThread rst = new ReliableSingleThread(new Runnable() { public void run() { try { _run() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_run()"; }});
volatile boolean retired = false;
Q() {}
Q(String name) {
this.name = name;}
void add(Runnable r) {
q.add(r);
_trigger();
}
void addInFront(Runnable r) {
q.add(0, r);
_trigger();
}
void _trigger() {
rst.name = name;
rst.go();
}
void add(Object r) {
add(toRunnable(r));
}
void _run() {
Runnable r;
while (licensed() && !retired && (r = syncPopFirst(q)) != null) {
try { r.run(); } catch (Throwable __e) { _handleException(__e); }
}
}
public void close() { retired = true; } // TODO: interrupt thread
void done() {} // legacy function
boolean isEmpty() { return q.isEmpty(); }
int size() { return q.size(); }
Object mutex() { return q; } // clients can synchronize on this
List snapshot() { return cloneList(q); }
}static class ReliableSingleThread implements Runnable {
boolean _isTransient() { return true; }
Object runnable;
String name = "Single Thread";
boolean cancelBeforeTrigger = false; // always cancel running thread and wait for it to end before starting new operation
F0 enter; // optional ownership marker, e.g. for DynModules
int cancelTimeOut = 10000;
boolean trigger = false;
Thread thread;
WeakReference threadBeingCancelled;
ReliableSingleThread(Object runnable) {
this.runnable = runnable;}
void trigger() { go(); }
synchronized void go() {
if (cancelBeforeTrigger) cancel();
trigger = true;
if (!running()) {
AutoCloseable __1 = callF(enter); try {
thread = startThread(name, new Runnable() { public void run() { try {
AutoCloseable __2 = callF(enter); try {
_run();
} finally { _close(__2); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp callF(enter);\r\n _run();"; }});
} finally { _close(__1); }}
}
public void run() { go(); }
void get() { go(); } // so you can use the ! syntax
synchronized boolean running() { return thread != null; }
// use only if this is the last time you trigger this
void triggerAndWait() {
trigger();
waitUntilDone();
}
void waitUntilDone() {
while (running()) sleep(1);
}
void _run() { try {
while (licensed()) {
Thread oldThread;
synchronized(this) {
if (!trigger) {
thread = null;
break;
}
oldThread = getWeakRef(threadBeingCancelled);
trigger = false;
}
if (oldThread != null && oldThread != currentThread())
oldThread.join(cancelTimeOut);
pcallF(runnable);
}
} catch (Exception __e) { throw rethrow(__e); } }
synchronized void cancel() {
if (thread == null) return;
threadBeingCancelled = new WeakReference(thread);
cancelAndInterruptThread(thread);
thread = null;
}
void cancelAndTrigger() {
cancel();
trigger();
}
synchronized boolean triggered() { return trigger; }
void cleanMeUp() { cancel(); }
ReliableSingleThread cancelBeforeTrigger() {
cancelBeforeTrigger = true;
return this;
}
}
static List myInnerClasses_list=litlist(
"VF1", null, "Derefable", "VF2", "TableSearcher", "Var", "TokCondition", "IFieldIndex", "talkToThisVM_IO", "Str", "findCodeTokens_Matcher", "ReliableSingleThread", "FixedRateTimer", "DynModule", "Concept", "Rect", "Pt", "ProgramScan", "F0", "F1", "IterableIterator", "F2", "RemoteDB", "betterCIComparator_C", "MakesBufferedImage", "Flag", "unstructure_Receiver", "ScannedBot", "Concepts", "RC", "XRef", "IF0", "CloseableIterableIterator", "BaseXRef", "getOpt_Map", "IFieldsToList", "IF2", "Producer", "ModuleInfo", "guessDeepObjectSize_recursive_Data", "IF1", "structure_Data", "IVF1", "tablePopupMenu_Maker", "IVF2", "IVar", "_SimulatedArrayStub", "_MethodCache", "talkTo_IO", "Matches", "structure_ClassInfo", "TableWithTooltips", "LiveValue", "Q", "CriticalAction", "DialogHandler", "Lowest", "IResourceLoader", "MultiSet", "Pair", "DynObjectTable", "DialogIO", "IConceptCounter", "ModuleRAMSizes", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "TransferableImage", "DynamicObject", "IConceptIndex", "PersistableThrowable", "talkToSubBot_IO", "Scored", "Android3", "SmartTimerTask", "Responder");
static List myInnerClasses() {
return myInnerClasses_list;
}
static DynModule dm_currentModule() {
return (DynModule) dm_current_generic();
}
static void cancelTimerOrInterruptThread(Object timer) {
if (timer instanceof Thread && !(timer instanceof AutoCloseable)) // AutoCloseable takes precedence
interruptThread((Thread) timer);
else
cancelTimer(timer);
}
static boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class
&& eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static Set allInterfacesImplementedBy(Class c) {
if (c == null) return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c)) return;
do {
for (Class intf : c.getInterfaces())
allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static 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 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 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 Map humanizeKeys(Map map) {
return mapKeys("humanizeFormLabel",map);
}
// o is either a map already (string->object) or an arbitrary object,
// in which case its fields are converted into a map.
static Map objectToMap_inOrder_withoutFields(Object o, Collection withoutFields) {
if (o == null) return null;
if (o instanceof Map) return (Map) o;
LinkedHashMap map = new LinkedHashMap();
for (String field : listWithoutSet(fieldsInOrder(o), withoutFields))
map.put(field, get(o, field));
return map;
}
// o is either a map already (string->object) or an arbitrary object,
// in which case its fields are converted into a map.
static Map objectToMap(Object o) { try {
if (o instanceof Map) return (Map) o;
TreeMap map = new TreeMap();
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (final Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
final Object value = field.get(o);
if (value != null)
map.put(field.getName(), value);
}
c = c.getSuperclass();
}
// XXX NEW - hopefully this doesn't break anything
if (o instanceof DynamicObject)
map.putAll(((DynamicObject) o).fieldValues);
return map;
} catch (Exception __e) { throw rethrow(__e); } }
// same for a collection (convert each element)
static List> objectToMap(Iterable l) {
if (l == null) return null;
List x = new ArrayList();
for (Object o : l)
x.add(objectToMap(o));
return x;
}
static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map))
m.put(key, callF(func, map.get(key)));
return m;
}
static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static Map mapValues(IF1 f, Map map) {
return mapValues((Object) f, map);
}
static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static A onChange(A spinner, Object r) {
{ swing(new Runnable() { public void run() { try { spinner.addChangeListener(changeListener(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "spinner.addChangeListener(changeListener(r));"; }}); }
return spinner;
}
static A onChange(A b, Object r) {
{ swing(new Runnable() { public void run() { try { b.addItemListener(itemListener(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addItemListener(itemListener(r));"; }}); }
return b;
}
static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static A onChange(A slider, final Object r) {
{ swing(new Runnable() { public void run() { try { slider.addChangeListener(changeListener(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "slider.addChangeListener(changeListener(r));"; }}); }
return slider;
}
static JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() { public void get(String s) { try { callF(r) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(r)"; }});
return cb;
}
static List addDyn_sync(List l, A a) {
if (l == null) l = synchroList();
l.add(a);
return l;
}
static String programTitle() {
return getProgramName();
}
static int count(Collection l, Object o) {
int count = 0;
for (Object x : l)
if (eq(x, o))
++count;
return count;
}
static JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static JTable dataToTable_uneditable(final JTable table, final Object data) {
if (table != null) { 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 JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static boolean sexyTable_drag = false;
static JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table); // TODO: seems to interfere with double clicks
return table;
}
static JTable onDoubleClickOrEnter(final JTable table, final Object runnable) {
onDoubleClick(table, runnable);
onEnter(table, runnable);
return table;
}
static JList onDoubleClickOrEnter(final JList list, final Object runnable) {
onDoubleClick(list, runnable);
onEnter(list, runnable);
return list;
}
static JTable onDoubleClickOrEnter(Object runnable, JTable table) {
return onDoubleClickOrEnter(table, runnable);
}
static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static Object _get(Object o, String field) {
return get(o, field);
}
static Object _get(String field, Object o) {
return get(o, field);
}
static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// runnable can be a func(O o) {} receving the selected item
static JList onDoubleClick(final JList list, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = list.locationToIndex(evt.getPoint());
Object item = list.getModel().getElementAt(idx);
list.setSelectedIndex(idx);
callF(runnable, item);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "list.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mous..."; }}); }
return list;
}
// runnable can be a func(O o) {} receving the selected row index
static JTable onDoubleClick(final JTable table, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int idx = table.rowAtPoint(evt.getPoint());
table.setRowSelectionInterval(idx, idx);
callF(runnable, idx);
}
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(Mou..."; }}); }
return table;
}
// other components get the pointer position
// only reacts on left button
static void onDoubleClick(final JComponent c, final Object runnable) {
{ swing(new Runnable() { public void run() { try {
c.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getButton() == 1 && evt.getClickCount() == 2)
callF(runnable, evt.getPoint());
}
});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "c.addMouseListener(new MouseAdapter {\r\n public void mouseClicked(MouseEv..."; }}); }
}
static class TableSearcher {
JTable table;
JTextField tfInput;
JComponent searchPanel, panel;
F2 rowTester;
List rowIndices;
String input() { return gtt(tfInput); }
}
static TableSearcher tableWithSearcher2(final JTable t, Object... __) {
final TableSearcher s = new TableSearcher();
final boolean precise = true;
s.table = t;
s.tfInput = jtextfield();
s.rowTester = new F2() { public Boolean get(String pat, Map row) { try { return anyValueContainsIgnoreCase(row, pat); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "anyValueContainsIgnoreCase(row, pat)"; }};
onUpdate(s.tfInput, new Runnable() {
List lastFiltered, lastOriginal;
public void run() {
String pat = s.input();
List> data = rawTableData(t);
if (eq(lastFiltered, data))
data = lastOriginal;
//print("Searching " + n(l(data), "entry"));
List data2 = new ArrayList();
List rowIndices = new ArrayList();
for (int i = 0; i < l(data); i++) {
Map map = data.get(i);
if (isTrue(callF(s.rowTester, pat, map))) {
data2.add(map);
rowIndices.add(i);
}
}
//print("Found " + n(l(data2), "entry"));
lastFiltered = data2;
lastOriginal = data;
dataToTable(t, data2);
if (precise) lastFiltered = rawTableData(t);
s.rowIndices = rowIndices;
}
});
s.searchPanel = withLabel("Search:", s.tfInput);
JComponent top = s.searchPanel;
s.panel = boolOptPar(__, "withMargin") ? northAndCenterWithMargin(top, t) : northAndCenter(top, t);
return s;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static A swing(IF0 f) {
return (A) swingAndWait(f);
}
static Point enclosingViewPosition(Component c) {
JScrollPane sp = enclosingScrollPane(c);
return sp == null ? null : swing(new F0() { public Point get() { try { return sp.getViewport().getViewPosition(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret sp.getViewport().getViewPosition();"; }});
}
static void setEnclosingViewPosition(Component c, Point p) {
if (p == null) return;
JScrollPane sp = enclosingScrollPane(c);
if (sp != null) { swing(new Runnable() { public void run() { try { sp.getViewport().setViewPosition(p);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sp.getViewport().setViewPosition(p);"; }}); }
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(Map map) { return n2(l(map)); }
static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static String n2(Map m, String singular) {
return n2(l(m), singular);
}
static String n2(Object[] a, String singular) { return n2(l(a), singular); }
static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); }
static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
static void syncClear(Collection c) {
if (c != null) synchronized(c) { c.clear(); }
}
static boolean syncAdd(Collection c, A b) {
if (c == null) return false;
synchronized(c) { return c.add(b); }
}
static void syncAdd(List l, int idx, A b) {
if (l != null) synchronized(l) { l.add(idx, b); }
}
static void add(BitSet bs, int i) {
bs.set(i);
}
static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static void add(Container c, Component x) {
addToContainer(c, x);
}
static boolean syncAddAll(Collection c, Collection b) {
if (c == null || b == null) return false;
synchronized(c) {
return c.addAll(b);
}
}
static boolean syncRemove(Collection c, A b) {
if (c == null) return false;
synchronized(collectionMutex(c)) { return c.remove(b); }
}
static B syncRemove(Map map, A key) {
return map == null ? null : map.remove(key);
}
static boolean syncRemoveAll(Collection c, Collection b) {
if (c == null || b == null) return false;
synchronized(collectionMutex(c)) { return c.removeAll(b); }
}
static void removeAll(Collection a, Collection b) {
if (a != null && b != null) a.removeAll(b);
}
static void removeAll(Map a, Collection b) {
if (a != null && b != null)
for (A x : b)
a.remove(x);
}
static int[] selectedTableRows_array(final JTable table) {
return table == null ? null : swing(new F0() { public int[] get() { try { return table.getSelectedRows(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret table.getSelectedRows();"; }});
}
static void dm_vmBus_send(String msg, Object... args) {
vmBus_send(msg, args);
}
static void dm_vmBus_send(String msg) {
vmBus_send(msg);
}
static void change() {
//mainConcepts.allChanged();
// safe version for now cause function is sometimes included unnecessarily (e.g. by EGDiff)
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static void selectTableRows(final JTable table, int[] rows) {
if (table != null) { swing(new Runnable() { public void run() { try {
ListSelectionModel model = table.getSelectionModel();
int n = tableRows(table);
model.clearSelection();
if (rows != null) for (int row : rows)
if (row < n)
model.addSelectionInterval(row, row);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ListSelectionModel model = table.getSelectionModel();\r\n int n = tableRows(..."; }}); }
}
static int syncL(Collection l) {
if (l == null) return 0;
synchronized(l) { return l.size(); }
}
static List syncL() {
return syncList();
}
static A syncGet(List l, int idx) {
if (l == null || idx < 0) return null;
synchronized(l) {
return idx < l(l) ? l.get(idx) : null;
}
}
static B syncGet(Map map, A a) {
if (map == null) return null;
synchronized(map) {
return map.get(a);
}
}
static int selectedTableRowInModel(final JTable t) {
return t == null ? -1 : swing(new F0() { public Integer get() { try {
int i = t.getSelectedRow();
return i < 0 ? i : t.convertRowIndexToModel(i);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "int i = t.getSelectedRow();\r\n ret i < 0 ? i : t.convertRowIndexToModel(i);"; }});
}
static List syncListGetMulti(final List l, List indices) {
synchronized(collectionMutex(l)) {
return listGetMulti(l, indices);
}
}
static int selectedTableRow(final JTable t) {
return t == null ? -1 : swing(new F0() { public Integer get() { try { return t.getSelectedRow(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret t.getSelectedRow();"; }});
}
static List selectedTableRowsInModel(final JTable t) {
return t == null ? emptyList() : swing(new F0>() { public List get() { try {
return map(selectedTableRows(t), i -> t.convertRowIndexToModel(i));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret map(selectedTableRows(t), i -> t.convertRowIndexToModel(i));"; }});
}
static void selectRow(final JTable table, final int i) {
if (table != null) { swing(new Runnable() { public void run() { try {
if (i >= 0 && i < table.getRowCount()) {
table.setRowSelectionInterval(i, i);
scrollRowToVisible(table, i);
} else
table.clearSelection();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (i >= 0 && i < table.getRowCount()) {\r\n table.setRowSelectionInterval..."; }}); }
}
static void selectRow(final JList list, final int i) {
if (list != null) { swing(new Runnable() { public void run() { try {
if (i >= 0 && i < listRowCount(list))
list.setSelectedIndex(i);
else
list.clearSelection();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (i >= 0 && i < listRowCount(list))\r\n list.setSelectedIndex(i);\r\n e..."; }}); }
}
static JComboBox selectItem(final String item, final JComboBox cb) {
if (cb != null) { swing(new Runnable() { public void run() { try { cb.setSelectedItem(item);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.setSelectedItem(item);"; }}); }
return cb;
}
static JComboBox selectItem(final JComboBox cb, final String item) {
return selectItem(item, cb);
}
static JList selectItem(JList list, A item) {
{ swing(new Runnable() { public void run() { try { selectRow(list, jlist_indexOf(list, item));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectRow(list, jlist_indexOf(list, item));"; }}); }
return list;
}
// action: voidfunc(int row)
static JTable tablePopupMenuItemsThreaded(final JTable table, Object... params) {
for (int i = 0; i+1 < l(params); i += 2) {
final Object action = params[i+1];
final Object threadInfo = _threadInfo();
tablePopupMenuItem(table, str(params[i]), new VF1() { public void get(final Integer row) { try {
_threadInheritInfo(threadInfo);
{ startThread(new Runnable() { public void run() { try { try {
callF(action, row);
} catch (Throwable __e) { messageBox(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo..."; }}); }
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act..."; }});
}
return table;
}
// action: voidfunc(int row)
static JTable tablePopupMenuItemsThreaded_top(final JTable table, Object... params) {
params = reverseParams(params);
for (int i = 0; i+1 < l(params); i += 2) {
final Object action = params[i+1];
final Object threadInfo = _threadInfo();
tablePopupMenuItem_top(table, str(params[i]), new VF1() { public void get(final Integer row) { try {
_threadInheritInfo(threadInfo);
{ startThread(new Runnable() { public void run() { try { try {
callF(action, row);
} catch (Throwable __e) { messageBox(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n callF(action, row);\r\n } catch (Throwable __e) { messageBo..."; }}); }
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "_threadInheritInfo(threadInfo);\r\n thread-messagebox {\r\n callF(act..."; }});
}
return table;
}
static void _addAll(Collection c, Iterable b) {
addAll(c, b);
}
static boolean _addAll(Collection c, Collection b) {
return addAll(c, b);
}
static boolean _addAll(Collection c, B... b) {
return addAll(c, b);
}
static void scrollTableDownNow(final JTable table) {
if (table != null) { swing(new Runnable() { public void run() { try {
table.scrollRectToVisible(table.getCellRect(table.getRowCount()-1, 0, true));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "table.scrollRectToVisible(table.getCellRect(table.getRowCount()-1, 0, true));"; }}); }
}
static List list(Class type) {
return db_mainConcepts().list(type);
}
static List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static List list(String type) {
return db_mainConcepts().list(type);
}
static List list(Concepts concepts, String type) {
return concepts.list(type);
}
static List getList(Map map, Object key) {
return map == null ? null : (List) map.get(key);
}
static List getList(List l, int idx) {
return (List) get(l, idx);
}
static List getList(Object o, Object key) {
if (o instanceof Map) return getList((Map) o, key);
if (key instanceof String)
return (List) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static List getList(String name, Object o) {
return getList(o, name);
}
static ArrayList clonedList(Iterable l) {
return cloneList(l);
}
static ArrayList clonedList(Collection l) {
return cloneList(l);
}
static File programFile(String name) {
return prepareProgramFile(name);
}
static File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static String ymd_minus_hms_minus_millis() {
return ymd() + "-" +
spliceString(replace(hmsWithColonsAndMS(), ":", ""), 6, 6, "-");
}
static void saveGZStructToFile(String file, Object o) {
saveGZStructureToFile(file, o);
}
static void saveGZStructToFile(File file, Object o) {
saveGZStructureToFile(file, o);
}
static File printFileInfo(File f) {
print(renderFileInfo(f));
return f;
}
static 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);
// Octal escape?
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;
// Hex Unicode: u????
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; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s; // not quoted - return original
}
static List quoteAll(Collection l) {
List x = new ArrayList();
for (String s : l)
x.add(quote(s));
return x;
}
static int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static ArrayList toList(A[] a) { return asList(a); }
static ArrayList toList(int[] a) { return asList(a); }
static ArrayList toList(Set s) { return asList(s); }
static ArrayList toList(Iterable s) { return asList(s); }
static boolean arraysEqual(Object[] a, Object[] b) {
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++)
if (neq(a[i], b[i])) return false;
return true;
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
static String defaultTimerName_name;
static String defaultTimerName() {
if (defaultTimerName_name == null)
defaultTimerName_name = "A timer by " + programID();
return defaultTimerName_name;
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static Flag dm_initErrorHandling_flag = new Flag();
static void dm_initErrorHandling() {
raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() { public void run() { try {
_handleException_addHandler("dm_initErrorHandling_handler");
assertNull(_onRegisterThread);
_onRegisterThread = new VF1() { public void get(Thread t) { try {
DynModule m = dm_currentModule();
if (m == null) printStackTrace("New thread made outside of a module");
else m.ownTimer(t);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ..."; }};
_threadInfo_makers.add(new VF1