Warning : session_start(): open(/var/lib/php/sessions/sess_2odgh2t2uvfp59b5sq55m5ld1a, 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 static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.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;
import java.nio.file.Files;
import java.nio.file.Path;
class main {
public static class Entry extends Concept {
public long msgID;
public String line;
public String preprocessed;
public String ruleIDs;
public static String _fieldOrder = "msgID line preprocessed";
}
public static class GPreprocessedLines extends DynCRUD {
public GPreprocessedLines() {
super(Entry.class);
}
public transient int maxInterpretablesPerLine = 20;
public void start() {
super.start();
dbIndexing(Entry.class, "msgID");
addCountToName();
}
public JComponent visualize() {
return withCenteredButtons(super.visualize(), "Full Scan", runnableThread(new Runnable() {
public void run() {
try {
fullScan();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "fullScan();";
}
}));
}
public void fullScan() {
AutoCloseable __7 = enter();
try {
List list = new ArrayList();
Flag interrupted = new Flag();
AutoCloseable action = dm_currentAction("Scanning chat", rRaiseFlag(interrupted));
try {
F0 contextMaker = new GazelleContextCache_v2().fill();
List lines = dm_discord_allLines();
for (GazelleLine line : iterateOverListSendingPercentage(new VF1() {
public void get(Object percent) {
try {
callOpt(action, "setText", percent + "% - Scanning chat");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(action, 'setText, percent + \"% - Scanning chat\")";
}
}, reversed(lines))) {
if (!licensed() || interrupted.get())
break;
scanLine(line, "contextMaker", contextMaker);
}
} finally {
_close(action);
}
} finally {
_close(__7);
}
}
public void scanLine(GazelleLine line, Object... __) {
List list = new ArrayList();
Collection l = takeFirst(maxInterpretablesPerLine, gazelle_preprocess(line.text, __));
for (GInterpretable intp : l) {
if (eq(intp.text, line.text))
continue;
list.add(unlistedWithValues(Entry.class, "msgID", line.msgID, "line", line.text, "preprocessed", intp.text, "ruleIDs", intp.ruleID));
}
replaceItemsForMessage(line.msgID, list);
}
public void replaceItemsForMessage(long msgID, List items) {
deleteConceptsWhere(Entry.class, "msgID", msgID);
registerAll(items);
}
}
public static boolean _moduleClass_GPreprocessedLines = false;
public static 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);
}
}
public static A callF(F0 f) {
return f == null ? null : f.get();
}
public static A callF(IF0 f) {
return f == null ? null : f.get();
}
public static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
public static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
public static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
public static void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
public static Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
public static Object call(Object o) {
return callF(o);
}
public static Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
public static void _onLoad_initUtils() {
utils.__javax = javax();
}
public static 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...";
}
});
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent = false;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static volatile Object print_preprocess;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static 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);
}
public static void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
public static void print_autoRotate() {
}
public static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
public static void dbIndexing(Object... params) {
db();
for (int i = 0; i < l(params); i += 2) indexConceptField((Class) params[i], (String) params[i + 1]);
}
public static JPanel withCenteredButtons(JComponent center, Object... params) {
return centerAndSouth(center, withMargin(jcenteredbuttons(params)));
}
public static 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)";
}
};
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
public static AutoCloseable dm_currentAction(String text, Runnable cancelMe) {
return (AutoCloseable) dm_callModule(dm_makeOrShowModule("#1019874/CurrentAction"), "showAction", text, cancelMe);
}
public static Runnable rRaiseFlag(final Flag flag) {
return flag == null ? null : new Runnable() {
public void run() {
try {
flag.raise();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "flag.raise()";
}
};
}
public static List dm_discord_allLines() {
return map("dm_discord_importLine", (List) dm_call(dm_gazelle_linesCRUD(), "concepts"));
}
public static IterableIterator iterateOverListSendingPercentage(Object onPercentage, List l) {
return iff(new Object() {
public int n = l(l), i = 0, lastPercent = 0;
public Object get() {
if (i >= n)
return endMarker();
Object o = l.get(i++);
int percent = intPercentRatio(i, n);
if (percent > lastPercent)
pcallF(onPercentage, lastPercent = percent);
return o;
}
});
}
public static List reversed(Collection l) {
return reversedList(l);
}
public static List reversed(A[] l) {
return reversedList(asList(l));
}
public static String reversed(String s) {
return reversedString(s);
}
public static volatile boolean licensed_yes = true;
public static boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
public static void licensed_off() {
licensed_yes = false;
}
public static 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);
}
}
public static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
public static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
public static String takeFirst(int n, String s) {
return substring(s, 0, n);
}
public static String takeFirst(String s, int n) {
return substring(s, 0, n);
}
public static List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_1322 = 0; _repeat_1322 < n; _repeat_1322++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
public static Collection gazelle_preprocess(String input1, Object... __) {
List interpretables = new ArrayList();
int max = optPar("max", __, 20);
Collector collector = limitedCollector(interpretables, max);
Map evalCache = new HashMap();
F1 eval = boolPar("noEvals", __) ? f_id() : new F1() {
public String get(String s) {
try {
return gazelle_processSafeEvals(s, evalCache);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "gazelle_processSafeEvals(s, evalCache)";
}
};
input1 = callF(eval, input1);
Set texts = litCISet(input1);
collector.add(new GInterpretable(input1));
RuleEngine2 engine = ((F0) optPar("contextMaker", __)).get().engine;
int nInterpreted = 0;
bigLoop: while (!collector.full() && nInterpreted < l(interpretables)) {
GInterpretable workingOn = get(interpretables, nInterpreted);
String input = workingOn.text;
String ruleBase = empty(workingOn.ruleID) ? "" : workingOn.ruleID + "+";
++nInterpreted;
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
for (String out : gazelle_executeSplitterRule(engine, rule, input)) if (texts.add(out = callF(eval, out)))
if (collector.add(new GInterpretable(out, ruleBase + rule.globalID)))
break bigLoop;
} catch (Throwable __e) {
_handleException(__e);
}
}
for (GazelleTree t : dm_gazelle_reasonAboutChatInput_v2(null, input, paramsPlus(__, "skipSplitters", true, "acceptablePurposes", litset("preprocess"), "skipUserName", true, "skipUserID", true))) {
String s = callF(eval, t.line);
if (texts.add(s))
if (collector.add(new GInterpretable(s, ruleBase + t.ruleID(), t.mr)))
break bigLoop;
}
}
return interpretables;
}
public static boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
public static A unlistedWithValues(Class c, Object... params) {
A a = unlisted(c);
cset(a, params);
return a;
}
public static List deleteConceptsWhere(Class c, Object... params) {
return deleteConcepts(c, params);
}
public static void registerAll(Collection extends Concept> l) {
if (l != null)
for (Concept c : l) register(c);
}
public static Class mc() {
return main.class;
}
public static Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
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 in " + c);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Class javax() {
return getJavaX();
}
public static void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
public static HashMap findClass_fullName_cache = new HashMap();
public static 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;
}
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static String substring(String s, int x) {
return substring(s, x, strL(s));
}
public static String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
public static Object _defaultClassFinder_value = defaultDefaultClassFinder();
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static String programID;
public static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
public static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
public static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
public static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
public static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
public static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
public static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
public static void db() {
conceptsAndBot();
}
public static void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
public static void indexConceptField(Class extends Concept> c, String field) {
indexConceptField(db_mainConcepts(), c, field);
}
public static void indexConceptField(Concepts concepts, Class extends Concept> c, String field) {
if (!isConceptFieldIndexed(concepts, c, field))
new ConceptFieldIndex(concepts, c, field);
}
public static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static 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...";
}
});
}
public static JPanel jcenteredbuttons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return jcenteredline(l);
}
public static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
public static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
public static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static Object dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __951 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__951);
}
}
public static String dm_makeOrShowModule(String moduleLibID) {
return (String) dm_callOS("makeOrShowModule", moduleLibID);
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
public static List map(IF1 f, Iterable l) {
return map(l, f);
}
public static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(IF1 f, A[] l) {
return map(l, f);
}
public static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(Object f, Object[] l) {
return map(f, asList(l));
}
public static List map(Object[] l, Object f) {
return map(f, l);
}
public static List map(Object f, Map map) {
return map(map, f);
}
public static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
public static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
public static GazelleLine dm_discord_importLine(Object lineConcept) {
return lineConcept == null ? null : nu(GazelleLine.class, "timestamp", _get("created", lineConcept), "user", call(lineConcept, "userName"), "bot", _get("bot", lineConcept), "text", _get("text", lineConcept), "msgID", getLong("msgID", lineConcept), "context", _get("context", lineConcept), "channelID", rcall("channelID", lineConcept), "reactions", map(getList(lineConcept, "reactions"), new F1() {
public GazelleReaction get(Object r) {
try {
return nu(GazelleReaction.class, "userID", getLong((Object) getOpt("user", r), "userID"), "created", _get("created", r), "emoji", _get("emoji", r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "nu GazelleReaction(\r\n userID := getLong((O) getOpt user(r), 'userID),\r...";
}
}));
}
public static Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __793 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__793);
}
}
public static String dm_gazelle_linesCRUD() {
return dm_require("#1021628/GLines");
}
public static IterableIterator iff(Object f) {
return iteratorFromFunction_withEndMarker(f);
}
public static IterableIterator iff(F0 f) {
return iteratorFromFunction_withEndMarker(f);
}
public static IterableIterator iff(IF0 f) {
return iteratorFromFunction_withEndMarker(f);
}
public static Object endMarker() {
return iteratorFromFunction_endMarker;
}
public static int intPercentRatio(double x, double y) {
return ratioToIntPercent(x, y);
}
public static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
public static A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
public static B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static List reversedList(Collection l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
public static String reversedString(String s) {
return reverseString(s);
}
public static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
public static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
public static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
public static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
public static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
public static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
public static Object optPar(String name, Map params) {
return optParam(name, params);
}
public static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static Collector limitedCollector(Collection l, int max) {
return limitedListCollector(l, max);
}
public static boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
public static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Map __) {
return boolOptParam(name, __);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static F1 f_id_value;
public static F1 f_id() {
if (f_id_value == null)
f_id_value = new F1 () {
public A get(A a) {
try {
return a;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret a;";
}
};
return f_id_value;
}
public static String gazelle_processSafeEvals(String text, Map evalCache) {
String l = dm_processEmbeddedSafeEvals(text, "evalCache", evalCache);
if (l != text) {
print("Processed eval: " + text + " => " + l);
text = l;
}
return text;
}
public static TreeSet litCISet(String... items) {
return litciset(items);
}
public static boolean empty(Collection c) {
return c == null || c.isEmpty();
}
public static boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
public static boolean empty(Map map) {
return map == null || map.isEmpty();
}
public static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
public static boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
public static boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
public static boolean empty(float[] a) {
return a == null || a.length == 0;
}
public static boolean empty(int[] a) {
return a == null || a.length == 0;
}
public static boolean empty(long[] a) {
return a == null || a.length == 0;
}
public static boolean empty(byte[] a) {
return a == null || a.length == 0;
}
public static boolean empty(short[] a) {
return a == null || a.length == 0;
}
public static boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
public static boolean empty(File f) {
return getFileSize(f) == 0;
}
public static Collection gazelle_executeSplitterRule(RuleEngine2 engine, RuleEngine2.SimplifyWithRule rule, String input) {
Object f = rule.function();
Collection out = (Collection) ((f instanceof String ? callF(engine.callFunctionOnString, (String) f, input) : callF(f, input)));
if (l(out) == 1 && eq(first(out), input))
return emptyList();
return out;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static List dm_gazelle_reasonAboutChatInput_v2(String userName, String content, Object... __) {
boolean debug = boolPar("debug", __);
boolean debugRules = boolPar("debugRules", __) || debug;
List preContext = (List) (optPar("preContext", __));
GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __));
F0 contextMaker = (F0) (optPar("contextMaker", __));
if (debugRules)
print("Have ctx: " + (ctx != null) + ", contextMaker: " + (contextMaker != null));
if (ctx == null && contextMaker != null) {
ctx = contextMaker.get();
if (debugRules)
print("Called contextMaker, got " + nRules(ctx.engine.rules));
}
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord")));
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
if (debug)
print(" == PROCESSING INPUT: " + content);
gazelle_dropRulesNotOnInput(ctx);
if (acceptablePurposes != null) {
if (debugRules) {
print("Purposes: " + acceptablePurposes);
print("Have purposes: " + collectUnique("purpose", ctx.engine.rules));
}
int nBefore = l(ctx.engine.rules);
ctx.engine.dropRulesWhere(r -> !acceptablePurposes.contains(unnull(r.purpose)));
if (debugRules)
print("Retaining " + n2(ctx.engine.rules, "rule") + " of " + nBefore);
}
if (debugRules)
print("Have rules: " + collect("globalID", ctx.engine.rules));
gazelle_addHelpers(ctx, __);
Object[] params = paramsPlus(paramsMinus(__, "ctx"), "firstConditionOnly", true, "dialogHistory", preContext);
GazelleTree tree1 = (GazelleTree) (optPar("tree", __));
if (tree1 == null)
tree1 = new GazelleTree(ctx, content);
List l = gazelle_getChildren_withContinuations(tree1, params);
if (nempty(userName) && !boolPar("skipUserName", __)) {
GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content);
if (debug)
print("Tree2: " + tree2);
l.addAll(gazelle_getChildren_withContinuations(tree2, paramsPlus(__, "tree2", true)));
}
Long userID = (Long) (optPar("userID", __));
if (userID != null && userID != 0 && !boolPar("skipUserID", __)) {
GazelleTree tree3 = new GazelleTree(ctx, "user with id " + userID + " says: " + content);
l.addAll(gazelle_getChildren_withContinuations(tree3, paramsPlus(__, "tree3", true)));
}
if (boolPar("skipBad", __, true))
l = filter(l, new F1() {
public Boolean get(GazelleTree t) {
try {
return neq(t.prediction, "bad");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "neq(t.prediction, \"bad\")";
}
});
gazelle_sortChildren(l);
Map inputMap = gazelle_inputMapFromLineAndHistory(content, listPlus(preContext, content));
if (debug)
print("reasonAbout inputMap=" + sfu(asTreeMap(inputMap)));
for (GazelleTree t : l) {
if (t.mr == null)
continue;
int iCond;
do {
iCond = t.mr.iCond;
dm_gazelle_matchStep_statement(t, passParams(__, "debug", "dm_gazelle_matchStatementsDebug"));
dm_gazelle_matchStep_additionalInput(t, inputMap, __);
dm_gazelle_matchStep_condition(t, __);
} while (t.mr.iCond > iCond);
}
for (GazelleTree t : l) t.flush();
int n = l(l);
l = gazelle_dropUnsatisfiedEntries(l);
if (debug)
print("Filtered out " + (n - l(l)) + " unsatisfied entries (keeping " + l(l) + ")");
if (!boolPar("keepDefaults", __))
gazelle_dropMatchedDefaultRules(l, __);
return l;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], a2) };
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
public static HashSet litset(A... items) {
return lithashset(items);
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
public static void deleteConcepts(List conceptsOrIDs) {
db_mainConcepts().deleteConcepts(conceptsOrIDs);
}
public static List deleteConcepts(Class c, Object... params) {
List l = findConceptsWhere(c, params);
deleteConcepts(l);
return l;
}
public static void register(Concept c) {
db_mainConcepts().register(c);
}
public static final Map callOpt_cache = newDangerousWeakHashMap();
public static Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
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);
}
}
public static _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
public static Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
public static String joinWithComma(Collection c) {
return join(", ", c);
}
public static String joinWithComma(String... c) {
return join(", ", c);
}
public static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
public static List classNames(Collection l) {
return getClassNames(l);
}
public static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
public static int strL(String s) {
return s == null ? 0 : s.length();
}
public static int listL(Collection l) {
return l == null ? 0 : l.size();
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static Object iteratorFromFunction_endMarker = new Object();
public static IterableIterator iteratorFromFunction_withEndMarker(final Object f) {
class IFF extends IterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = (A) callF(f);
if (a == iteratorFromFunction_endMarker)
done = true;
}
}
;
return new IFF();
}
public static IterableIterator iteratorFromFunction_withEndMarker(final F0 f) {
return iteratorFromFunction_withEndMarker_f0(f);
}
public static List splitAtEllipsis(String s) {
return splitAtTokens(javaTokWithBrackets(s), ".", "", ".", "", ".");
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "loadableUtils.utils$"))
return findClass_fullName("main" + substring(name, 19));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
};
}
public static boolean nempty(Collection c) {
return !empty(c);
}
public static boolean nempty(CharSequence s) {
return !empty(s);
}
public static boolean nempty(Object[] o) {
return !empty(o);
}
public static boolean nempty(byte[] o) {
return !empty(o);
}
public static boolean nempty(int[] o) {
return !empty(o);
}
public static boolean nempty(Map m) {
return !empty(m);
}
public static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
public static boolean nempty(Object o) {
return !empty(o);
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
public static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
public static Class getMainClass() {
return mc();
}
public static Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean ping_pauseAll = false;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions = false;
public static Map ping_actions = newWeakHashMap();
public static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
public static boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
public static 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);
}
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
public static volatile boolean conceptsAndBot_running = false;
public static boolean conceptsAndBot_thinOnStart = true;
public static void conceptsAndBot() {
conceptsAndBot(null);
}
public static 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);
}
}
}
public static volatile Concepts mainConcepts;
public static Concepts db_mainConcepts() {
if (mainConcepts == null) {
mainConcepts = new Concepts(getDBProgramID());
mainConcepts.classFinder = _defaultClassFinder();
}
return mainConcepts;
}
public static boolean isConceptFieldIndexed(Class extends Concept> c, String field) {
return isConceptFieldIndexed(db_mainConcepts(), c, field);
}
public static boolean isConceptFieldIndexed(Concepts concepts, Class extends Concept> c, String field) {
return concepts.getFieldIndex(c, field) != null;
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static A swing(IF0 f) {
return (A) swingAndWait(f);
}
public static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
public static JButton jbutton(String text) {
return newButton(text, null);
}
public static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
public static JPanel jcenteredline(final Component... components) {
return swing(new F0() {
public JPanel get() {
try {
return jFullCenter(hstackWithSpacing(components));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret jFullCenter(hstackWithSpacing(components));";
}
});
}
public static JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
public static String defaultThreadName_name;
public static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
public static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
public static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
public static Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
public static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
public static 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)";
}
};
}
public static Map _registerThread_threads;
public static Object _onRegisterThread;
public static 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;
}
public static void _registerThread() {
_registerThread(Thread.currentThread());
}
public static Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static Object _get(Object o, String field) {
return get(o, field);
}
public static Object _get(String field, Object o) {
return get(o, field);
}
public static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static Android3 bot(String greeting) {
return makeAndroid3(greeting);
}
public static Android3 bot(Android3 a) {
return makeBot(a);
}
public static Android3 bot(String greeting, Object responder) {
return makeBot(greeting, responder);
}
public static Android3 bot() {
return makeBot();
}
public static long getLong(Object o, String field) {
return toLong(getOpt(o, field));
}
public static long getLong(String field, Object o) {
return getLong(o, field);
}
public static Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
public static List getList(Map map, Object key) {
return map == null ? null : (List) map.get(key);
}
public static List getList(List l, int idx) {
return (List) get(l, idx);
}
public static List getList(Object o, Object key) {
if (o instanceof Map)
return getList((Map) o, key);
if (key instanceof String)
return (List) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static int ratioToIntPercent(double x, double y) {
return roundToInt(x * 100 / y);
}
public static Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static float min(float a, float b) {
return Math.min(a, b);
}
public static float min(float a, float b, float c) {
return min(min(a, b), c);
}
public static double min(double a, double b) {
return Math.min(a, b);
}
public static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
public static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
public static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
public static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
public static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
public static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
public static A optParam(ThreadLocal tl) {
return optPar(tl);
}
public static Object optParam(String name, Map params) {
return mapGet(params, name);
}
public static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
public static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
public static Collector limitedListCollector(final Collection l, final int max) {
return new Collector () {
public boolean full() {
return l(l) >= max;
}
public boolean add(A a) {
if (full())
return false;
l.add(a);
return full();
}
public boolean contains(A a) {
return l.contains(a);
}
};
}
public static boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
public static boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
public static boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
public static String dm_processEmbeddedSafeEvals(String s, Object... __) {
Map evalCache = (Map) (optPar("evalCache", __));
if (!contains(s, "{="))
return s;
List tok = javaTok(s);
Map bracketMap = curlyBracketMap(tok);
for (int i = 1; i < l(tok) - 4; i += 2) {
{
if (!(eq(tok.get(i), "{") && eqGet(tok, i + 1, "") && eqGet(tok, i + 2, "=")))
continue;
}
int j = or(bracketMap.get(i), l(tok));
String code = joinSubList(tok, i + 4, j - 1);
if (!isSafeCodeFragment(code))
replaceTokens(tok, i + 2, i + 4, "UNSAFE: ");
else {
String result = mapGet(evalCache, code);
if (result == null) {
print("Evaluating: " + code);
try {
result = strOrEmpty(dm_javaEvalOrInterpret(code));
} catch (Throwable e) {
printStackTrace(e);
result = "";
}
mapPut(evalCache, code, result);
}
replaceTokens(tok, i, j + 1, result);
}
i = j - 2;
}
return trim(join(tok));
}
public static TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
public static String getType(Object o) {
return getClassName(o);
}
public static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
public static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static A first(T3 t) {
return t == null ? null : t.a;
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static String nRules(int n) {
return n2(n, "rule");
}
public static String nRules(Collection l) {
return n2(l, "rule");
}
public static GazelleEvalContext dm_gazelle_stdEvalContext() {
return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs());
}
public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules, Object... __) {
GazelleEvalContext ctx = gazelle_stdEvalContext_v2(rules, __);
ctx.engine.callFunctionOnString = new F2() {
public Object get(String function, String s) {
try {
return dm_callFunctionOnString(function, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_callFunctionOnString(function, s)";
}
};
return ctx;
}
public static List> dm_gazelle_allRulesWithComment(final String comment) {
List> l = dm_allRulesFromRulesModuleWithCommentsAndIDs();
return empty(comment) ? l : filter(l, new F1, Boolean>() {
public Boolean get(T3 t) {
try {
return cic(tlft(t.b), comment);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cic(tlft(t.b), comment)";
}
});
}
public static void gazelle_dropRulesNotOnInput(GazelleEvalContext ctx) {
ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement", "disable"));
}
public static HashSet collectUnique(Collection c, String field) {
HashSet set = new HashSet();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
set.add(val);
}
return set;
}
public static HashSet collectUnique(String field, Collection c) {
return collectUnique(c, field);
}
public static String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
public static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static void gazelle_addHelpers(GazelleEvalContext ctx, Object... __) {
if (ctx.engine.hasHelpers)
return;
print("Adding helpers");
ctx.engine.hasHelpers = true;
gazelle_addHelperTablesToRules(ctx.engine);
gazelle_addVarSplittersToRules(ctx.engine, __);
gazelle_addVarDiscriminators(ctx.engine, __);
gazelle_addVarConvertersToRules(ctx.engine, __);
gazelle_addCalculationFunctionsToRules(ctx.engine, __);
gazelle_addRespondToHumanOnlyHelpers(ctx.engine, __);
gazelle_addForbiddenBindingHelpers(ctx.engine, __);
}
public static Object[] paramsMinus(Object[] a1, Object... keys) {
return paramsWithout(a1, keys);
}
public static List gazelle_getChildren_withContinuations(GazelleTree tree, Object... __) {
List l = gazelle_getChildren(tree, __);
boolean debug = boolPar("debug", __) || boolPar("debugContinuations", __);
Matches m = new Matches();
boolean changes = false;
for (int i = 0; i < l(l); i++) {
GazelleTree t = l.get(i);
{
if (!(eq(t.lineType, "instruction") && match("continue with line * of rule * without variables", t.line, m)))
continue;
}
if (debug)
print("Processing continuation: " + sfu(m));
String ruleID = m.unq(1);
RuleEngine2.Rule rule = t.ctx.engine.getRule(ruleID);
if (rule == null) {
print("Follow-up rule not found: " + ruleID);
{
l.remove(i--);
continue;
}
}
changes = true;
t.mr.rule = rule;
t.mr.iCond = parseInt(m.unq(0)) - 1;
t.mr.map = ciMap();
if (!t.mr.moreConditions()) {
t.line = rule.out;
t.lineType = rule.outType();
}
gazelle_addPredictionToTreeNode(t);
}
if (changes)
gazelle_sortChildren(l);
return l;
}
public static String optCurly(String s) {
return curlyBraceOptIfMoreThanOneToken(s);
}
public static 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;
}
public static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
public static 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;
}
public static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
public static 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;
}
public static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
public static void gazelle_sortChildren(GazelleTree tree) {
if (tree == null)
return;
gazelle_sortChildren(tree.children);
}
public static void gazelle_sortChildren(List children) {
if (children != null)
sortByCalculatedFieldDesc(children, new F1() {
public Integer get(GazelleTree c) {
try {
return ai_goodBadToInt(c.prediction);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ai_goodBadToInt(c.prediction)";
}
});
}
public static Map gazelle_inputMapFromLineAndHistory(String line, List history) {
Map inputMap = litmap("standard", line);
for (int i = 0; i < l(history); i++) inputMap.put("history-" + (l(history) - i), history.get(i));
return inputMap;
}
public static List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
public static String sfu(Object o) {
return structureForUser(o);
}
public static TreeMap asTreeMap(Map map) {
return map instanceof TreeMap ? (TreeMap) map : new TreeMap(map);
}
public static boolean dm_gazelle_matchStep_statement(GazelleTree t, Object... __) {
if (t.rule() == null)
return false;
boolean debug = boolPar("debug", __) || boolPar("matchStatementsDebug", __);
RuleEngine2_MatchedRule mr = t.mr;
List in = t.rule().in;
int iCond = t.mr.iCond;
if (debug)
print("matchStatements: iCond=" + iCond + " in " + in);
if (iCond >= l(in))
return false;
List conditions = dropFirst(iCond, in);
if (debug)
print("Remaining conditions for " + t.ruleID() + " with " + t.mr.map + ": " + conditions);
Matches m = new Matches();
if (!matchAny("in " + (iCond + 1) + " = statement *", t.rule().comments, m))
return false;
String subRuleID = m.unq(0);
if (debug)
print("Found subrule: " + subRuleID);
List fulfillments = dm_gazelle_fulfillmentsForRule(subRuleID);
Lowest> bestMap = new Lowest();
if (debug)
print("Have " + n2(fulfillments, "fulfillment") + ".");
for (Object f : fulfillments) {
Map varMap = asCIMap(safeUnstructMap(getString("varMap", f)));
if (debug)
print("fulfillment => " + sfu(varMap));
boolean selfVarsFix = boolPar("selfVarsFix", __, true);
if (selfVarsFix) {
String cond = first(conditions);
for (String x : identifiersOnly(codeTokens(mr.tokenize(cond)))) if (!varMap.containsKey(x)) {
if (debug)
print("Self-linking " + x);
varMap.put(x, x);
}
}
if (debug)
print("Original map: " + t.mr.map);
Map newMap = mergeMapsStrictlyIC(asCIMap(t.mr.map), varMap);
if (newMap == null) {
if (debug)
printIndent("Can't merge maps");
continue;
}
if (debug)
printIndent("Maps merged! => " + sfu(newMap));
newMap = ciMapWithoutKeysEqualToValues(newMap);
if (debug)
printIndent("Map simplified => " + sfu(newMap));
{
if (gazelle_isRecentlyUsedMapping(t, newMap, __))
continue;
}
bestMap.put(newMap, l(newMap));
}
Map newMap = bestMap.get();
if (newMap == null) {
if (debug)
print("No matching statement found");
return false;
}
t.mr.map = newMap;
t.mr.iCond++;
t.mr.remainingConditions = dropFirst(t.mr.remainingConditions);
t.mr.remainingConditionsWithType = dropFirst(t.mr.remainingConditionsWithType);
t.mr.out = null;
t.line = t.mr.outText();
if (debug)
print("Rewrote " + t.mr.rule.out + " to: " + t.line);
return true;
}
public static Object[] passParams(Object[] __, String... params) {
Map map = paramsToMap(__);
List l = new ArrayList();
int n = l(l) - 1;
for (String key : params) if (map.containsKey(key)) {
l.add(key);
l.add(map.get(key));
}
return empty(l) ? null : toObjectArray(l);
}
public static void dm_gazelle_matchStep_additionalInput(GazelleTree t, Map inputsByType, Object... __) {
if (t.rule() == null)
return;
boolean debug = boolPar("debug", __);
TextAndType next = get(t.rule().insWithType, t.mr.iCond);
if (next == null || !startsWith(next.type, "history-"))
return;
if (ai_ruleEngine2_matchStep(t.mr, inputsByType, true, __)) {
if (debug)
print("Input match OK. new map: " + t.mr.map + ". Updating prediction.");
gazelle_addPredictionToTreeNode(t);
} else if (debug)
print("Input match failed");
}
public static void dm_gazelle_matchStep_condition(GazelleTree t, Object... __) {
if (t.rule() == null)
return;
boolean debug = boolPar("debug", __) || boolPar("debugConditions", __);
GRuleLine next = get(t.rule().insWithType, t.mr.iCond);
if (debug)
print("matchStep_condition: " + getString("type", next));
if (next == null || !eq(next.type, "condition"))
return;
boolean satisfied = false;
String cond = t.mr.applyMappingTo(next);
if (gazelle_isEmbeddedEval(cond)) {
if (debug)
print("Embedded eval: " + cond);
satisfied = eqic(dm_processEmbeddedSafeEvals(cond), "true");
} else {
GazelleEvalContext subCtx = (GazelleEvalContext) (callF(requiredPar("contextMaker", __)));
subCtx.engine.dropRulesWhere(r -> neq(r.purpose, "condition to eval"));
List l = dm_gazelle_reasonAboutChatInput_v2(null, cond, paramsPlus(paramsMinus(__, "acceptablePurposes"), "ctx", subCtx));
gazelle_processSafeEvalsInTree(l);
if (debug) {
print("Sub-Tree for condition " + cond + ":");
printIndentLines(l);
}
for (GazelleTree tree : l) if (eqic(tree.line, "true")) {
satisfied = true;
break;
} else if (eqic(tree.line, "false"))
break;
}
if (debug)
print("satisfied=" + satisfied);
if (!satisfied)
return;
t.mr.iCond++;
gazelle_addPredictionToTreeNode(t);
t.mr.remainingConditions = dropFirst(t.mr.remainingConditions);
t.mr.remainingConditionsWithType = dropFirst(t.mr.remainingConditionsWithType);
}
public static List gazelle_dropUnsatisfiedEntries(List l) {
return antiFilter(l, t -> t.mr != null && t.mr.moreConditions());
}
public static void gazelle_dropMatchedDefaultRules(List l, Object... __) {
List l2 = filter(l, t -> !eqic(t.lineType, "temporary fact"));
Set trumpedRules = new HashSet();
for (GazelleTree t : l2) addAll(trumpedRules, matchAll_first("trumps rule *", t.ruleComments()));
List trumped = filter(l2, new F1() {
public Boolean get(GazelleTree t) {
try {
return contains(t.ruleComments(), "default") || trumpedRules.contains(t.ruleID());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "contains(t.ruleComments(), \"default\")\r\n || trumpedRules.contains(t.ruleID())";
}
});
if (nempty(trumped) && l(trumped) < l(l2)) {
if (boolPar("debug", __) || boolPar("debugDefaults", __)) {
print("Removing default/trumped rules:");
printIndentLines(trumped);
print("Because there are also:");
printIndentLines(listMinusSet(l2, trumped));
}
l.removeAll(trumped);
}
}
public static Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
public static Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
public static LinkedHashMap paramsToOrderedMap(Object... params) {
return asLinkedHashMap(paramsToMap(params));
}
public static Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
public static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
public static Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static 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);
}
}
public static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static List findConceptsWhere(Class c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
public static List findConceptsWhere(String c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
public static List 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) {
List 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);
}
public static List findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
public static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
public static String joinWithSpace(Collection c) {
return join(" ", c);
}
public static String joinWithSpace(String... c) {
return join(" ", c);
}
public static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
public static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
public static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
public static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
public static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
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));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
public static IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) {
class IFF2 extends IterableIterator {
public A a;
public boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
public void getNext() {
if (done || have)
return;
a = f.get();
have = true;
if (a == iteratorFromFunction_endMarker)
done = true;
}
}
;
return new IFF2();
}
public static List splitAtTokens(String s, List tokens) {
return splitAtTokens(javaTok(s), tokens);
}
public static List splitAtTokens(List tok, List tokens) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, tokens, i);
if (i >= l(tok))
break;
if (j < 0)
j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j + l(tokens);
}
return l;
}
public static List splitAtTokens(List tok, String... tokens) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, tokens, i);
if (i >= l(tok))
break;
if (j < 0)
j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j + l(tokens);
}
return l;
}
public static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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;
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
public static 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);
}
}
public static void ensureDBNotRunning() {
ensureDBNotRunning(dbBotStandardName());
}
public static String dbBotStandardName() {
String home = userHome();
String name = dbBotName(getDBProgramID());
if (neq(home, actualUserHome()))
name += " " + quote(home);
return name + ".";
}
public static volatile Android3 dbBot_instance;
public static Android3 dbBot() {
return dbBot(dbBotStandardName());
}
public static Android3 dbBot(String name) {
ensureDBNotRunning(name);
return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock);
}
public static void thinAProgramsBackups(String progID, boolean doIt) {
List files = new ArrayList();
Map ageMap = new HashMap();
Pattern pat = Pattern.compile("^(.*)\\.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();
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"));
}
public static boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) {
return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge);
}
public static String getDBProgramID_id;
public static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static 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();
}
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
public static JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
public static JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static boolean newButton_autoToolTip = true;
public static 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...";
}
});
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static JPanel jFullCenter(final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;";
}
});
}
public static int hstackWithSpacing_spacing = 10;
public static JPanel hstackWithSpacing(Object... parts) {
parts = flattenArray2(parts);
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
public static Object[] asArray(List l) {
return toObjectArray(l);
}
public static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
public static 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 }";
}
};
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static boolean isString(Object o) {
return o instanceof String;
}
public static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
public static Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
public static boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
public static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
public static Object dm_os() {
{
Object __352 = vm_generalMap_get("stefansOS");
if (__352 != null)
return __352;
}
return creator();
}
public static A setAll(A o, Map fields) {
if (fields == null)
return o;
for (String field : keys(fields)) set(o, field, fields.get(field));
return o;
}
public static A setAll(A o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
return o;
}
public static boolean makeAndroid3_disable = false;
public static 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() {
}
public synchronized 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 + "]";
}
}
public abstract static class Responder {
public abstract String answer(String s, List history);
}
public static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
public static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
public static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable)
return a;
if (a.responder == null)
a.responder = new Responder() {
public String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse()))
a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort)
return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet)
startDialogServer_quiet.set(true);
try {
a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
public static void makeAndroid3_handleConsole(final Android3 a) {
if (!a.quiet)
print("You may also type on this console.");
{
startThread(new Runnable() {
public void run() {
try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null)
break;
{
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a));
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri...";
}
});
}
}
public static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else
try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
}
}
}
};
}
public static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null)
originalAnswer = "?";
if (a.newLineAboveAnswer)
print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer)
print();
}
return answer;
}
public static String makeAndroid3_fallback(String s, List history, String answer) {
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s))
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null)
answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
public static boolean makeAndroid3_consoleInUse() {
if (isTrue(vm_generalMap_get("consoleInUse")))
return true;
for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
public static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
public String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
public static ThreadLocal makeAndroid3_io = new ThreadLocal();
public static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
public static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
public static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
public static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
public static Android3 makeBot() {
return makeAndroid3(defaultBotName());
}
public static long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static String dm_makeModule(String moduleLibID) {
return (String) dm_callOS("makeModule", moduleLibID);
}
public static int roundToInt(double d) {
return (int) Math.round(d);
}
public static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
public static Object collectionMutex(List l) {
return l;
}
public static Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
public static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
public static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
public static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
public static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
public static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt = false;
public static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
public static Map curlyBracketMap(List tok) {
TreeMap map = new TreeMap();
List stack = new ArrayList();
int n = l(tok);
for (int i = 1; i < n; i += 2) {
String t = tok.get(i);
if (eq(t, "{"))
stack.add(i);
else if (eq(t, "}") && nempty(stack))
map.put(liftLast(stack), i);
}
return map;
}
public static boolean eqGet(List l, int i, Object o) {
return eq(get(l, i), o);
}
public static boolean eqGet(Map map, A key, Object o) {
return eq(mapGet(map, key), o);
}
public static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
public static String joinSubList(List l, int i) {
return join(subList(l, i));
}
public static boolean isSafeCodeFragment(String code) {
return eq("safe", joinWithComma(getCodeFragmentSafety(code)));
}
public static void replaceTokens(List tok, int i, int j, String s) {
clearAllTokens(subList(tok, i, j));
tok.set(i, s);
}
public static void replaceTokens(List tok, String s) {
clearAllTokens(tok);
tok.set(0, s);
}
public static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
public static Object dm_javaEvalOrInterpret(String code) {
final Object module = dm_current_generic();
code = trim(code);
if (canQuickEval(code))
return quickEval(code);
Pair> p = tok_parseFunctionCall(code);
if (p != null) {
if (module != null)
makeAndCall_initChild.set(new F1() {
public AutoCloseable get(Class c) {
try {
shareMyCreatorWith(c);
InheritableThreadLocal tl = (InheritableThreadLocal) (getOpt(c, "dm_currentModule_value"));
return tempSetTL(tl, weakRef(module));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shareMyCreatorWith(c);\r\n InheritableThreadLocal tl = cast...";
}
});
return callAndMake(p.a, toObjectArray(map("dm_javaEvalOrInterpret", p.b)));
}
return dm_javaEval(code);
}
public static A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
public static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
public static String trim(StringBuilder buf) {
return buf.toString().trim();
}
public static String trim(StringBuffer buf) {
return buf.toString().trim();
}
public static TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
public static TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
public static TreeSet treeSet() {
return new TreeSet();
}
public static Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return collectThreeFieldsAsTriple("text", "comments", "globalID", (List) dm_call(dm_gazelle_rulesModule(), "concepts"));
}
public static GazelleEvalContext gazelle_stdEvalContext_v2(List> rules, Object... __) {
long startTime = sysNow();
GazelleEvalContext ctx = new GazelleEvalContext();
ctx.engine = new RuleEngine2();
ctx.engine.addRules2(rules);
gazelle_changeInTypesForRulesWithMultipleInputs(ctx.engine);
MultiSet statements = dm_gazelle_statementsFromAppliedRules_multiSet();
ctx.dataByRule = new HashMap();
Map> statementsByRule = ai_gazelle_indexStatementsByRule_multiSet(statements);
for (String ruleID : keys(statementsByRule)) {
MultiSet statements2 = statementsByRule.get(ruleID);
ctx.dataByRule.put(ruleID, ai_gazelle_analyzeStatementsForRule_multiSet(statements2));
}
ctx.predictor = dm_gazelle_standardPredictor(__);
done2(startTime, "Making engine with " + n2(rules, "rule"));
return ctx;
}
public static Object dm_callFunctionOnString(String code, String s) {
return callF(dm_codeWithHintsToFunctionOnString(code), s);
}
public static boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
public static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static boolean cicOneOf(String s, String... l) {
for (String x : l) if (cic(s, x))
return true;
return false;
}
public static boolean cicOneOf(Collection l, String... bla) {
for (String x : unnull(l)) if (eqicOneOf(x, bla))
return true;
return false;
}
public static Map emptyMap() {
return new HashMap();
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
public static class gazelle_addHelperTablesToRules_Massager {
public List> helperTable;
public Map> helperIndex;
public gazelle_addHelperTablesToRules_Massager() {
}
public gazelle_addHelperTablesToRules_Massager(List> helperTable, Map> helperIndex) {
this.helperIndex = helperIndex;
this.helperTable = helperTable;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
for (String t : codeTokens(matched.tokenize(matched.rule.out))) {
if (map.containsKey(t))
continue;
Pair idx = helperIndex.get(t);
if (idx == null)
continue;
{
final Map __140 = cloneMap(map);
for (String key : keys(__140)) {
String val = __140.get(key);
int idx2 = indexOfIC(helperTable.get(idx.a), key);
if (idx2 < 0)
continue;
Pair idxVal = helperIndex.get(val);
if (idxVal == null)
continue;
String out = _get(_get(helperTable, idxVal.a), idx.b);
print("Massaged: " + t + " <-> " + key + " => " + out);
mapPut(map, t, out);
}
}
}
return map;
}
}
public static void gazelle_addHelperTablesToRules(RuleEngine2 engine) {
Matches m = new Matches();
for (final RuleEngine2.Rule r : engine.rules) {
{
if (!(matchAny("use helper table mech list *", r.comments, m)))
continue;
}
List entries = mL(m.unq(0));
{
if (empty(entries))
continue;
}
final List> helperTable = map("tok_splitAtCommaOrDoubleArrow", entries);
final Map> helperIndex = indexTwoDArrayIC(helperTable);
r.addMapMassager(new gazelle_addHelperTablesToRules_Massager(helperTable, helperIndex));
}
}
public static class gazelle_addVarSplittersToRules_VarSplitter {
public String var;
public boolean debug = false;
public gazelle_addVarSplittersToRules_VarSplitter() {
}
public gazelle_addVarSplittersToRules_VarSplitter(String var, boolean debug) {
this.debug = debug;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = getOrKeep(map, curly(var));
List tok1 = matched.tokenize(var);
List tok2 = matched.tokenize(uncurly(value));
if (debug)
print("VarSplitter: " + tok1 + " / " + tok2);
if (l(tok1) != l(tok2))
return null;
int oldSize = l(map);
for (int i = 1; i < l(tok1); i += 2) if (!strictPutIC(map, tok1.get(i), tok2.get(i)))
return null;
if (debug)
print("VarSplitter done => " + map);
matched.nPossibleVars = matched.nPossibleVars() + l(map) - oldSize;
return map;
}
}
public static void gazelle_addVarSplittersToRules(RuleEngine2 engine, Object... __) {
Matches m = new Matches();
boolean debug = boolPar("debug", __);
for (final RuleEngine2.Rule r : engine.rules) {
{
if (!(jmatchAny("split *", r.comments, m) && isQuoted(m.get(0))))
continue;
}
String var = m.unq(0);
if (debug)
print("Made splitter for: " + var);
r.addMapMassager(new gazelle_addVarSplittersToRules_VarSplitter(var, debug));
}
}
public static class gazelle_addVarDiscriminators_MechListContains extends F1 {
public String list;
public gazelle_addVarDiscriminators_MechListContains() {
}
public gazelle_addVarDiscriminators_MechListContains(String list) {
this.list = list;
}
public Boolean get(String s) {
boolean ok = mechCISetContains(list, s);
print("MechListContains: " + list + " / " + s + " => " + ok);
return ok;
}
}
public static class gazelle_addVarDiscriminators_VarDiscriminator {
public String var;
public Object discriminator;
public boolean debug = false;
public gazelle_addVarDiscriminators_VarDiscriminator() {
}
public gazelle_addVarDiscriminators_VarDiscriminator(String var, Object discriminator, boolean debug) {
this.debug = debug;
this.discriminator = discriminator;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = map.get(var);
if (value != null && !isTrue(callAndMake_orF1(discriminator, value))) {
if (debug)
print("Rejecting var: " + var + " -> " + value + " because of " + discriminator);
return null;
}
return map;
}
}
public static void gazelle_addVarDiscriminators(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("debugVarDiscriminators", __);
for (final RuleEngine2.Rule r : engine.rules) {
for (Matches m : getJMatches_all("var * should satisfy *", r.comments)) {
String var = m.unq(0), discriminator = m.unq(1);
if (debug)
print("Made discriminator for: " + var);
r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, discriminator, debug));
}
for (Matches m : getJMatches_all("var * should be in list *", r.comments)) {
String var = m.unq(0), list = m.unq(1);
r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, new gazelle_addVarDiscriminators_MechListContains(list), debug));
}
for (Matches m : getJMatches_all("* has to be between * and *", r.comments)) {
String var = m.unq(0);
double min = parseDouble(m.unq(1)), max = parseDouble(m.unq(2));
if (debug)
print("Made discriminator for: " + var);
r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, new F1() {
public Boolean get(String value) {
try {
try {
return isBetween_double(parseDouble(or(value, var)), min, max);
} catch (Throwable __e) {
silentException(__e);
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall-silent {\r\n ret isBetween_double(parseDouble(or(value, var)), m...";
}
}, debug));
}
for (Matches m : getJMatches_all("* has to be * or *", r.comments)) {
String var = m.unq(0);
Set values = litciset(m.unq(1), m.unq(2));
if (debug)
print("Made discriminator for: " + var);
r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, new F1() {
public Boolean get(String value) {
try {
return contains(values, or(value, var));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "contains(values, or(value, var))";
}
}, debug));
}
}
}
public static class gazelle_addVarConvertersToRules_VarConverter {
public String var1, var2;
public Object converter;
public boolean debug = false;
public gazelle_addVarConvertersToRules_VarConverter() {
}
public gazelle_addVarConvertersToRules_VarConverter(String var1, String var2, Object converter, boolean debug) {
this.debug = debug;
this.converter = converter;
this.var2 = var2;
this.var1 = var1;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = map.get(var1);
if (value == null)
return map;
String value2 = (String) callAndMake_orF1(converter, value);
if (debug)
print("VarConverter: " + value + " => " + value2);
if (!strictPutIC(map, var2, value2))
return null;
return map;
}
}
public static void gazelle_addVarConvertersToRules(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("varConverterDebug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("convert var * to * with *", r.comments)) r.addMapMassager(new gazelle_addVarConvertersToRules_VarConverter(m.unq(0), m.unq(1), m.unq(2), debug));
}
public static class gazelle_addCalculationFunctionsToRules_Calculator {
public String var1, var2, var3;
public Object function;
public boolean debug = false;
public gazelle_addCalculationFunctionsToRules_Calculator() {
}
public gazelle_addCalculationFunctionsToRules_Calculator(String var1, String var2, String var3, Object function, boolean debug) {
this.debug = debug;
this.function = function;
this.var3 = var3;
this.var2 = var2;
this.var1 = var1;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
double result;
try {
String value1 = getOrKeep(map, var1), value2 = getOrKeep(map, var2);
result = (double) callAndMake_orF2(function, parseDouble(value1), parseDouble(value2));
} catch (Throwable _e) {
return null;
}
if (!strictPutIC(map, var3, str(iround(result))))
return null;
return map;
}
}
public static void gazelle_addCalculationFunctionsToRules(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("calcDebug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("compute var * from * and * using *", r.comments)) {
r.addMapMassager(new gazelle_addCalculationFunctionsToRules_Calculator(m.unq(1), m.unq(2), m.unq(0), m.unq(3), debug));
if (debug)
print("Calculator made");
}
}
public static class gazelle_addRespondToHumanOnlyHelpers_Check {
public boolean debug = false;
public gazelle_addRespondToHumanOnlyHelpers_Check() {
}
public gazelle_addRespondToHumanOnlyHelpers_Check(boolean debug) {
this.debug = debug;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
if (debug)
print("humanOnlyHelper for " + matched.ruleID() + ": " + matched.inputsByType);
if (!eq("true", matched.inputsByType.get("_respondingToHuman")))
return null;
return map;
}
}
public static void gazelle_addRespondToHumanOnlyHelpers(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("humanOnlyDebug", __);
for (final RuleEngine2.Rule r : engine.rules) if (cic(r.comments, "only answer to human")) {
if (debug)
print("Made human-only helper");
r.addMapMassager(new gazelle_addRespondToHumanOnlyHelpers_Check(debug));
}
}
public static class gazelle_addForbiddenBindingHelpers_Blocker {
public String var, value;
public boolean debug = false;
public gazelle_addForbiddenBindingHelpers_Blocker() {
}
public gazelle_addForbiddenBindingHelpers_Blocker(String var, String value, boolean debug) {
this.debug = debug;
this.value = value;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
if (value == null) {
if (map.containsKey(var))
return null;
} else if (eqic(value, map.get(var)))
return null;
return map;
}
}
public static class gazelle_addForbiddenBindingHelpers_TotalBlocker {
public Map get(Map map, List