Warning : session_start(): open(/var/lib/php/sessions/sess_kvppepbdb8ck8plfaltihpfe2t, 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 x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
class main {
static public class Scenario extends Concept {
public String name;
public List conditions;
public List actions;
public String toString() {
return "Scenario " + quote(name);
}
}
static public class Scenarios extends DynCRUD {
public Scenarios() {
super(Scenario.class);
}
transient public Scenario selected;
public List undoList = new ArrayList();
public Scenario findConceptWithName(String name) {
return conceptWhereCI(Scenario.class, "name", name);
}
public String answer(String s) {
return dm_q(() -> {
print("answering: " + s);
Matches m = new Matches();
if (match("undo", s))
return singleUndo();
if (match("anything to undo", s))
return empty(undoList) ? "Nothing to undo" : n2(undoList, "undoable action");
if (match("clear undos", s)) {
clearUndos();
return "OK";
}
if (match("how many scenarios", s))
return str(countConcepts(Scenario.class));
if (match("delete scenario *", s, m)) {
String name = m.unq(0);
setField("selected", null);
Scenario sc = findConceptWithName(name);
if (sc == null)
return format("Scenario * not found", name);
unregisterConcept(sc);
addUndo(new UndoDeleteConcept(sc));
return format("Scenario * deleted", name);
}
if (match("new scenario *", s, m)) {
String name = m.unq(0);
Scenario sc = conceptWhereCI(Scenario.class, "name", name);
if (sc != null)
return format("Scenario * exists", name);
setField("selected", uniqCI(Scenario.class, "name", name));
addUndo(new UndoCreateConcept(selected.id));
return format("Scenario * created", name);
}
if (match("list scenarios", s))
return or2(joinWithComma(collect("name", list(Scenario.class))), "No scenarios defined");
if (match("rename scenario * to *", s, m)) {
String name1 = m.unq(0), name2 = m.unq(1);
if (!eqic(name1, name2) && conceptWhereCI(Scenario.class, "name", name2) != null)
return format("A scenario named * exists", name2);
Scenario sc = findConceptWithName(name1);
if (sc == null)
return format("Scenario * not found", name1);
addUndo(new UndoSetConceptField(sc.id, "name", name1, name2));
cset(sc, "name", name2);
return format("Scenario * renamed to *", name1, name2);
}
return null;
});
}
public void addUndo(UndoableWithAnswer undo) {
if (undo == null)
return;
undoList.add(undo);
change();
print("Undo added: " + undo);
}
public JComponent visualize() {
JComponent _c = super.visualize();
addComponent(crud.buttons, jbutton("Talk to me", runnableThread(new Runnable() {
public void run() {
try {
talkToMe();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "talkToMe();";
}
})));
return _c;
}
public void talkToMe() {
AutoCloseable __9 = enter();
try {
dm_showConversationPopupForModule();
} finally {
_close(__9);
}
}
public void clearUndos() {
dm_q(new Runnable() {
public void run() {
try {
if (empty(undoList))
return;
undoList.clear();
change();
print("Undo list cleared");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (empty(undoList)) return;\r\n undoList.clear();\r\n change;\r\n print(\"...";
}
});
}
public String singleUndo() {
UndoableWithAnswer undo = popLast(undoList);
if (undo == null)
return "Nothing to undo";
change();
return or2(undo.undo(), "Last action undone");
}
public UndoableWithAnswer lastUndo() {
return dm_q(() -> last(undoList));
}
}
static public boolean _moduleClass_Scenarios = true;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
});
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static public void print_autoRotate() {
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public A conceptWhereCI(Class c, Object... params) {
return findConceptWhereCI(c, params);
}
static public Concept conceptWhereCI(String c, Object... params) {
return findConceptWhereCI(db_mainConcepts(), c, params);
}
static public A conceptWhereCI(Concepts concepts, Class c, Object... params) {
return findConceptWhereCI(concepts, c, params);
}
static public Concept conceptWhereCI(Concepts concepts, String c, Object... params) {
return findConceptWhereCI(concepts, c, params);
}
static public Q dm_q() {
return dm_current_mandatory().q();
}
static public void dm_q(Runnable r) {
dm_inQ(r);
}
static public void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
static public A dm_q(IF0 f) {
return dm_evalInQ(if0ToF0(f));
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public int countConcepts(Concepts concepts, Class c, Object... params) {
return concepts.countConcepts(c, params);
}
static public int countConcepts(Class c, Object... params) {
return db_mainConcepts().countConcepts(c, params);
}
static public int countConcepts() {
return db_mainConcepts().countConcepts();
}
static public int countConcepts(String className) {
return db_mainConcepts().countConcepts(className);
}
static public int countConcepts(Concepts concepts, String className) {
return concepts.countConcepts(className);
}
static public int countConcepts(Concepts concepts) {
return concepts.countConcepts();
}
static public String format(String pat, Object... args) {
return format3(pat, args);
}
static public void unregisterConcept(Concept c) {
if (c == null)
return;
long id = c.id;
c.delete();
c.id = id;
}
static public A uniqCI(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqCI(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhereCI(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
}
return x;
} finally {
_close(__1);
}
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List collect(Iterable c, String field) {
return collectField(c, field);
}
static public List collect(String field, Iterable c) {
return collectField(c, field);
}
static public List list(Class type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public A addComponent(final A c, final Component component) {
if (component != null) {
swing(new Runnable() {
public void run() {
try {
c.add(component);
revalidate(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.add(component);\r\n revalidate(c);";
}
});
}
return c;
}
static public JButton jbutton(String text, Object action) {
return newButton(text, action);
}
static public JButton jbutton(String text) {
return newButton(text, null);
}
static public JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
static public Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static public void dm_showConversationPopupForModule() {
dm_showConversationPopupForModule(dm_current_generic());
}
static public void dm_showConversationPopupForModule(Object mod) {
String moduleID = dm_moduleID(mod);
if (moduleID != null)
dm_showModuleWithParams("#1027446/ConvoPopupSingleModule", "forModuleID", moduleID);
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public A popLast(List l) {
return liftLast(l);
}
static public List popLast(int n, List l) {
return liftLast(n, l);
}
static public A last(List l) {
return empty(l) ? null : l.get(l.size() - 1);
}
static public char last(String s) {
return empty(s) ? '#' : s.charAt(l(s) - 1);
}
static public int last(int[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public double last(double[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public A last(A[] a) {
return l(a) != 0 ? a[l(a) - 1] : null;
}
static public A last(Iterator it) {
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
static public A last(Collection l) {
if (l == null)
return null;
Iterator it = iterator(l);
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
static public A last(SortedSet l) {
return l == null ? null : l.last();
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static public Class mc() {
return main.class;
}
static public Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public String programID;
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public A findConceptWhereCI(Class c, Object... params) {
return findConceptWhereCI(db_mainConcepts(), c, params);
}
static public A findConceptWhereCI(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.ciFieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i + 1])) if (checkConceptFieldsIC(x, params))
return x;
return null;
}
}
for (A x : concepts.list(c)) if (checkConceptFieldsIC(x, params))
return x;
return null;
}
static public Concept findConceptWhereCI(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) if (checkConceptFieldsIC(x, params))
return x;
return null;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null) {
mainConcepts = new Concepts(getDBProgramID());
mainConcepts.classFinder = _defaultClassFinder();
}
return mainConcepts;
}
static public void dm_inQ(Runnable r) {
dm_q().add(r);
}
static public A dm_evalInQ(F0 f) {
return dm_evalInQ(dm_current_mandatory(), f);
}
static public A dm_evalInQ(DynModule module, F0 f) {
return evalInQ(module.q(), f);
}
static public F0 if0ToF0(IF0 f) {
return f == null ? null : new F0 () {
public A get() {
try {
return f.get();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.get();";
}
};
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public A uniqueConcept(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqueConcept(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhere(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
}
return x;
} finally {
_close(__1);
}
}
static public AutoCloseable tempDBLock(Concepts concepts) {
return tempLock(concepts.lock);
}
static public AutoCloseable tempDBLock() {
return tempDBLock(db_mainConcepts());
}
static public Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static public A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static public int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static public int csetAll(Iterable extends Concept> l, Object... values) {
int n = 0;
for (Concept c : unnull(l)) n += cset(c, values);
return n;
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
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 public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static public boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public Object getOptMC(String field) {
return getOpt(mc(), field);
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(new Runnable() {
public void run() {
try {
c.revalidate();
c.repaint();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r...";
}
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public boolean newButton_autoToolTip = true;
static public JButton newButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
}
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt...";
}
});
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static public String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
static public String dm_moduleID() {
return dm_moduleID(dm_current_mandatory_generic());
}
static public String dm_showModuleWithParams(String moduleLibID, Object... params) {
String moduleID = dm_makeModuleWithParams(moduleLibID, params);
dm_showModule(moduleID);
return moduleID;
}
static public 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 public List liftLast(int n, List l) {
int i = l(l) - n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
static public Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("loadableUtils.utils$"))
return findClass_fullName("main" + name.substring(19));
return null;
}
};
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public boolean checkConceptFieldsIC(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(cget(x, (String) data[i]), deref(data[i + 1])))
return false;
return true;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public A evalInQ(Q q, final F0 f) {
if (isInQ(q))
return callF(f);
final Var> var = new Var();
q.add(new Runnable() {
public void run() {
try {
try {
var.set(main.eitherA(callF(f)));
} catch (Throwable e) {
var.set(main. eitherB(e));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n var.set(main. eitherA(callF(f)));\r\n } catch (Th...";
}
});
return returnOrThrow_either(waitForVarToBeNotNull(var));
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public A findConceptWhere(Class c, Object... params) {
return findConceptWhere(db_mainConcepts(), c, params);
}
static public A findConceptWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params))
return x;
return null;
}
}
for (A x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
static public Concept findConceptWhere(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
static public AutoCloseable tempLock(final Lock lock) {
if (lock == null)
return null;
lock(lock);
return new AutoCloseable() {
public String toString() {
return "unlock(lock);";
}
public void close() throws Exception {
unlock(lock);
}
};
}
static public String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static public void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static public ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public 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 public String dm_makeModuleWithParams(String moduleLibID, Object... params) {
String mod = dm_findModuleWithParams(moduleLibID, params);
if (mod != null)
return mod;
return dm_makeNewModuleWithParams(moduleLibID, params);
}
static public void dm_showModule(Object module) {
Object stem = dm_getStem(module);
if (stem != null)
dm_callOS("showModule", stem);
}
static public void dm_showModule() {
dm_showModule(dm_current_mandatory_generic());
}
static public List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static public List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static public void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
static public void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Collection c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public boolean eqicOrEq(Object a, Object b) {
return a instanceof String && b instanceof String ? eqic((String) a, (String) b) : eq(a, b);
}
static public A cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref)
return (A) ((Concept.Ref) o).get();
return (A) o;
}
static public A cget(String field, Object c) {
return cget(c, field);
}
static public Object deref(Object o) {
if (o instanceof Derefable)
o = ((Derefable) o).get();
return o;
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public boolean isInQ(Q q) {
return q != null && isCurrentThread(q.rst.thread);
}
static public Either eitherA(A a) {
return new Either(1, a);
}
static public Either eitherB(B b) {
return new Either(2, b);
}
static public A returnOrThrow_either(Either e) {
if (isEitherB(e))
throw rethrow(e.b());
return eitherAOpt(e);
}
static public A waitForVarToBeNotNull(Var v) {
try {
synchronized (v) {
while (!v.has()) v.wait();
return v.get();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1])))
return false;
return true;
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
static public Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
return fields;
}
static public String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static public String n(Collection l, String name) {
return n(l(l), name);
}
static public String n(Map m, String name) {
return n(l(m), name);
}
static public String n(Object[] a, String name) {
return n(l(a), name);
}
static public String n(MultiSet ms, String name) {
return n(l(ms), name);
}
static public boolean odd(int i) {
return (i & 1) != 0;
}
static public boolean odd(long i) {
return (i & 1) != 0;
}
static public boolean odd(BigInteger i) {
return odd(toInt(i));
}
static public A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public Map emptyMap() {
return new HashMap();
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static public ThreadLocal> holdInstance_l = new ThreadLocal();
static public AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static public void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
static public void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static public Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public boolean isString(Object o) {
return o instanceof String;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static public boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public 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 public String dm_findModuleWithParams(String moduleLibID, Object... params) {
return firstThat(dm_modulesWithLibID(moduleLibID), mod -> checkFields(dm_mod(mod), params));
}
static public String dm_makeNewModuleWithParams(String moduleLibID, Object... params) {
return (String) dm_callOS("makeNewModule", moduleLibID, false, "beforeStart", new VF1() {
public void get(Object mod) {
try {
print("Got module: " + dm_mod(mod));
dm_call(mod, "setFields", params);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Got module: \" + dm_mod(mod));\r\n dm_call(mod, 'setFields, params);";
}
});
}
static public Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
static public List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static public List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public 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 volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static public String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public boolean isCurrentThread(Thread t) {
return t != null && t == currentThread();
}
static public boolean isEitherB(Either e) {
return eitherIsB(e);
}
static public A eitherAOpt(Either e) {
return e != null && e.isA() ? e.a() : null;
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess");
static public Set singular_specials2 = litciset("time", "machine", "line", "rule");
static public String singular(String s) {
if (s == null)
return null;
{
String __1 = singular_specials.get(s);
if (!empty(__1))
return __1;
}
if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s))))
return dropSuffix("s", s);
if (s.endsWith("ness"))
return s;
if (s.endsWith("ges"))
return dropSuffix("s", s);
if (endsWith(s, "bases"))
return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static public List getPlural_specials = ll("sheep", "fish");
static public String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s))
return s;
if (ewic(s, "y"))
return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss"))
return s + "es";
if (ewic(s, "s"))
return s;
return s + "s";
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt(((String) o));
if (o instanceof Boolean)
return boolToInt(((Boolean) o));
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
static public A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
static public boolean headless() {
return isHeadless();
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll("printStackTrace2"));
static public void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
static public WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__1 != null)
return __1;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
static public String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static public String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static public Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
static public A firstThat(Iterable l, Object pred) {
if (l != null)
for (A a : l) if (checkCondition(pred, a))
return a;
return null;
}
static public A firstThat(Iterable l, IF1 pred) {
return firstThat(l, (Object) pred);
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public List dm_modulesWithLibID(final String moduleLibID) {
return filter(dm_moduleIDs(), new F1() {
public Boolean get(String m) {
try {
return eq(dm_moduleLibID(m), moduleLibID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "eq(dm_moduleLibID(m), moduleLibID)";
}
});
}
static public boolean checkFields(Object x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1]))
return false;
return true;
}
static public Object dm_mod(Object moduleOrID) {
return dm_getModule(moduleOrID);
}
static public Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __1 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__1);
}
}
static public Object dm_os() {
{
Object __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static public boolean eitherIsB(Either e) {
return e != null && e.isB();
}
static public Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static public Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
static public String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public String afterLastSpace(String s) {
return s == null ? null : substring(s, s.lastIndexOf(' ') + 1);
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static public boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static public boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static public String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public Throwable innerException(Throwable e) {
return getInnerException(e);
}
static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __1 = pcallF(f, args);
if (__1 != null)
return __1;
}
return null;
}
static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __2 = pcallF(it.next(), args);
if (__2 != null)
return __2;
}
return null;
}
static public String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static public String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
static public boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static public boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static public List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
static public List dm_moduleIDs() {
return dm_listModuleIDs();
}
static public String dm_moduleLibID() {
return programID() + "/" + shortClassName(dm_current_mandatory());
}
static public String dm_moduleLibID(Object mod) {
if (mod == null)
return null;
mod = dm_getModule(mod);
if (hasSuperclassShortNamed(mod, "DynModule"))
return programID(mod) + "/" + shortClassName(mod);
return null;
}
static public AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public 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 public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static public String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
static public TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
static public TreeSet treeSet() {
return new TreeSet();
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(List a, String b, int i) {
int n = a == null ? 0 : a.size();
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
static public boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public List dm_listModuleIDs() {
return map("dm_moduleID", dm_listStems());
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public boolean hasSuperclassShortNamed(Object o, String name) {
Class c = _getClass(o);
while (c != null) if (shortClassNameIs(c, name))
return true;
else
c = c.getSuperclass();
return false;
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public String className(Object o) {
return getClassName(o);
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
static public String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
static public TreeSet caseInsensitiveSet_treeSet() {
return new TreeSet(caseInsensitiveComparator());
}
static public TreeSet caseInsensitiveSet_treeSet(Collection c) {
return toCaseInsensitiveSet_treeSet(c);
}
static public int indexOfIgnoreCase_manual(String a, String b) {
int la = strL(a), lb = strL(b);
if (la < lb)
return -1;
int n = la - lb;
loop: for (int i = 0; i <= n; i++) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i + j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public 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 public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public 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 public List map(IF1 f, A[] l) {
return map(l, f);
}
static public 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 public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public List dm_listStems() {
return (List) dm_callOS("onModules");
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public boolean shortClassNameIs(Object o, String name) {
return eq(shortClassName(o), name);
}
static public boolean shortClassNameIs(String name, Object o) {
return shortClassNameIs(o, name);
}
static public Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public TreeSet toCaseInsensitiveSet_treeSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, c);
return set;
}
static public TreeSet toCaseInsensitiveSet_treeSet(String... x) {
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, x);
return set;
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
static public int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
static public betterCIComparator_C betterCIComparator_instance;
static public betterCIComparator_C betterCIComparator() {
if (betterCIComparator_instance == null)
betterCIComparator_instance = new betterCIComparator_C();
return betterCIComparator_instance;
}
static public class betterCIComparator_C implements Comparator {
public int compare(String s1, String s2) {
if (s1 == null)
return s2 == null ? 0 : -1;
if (s2 == null)
return 1;
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
return c1 - c2;
}
}
}
}
return n1 - n2;
}
}
static public boolean isCISet(Iterable l) {
return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null)
a.putAll(b);
return a;
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public class UndoCreateConcept implements UndoableWithAnswer, IFieldsToList {
public long conceptID;
public UndoCreateConcept() {
}
public UndoCreateConcept(long conceptID) {
this.conceptID = conceptID;
}
public boolean equals(Object o) {
if (!(o instanceof UndoCreateConcept))
return false;
UndoCreateConcept x = (UndoCreateConcept) o;
return eq(conceptID, x.conceptID);
}
public int hashCode() {
int h = -1406548184;
h = boostHashCombine(h, _hashCode(conceptID));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { conceptID };
}
public String toString() {
return "Create " + getConcept(conceptID);
}
public String undo() {
Concept c = getConcept(conceptID);
String result = "Deleted " + c + " again";
deleteConcept(conceptID);
return result;
}
}
static public class UndoDeleteConcept implements UndoableWithAnswer, IFieldsToList {
public Concept concept;
public UndoDeleteConcept() {
}
public UndoDeleteConcept(Concept concept) {
this.concept = concept;
}
public boolean equals(Object o) {
if (!(o instanceof UndoDeleteConcept))
return false;
UndoDeleteConcept x = (UndoDeleteConcept) o;
return eq(concept, x.concept);
}
public int hashCode() {
int h = 437129113;
h = boostHashCombine(h, _hashCode(concept));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { concept };
}
public String toString() {
return "Delete " + concept;
}
public String undo() {
registerConcept(concept);
return "Restored " + concept;
}
}
static public class UndoSetConceptField implements UndoableWithAnswer, IFieldsToList {
static final public String _fieldOrder = "conceptID field value newValue";
public long conceptID;
public String field;
public Object value;
public Object newValue;
public UndoSetConceptField() {
}
public UndoSetConceptField(long conceptID, String field, Object value, Object newValue) {
this.newValue = newValue;
this.value = value;
this.field = field;
this.conceptID = conceptID;
}
public boolean equals(Object o) {
if (!(o instanceof UndoSetConceptField))
return false;
UndoSetConceptField x = (UndoSetConceptField) o;
return eq(conceptID, x.conceptID) && eq(field, x.field) && eq(value, x.value) && eq(newValue, x.newValue);
}
public int hashCode() {
int h = 773474128;
h = boostHashCombine(h, _hashCode(conceptID));
h = boostHashCombine(h, _hashCode(field));
h = boostHashCombine(h, _hashCode(value));
h = boostHashCombine(h, _hashCode(newValue));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { conceptID, field, value, newValue };
}
public String toString() {
return "Set " + field + " of " + getConcept(conceptID) + " to " + newValue;
}
public String undo() {
Concept c = getConcept(conceptID);
String result = "Reset " + field + " of " + c + " to " + value;
cset(c, field, value);
return result;
}
}
static public interface IF0 {
public A get();
}
static public interface IF2 {
public C get(A a, B b);
}
static public class Var implements IVar {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
abstract static public class DynCRUD extends DynModule {
transient public Class conceptClass;
transient public SimpleCRUD crud;
public String caseID;
transient public boolean addCountToName = true, addCountToName_installed;
public void start_DynCRUD() {
dbWithCase(caseID);
crud = makeCRUD();
if (addCountToName)
addCountToName();
}
public JComponent visualize() {
makeConceptsTable_idWidth = 0;
showConceptsTable_afterUpdate.set(new VF1() {
public void get(JTable t) {
try {
int n = tableColumnCount(t);
for (int i = 0; i < n; i++) setColumnName(t, i, i == 0 ? "" : humanizeFormLabel(getColumnName(t, i)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int n = tableColumnCount(t);\r\n for i to n:\r\n setColumnName(t, i, i ==...";
}
});
return withMargin(crud.make_dontStartBots());
}
public SimpleCRUD makeCRUD() {
return new SimpleCRUD (db_mainConcepts(), conceptClass);
}
public JTable table() {
return crud == null ? null : crud.table;
}
public A selected() {
return crud == null ? null : crud.selectedConcept();
}
public void addButton(JComponent button) {
if (crud != null)
addComponent(crud.buttons, button);
}
public void addButton(String name, Object action) {
addButton(jbutton(name, action));
}
public void addSelectionDependentButton(String name, Object action) {
addButton(tableDependentButton(table(), name, action));
}
public void makeSortable() {
addRowSorter(table());
rowSorter_setComparatorForAllColumns(table(), alphaNumComparator());
}
public String searchTerm() {
return crud == null || crud.tableSearcher == null ? null : gtt(crud.tableSearcher.tfInput);
}
public void addCountToName() {
if (addCountToName_installed)
return;
addCountToName_installed = true;
onConceptChangeAndNow(new Runnable() {
public void run() {
try {
AutoCloseable __37 = enter();
try {
setModuleName(dm_originalModuleName() + " (" + conceptCount() + ")");
} finally {
_close(__37);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); setModuleName(dm_originalModuleName() + \" (\" + conceptCount() ...";
}
});
}
public Concepts conceptsObject() {
return crud.concepts;
}
public List list(Class c) {
return conceptsObject().list(c);
}
public List concepts() {
AutoCloseable __38 = enter();
try {
return list(conceptClass);
} finally {
_close(__38);
}
}
public List data() {
return concepts();
}
public List list() {
return concepts();
}
public List conceptsOfType(String type) {
AutoCloseable __39 = enter();
try {
return conceptsObject().list(type);
} finally {
_close(__39);
}
}
public List conceptsOfTypeWhere(String type, Object[] params) {
AutoCloseable __40 = enter();
try {
return filterConcepts(conceptsOfType(type), params);
} finally {
_close(__40);
}
}
public int conceptCount() {
AutoCloseable __41 = enter();
try {
return countConcepts(conceptClass);
} finally {
_close(__41);
}
}
public void deleteAll() {
AutoCloseable __42 = enter();
try {
deleteConcepts(conceptClass);
} finally {
_close(__42);
}
}
public void addDialog() {
AutoCloseable __43 = enter();
try {
crud.newConcept();
} finally {
_close(__43);
}
}
public A uniqConcept(Object... params) {
return uniq_sync(conceptClass, params);
}
public Pair uniqConcept2(Object... params) {
return uniq2_sync(conceptClass, params);
}
public int cset(Concept c, Object... values) {
return _cset(c, values);
}
public DynCRUD() {
}
public DynCRUD(Class conceptClass) {
this.conceptClass = conceptClass;
}
public void start() {
try {
super.start();
start_DynCRUD();
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public class Either {
public byte which;
public Object value;
public Either() {
}
public Either(int which, Object value) {
this.which = (byte) which;
this.value = value;
}
public boolean isA() {
return which == 1;
}
public boolean isB() {
return which == 2;
}
public A a() {
if (which != 1)
_failMe();
return (A) value;
}
public B b() {
if (which != 2)
_failMe();
return (B) value;
}
public void _failMe() {
throw fail("Either object is of wrong type: " + shortClassName(value));
}
}
static public interface UndoableWithAnswer {
public String undo();
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public interface IVar {
public void set(A a);
public A get();
default public boolean has() {
return get() != null;
}
default public void clear() {
set(null);
}
}
static public boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static public 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 public Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static public 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 public Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public Concept getConcept(long id) {
return db_mainConcepts().getConcept(id);
}
static public A getConcept(Class cc, long id) {
return getConcept(db_mainConcepts(), cc, id);
}
static public A getConcept(Concepts concepts, Class cc, long id) {
Concept c = concepts.getConcept(id);
if (c == null)
return null;
if (!isInstance(cc, c))
throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")");
return (A) c;
}
static public void deleteConcept(long id) {
db_mainConcepts().deleteConcept(id);
}
static public void deleteConcept(Concepts concepts, long id) {
concepts.deleteConcept(id);
}
static public void deleteConcept(Concept c) {
if (c != null)
c.delete();
}
static public void deleteConcept(Concept.Ref ref) {
if (ref != null)
deleteConcept(ref.get());
}
static public void registerConcept(Concept c) {
db_mainConcepts().register(c);
}
static public String b(Object contents, Object... params) {
return tag("b", contents, params);
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
static public String tag(String tag) {
return htag(tag);
}
static public String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static public String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static public String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
static public String htag(String tag) {
return htag(tag, "");
}
static public String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
static public 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 public String hopeningTag(String tag, Map params) {
return hopeningTag(tag, mapToParams(params));
}
static public String hopeningTag(String tag, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
for (int i = 0; i < l(params); i += 2) {
String name = (String) get(params, i);
Object val = get(params, i + 1);
if (nempty(name) && val != null) {
if (val == html_valueLessParam())
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
static public boolean neqic(String a, String b) {
return !eqic(a, b);
}
static public boolean neqic(char a, char b) {
return !eqic(a, b);
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static public Object html_valueLessParam_cache;
static public Object html_valueLessParam() {
if (html_valueLessParam_cache == null)
html_valueLessParam_cache = html_valueLessParam_load();
return html_valueLessParam_cache;
}
static public Object html_valueLessParam_load() {
return new Object();
}
static public String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static public Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
return array;
}
static public String htmlencode_forParams(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public class Pair implements Comparable> {
public A a;
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair 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 public void dbWithCase(String caseID) {
caseID(caseID);
db();
}
static public int tableColumnCount(JTable table) {
return tableNumColumns(table);
}
static public void setColumnName(final JTable table, final int idx, final String name) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
if (table.getColumnCount() > idx)
table.getColumnModel().getColumn(idx).setHeaderValue(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (table.getColumnCount() > idx)\r\n table.getColumnModel().getColumn(idx...";
}
});
}
}
static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public String getColumnName(final JTable table, final int idx) {
return table == null ? null : swing(new F0() {
public String get() {
try {
return table.getColumnCount() <= idx ? null : str(table.getColumnModel().getColumn(idx).getHeaderValue());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret table.getColumnCount() <= idx ? null\r\n : str(table.getColumnModel()....";
}
});
}
static public int withMargin_defaultWidth = 6;
static public JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static public JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static public JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public JButton tableDependentButton(JTable tbl, String text, Object action) {
return tableDependButton(tbl, jbutton(text, action));
}
static public JTable addRowSorter(final JTable table) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
table.setRowSorter(new TableRowSorter(table.getModel()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "table.setRowSorter(new TableRowSorter(table.getModel()));";
}
});
}
return table;
}
static public void rowSorter_setComparatorForAllColumns(JTable table, final Comparator comparator) {
if (table == null)
return;
setTableModel_fixSorter.put(table, new VF2() {
public void get(JTable table, RowSorter sorter) {
try {
if (sorter instanceof TableRowSorter) {
int n = tableColumnCount(table);
for (int i = 0; i < n; i++) ((TableRowSorter) sorter).setComparator(i, comparator);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (sorter cast TableRowSorter) {\r\n int n = tableColumnCount(table);\r\n ...";
}
});
}
static public AlphanumComparator alphaNumComparator_instance;
static public Comparator alphaNumComparator() {
if (alphaNumComparator_instance == null)
alphaNumComparator_instance = new AlphanumComparator();
return alphaNumComparator_instance;
}
static public String gtt(JTextComponent c) {
return getTextTrim(c);
}
static public String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static public void onConceptChangeAndNow(Runnable r) {
onConceptsChangeAndNow(r);
}
static public String dm_originalModuleName() {
return dm_originalModuleName(assertNotNull(dm_current()));
}
static public String dm_originalModuleName(Object module) {
return (String) callOpt(dm_getStem(module), "originalModuleName");
}
static public void concepts() {
conceptsAndBot();
}
static public void concepts(int autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static public List conceptsOfType(String type) {
return db_mainConcepts().conceptsOfType(type);
}
static public List filterConcepts(List list, Object... params) {
if (empty(params))
return list;
List l = new ArrayList();
for (A x : list) if (checkConceptFields(x, params))
l.add(x);
return l;
}
static public void deleteConcepts(List conceptsOrIDs) {
db_mainConcepts().deleteConcepts(conceptsOrIDs);
}
static public List deleteConcepts(Class c, Object... params) {
List l = asList(findConceptsWhere(c, params));
deleteConcepts(l);
return l;
}
static public A uniq_sync(final Class c, final Object... params) {
return uniq(c, params);
}
static public A uniq_sync(Concepts concepts, Class c, final Object... params) {
return uniq(concepts, c, params);
}
static public Pair uniq2_sync(Class c, final Object... params) {
return uniq2(c, params);
}
static public Pair uniq2_sync(Concepts cc, Class c, final Object... params) {
return uniq2(cc, c, params);
}
static public int _cset(Concept c, Object... values) {
return cset(c, values);
}
static public int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static public Map> setTableModel_after = weakHashMap();
static public Map> setTableModel_fixSorter = weakHashMap();
static public void setTableModel(final JTable table, final TableModel model) {
{
swing(new Runnable() {
public void run() {
try {
Map widths = tableColumnWidthsByName(table);
int[] i = table.getSelectedRows();
TableRowSorter sorter = model.getColumnCount() == tableColumnCount(table) ? (TableRowSorter) table.getRowSorter() : null;
List extends RowSorter.SortKey> sortKeys = sorter == null ? null : sorter.getSortKeys();
table.setModel(model);
int n = model.getRowCount();
ListSelectionModel sel = table.getSelectionModel();
for (int j = 0; j < i.length; j++) if (i[j] < n)
sel.addSelectionInterval(i[j], i[j]);
tableSetColumnPreferredWidths(table, widths);
if (sorter != null) {
sorter.setModel(model);
callF(setTableModel_fixSorter.get(table), table, sorter);
if (sortKeys != null)
sorter.setSortKeys(sortKeys);
}
table.setRowSorter(sorter);
callF(setTableModel_after.get(table), table);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Map widths = tableColumnWidthsByName(table);\r\n int[] i = ...";
}
});
}
}
static public void db() {
conceptsAndBot();
}
static public void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static public int tableNumColumns(final JTable table) {
return swing(new F0() {
public Integer get() {
try {
return table.getColumnCount();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret table.getColumnCount();";
}
});
}
static public boolean containsSpace(String s) {
return containsSpaces(s);
}
static public String firstToUpper(String s) {
if (empty(s))
return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static public List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
static public List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static public JButton tableDependButton(JTable tbl, JButton b) {
tableDependButtons(tbl, ll(b));
return b;
}
static public JButton tableDependButton(JTable tbl, String text, Object action) {
return tableDependButton(tbl, jbutton(text, action));
}
static public String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
static public String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
static public String getTextTrim(JComponent c) {
if (c instanceof JLabel)
return trim(((JLabel) c).getText());
if (c instanceof JComboBox)
return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
static public void onConceptsChangeAndNow(Runnable r) {
onConceptsChange(r);
callF(r);
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public DynModule dm_current() {
return dm_currentModule();
}
volatile static public boolean conceptsAndBot_running = false;
static public boolean conceptsAndBot_thinOnStart = true;
static public void conceptsAndBot() {
conceptsAndBot(null);
}
static public void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running)
return;
conceptsAndBot_running = true;
try {
ensureDBNotRunning(dbBotStandardName());
} catch (Throwable _e) {
db_mainConcepts().dontSave = true;
throw rethrow(_e);
}
db_mainConcepts().persist(autoSaveInterval);
dbBot();
if (conceptsAndBot_thinOnStart) {
try {
thinAProgramsBackups(getDBProgramID(), true);
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public Collection findConceptsWhere(Class c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(String c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
Collection rawList = index.getAll(params[i + 1]);
params = dropEntryFromParams(params, i);
if (params == null)
return rawList;
List l = new ArrayList();
for (A x : rawList) if (checkConceptFields(x, params))
l.add(x);
return l;
}
}
return filterConcepts(concepts.list(c), params);
}
static public Collection findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
static public A uniq(Class c, Object... params) {
return uniqueConcept(c, params);
}
static public A uniq(Concepts cc, Class c, Object... params) {
return uniqueConcept(cc, c, params);
}
static public Pair uniq2(Class c, Object... params) {
return uniq2(db_mainConcepts(), c, params);
}
static public Pair uniq2(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhere(c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
return pair(x, true);
}
return pair(x, false);
} finally {
_close(__1);
}
}
static public Map weakHashMap() {
return newWeakHashMap();
}
static public Map tableColumnWidthsByName(JTable table) {
TableColumnModel tcm = table.getColumnModel();
if (tcm == null)
return null;
int n = tcm.getColumnCount();
TreeMap map = new TreeMap();
for (int i = 0; i < n; i++) {
TableColumn tc = tcm.getColumn(i);
map.put(str(tc.getHeaderValue()), tc.getWidth());
}
return map;
}
static public boolean tableSetColumnPreferredWidths_debug = false;
static public void tableSetColumnPreferredWidths(final JTable table, final Map widths) {
if (table == null || widths == null)
return;
{
swing(new Runnable() {
public void run() {
try {
try {
TableColumnModel tcm = table.getColumnModel();
int n = tcm.getColumnCount();
for (int i = 0; i < n; i++) {
TableColumn tc = tcm.getColumn(i);
Integer w = widths.get(str(tc.getHeaderValue()));
if (w != null) {
tc.setPreferredWidth(w);
if (tableSetColumnPreferredWidths_debug)
print("Setting preferred width of column " + i + " to " + w);
}
}
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n TableColumnModel tcm = table.getColumnModel();\r\n int n = tcm....";
}
});
}
}
static public void tableSetColumnPreferredWidths(JTable table, Object... widths) {
tableSetColumnPreferredWidths(table, litorderedmap(widths));
}
static public boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
static public A getOrKeep(Map map, A a) {
if (map == null)
return a;
A v = map.get(a);
return v != null ? v : a;
}
static public List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
if (isAllUpperCase(s)) {
l.add(s);
return l;
}
for (int i = 0; i < l(s); i++) if (i > j && isUpperCaseLetter(s.charAt(i))) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static public void tableDependButtons(final JTable table, List extends Component> buttons) {
for (Component c : buttons) if (c instanceof JButton) {
final JButton b = (JButton) c;
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
b.setEnabled(table.getSelectedRow() >= 0);
}
});
b.setEnabled(table.getSelectedRow() >= 0);
}
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public void onConceptsChange(Runnable r) {
onConceptsChange(db_mainConcepts(), r);
}
static public void onConceptsChange(Concepts cc, Runnable r) {
cc.addConceptIndex(simpleConceptIndex(r));
cc.onAllChanged.add(r);
}
static public void ensureDBNotRunning(String name) {
if (hasBot(name)) {
try {
String framesBot = dropSuffix(".", name) + " Frames";
print("Trying to activate frames of running DB: " + framesBot);
if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram())
cleanKill();
} catch (Throwable __e) {
_handleException(__e);
}
throw fail("Already running: " + name);
}
}
static public void ensureDBNotRunning() {
ensureDBNotRunning(dbBotStandardName());
}
static public String dbBotStandardName() {
String home = userHome();
String name = dbBotName(getDBProgramID());
if (neq(home, actualUserHome()))
name += " " + quote(home);
return name + ".";
}
static volatile public Android3 dbBot_instance;
static public Android3 dbBot() {
return dbBot(dbBotStandardName());
}
static public Android3 dbBot(String name) {
ensureDBNotRunning(name);
return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock);
}
static public void thinAProgramsBackups(String progID, boolean doIt) {
List files = new ArrayList();
Map ageMap = new HashMap();
java.util.regex.Pattern pat = regexp("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)$");
File dir = programDir(progID);
for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) {
String s = f.getName();
java.util.regex.Matcher matcher = pat.matcher(s);
{
if (!(matcher.find()))
continue;
}
String originalName = matcher.group(1);
{
if (!(eq(originalName, "concepts.structure.gz")))
continue;
}
int year = matcherInt(matcher, 2);
int month = matcherInt(matcher, 3);
int day = matcherInt(matcher, 4);
int hour = matcherInt(matcher, 5);
long time = timestampFromYMDH(year, month, day, hour);
double age = ((now() - time) / 1000.0 / 60 / 60 / 24);
ageMap.put(f, age);
files.add(f);
}
int numDeleted = 0;
sortByMap_inPlace(files, ageMap);
double lastAge = -1;
for (File f : files) {
double age = ageMap.get(f);
if (!thinAProgramsBackups_shouldKeep(age, lastAge)) {
++numDeleted;
if (doIt) {
print("Deleting: " + f);
f.delete();
}
} else {
lastAge = age;
}
}
if (numDeleted != 0)
print((doIt ? "Deleted: " : "Would delete: ") + n(numDeleted, "file"));
}
static public boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) {
return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge);
}
static public Object[] dropEntryFromParams(Object[] params, int i) {
int n = l(params);
if (i < 0 || i >= n)
return params;
if (n == 2)
return null;
Object[] p = new Object[n - 2];
System.arraycopy(params, 0, p, 0, i);
System.arraycopy(params, i + 2, p, i, n - i - 2);
return p;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public boolean isAllUpperCase(String s) {
return hasLettersAllUpperCase(s);
}
static public boolean isUpperCaseLetter(char c) {
return Character.isUpperCase(c);
}
static public boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
static public IConceptIndex simpleConceptIndex(final Runnable r) {
return new IConceptIndex() {
public void update(Concept c) {
pcallF(r);
}
public void remove(Concept c) {
pcallF(r);
}
};
}
static public boolean hasBot(String searchPattern) {
try {
DialogIO io = findBot(searchPattern);
if (io != null) {
io.close();
return true;
} else
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isOK(String s) {
s = trim(s);
return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s);
}
static public String sendOpt(String bot, String text, Object... args) {
return sendToLocalBotOpt(bot, text, args);
}
static public boolean isMainProgram() {
return creator() == null;
}
static public void cleanKill() {
cleanKillVM();
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public String dbBotName(String progIDWithCase) {
return fsI_flex(progIDWithCase) + " Concepts";
}
static public String actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) {
return methodsBot2(name, receiver, exposedMethods, null);
}
static public Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) {
Android3 android = new Android3();
android.greeting = name;
android.console = false;
android.responder = new Responder() {
public String answer(String s, List history) {
return exposeMethods2(receiver, s, exposedMethods, lock);
}
};
return makeBot(android);
}
static public List db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount");
static public List db_standardExposedMethods() {
return db_standardExposedMethods_list;
}
static public Matcher regexp(String pat, String s) {
return regexp(compileRegexp(pat), unnull(s));
}
static public Matcher regexp(java.util.regex.Pattern pat, String s) {
return pat.matcher(unnull(s));
}
static public java.util.regex.Pattern regexp(String pat) {
return compileRegexp(pat);
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public List listFilesNotDirs(String dir) {
return listFilesOnly(dir);
}
static public List listFilesNotDirs(File... dirs) {
return listFilesOnly(dirs);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public int matcherInt(Matcher m, int i) {
return parseInt(m.group(i));
}
static public long timestampFromYMDH(int y, int m, int d, int h) {
return new GregorianCalendar(y, m - 1, d, h, 0).getTimeInMillis();
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public List sortByMap_inPlace(List l, Map map) {
sort(l, mapComparator(map));
return l;
}
static public boolean defaultAgeBasedBackupRetentionStrategy_shouldKeep(double age, double lastAge) {
if (age <= 0.5)
return true;
if (age <= 7 && age >= lastAge + 1)
return true;
if (age <= 28 && age >= lastAge + 7)
return true;
if (age >= lastAge + 365.0 / 12)
return true;
return false;
}
static public boolean hasLettersAllUpperCase(String s) {
return hasLetters(s) && !containsLowerCase(s);
}
static public Map findBot_cache = synchroHashMap();
static public int findBot_timeout = 5000;
static public DialogIO findBot(String searchPattern) {
String subBot = null;
int i = searchPattern.indexOf('/');
if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) {
subBot = searchPattern.substring(i + 1);
searchPattern = searchPattern.substring(0, i);
if (!isInteger(searchPattern))
searchPattern = "Multi-Port at " + searchPattern + ".";
}
if (isInteger(searchPattern))
return talkToSubBot(subBot, talkTo(parseInt(searchPattern)));
if (eq(searchPattern, "remote"))
return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999));
Integer port = findBot_cache.get(searchPattern);
if (port != null)
try {
DialogIO io = talkTo("localhost", port);
io.waitForLine();
String line = io.readLineNoBlock();
if (indexOfIgnoreCase(line, searchPattern) == 0) {
call(io, "pushback", line);
return talkToSubBot(subBot, io);
}
} catch (Exception e) {
e.printStackTrace();
}
List bots = quickBotScan();
for (ProgramScan.Program p : bots) {
if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) {
findBot_cache.put(searchPattern, p.port);
return talkToSubBot(subBot, talkTo("localhost", p.port));
}
}
for (ProgramScan.Program p : bots) {
String botName = firstPartOfHelloString(p.helloString);
boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM.");
boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM;
if (shouldRecurse)
try {
Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots"));
for (Number vport : subBots.keySet()) {
String name = subBots.get(vport);
if (startsWithIgnoreCase(name, searchPattern))
return talkToSubBot(vport.longValue(), talkTo("localhost", p.port));
}
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
return null;
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public boolean matchStart(String pat, String s) {
return matchStart(pat, s, null);
}
static public boolean matchStart(String pat, String s, Matches matches) {
if (s == null)
return false;
return matchStart(pat, parse3_cachedInput(s), matches);
}
static public boolean matchStart(String pat, List toks, Matches matches) {
if (toks == null)
return false;
List tokpat = parse3_cachedPattern(pat);
if (toks.size() < tokpat.size())
return false;
String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
if (m == null)
return false;
if (matches != null) {
matches.m = new String[m.length + 1];
arraycopy(m, matches.m);
matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size());
}
return true;
}
static public String sendToLocalBotOpt(String bot, String text, Object... args) {
if (bot == null)
return null;
text = format(text, args);
DialogIO channel = findBot(bot);
try {
if (channel == null) {
print(quote(bot) + " not found, skipping send: " + quote(text));
return null;
}
try {
channel.readLine();
print(shorten(bot + "> " + text, 200));
channel.sendLine(text);
String s = channel.readLine();
print(shorten(bot + "< " + s, 200));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public void cleanKillVM() {
try {
ping();
assertNotOnAWTThread();
cleanKillVM_noSleep();
Object o = new Object();
synchronized (o) {
o.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void cleanKillVM_noSleep() {
call(getJavaX(), "cleanKill");
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public String fsI_flex(String s) {
return startsWithDigit(s) ? "#" + s : s;
}
static public boolean exposeMethods2_debug = false;
static public String exposeMethods2(Object receiver, String s, List methodNames) {
return exposeMethods2(receiver, s, methodNames, null);
}
static public String exposeMethods2(Object receiver, String s, List methodNames, Lock lock) {
Matches m = new Matches();
if (exposeMethods2_debug)
print("Received: " + s);
if (match("call *", s, m)) {
List l;
if (isIdentifier(m.unq(0)))
l = ll(m.unq(0));
else
l = (List) unstructure(m.unq(0));
String method = getString(l, 0);
if (!contains(methodNames, method))
throw fail("Method not allowed: " + method);
if (lock != null)
lock.lock();
try {
if (exposeMethods2_debug)
print("Calling: " + method);
Object o = call(receiver, method, asObjectArray(subList(l, 1)));
if (exposeMethods2_debug)
print("Got: " + getClassName(o));
return ok2(structure(o));
} finally {
if (lock != null)
lock.unlock();
}
}
if (match("list methods", s))
return ok2(structure(methodNames));
return null;
}
static public int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static public Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static public Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static public Android3 makeBot() {
return makeAndroid3(defaultBotName());
}
static public Map compileRegexp_cache = syncMRUCache(10);
static public java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null) {
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
}
return p;
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public File javaxDataDir_dir;
static public File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static public File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static public List listFilesOnly(String dir) {
return listFilesOnly(new File(dir));
}
static public List listFilesOnly(File... dirs) {
return concatMap(rcurry("listFilesWithSuffix", ""), dirs);
}
static public void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static public void sort(T[] a) {
Arrays.sort(a);
}
static public void sort(int[] a) {
if (a != null)
Arrays.sort(a);
}
static public void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static public void sort(List a) {
Collections.sort(a);
}
static public Comparator mapComparator(final Map map) {
return new Comparator () {
public int compare(A a, A b) {
return cmp(map.get(a), map.get(b));
}
};
}
static public List listFilesWithSuffix(File dir, String suffix) {
List l = new ArrayList();
for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
l.add(f);
return l;
}
static public boolean hasLetters(String s) {
for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
return true;
return false;
}
static public boolean containsLowerCase(String s) {
for (int i = 0; i < l(s); i++) if (isLowerCase(s.charAt(i)))
return true;
return false;
}
static public DialogIO talkToSubBot(final long vport, final DialogIO io) {
return talkToSubBot(String.valueOf(vport), io);
}
static public DialogIO talkToSubBot(final String subBot, final DialogIO io) {
if (subBot == null)
return io;
return new talkToSubBot_IO(subBot, io);
}
static public class talkToSubBot_IO extends DialogIO {
public String subBot;
public DialogIO io;
public talkToSubBot_IO(String subBot, DialogIO io) {
this.io = io;
this.subBot = subBot;
}
public boolean isStillConnected() {
return io.isStillConnected();
}
public String readLineImpl() {
return io.readLineImpl();
}
public boolean isLocalConnection() {
return io.isLocalConnection();
}
public Socket getSocket() {
return io.getSocket();
}
public void close() {
try {
io.close();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void sendLine(String line) {
io.sendLine(format3("please forward to bot *: *", subBot, line));
}
}
static public DialogIO talkTo(int port) {
return talkTo("localhost", port);
}
static public int talkTo_defaultTimeout = 10000;
static public int talkTo_timeoutForReads = 0;
static public ThreadLocal> talkTo_byThread = new ThreadLocal();
static public DialogIO talkTo(String ip, int port) {
try {
String full = ip + ":" + port;
Map map = talkTo_byThread.get();
if (map != null && map.containsKey(full))
return map.get(full);
if (isLocalhost(ip) && port == vmPort())
return talkToThisVM();
return new talkTo_IO(ip, port);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public class talkTo_IO extends DialogIO {
public String ip;
public int port;
public Socket s;
public Writer w;
public BufferedReader in;
public talkTo_IO(String ip, int port) {
this.port = port;
this.ip = ip;
try {
s = new Socket();
try {
if (talkTo_timeoutForReads != 0)
s.setSoTimeout(talkTo_timeoutForReads);
s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout);
} catch (Throwable e) {
throw fail("Tried talking to " + ip + ":" + port, e);
}
w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
public boolean isStillConnected() {
return !(eos || s.isClosed());
}
public void sendLine(String line) {
try {
Lock __0 = lock;
lock(__0);
try {
w.write(line + "\n");
w.flush();
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String readLineImpl() {
try {
return in.readLine();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void close() {
try {
if (!noClose)
s.close();
} catch (IOException e) {
}
}
public Socket getSocket() {
return s;
}
}
static public List quickBotScan() {
return ProgramScan.quickBotScan();
}
static public List quickBotScan(int[] preferredPorts) {
return ProgramScan.quickBotScan(preferredPorts);
}
static public List quickBotScan(String searchPattern) {
List l = new ArrayList();
for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0)
l.add(p);
return l;
}
static public String firstPartOfHelloString(String s) {
int i = s.lastIndexOf('/');
return i < 0 ? s : rtrim(s.substring(0, i));
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public Object unstructure(String text) {
return unstructure(text, false);
}
static public Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static public int structure_internStringsLongerThan = 50;
static public int unstructure_unquoteBufSize = 100;
static public int unstructure_tokrefs;
abstract static public class unstructure_Receiver {
abstract public void set(Object o);
}
static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static public Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
static public Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
final public Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
throw fail("unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
throw fail("unsatisfied token reference " + ref + " at " + tokIndex);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("ll")) {
consume();
{
parseList(new LinkedList(), out);
return;
}
}
if (t.equals("syncLL")) {
consume();
{
parseList(synchroLinkedList(), out);
return;
}
}
if (t.equals("sync")) {
consume();
{
parse(new unstructure_Receiver() {
public void set(Object value) {
if (value instanceof Map) {
if (value instanceof NavigableMap) {
out.set(Collections.synchronizedNavigableMap((NavigableMap) value));
return;
}
if (value instanceof SortedMap) {
out.set(Collections.synchronizedSortedMap((SortedMap) value));
return;
}
{
out.set(Collections.synchronizedMap((Map) value));
return;
}
} else {
out.set(Collections.synchronizedList((List) value));
return;
}
}
});
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
this.parseList(new ArrayList(), out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray") || t.equals("dblarray")) {
parseArray(out);
return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume();
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
if (eq(t, "cu")) {
consume();
t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = "main$" + t;
Class _c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (_c == null)
throw fail("Class not found: " + fullClassName);
parse(new unstructure_Receiver() {
public void set(Object value) {
out.set(call(_c, "_deserialize", value));
}
});
return;
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava());
return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t));
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = "main$" + t;
}
if (c == null) {
if (allDynamic)
c = null;
else
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c != null)
classesMap.put(className, c);
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
final LinkedHashMap fields = new LinkedHashMap();
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ","))
consume();
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields, hasOuter);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
String t = tpp();
if (!eq(t, "="))
throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t())...";
}
});
} else {
objRead(o, dO, fields, hasOuter);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) {
if (o != null) {
if (dO != null) {
setOptAllDyn(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
if (hasOuter)
fixOuterRefs(o);
} else
for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
tokrefs.put(i, list);
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume();
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r...";
}
});
}
public void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(\r\n ...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix("main$", name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v = false;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_initial(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
Boolean b = DynamicObject_loading.get();
DynamicObject_loading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_initial(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
DynamicObject_loading.set(b);
}
}
static public boolean unstructure_debug = false;
static public String sendToLocalBotQuietly(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = newFindBot2(bot);
try {
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotQuietly(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static public Map> parse3_cachedInput_cache = synchronizedMRUCache(1000);
static public List parse3_cachedInput(String s) {
List tok = parse3_cachedInput_cache.get(s);
if (tok == null)
parse3_cachedInput_cache.put(s, tok = parse3(s));
return tok;
}
static public Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000);
static synchronized public List parse3_cachedPattern(String s) {
List tok = parse3_cachedPattern_cache.get(s);
if (tok == null)
parse3_cachedPattern_cache.put(s, tok = parse3(s));
return tok;
}
static public String[] match2(List pat, List tok) {
int i = pat.indexOf("...");
if (i < 0)
return match2_match(pat, tok);
pat = new ArrayList(pat);
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i + 1, "");
}
return match2_match(pat, tok);
}
static public String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t)))
return null;
}
return result.toArray(new String[result.size()]);
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public int shorten_default = 100;
static public String shorten(String s) {
return shorten(s, shorten_default);
}
static public String shorten(String s, int max) {
return shorten(s, max, "...");
}
static public String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
static public String shorten(int max, String s) {
return shorten(s, max);
}
static public void assertNotOnAWTThread() {
assertFalse("Can't do this in AWT thread", isAWTThread());
}
static public boolean startsWithDigit(String s) {
return nempty(s) && isDigit(s.charAt(0));
}
static public String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static public String getString(List l, int idx) {
return (String) get(l, idx);
}
static public String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static public String getString(String key, Object o) {
return getString(o, (Object) key);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public 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 public Object[] asObjectArray(Collection l) {
return toObjectArray(l);
}
static public String ok2(String s) {
return "ok " + s;
}
static public boolean makeAndroid3_disable = false;
static public class Android3 {
public String greeting;
public boolean publicOverride = false;
public int startPort = 5000;
public Responder responder;
public boolean console = true;
public boolean quiet = false;
public boolean daemon = false;
public boolean incomingSilent = false;
public int incomingPrintLimit = 200;
public boolean useMultiPort = true;
public boolean recordHistory = false;
public boolean verbose = false;
public int answerPrintLimit = 500;
public boolean newLineAboveAnswer, newLineBelowAnswer;
public int port;
public long vport;
public DialogHandler handler;
public ServerSocket server;
public Android3(String greeting) {
this.greeting = greeting;
}
public Android3() {
}
synchronized public void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) {
try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public String toString() {
return "Bot: " + greeting + " [vport " + vport + "]";
}
}
static abstract public class Responder {
abstract public String answer(String s, List