Warning : session_start(): open(/var/lib/php/sessions/sess_v4gn2jqsqrbd80ih1cakni20is, 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.empty;
import static x30_pkg.x30_util.nempty;
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.print_byThread;
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.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_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
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.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.BWImage;
import loadableUtils.utils.MakesBufferedImage;
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 net.dv8tion.jda.core.*;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.hooks.*;
import net.dv8tion.jda.core.events.message.*;
import net.dv8tion.jda.core.events.message.react.*;
import java.text.*;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
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 ReasoningForLine {
public long timestamp = now();
public long outMsgID;
public String outText;
public long inMsgID, inUserID, inChannelID;
public String inText;
public GazelleTree tree;
public int treeIndex;
}
public static boolean _moduleClass_DiscordBot;
public static class DiscordBot extends DynPrintLogAndEnabled {
public transient JDA bot;
public transient Set msgsReactedTo = new HashSet();
public transient double deleteDelay = 60.0;
public transient boolean doDelete;
public transient Color imageEmbedMysteriousLineColor = colorFromHex("36393f");
public transient boolean skipBad = true;
public transient InheritableThreadLocal currentChannel = new InheritableThreadLocal();
public transient InheritableThreadLocal respondingTo = new InheritableThreadLocal();
public void start() {
super.start();
logModuleOutput();
dm_useLocalMechListCopies();
bot = discordBot(new ListenerAdapter() {
public void onMessageReceived(MessageReceivedEvent e) {
try {
{
if (!enabled || !licensed())
return;
}
boolean bot = e.getAuthor().isBot();
final Message msg = e.getMessage();
print("Channel type: " + e.getChannelType());
boolean isPrivate = e.getChannelType() == ChannelType.PRIVATE;
print("Msg from " + e.getAuthor().getName() + ": " + e.getMessage().getContentDisplay());
String content = trim(msg.getContentRaw());
if (empty(content))
return;
final String originalContent = content;
Object user = userConcept(e.getAuthor());
long userID = e.getAuthor().getIdLong();
String userName = e.getAuthor().getName();
String crud = dm_gazelle_linesCRUD();
Object channel = dm_call(crud, "uniqChannel", msg.getChannel().getIdLong());
dm_call(crud, "cset", channel, litobjectarray("name", msg.getChannel().getName()));
Object lineConcept = dm_call(crud, "uniqConcept", litObjectArrayAsObject("msgID", e.getMessage().getIdLong()));
dm_call(crud, "cset", lineConcept, litobjectarray("text", content, "bot", bot, "isPrivate", isPrivate, "author", user, "channel", channel));
vmBus_send("newDiscordLine", lineConcept);
{
if (bot)
return;
}
final MessageChannel ch = e.getChannel();
long channelID = ch.getIdLong();
Matches m = new Matches();
try {
if (swicOneOf(content, "!eval ", "!fresh ", "!real-eval", "!safe-eval ") || eqic(content, "!fresh")) {
Object safetyCheck = null;
boolean authed = dm_discord_userCanEval(userID);
if (swic(content, "!safe-eval ", m)) {
content = "!eval " + m.rest();
authed = false;
}
if (!authed) {
safetyCheck = new F1() {
public String get(String code) {
try {
String safety = joinWithComma(getCodeFragmentSafety(code));
if (eq(safety, "safe"))
return "";
String s = "Sorry. Safety level is " + safety;
Set unknown = codeAnalysis_getUnknownIdentifiers(code);
if (nempty(unknown))
s += ". Unknown identifiers: " + joinWithComma(unknown);
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S safety = joinWithComma(getCodeFragmentSafety(code));\r\n if (e...";
}
};
}
AutoCloseable __6 = tempSetTL(currentChannel, ch);
try {
AutoCloseable __7 = tempSetTL(respondingTo, msg);
try {
{
dm_bot_execEvalCmd(new VF1() {
public void get(String s) {
try {
if (s != null)
postInChannel(ch, shorten(s, 1000));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (s != null)\r\n postInChannel(ch, shorten(s, 1000))";
}
}, content, "safetyCheck", safetyCheck);
return;
}
} finally {
_close(__7);
}
} finally {
_close(__6);
}
}
if (eqic(content, "!rule")) {
List lines = linesInChannelBy(channelID, userID);
if (contains(nextToLast(lines), "=>"))
content = "!rule " + nextToLast(lines);
else {
if (l(lines) < 3)
throw fail("Too few lines");
content = "!rule " + nextToNextToLast(lines) + " => " + nextToLast(lines);
}
}
if (swic_trim(content, "!rule ", m)) {
String s = m.rest();
String opt = leadingSquareBracketStuff(s);
s = dropActuallyLeadingSquareBracketStuff(s);
if (startsWith(s, "=>"))
s = assertNotNull("No last line in channel", nextToLast(linesInChannelBy(channelID, userID))) + "\n" + s;
List comments = ll("discord");
if (cic(pairB(tok_splitAtDoubleArrow_pair(s)), userName)) {
s = optCurly(userName) + " says: " + s;
comments.add("with user name");
}
if (match("with *", opt, m) && remoteMechListMirror_isPublic(m.unq(0)))
comments.add("use helper table mech list " + quote(m.unq(0)));
s = replace(s, " + ", "\n+ ");
s = gazelle_processSquareBracketAnnotations(s, comments);
dm_gazelle_addRuleWithComment(s, lines_rtrim(comments));
{
postInChannel(ch, dm_gazelle_addRuleWithComment_msg.get());
return;
}
}
List l = dm_gazelle_reasonAboutChatInput(userName, content, "skipBad", skipBad);
int idx = 0;
for (final GazelleTree t : takeFirst(10, l)) {
final int _idx = idx++;
final String out = tok_dropCurlyBrackets(t.line);
print(">> " + t);
postInChannelWithDelete(ch, out, new VF1() {
public void get(Message msg2) {
try {
ReasoningForLine reasoning = nu(ReasoningForLine.class, "outMsgID", msg2.getIdLong(), "outText", out, "inMsgID", msg.getIdLong(), "inUserID", userID, "inChannelID", channelID, "inText", originalContent, "tree", t, "treeIndex", _idx);
saveGZStructToFileVerbose(javaxDataDir("Discord Reasonings/" + reasoning.outMsgID + ".gz"), reasoning);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ReasoningForLine reasoning = nu(ReasoningForLine,\r\n outMsgID :...";
}
});
}
} catch (Throwable error) {
_handleException(error);
postInChannel(ch, exceptionToStringShort(error));
}
} catch (Throwable __e) {
_handleException(__e);
}
}
public void onMessageReactionAdd(MessageReactionAddEvent e) {
try {
{
if (!enabled || !licensed())
return;
}
MessageReaction r = e.getReaction();
boolean bot = e.getUser().isBot();
long msgID = r.getMessageIdLong();
add(msgsReactedTo, msgID);
print("User " + e.getUser() + (bot ? " (bot)" : "") + " reacted to message " + msgID + " with " + r.getReactionEmote());
if (bot)
return;
String crud = dm_gazelle_linesCRUD();
Object lineConcept = dm_call(crud, "uniqConcept", litObjectArrayAsObject("msgID", msgID));
List reactions = (List) (get(lineConcept, "reactions"));
print("lineConcept=" + lineConcept);
print("reactions=" + reactions);
Object reaction = dm_call(crud, "nuReaction", litObjectArrayAsObject("user", userConcept(e.getUser()), "emoji", r.getReactionEmote().getName(), "created", now()));
print("reaction=" + reaction);
dm_call(crud, "cset", lineConcept, litobjectarray("reactions", listPlus(reactions, reaction)));
dm_discord_gatherFeedbackFromLine(dm_discord_importLine(lineConcept));
} catch (Throwable __e) {
_handleException(__e);
}
}
});
dm_registerAs("discordBot");
print("Started bot");
}
public void cleanMeUp() {
if (bot != null) {
try {
print("Shutting down bot");
bot.shutdown();
print("Bot shut down");
} catch (Throwable __e) {
_handleException(__e);
}
}
bot = null;
}
public Object userConcept(User user) {
String crud = dm_gazelle_linesCRUD();
Object userConcept = dm_call(crud, "uniqUser", user.getIdLong());
dm_call(crud, "cset", userConcept, litobjectarray("name", user.getName()));
return userConcept;
}
public void postInChannel(long channelID, String msg) {
postInChannel(bot.getTextChannelById(channelID), msg);
}
public void postInChannel(MessageChannel channel, String msg) {
channel.sendMessage(msg).queue();
}
public void postInChannel(String channel, String msg) {
long id = dm_discord_channelID(channel);
if (id == 0)
throw fail("Channel not found: " + channel);
postInChannel(id, msg);
}
public void postInChannelWithDelete(MessageChannel channel, String msg, VF1 onPost) {
channel.sendMessage(msg).queue(msg2 -> {
pcallF(onPost, msg2);
final long msgId = msg2.getIdLong();
print("I sent msg: " + msgId);
if (doDelete)
doLater(deleteDelay, new Runnable() {
public void run() {
try {
{
if (contains(msgsReactedTo, msgId))
return;
}
print("Deleting msg " + msgId);
msg2.delete().queue();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return if contains(msgsReactedTo, msgId);\r\n print(\"Deleting msg \" + ms...";
}
});
});
}
public void postImage(String url) {
postImage(currentChannel.get(), url);
}
public void postImage(String url, String title) {
postImage(currentChannel.get(), url, title);
}
public void postImage(MessageChannel channel, String url) {
postImage(channel, url, "");
}
public void postImage(MessageChannel channel, String url, String description) {
channel.sendMessage(new EmbedBuilder().setImage(absoluteURL(url)).setDescription(unnull(description)).setColor(imageEmbedMysteriousLineColor).build()).queue();
}
public List linesInChannelBy(long channelID, long userID) {
return collect("text", dm_discord_linesInChannelBy(channelID, userID));
}
public MessageChannel currentChannel() {
return currentChannel.get();
}
public Message respondingTo() {
return respondingTo.get();
}
}
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 B callF(F1 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 A call(Object o, String method, Object... args) {
return x30_util.call(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;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
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 = print_byThread == null ? null : print_byThread.get();
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) {
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 long now_virtualTime;
public static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
public static java.awt.Color colorFromHex(String hex) {
return awtColor(hex);
}
public static boolean logModuleOutput_installed;
public static void logModuleOutput() {
if (logModuleOutput_installed)
return;
logModuleOutput_installed = true;
final File logFile = getProgramFile("output.txt");
final LineBuffer buf = new LineBuffer(new VF1() {
public void get(String line) {
try {
appendToTextFile(logFile, "[" + localDateWithMilliseconds() + "] " + line + "\n");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "appendToTextFile(logFile, \"[\" + localDateWithMilliseconds() + \"] \" + line + \"...";
}
});
print_forAllThreads(new VF1() {
public void get(String s) {
try {
buf.append(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "buf.append(s);";
}
});
}
public static void dm_useLocalMechListCopies() {
dm_useLocallyCopiedMechLists();
}
public static JDA discordBot(final VF1 onMessage) {
return discordBot(new ListenerAdapter() {
@Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) {
print(" Msg from bot, skipping");
return;
}
pcallF(onMessage, e);
}
});
}
public static JDA discordBot(ListenerAdapter listener) {
try {
JDABuilder builder = new JDABuilder(AccountType.BOT);
File tokenFile = javaxSecretDir("discord-bot-token");
builder.setToken(assertNempty("Need: " + tokenFile, trim(loadTextFile(tokenFile))));
builder.addEventListener(listener);
return builder.build();
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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 String dm_gazelle_linesCRUD() {
return dm_require("#1021628/GLines");
}
public static A dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __26 = dm_enter(mod);
try {
return (A) call(mod, method, args);
} finally {
_close(__26);
}
}
public static Object[] litobjectarray(Object... l) {
return litObjectArray(l);
}
public static Object litObjectArrayAsObject(Object... l) {
return litobjarrayAsObject(l);
}
public static void vmBus_send(String msg, Object... args) {
Object arg = empty(args) ? null : l(args) == 1 ? args[0] : args;
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
public static boolean swicOneOf(String s, String... l) {
for (String x : l) if (swic(s, x))
return true;
return false;
}
public static boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
public static boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
public static boolean dm_discord_userCanEval(long userID) {
return (boolean) dm_requireAndCall("#1021656/GUsers", "canEval", userID);
}
public static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
public static boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
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 Collection getCodeFragmentSafety(String code) {
Map map = codeAnalysis_identifierSafetyMap();
Set identifiers = tok_allIdentifiers(code);
Collection tags = treeSet();
for (String id : identifiers) {
String tag;
if (codeAnalysis_isSafeIdentifier(id))
tag = "safe";
else
tag = or2(map.get(id), "?");
tags.addAll(tokSplitAtComma(tag));
}
tags = simplifySafetyTags(tags);
if (empty(tags))
tags.add("safe");
return tags;
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static Set codeAnalysis_getUnknownIdentifiers(String code) {
Map map = codeAnalysis_identifierSafetyMap();
Set identifiers = tok_allIdentifiers(code);
TreeSet set = new TreeSet();
for (String id : identifiers) {
if (!codeAnalysis_isSafeIdentifier(id) && (!map.containsKey(id) || contains(map.get(id), "?")))
set.add(id);
}
return set;
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
public static boolean dm_bot_execEvalCmd(VF1 postMessage, String s, Object... __) {
double timeout = optPar("timeout", __, 60.0);
Object safetyCheck = optPar("safetyCheck", __);
Matches m = new Matches();
boolean freshMe = swic_trim(s, "!fresh ", m);
if (freshMe || eq(s, "!fresh")) {
dm_refreshTranspiler();
if (!freshMe) {
callF(postMessage, "OK");
return true;
}
}
if (swic_trim(s, "!eval ", m)) {
callF(postMessage, pcallOrExceptionText_strOrNull(new F0() {
public Object get() {
try {
String code = m.rest();
{
String _a_62 = (String) callF(safetyCheck, code);
if (!empty(_a_62))
return _a_62;
}
return strOrNull(dm_javaEvalOrInterpret(code));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S code = m.rest();\r\n try answer (S) callF(safetyCheck, code);\r\n ret...";
}
}));
return true;
}
if (freshMe || swic_trim(s, "!real-eval ", m)) {
callF(postMessage, evalWithTimeout_text(timeout, new F0() {
public Object get() {
try {
String code = m.rest();
{
String _a_63 = (String) callF(safetyCheck, code);
if (!empty(_a_63))
return _a_63;
}
return dm_javaEval(code);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S code = m.rest();\r\n try answer (S) callF(safetyCheck, code);\r\n ret...";
}
}));
return true;
}
return false;
}
public static int shorten_default = 100;
public static String shorten(String s) {
return shorten(s, shorten_default);
}
public static String shorten(String s, int max) {
return shorten(s, max, "...");
}
public static String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
public static String shorten(int max, String s) {
return shorten(s, max);
}
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 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 A nextToLast(List l) {
return get(l, l(l) - 2);
}
public static A nextToNextToLast(List l) {
return get(l, l(l) - 3);
}
public static boolean swic_trim(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { trim(substring(a, l(b))) };
return true;
}
public static String leadingSquareBracketStuff(String s) {
if (!startsWith(s, '['))
return null;
return substring(s, 1, smartIndexOf(s, 1, ']'));
}
public static String dropActuallyLeadingSquareBracketStuff(String s) {
return startsWith(s, "[") ? dropLeadingSquareBracketStuff(s) : s;
}
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 A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
public static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
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 B pairB(Pair p) {
return p == null ? null : p.b;
}
public static Pair tok_splitAtDoubleArrow_pair(String s) {
return splitAtDoubleArrow_pair(s);
}
public static Pair tok_splitAtDoubleArrow_pair(List tok) {
return splitAtDoubleArrow_pair(tok);
}
public static String optCurly(String s) {
return curlyBraceOptIfMoreThanOneToken(s);
}
public static boolean remoteMechListMirror_isPublic(String listName) {
return cic(remoteMechListMirrorStatus(listName), "PUBLIC READ");
}
public static String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public static String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
public static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
public static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
public static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
public static String gazelle_processSquareBracketAnnotations(String ruleText, List comments) {
List lines = tlft(ruleText);
for (int i = 0; i < l(lines); i++) {
String s = lines.get(i);
Pair p = splitTrailingSquareBracketStuff(s);
if (nempty(p.b))
comments.add("in " + (i + 1) + " = " + p.b);
lines.set(i, p.a);
}
return lines_rtrim(lines);
}
public static ThreadLocal dm_gazelle_addRuleWithComment_msg = new ThreadLocal();
public static Pair dm_gazelle_addRuleWithComment(String text, String comment) {
Pair p = (Pair) (quickImport(dm_call(dm_gazelle_rulesModule(), "addRuleWithComment", text, comment)));
String rendered = newLinesToSpaces_trim(text);
infoBox(setTLAndReturn(dm_gazelle_addRuleWithComment_msg, p.b ? "Rule " + p.a + " added: " + rendered : "Rule already there: " + p.a + " - " + rendered));
return p;
}
public static Pair dm_gazelle_addRuleWithComment(String when, String then, String comment) {
return dm_gazelle_addRuleWithComment(when + "\n=> " + then, comment);
}
public static String lines_rtrim(Collection lines) {
return rtrim_fromLines(lines);
}
public static List dm_gazelle_reasonAboutChatInput(String userName, String content, Object... __) {
boolean debug = boolPar("debug", __);
boolean selfVarsFix = boolPar("selfVarsFix", __, true);
GazelleEvalContext ctx = optPar("ctx", __);
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord")));
ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement"));
if (debug)
print("Have rules: " + collect("globalID", ctx.engine.rules));
gazelle_addHelperTablesToRules(ctx.engine);
GazelleTree tree1 = new GazelleTree(ctx, content);
List l = dm_gazelle_getChildren(tree1, "firstConditionOnly", true);
GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content);
l.addAll(dm_gazelle_getChildren(tree2, "firstConditionOnly", 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);
for (GazelleTree t : l) if (t.rule() != null) {
RuleEngine2_MatchedRule mr = t.mr;
List in = t.rule().in;
int iCond = t.mr.iCond;
if (l(in) > iCond) {
List conditions = dropFirst(iCond, in);
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)) {
print("Unwired condition");
continue;
}
String subRuleID = m.unq(0);
print("Found subrule: " + subRuleID);
List fulfillments = dm_gazelle_fulfillmentsForRule(subRuleID);
print("Have fulfillments:");
for (Object f : fulfillments) {
Map varMap = asCIMap(safeUnstructMap(getString("varMap", f)));
printIndent(sfu(varMap));
if (selfVarsFix) {
String cond = first(conditions);
for (String x : identifiersOnly(codeTokens(mr.tokenize(cond)))) if (!varMap.containsKey(x)) {
print("Self-linking " + x);
varMap.put(x, x);
}
}
Map newMap = mergeMapsStrictlyIC(asCIMap(t.mr.map), varMap);
if (newMap == null) {
printIndent("Can't merge maps");
continue;
}
printIndent("Maps merged! => " + sfu(newMap));
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();
print("Rewrote " + t.mr.rule.out + " to: " + t.line);
break;
}
}
}
l = filter(l, new F1() {
public Boolean get(GazelleTree t) {
try {
return t.mr == null || !t.mr.moreConditions();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "t.mr == null || !t.mr.moreConditions()";
}
});
return l;
}
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_85 = 0; _repeat_85 < n; _repeat_85++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
public static String tok_dropCurlyBrackets(String s) {
return join(tok_dropCurlyBrackets(javaTok(s)));
}
public static List tok_dropCurlyBrackets(List tok) {
for (int i = 1; i < l(tok); i += 2) {
while (eqGetOneOf(tok, i, "{", "}")) {
tokAppend(tok, i - 1, tok.get(i + 1));
removeSubList(tok, i, i + 2);
}
}
return tok;
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static void saveGZStructToFileVerbose(File file, Object o) {
saveGZStructureToFile(file, o);
printFileSaved(file);
}
public static File javaxDataDir_dir;
public static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
public static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
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 String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
public static void add(BitSet bs, int i) {
bs.set(i);
}
public static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
public static void add(Container c, Component x) {
addToContainer(c, x);
}
public static List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
public static void dm_discord_gatherFeedbackFromLine(GazelleLine l) {
try {
String mrStruct = gazelle_discord_matchedRuleStructForMsgID(l.msgID);
if (mrStruct == null)
return;
print("Processing: " + l.msgID + " - " + l.text);
printIndent(shorten(mrStruct, 50));
printIndent(l.reactions);
List posNeg = uniquifyCI(map("dm_posNegStringForEmoji", collect("emoji", l.reactions)));
printIndent("posNeg = " + posNeg);
if (l(posNeg) > 1) {
warn(" Mixed feedback, skipping");
return;
}
String judgement = cic(posNeg, "positive") ? "good" : "bad";
dm_gazelle_saveAppliedRule("judgement", judgement, "matchedRuleStruct", mrStruct, "context", "discord msg " + l.msgID);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static GazelleLine dm_discord_importLine(Object lineConcept) {
return lineConcept == null ? null : nu(GazelleLine.class, "timestamp", _get("created", lineConcept), "text", _get("text", lineConcept), "msgID", getLong("msgID", 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 AutoCloseable dm_registerAs(String msg) {
return dm_vmBus_answerToMessage(msg, new F0() {
public Object get() {
try {
return dm_moduleID();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret dm_moduleID();";
}
});
}
public static long dm_discord_channelID(String name) {
return dm_call(dm_gazelle_linesCRUD(), "getChannelID", name);
}
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 java.util.Timer doLater(long delay, final Object r) {
ping();
final java.util.Timer timer = new java.util.Timer();
timer.schedule(timerTask(r, timer), delay);
return timer;
}
public static java.util.Timer doLater(double delaySeconds, final Object r) {
return doLater(toMS(delaySeconds), r);
}
public static String absoluteURL(String url) {
return isAbsoluteURL(url) ? url : "http://" + url;
}
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 Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
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 List dm_discord_linesInChannelBy(long channelID, long userID) {
return map("dm_discord_importLine", (List) dm_call(dm_gazelle_linesCRUD(), "linesInChannelBy", channelID, userID));
}
public static List dm_discord_linesInChannelBy(String channelName, String userName) {
return dm_discord_linesInChannelBy((long) dm_call(dm_gazelle_linesCRUD(), "idForChannel", channelName), (long) dm_call(dm_gazelle_linesCRUD(), "idForUser", userName));
}
public static Class mc() {
return main.class;
}
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 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 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 _defaultClassFinder_value;
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 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 StringBuilder))
return;
StringBuilder buf = (StringBuilder) (_buf);
max /= 2;
if (buf.length() > max)
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static java.awt.Color awtColor(String hex) {
byte[] b = bytesFromHex(dropPrefix("#", hex));
return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
}
public static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
public static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
public static void appendToTextFile(File file, String contents) {
try {
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String localDateWithMilliseconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS");
return format.format(time);
}
public static String localDateWithMilliseconds() {
return localDateWithMilliseconds(now());
}
public static void print_forAllThreads(Object f) {
assertNull("todo", print_allThreads);
print_allThreads = f;
}
public static void dm_useLocallyCopiedMechLists() {
dm_requireModule("#1016073/MechLists");
useLocalMechListCopies(true);
setOptMC("serverMechList_raw_fresh_verbose", true);
setOptMC("mechList_goToCreator_dont", true);
}
public static File javaxSecretDir_dir;
public static File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
public static File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
public static A assertNempty(A a) {
return assertNempty("empty", a);
}
public static A assertNempty(String msg, A a) {
if (empty(a))
throw fail(msg + ": " + a);
return a;
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
public static String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
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[] litObjectArray(Object... l) {
return l;
}
public static Object litobjarrayAsObject(Object... l) {
return l;
}
public static void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
public static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
public static Set vm_busListeners_live_cache;
public static Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
public static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
public static Map vm_busListenersByMessage_live_cache;
public static Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
public static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static Object dm_requireAndCall(String moduleLibID, String method, Object... args) {
return dm_requireAndCallModule(moduleLibID, method, args);
}
public static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
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 String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static Map codeAnalysis_identifierSafetyMap() {
return mechHashMap("JavaX Identifier Safety");
}
public static Set tok_allIdentifiers(String s) {
return new HashSet(filter("isIdentifier", javaTokC(s)));
}
public static TreeSet treeSet() {
return new TreeSet();
}
public static boolean codeAnalysis_isSafeIdentifier(String id) {
return startsWith(id, "$");
}
public static String or2(String a, String b) {
return nempty(a) ? a : b;
}
public static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
public static List tokSplitAtComma(String s) {
List tok = javaTok(s);
List l = new ArrayList();
while (l(tok) > 1) {
int i = smartIndexOf(tok, ",");
l.add(trim(join(subList(tok, 0, i))));
tok = subList(tok, i + 1);
}
return l;
}
public static Collection simplifySafetyTags(Collection tags) {
List l = uniquifyList(tags);
if (l.contains("safe") && containsAnythingNeq(l, "safe"))
return listMinus(l, "safe");
return l;
}
public static String simplifySafetyTags(String tags) {
List l = tokSplitAtComma(tags);
Collection l2 = simplifySafetyTags(l);
return l(l2) != l(l) ? joinWithComma(l2) : tags;
}
public static void _handleError(Error e) {
call(javax(), "_handleError", 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 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 A optPar(Object[] params, String name) {
return optParam(params, name);
}
public static A optPar(String name, Object[] params) {
return optParam(params, name);
}
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 void dm_refreshTranspiler() {
call(dm_moduleOfType("#1017065/Transpiler"), "refresh");
}
public static String pcallOrExceptionText_strOrNull(Object f, Object... args) {
try {
return strOrNull(callF(f, args));
} catch (Throwable e) {
_handleException(e);
return exceptionToStringShort(e);
}
}
public static String strOrNull(Object o) {
return o == null ? null : str(o);
}
public static Object dm_javaEvalOrInterpret(String code) {
final Object module = dm_current_mandatory_generic();
code = trim(code);
if (canQuickEval(code))
return quickEval(code);
Pair> p = tok_parseFunctionCall(code);
if (p != null) {
makeAndCall_initChild.set(new F1() {
public AutoCloseable get(Class c) {
try {
shareMyCreatorWith(c);
InheritableThreadLocal tl = getOpt(c, "dm_currentModule_generic");
return tempSetTL(tl, weakRef(module));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shareMyCreatorWith(c);\r\n InheritableThreadLocal tl = getO...";
}
});
return callAndMake(p.a, toObjectArray(map("javaEvalOrInterpret", p.b)));
}
return dm_javaEval(code);
}
public static String evalWithTimeout_text(double timeoutSeconds, final Object f) {
return evalWithTimeout_text(toMS_int(timeoutSeconds), f);
}
public static String evalWithTimeout_text(final int timeoutMS, final Object f) {
return pcallOrExceptionText_strOrNull(new F0() {
public Object get() {
try {
return evalWithTimeoutOrException(timeoutMS, new F0() {
public Object get() {
try {
return strOrNull(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret strOrNull(callF(f));";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret evalWithTimeoutOrException(timeoutMS, func -> O { strOrNull(callF(f)) });";
}
});
}
public static Object dm_javaEval(String expression) {
return dm_evalJava_withModule(expression);
}
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 int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
public static int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
public static int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
public static int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
public static int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
public static int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
public static int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
public static int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
public static String dropLeadingSquareBracketStuff(String s) {
return trimSubstring(s, indexOf(s, ']') + 1);
}
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 boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
public static boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
public static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
public static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
public static Pair splitAtDoubleArrow_pair(String s) {
return splitAtDoubleArrow_pair(javaTokWithBrackets(s));
}
public static Pair splitAtDoubleArrow_pair(List tok) {
return listToPair(splitAtDoubleArrow(tok));
}
public static String curlyBraceOptIfMoreThanOneToken(String s) {
return !isCurlyBraced(s) && numberOfJavaTokens(s) > 1 ? curlyBrace(s) : s;
}
public static String remoteMechListMirrorStatus(String listName) {
return (String) mapGet(safeUnstructMap(loadTextFile(remoteMechListMirrorMetaFile(listName))), "Status");
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static Pair splitTrailingSquareBracketStuff(String s) {
if (!endsWith(s, "]"))
return pair(s, "");
int i = smartLastIndexOf(s, '[');
return pair(trimSubstring(s, 0, i), substring(s, i + 1, l(s) - 1));
}
public static Object quickImport(Object o) {
return quickExport(o, mc());
}
public static String dm_gazelle_rulesModule() {
return dm_require("#1021352/Rules");
}
public static String newLinesToSpaces_trim(String s) {
return s == null ? null : trim(s).replaceAll("\\s*\r?\n\\s*", " ");
}
public static JWindow infoBox(String text) {
return infoMessage(text);
}
public static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
public static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
public static A setTLAndReturn(ThreadLocal tl, A value) {
return setThreadLocalAndReturn(tl, value);
}
public static String rtrim_fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null) {
boolean first = true;
for (Object line : lines) {
if (first)
first = false;
else
buf.append('\n');
buf.append(str(line));
}
}
return buf.toString();
}
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, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static GazelleEvalContext dm_gazelle_stdEvalContext() {
return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs());
}
public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules) {
GazelleEvalContext ctx = gazelle_stdEvalContext(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 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 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 __14 = cloneMap(map);
for (String key : keys(__14)) {
String val = __14.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.massageMap = new gazelle_addHelperTablesToRules_Massager(helperTable, helperIndex);
}
}
public static List dm_gazelle_getChildren(GazelleTree tree, Object... __) {
return gazelle_getChildren(tree, paramsPlus(__, "makeEvalContext", "dm_gazelle_stdEvalContext"));
}
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).booleanValue())
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).booleanValue())
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 String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
public static String[] dropFirst(String[] a) {
return drop(1, a);
}
public static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
public static List dropFirst(List l) {
return dropFirst(1, l);
}
public static List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
public static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
public static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
public static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
public static String dropFirst(int n, String s) {
return substring(s, n);
}
public static String dropFirst(String s) {
return substring(s, 1);
}
public static boolean matchAny(Collection patterns, String s, Matches m) {
for (String pattern : patterns) if (match(pattern, s, m))
return true;
return false;
}
public static boolean matchAny(Collection patterns, String s) {
return matchAny(patterns, s, null);
}
public static boolean matchAny(String pat, Iterable l) {
return matchAny(pat, l, null);
}
public static boolean matchAny(String pat, Iterable l, Matches m) {
if (l != null)
for (String s : l) if (match(pat, s, m))
return true;
return false;
}
public static List dm_gazelle_fulfillmentsForRule(String ruleID) {
return (List) dm_requireAndCall("#1021745/StatementFulfillments", "entriesForRule", ruleID);
}
public static TreeMap asCIMap(Map map) {
return asCaseInsensitiveMap(map);
}
public static Map safeUnstructMap(String s) {
return safeUnstructureMap(s);
}
public static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
public static String getString(List l, int idx) {
return (String) get(l, idx);
}
public static String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static String getString(String key, Object o) {
return getString(o, (Object) key);
}
public static A printIndent(A o) {
print(indentx(str(o)));
return o;
}
public static void printIndent(String indent, Object o) {
print(indentx(indent, str(o)));
}
public static void printIndent(int indent, Object o) {
print(indentx(indent, str(o)));
}
public static String sfu(Object o) {
return structureForUser(o);
}
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 identifiersOnly(Collection l) {
List out = new ArrayList();
for (String a : unnull(l)) if (isIdentifier(a))
out.add(a);
return out;
}
public static List codeTokens(List tok) {
return codeTokensOnly(tok);
}
public static Map mergeMapsStrictlyIC(Map map1, Map map2) {
if (map2 == null)
return map1;
if (map1 == null)
return map2;
if (!canPutAllStrictlyIC(map1, map2))
return null;
return mergeMaps(map1, map2);
}
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;
startIndex = max(0, startIndex);
endIndex = min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == l(l))
return l;
return cloneList(l.subList(startIndex, endIndex));
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt;
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)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++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 boolean eqGetOneOf(List l, int i, A... options) {
return eqOneOf(get(l, i), options);
}
public static void tokAppend(List tok, int i, String s) {
tok.set(i, tok.get(i) + s);
}
public static void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
public static void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
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);
m.setAccessible(true);
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 void setAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) set(o, field, fields.get(field));
}
public static void setAll(Object 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);
}
}
public static void saveGZStructureToFile(String file, Object o) {
saveGZStructureToFile(getProgramFile(file), o);
}
public static void saveGZStructureToFile(File file, Object o) {
try {
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
File tempFile = tempFileFor(file);
if (tempFile.exists())
try {
String saveName = tempFile.getPath() + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
try {
GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
structureToPrintWriter(o, printWriter);
printWriter.close();
gos.close();
fileOutputStream.close();
} catch (Throwable e) {
fileOutputStream.close();
tempFile.delete();
throw rethrow(e);
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + file.getPath());
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void printFileSaved(File f) {
print("Saved " + fileInfo(f));
}
public static String _userHome;
public static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
}
return _userHome;
}
public static File userHome(String path) {
return new File(userDir(), path);
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
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 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 volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
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 String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
public static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
public static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
public static void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
public static List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static String gazelle_discord_matchedRuleStructForMsgID(long msgID) {
return gazelle_matchedRuleStructFromReasoningForLine(unstructGZFile(gazelle_discord_reasoningFileForMsgID(msgID)));
}
public static List uniquifyCI(Collection l) {
TreeSet set = ciSet();
List out = new ArrayList();
for (String a : unnull(l)) if (set.add(a))
out.add(a);
return out;
}
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 (Object o : l) x.add(callF(f, 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 String dm_posNegStringForEmoji(String unicode) {
return (String) dm_requireAndCall("#1021646/EmojisCRUD", "getPosNeg", unicode);
}
public static boolean warn_on = true;
public static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
public static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
public static void dm_gazelle_saveAppliedRule(Object... params) {
dm_requireAndCall("#1021413/AppliedRules", "uniqConcept", (Object) params);
}
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 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 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 AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) {
final DynModule m = dm_current_mandatory();
Map map = vm_busListenersByMessage_live();
AutoCloseable c;
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
c = tempAdd(listeners, new F2() {
public Object get(String _msg, Object arg) {
try {
AutoCloseable __312 = m.enter();
try {
return callF(f);
} finally {
_close(__312);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n ret callF(f);";
}
});
}
dm_ownResource(c);
return c;
}
public static String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
public static String dm_moduleID() {
return dm_moduleID(dm_current_mandatory());
}
public static Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static volatile boolean ping_pauseAll;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions;
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 TimerTask timerTask(final Object r, final java.util.Timer timer) {
return new TimerTask() {
public void run() {
if (!licensed())
timer.cancel();
else
pcallF(r);
}
};
}
public static long toMS(double seconds) {
return (long) (seconds * 1000);
}
public static boolean isAbsoluteURL(String s) {
return contains(s, "://");
}
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(Class c) {
return new ArrayList();
}
public static Map emptyMap() {
return new HashMap();
}
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 __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static int ubyteToInt(byte b) {
return b & 0x0FF;
}
public static File getProgramDir() {
return programDir();
}
public static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
public static SimpleDateFormat simpleDateFormat_local(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTimeZone());
return sdf;
}
public static A assertNull(A a) {
assertTrue(a == null);
return a;
}
public static A assertNull(String msg, A a) {
assertTrue(msg, a == null);
return a;
}
public static String dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static boolean useLocalMechListCopies_flag;
public static boolean useLocalMechListCopies() {
return useLocalMechListCopies_flag;
}
public static void useLocalMechListCopies(boolean flag) {
useLocalMechListCopies_flag = flag;
if (flag)
mechMode().readMode = "localCopies";
}
public static void setOptMC(String field, Object value) {
setOpt(mc(), field, value);
}
public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
public static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
public static String dm_makeModule(String moduleLibID) {
return (String) callCreator("makeModule", moduleLibID);
}
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 A dm_callOS(String functionName, Object... args) {
return (A) call(dm_os(), functionName, args);
}
public static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
public static A dm_requireAndCallModule(String moduleLibID, String method, Object... args) {
return dm_callModule(dm_requireModule(moduleLibID), method, args);
}
public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
public static Map>> mechHashMap_cache = synchroMap();
public static Map mechHashMap(String listName) {
Pair> p = mechHashMap_cache.get(listName);
String text = mechList_raw(listName);
if (p != null && eq(p.a, text))
return p.b;
String parsing = first(mechList_opt(listName + " | Parsing"));
p = pair(text, (Map) (parsing != null ? asHashMap((Map) callAndMake(parsing, text)) : parseDoubleArrowMap(new HashMap(), tlft(text))));
mechHashMap_cache.put(listName, p);
return p.b;
}
public static List javaTokC(String s) {
if (s == null)
return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
return tok;
}
public static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
startIndex = Math.max(0, startIndex);
endIndex = Math.min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
return l.subList(startIndex, endIndex);
}
public static List uniquifyList(Collection l) {
if (l == null)
return null;
if (l(l) < 2)
return asList(l);
HashSet set = new HashSet();
List out = new ArrayList();
for (A a : l) if (set.add(a))
out.add(a);
return out;
}
public static boolean containsAnythingNeq(Collection l, A a) {
for (A x : unnull(l)) if (neq(x, a))
return true;
return false;
}
public static List listMinus(Collection l, Object... stuff) {
if (l == null)
return null;
List l2 = similarEmptyList(l);
Set set = lithashset(stuff);
for (Object o : l) if (!set.contains(o))
l2.add(o);
return l2;
}
public static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
public static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
public static A optParam(ThreadLocal tl) {
return optPar(tl);
}
public static A optParam(Object[] opt, String name, A 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 A optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
public static Object dm_moduleOfType(String type) {
return first(dm_modulesOfType(type));
}
public static boolean canQuickEval(String t) {
return isQuoted(t) || isIdentifier(t) || isInteger(t) || isSnippetID(t);
}
public static Object quickEval(String t) {
if (isQuoted(t))
return unquote(t);
if (isInteger(t))
return parseInt(t);
if (isLongConstant(t))
return parseLong(t);
if (eq(t, "null"))
return null;
if (eq(t, "false"))
return false;
if (eq(t, "true"))
return true;
if (isIdentifier(t))
return getMC(t);
if (isSnippetID(t))
return t;
throw quickFail("Can't quick eval: " + t);
}
public static Pair> tok_parseFunctionCall(String s) {
return tok_parseFunctionCall(javaTok(s));
}
public static Pair> tok_parseFunctionCall(List tok) {
if (!(isIdentifier(get(tok, 1)) && eqGet(tok, 3, "(")))
return null;
Map bracketMap = getBracketMap(tok);
Integer iClosing = bracketMap.get(3);
if (!(eq(iClosing, l(tok) - 4) && eqGet(tok, l(tok) - 2, ";")) && neq(iClosing, l(tok) - 2))
return null;
int i = 5, argStart = 5;
List args = new ArrayList();
while (i < iClosing) {
Integer j = bracketMap.get(i);
if (j != null) {
i = j + 2;
continue;
}
if (eqGetOneOf(tok, i, ",")) {
if (i > argStart)
args.add(trimJoinSubList(tok, argStart, i));
argStart = i + 2;
}
i += 2;
}
if (i > argStart)
args.add(trimJoinSubList(tok, argStart, i));
return pair(tok.get(1), args);
}
public static void shareMyCreatorWith(Object o) {
setCreatorTo(o, creator());
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static Object callAndMake(String functionName, Object... args) {
return callAndMake_orDirect(functionName, args);
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static Object javaEvalOrInterpret(String code) {
if (!canJavaInterpret(code))
return javaEval(code);
if (canQuickEval(code))
return quickEval(code);
Pair> p = tok_parseFunctionCall(code);
if (p != null)
return callAndMake(p.a, toObjectArray(map("javaEvalOrInterpret", p.b)));
return javaEval(code);
}
public static int toMS_int(double seconds) {
return toInt_checked((long) (seconds * 1000));
}
public static Object evalWithTimeoutOrException(final Object f, int timeoutMS) {
return evalWithTimeoutOrException(timeoutMS, f);
}
public static Object evalWithTimeoutOrException(int timeoutMS, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutMS, f));
}
public static Object evalWithTimeoutOrException(double timeoutSeconds, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutSeconds, f));
}
public static A evalWithTimeoutOrException(int timeoutMS, F0 f) {
Either e = evalWithTimeout(timeoutMS, f);
if (e.isA())
return (A) e.a();
throw fail("Timeout after " + timeoutMS + " ms");
}
public static A evalWithTimeoutOrException(double timeoutSeconds, F0 f) {
return evalWithTimeoutOrException(toMS(timeoutSeconds), f);
}
public static Object dm_evalJava_withModule(String expression, Object... args) {
Object m = dm_current_mandatory_generic();
String code = evalJava_prep(expression) + "\r\n sO dm_current_mandatory_generic_value;\r\n \r\n sO dm_current_mandatory_generic() { ret dm_current_mandatory_generic_value; }\r\n sO dm_current_generic() { ret dm_current_mandatory_generic(); }\r\n ";
Object obj = veryQuickJava(code);
setOpt(obj, "programID", programID());
makeDependent(obj);
setOpt(obj, "creator_class", newWeakReference(dm_os()));
set(obj, "dm_current_mandatory_generic_value", m);
return evalJava_myProgramID_main_2(obj, args);
}
public static String trimSubstring(String s, int x) {
return trim(substring(s, x));
}
public static String trimSubstring(String s, int x, int y) {
return trim(substring(s, x, y));
}
public static int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
public static int indexOfIgnoreCase(List a, String b, int i) {
int n = l(a);
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
public static int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
public static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
public static Pair listToPair(List l) {
return l(l) != 2 ? null : pair(first(l), second(l));
}
public static List splitAtDoubleArrow(String s) {
return splitAtDoubleArrow(javaTok(s));
}
public static List splitAtDoubleArrow(List tok) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, ll("=", "", ">"), i);
if (i >= l(tok))
break;
if (j < 0)
j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j + 3;
}
return l;
}
public static boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
public static int numberOfJavaTokens(String s) {
return l(javaTokC(s));
}
public static String curlyBrace(String s) {
return "{" + s + "}";
}
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 File remoteMechListMirrorMetaFile(String listName) {
return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta");
}
public static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
public static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
public static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
public static Pair pair(A a, B b) {
return new Pair(a, b);
}
public static Pair pair(A a) {
return new Pair(a, a);
}
public static int smartLastIndexOf(String s, char c) {
if (s == null)
return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
public static Object quickExport(Object o, Object dest) {
return quickExport_impl(o, dest, new IdentityHashMap(), new HashMap());
}
public static Object quickExport(Object o, Object dest, int expectedNumberOfObjects) {
return quickExport_impl(o, dest, new IdentityHashMap(expectedNumberOfObjects), new HashMap());
}
public static Object quickExport_impl(Object o, Object dest, IdentityHashMap seen, HashMap classMap) {
try {
if (o == null || o instanceof String || o instanceof Number)
return o;
Object oo = seen.get(o);
if (oo != null)
return oo;
if (o instanceof Object[]) {
Object[] l = (Object[]) o;
Object[] destO = newObjectArrayOfSameType(l, l.length);
seen.put(o, destO);
for (int i = 0; i < l.length; i++) destO[i] = quickExport_impl(l[i], dest, seen, classMap);
return destO;
}
if (o instanceof List) {
List l = (List) (o);
List destO = new ArrayList(l.size());
seen.put(o, destO);
for (int i = 0; i < l.size(); i++) destO.add(quickExport_impl(l.get(i), dest, seen, classMap));
return destO;
}
if (o instanceof Map) {
Map m = (Map) (o);
Map destO = new HashMap();
seen.put(o, destO);
for (Object e : ((Map) o).entrySet()) destO.put(quickExport_impl(((Map.Entry) e).getKey(), dest, seen, classMap), quickExport_impl(((Map.Entry) e).getValue(), dest, seen, classMap));
return destO;
}
Class c = o.getClass();
String className = c.getName();
if (className.startsWith("main$")) {
Class destClass = classMap.get(c);
if (destClass == null) {
if (!classMap.containsKey(c)) {
if (!isAnonymousClassName(className))
destClass = getClass_vmName(dest, className);
classMap.put(c, destClass);
}
if (destClass == null)
return o;
}
if (c == destClass)
return o;
Object destO = nuObjectWithoutArguments(destClass);
seen.put(o, destO);
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
Object value = field.get(o);
setOpt(destO, field.getName(), quickExport_impl(value, dest, seen, classMap));
}
c = c.getSuperclass();
}
return destO;
}
return o;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean infoMessage_alwaysOnTop = true;
public static double infoMessage_defaultTime = 5.0;
public static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
public static JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
public static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
public static JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text))
return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless())
return null;
return (JWindow) swingAndWait(new F0() {
public Object get() {
try {
final JWindow window = showWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s...";
}
});
}
public static JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
public static A setThreadLocalAndReturn(ThreadLocal tl, A value) {
if (tl != null)
tl.set(value);
return value;
}
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 List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return collectThreeFieldsAsTriple("text", "comments", "globalID", (List) dm_call(dm_gazelle_rulesModule(), "concepts"));
}
public static GazelleEvalContext gazelle_stdEvalContext(List> rules) {
GazelleEvalContext ctx = new GazelleEvalContext();
ctx.engine = new RuleEngine2();
ctx.engine.addRules2(rules);
gazelle_changeInTypesForRulesWithMultipleInputs(ctx.engine);
MultiMap statementsByRule = ai_gazelle_indexStatementsByRule(dm_gazelle_statementsFromAppliedRules());
ctx.dataByRule = mapValues("ai_gazelle_analyzeStatementsForRule", multiMapToMap(statementsByRule));
return ctx;
}
public static A dm_callFunctionOnString(String code, String s) {
return (A) callF(dm_codeWithHintsToFunctionOnString(code), s);
}
public static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
public static Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static int indexOfIC(List a, String b) {
return indexOfIgnoreCase(a, b);
}
public static int indexOfIC(List a, String b, int i) {
return indexOfIgnoreCase(a, b, i);
}
public static int indexOfIC(String a, String b) {
return indexOfIgnoreCase(a, b);
}
public static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
public static List mL(String name) {
return mechList_opt(name);
}
public static List tok_splitAtCommaOrDoubleArrow(String s) {
return tok_splitAtCommaOrDoubleArrow(javaTok(s));
}
public static List tok_splitAtCommaOrDoubleArrow(List tok) {
List l = splitAtDoubleArrow(tok);
if (l(l) > 1)
return l;
return tok_splitAtComma(tok);
}
public static Map> indexTwoDArrayIC(List> table) {
if (table == null)
return null;
Map> map = ciMap();
for (int i = 0; i < l(table); i++) {
List row = table.get(i);
for (int j = 0; j < l(row); j++) map.put(row.get(j), pair(i, j));
}
return map;
}
public static List gazelle_getChildren(GazelleTree tree, Object... __) {
if (tree == null)
return null;
if (tree.children != null)
return tree.children;
tree.children = new ArrayList();
double qualityCutOff = optPar("qualityCutOff", __, -0.75);
List dialogHistory = optPar("dialogHistory", __);
if (tree.ctx == null)
tree.setContext(assertNotNull("evalContext", (GazelleEvalContext) callF(assertNotNull("makeEvalContext", optPar("makeEvalContext", __)))));
GazelleEvalContext ctx = tree.ctx;
RuleEngine2 engine = ctx.engine;
Map inputMap = gazelle_inputMapFromLineAndHistory(tree.line, concatLists(dialogHistory, tree.history()));
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
Object f = rule.function();
Collection out = (Collection) ((f instanceof String ? callF(engine.callFunctionOnString, (String) f, tree.line) : callF(f, tree.line)));
if (l(out) < 2)
continue;
GazelleTree child = new GazelleTree(joinWithVBar(out));
child.isSplitNode = true;
tree.add(child);
for (String line : out) child.add(new GazelleTree(line));
} catch (Throwable __e) {
_handleException(__e);
}
}
boolean firstConditionOnly = boolPar("firstConditionOnly", __);
Object[] params = litobjectarray("debug", optPar("debug", __), "tree", tree);
List l = sortByMethodDesc("qualitySum", firstConditionOnly ? ai_ruleEngine2_rulesForInput_5(engine, inputMap, params) : ai_ruleEngine2_rulesForInput_5_allConditions(engine, inputMap, params));
for (RuleEngine2_MatchedRule r : l) {
if (r.relativeQuality() < qualityCutOff)
continue;
String line = r.outText();
GazelleTree child = new GazelleTree(line);
child.mr = r;
ai_gazelle_analyzeStatementsForRule_Data data = ctx.dataByRule.get(r.rule.globalID);
child.prediction = data == null ? null : ai_gazelle_predictor1_onData(r, data);
tree.add(child);
}
gazelle_sortChildren(tree);
return tree.children;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null || l(a2) == 2 && a2[0] == null)
return a1;
if (a1 == null)
return a2;
return concatArrays(assertEvenLength(a1), assertEvenLength(a2));
}
public static List sortByCalculatedFieldDesc(Collection c, final Object f) {
return sortByCalculatedFieldDesc_inPlace(cloneList(c), f);
}
public static List sortByCalculatedFieldDesc(Object f, Collection c) {
return sortByCalculatedFieldDesc(c, f);
}
public static int ai_goodBadToInt(String s) {
if (eq(s, "good"))
return 1;
if (eq(s, "bad"))
return -1;
return 0;
}
public static String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static ArrayList toList(A[] a) {
return asList(a);
}
public static ArrayList toList(int[] a) {
return asList(a);
}
public static ArrayList toList(Set s) {
return asList(s);
}
public static ArrayList toList(Iterable s) {
return asList(s);
}
public static TreeMap asCaseInsensitiveMap(Map map) {
if (isCIMap(map))
return (TreeMap) map;
TreeMap m = ciMap();
m.putAll(map);
return m;
}
public static Map safeUnstructureMap(String s) {
return (Map) safeUnstructure(s);
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static String indentx(String s) {
return indentx(indent_default, s);
}
public static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
public static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
public static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
public static List codeTokensOnly(List tok) {
List l = new ArrayList();
for (int i = 1; i < tok.size(); i += 2) l.add(tok.get(i));
return l;
}
public static