Warning : session_start(): open(/var/lib/php/sessions/sess_05q7k41k86jg90auli31vevlb1, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.nio.file.Files;
import java.nio.file.Path;
public class main {
public static String data = "\r\n\r\n -- rule\r\n \r\n i like this stuff => ok\r\n [don't change anything]\r\n \r\n -- test input\r\n \r\n i like that stuff\r\n\r\n -- expected output\r\n \r\n";
public static List> rules = new ArrayList();
public static List fulfillments = new ArrayList();
public static LinkedHashSet temporaryFacts = new LinkedHashSet();
public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return rules;
}
public static void dm_gazelle_setRuleComments_verbose(String ruleID, String comments) {
set(objectWhere(rules, "c", ruleID), "b", comments);
}
public static Pair dm_textAndCommentForRule(String ruleID) {
T3 t = objectWhere(rules, "c", ruleID);
return t == null ? null : pair(t.a, t.b);
}
public static Pair dm_gazelle_addRuleWithComment(String text, String comment) {
T3 t = objectWhere(rules, "a", text, "b", comment);
if (t != null)
return pair(t.c, false);
String id = aGlobalID();
rules.add(t3(text, comment, id));
return pair(id, true);
}
public static List dm_gazelle_fulfillmentsForRule(String ruleID) {
return objectsWhere(fulfillments, "rule", ruleID);
}
public static GazelleEvalContext dm_gazelle_stdEvalContext() {
return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs());
}
public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules) {
return gazelle_stdEvalContext(rules);
}
public static String dm_gazelle_addTempFact(String text) {
temporaryFacts.add(text);
return aGlobalID();
}
public static void main(final String[] args) throws Exception {
pExperiment();
gazelle_fakery_performTest(data);
}
public static void set(Object o, String field, Object value) {
if (o == null)
return;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static A objectWhere(Collection c, Object... data) {
return findWhere(c, data);
}
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 String aGlobalID() {
return randomID(globalIDLength());
}
public static T3 t3(A a, B b, C c) {
return new T3(a, b, c);
}
public static List objectsWhere(Collection c, Object... data) {
return filterByFields(c, data);
}
public static GazelleEvalContext gazelle_stdEvalContext(List> rules) {
long startTime = sysNow();
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));
ctx.predictor = dm_gazelle_standardPredictor();
done2(startTime, "Making engine with " + n2(rules, "rule"));
return ctx;
}
public static void pExperiment() {
if (!isMain())
return;
autoRestart(5);
experimentIcon();
centerHigherConsole();
tt();
}
public static void gazelle_fakery_performTest(String data, Object... __) {
centerBigTTConsole();
TreeMap sections = minusSignSectionsCI(data);
gazelle_fakery_gatherRulesFromSections(sections);
dm_gazelle_wireStatementConditions();
pnlStruct(rules);
gazelle_fakery_processInput_multi_v2(sections, __);
}
public static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
throw e;
}
}
public static A findWhere(Collection c, Object... data) {
if (c != null)
for (A x : c) if (checkFields(x, data))
return x;
return null;
}
public static int randomID_defaultLength = 12;
public static String randomID(int length) {
return makeRandomID(length);
}
public static String randomID() {
return randomID(randomID_defaultLength);
}
public static int globalIDLength() {
return 16;
}
public static List filterByFields(Collection c, Object... data) {
if (c == null)
return null;
List l = new ArrayList();
for (A x : c) if (checkFields(x, data))
l.add(x);
return l;
}
public static long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
public static void gazelle_changeInTypesForRulesWithMultipleInputs(RuleEngine2 e) {
for (RuleEngine2.Rule r : e.rules) {
int i = 0;
while (i < l(r.insWithType) && eq(r.insWithType.get(i).type, "standard")) ++i;
if (i > 1) {
reverseInPlace(subList(r.insWithType, 0, i));
for (int j = 1; j < i; j++) r.insWithType.get(j).type = "history-" + (j + 1);
}
}
}
public static MultiMap ai_gazelle_indexStatementsByRule(List statements) {
MultiMap mm = new MultiMap();
for (Matches m : getMatchesX_all("Rule *: ...", statements)) mm.put(m.unq(0), m.rest());
return mm;
}
public static List dm_gazelle_statementsFromAppliedRules() {
return keysList(dm_gazelle_statementsFromAppliedRules_multiSet());
}
public static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
public static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
public static class ai_gazelle_analyzeStatementsForRule_Data {
public MultiSet statements;
public Set possibleVars, usedVars, unusedVars, varsUsedInGood, varsUsedInBad, varsUsedInGoodOnly, varsUsedInBadOnly;
public Set unclearVars;
public MultiMap goodMappings, badMappings, alwaysGoodMappings, alwaysBadMappings;
public List> completeGoodMappings, completeBadMappings;
public Map, PosNegScore> varScores;
}
public static ai_gazelle_analyzeStatementsForRule_Data ai_gazelle_analyzeStatementsForRule(Collection l) {
Set possibleVars = asCISet(matchAny_firstGroups("possible variable *", l));
Set usedVars = asCISet(matchX_any_firstGroups("... variable * was used", l));
Set unusedVars = asCISet(listMinusSet(possibleVars, usedVars));
Set varsUsedInGood = asCISet(matchX_any_firstGroups("in a good mapping, variable * was used", l));
Set varsUsedInBad = asCISet(matchX_any_firstGroups("in a bad mapping, variable * was used", l));
Set unclearVars = setIntersection(varsUsedInGood, varsUsedInBad);
MultiMap goodMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a good mapping, variable * was mapped to *", l)));
MultiMap badMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a bad mapping, variable * was mapped to *", l)));
MultiMap alwaysGoodMappings = multiMapDiff(goodMappings, badMappings);
MultiMap alwaysBadMappings = multiMapDiff(badMappings, goodMappings);
List> completeGoodMappings = map("safeUnstruct", matchX_any_firstGroups("a good mapping is *", l));
List> completeBadMappings = map("safeUnstruct", matchX_any_firstGroups("a bad mapping is *", l));
return nu(ai_gazelle_analyzeStatementsForRule_Data.class, "possibleVars", possibleVars, "usedVars", usedVars, "unusedVars", unusedVars, "varsUsedInGood", varsUsedInGood, "varsUsedInBad", varsUsedInBad, "unclearVars", unclearVars, "varsUsedInGoodOnly", setDiff(varsUsedInGood, varsUsedInBad), "varsUsedInBadOnly", setDiff(varsUsedInBad, varsUsedInGood), "goodMappings", goodMappings, "badMappings", badMappings, "alwaysGoodMappings", alwaysGoodMappings, "alwaysBadMappings", alwaysBadMappings, "completeGoodMappings", completeGoodMappings, "completeBadMappings", completeBadMappings);
}
public static Map > multiMapToMap(MultiMap m) {
return m == null ? null : m.data;
}
public static GazellePredictor dm_gazelle_standardPredictor(Object... __) {
return (ctx, r) -> {
ai_gazelle_analyzeStatementsForRule_Data data = ctx.dataByRule.get(r.rule.globalID);
return data == null ? null : ai_gazelle_predictor1_onData(r, data, __);
};
}
public static int done2_minPrint = 10;
public static long done2(long startTime, String desc) {
return done2(startTime, desc, done2_minPrint);
}
public static long done2(long startTime, String desc, int minPrint) {
long time = sysNow() - startTime;
saveTiming_noPrint(time);
if (time >= minPrint)
print(desc + " [" + time + " ms]");
return time;
}
public static long done2(String desc, long startTime) {
return done2(startTime, desc);
}
public static long done2(long startTime) {
return done2(startTime, "");
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
public static boolean isMain() {
return isMainProgram();
}
public static double autoRestart_interval = 10;
public static boolean autoRestart_on, autoRestart_debug, autoRestart_simulate;
public static java.util.Timer autoRestart_timer;
public static void autoRestart(double interval) {
autoRestart_interval = interval;
autoRestart();
}
public static void autoRestart() {
if (!isMain() || autoRestart_on)
return;
autoRestart_on = true;
autoRestart_schedule();
preloadProgramTitle();
}
public static void autoRestart_off() {
if (!autoRestart_on)
return;
stopTimer(autoRestart_timer);
autoRestart_timer = null;
}
public static void autoRestart_schedule() {
autoRestart_timer = doLater_daemon(toMS(autoRestart_interval), "autoRestart_check");
}
public static void autoRestart_check() {
try {
String newMD5;
try {
newMD5 = serverAutoRestartMD5(programID());
} catch (Throwable e) {
return;
}
if (!isMD5(newMD5)) {
if (autoRestart_debug)
print("autoRestart: no server transpilation");
return;
}
if (autoRestart_localMD5 == null)
autoRestart_localMD5 = md5(loadCachedTranspilation(programID()));
String localMD5 = autoRestart_localMD5();
if (neq(localMD5, newMD5)) {
if (autoRestart_simulate)
print("Would upgrade now. " + localMD5 + " -> " + newMD5);
else {
infoBox("Upgrading " + programTitle());
restartWithDelay(500);
sleep();
}
}
} finally {
if (autoRestart_debug)
print("autoRestart: Done");
autoRestart_schedule();
}
}
public static void experimentIcon() {
consoleAndDefaultFrameIcon("#1101173");
}
public static void centerHigherConsole() {
if (headless())
return;
setConsoleHeight(600);
centerConsole();
}
public static void tt() {
typeWriterConsole();
}
public static String tt(Object contents, Object... params) {
return tag("tt", contents, params);
}
public static void centerBigTTConsole() {
swing(new Runnable() {
public void run() {
try {
tt();
setConsoleWidth(1000);
setConsoleHeight(600);
centerConsole();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tt();\r\n setConsoleWidth(1000);\r\n setConsoleHeight(600);\r\n centerConsole();";
}
});
}
public static TreeMap minusSignSectionsCI(String text) {
return asCIMap(minusSignsSections(text));
}
public static void gazelle_fakery_gatherRulesFromSections(TreeMap sections) {
gazelle_fakery_clean();
{
final Map __35 = keysStartingWith(sections, "rule");
for (String ruleID : keys(__35)) {
String ruleText = __35.get(ruleID);
List comments = new ArrayList();
ruleText = gazelle_processSquareBracketAnnotations(ruleText, comments);
rules.add(t3(ruleText, lines(comments), ruleID));
}
}
}
public static void dm_gazelle_wireStatementConditions() {
for (T3 t : dm_gazelle_allRulesWithComment("in 2 = statement")) dm_gazelle_wireStatementConditions((t.c));
}
public static void dm_gazelle_wireStatementConditions(String ruleID) {
try {
Pair p = dm_textAndCommentForRule(ruleID);
List lines = tlft(p.a);
Matches m = new Matches();
List comments = lines(p.b);
boolean change = false;
for (int i = 0; i < l(comments); i++) {
if (match("in * = statement", comments.get(i), m)) {
int line = parseInt(m.unq(0));
String s = dropPrefixTrim("+", get(lines, line - 1));
if (empty(s) || startsWith(s, "=>"))
continue;
String ruleID2 = dm_gazelle_findRuleForStatementCondition(s);
if (ruleID2 == null) {
print("No statement rule found for: " + s + ", making one");
ruleID2 = pairA(dm_gazelle_addRuleWithComment(s + "\n=> statement", "in = statement\n" + "made for rule " + ruleID + "\n" + p.b));
}
comments.set(i, "in " + line + " = statement " + ruleID2);
change = true;
}
}
if (change)
dm_gazelle_setRuleComments_verbose(ruleID, lines(comments));
} catch (Throwable __e) {
_handleException(__e);
}
}
public static void pnlStruct(Object o) {
if (o instanceof Collection)
pnlStruct(((Collection) o));
else if (o instanceof Map)
pnlStruct(((Map) o));
else if (o != null)
pnlStruct(ll(o));
}
public static Collection pnlStruct(Collection l) {
pnlStruct((Iterable ) l);
return l;
}
public static Iterable pnlStruct(Iterable l) {
int i = 0;
if (l != null)
for (A a : l) print((++i) + ". " + struct_noStringSharing(a));
return l;
}
public static A[] pnlStruct(A[] l) {
pnlStruct(asList(l));
return l;
}
public static Map pnlStruct(Map map) {
pnl(map(map, new F2 () {
public Object get(A a, B b) {
try {
return sfu(a) + " = " + sfu(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sfu(a) + \" = \" + sfu(b)";
}
}));
return map;
}
public static void gazelle_fakery_processInput_multi_v2(TreeMap sections, Object... __) {
int maxMonologue = optPar("maxMonologue", __, 5);
ErrorCounter errorCounter = optPar("errorCounter", __, new ErrorCounter());
for (final String key : startingWithIC(keys(sections), "test input")) errorCounter.run(key, new Runnable() {
public void run() {
try {
List inputLines = tlft(sections.get(key));
String expectedOutput = sections.get(replaceIC(key, "test input", "expected output"));
String expectedTempFacts = sections.get(replaceIC(key, "test input", "expected temporary facts"));
print("\nPROCESSING: " + key + "\n");
temporaryFacts.clear();
List lines = new ArrayList();
int nMonologue = 0;
for (int i = 0; i < l(inputLines); i++) {
String input = inputLines.get(i);
String user = leadingSquareBracketStuff(input);
input = dropActuallyLeadingSquareBracketStuff(input);
gazelle_gatherFulfillments(ll(nu(GazelleLine.class, "text", input, "extras", litmap("user", user))), fulfillments, "debug", true);
List l = dm_gazelle_reasonAboutChatInput_v2(user, input, paramsPlus(__, "preContext", subList(inputLines, 0, i), "respondingToHuman", nMonologue == 0, "requiredComment", null, "debug", true));
print("Got " + n2(l, "child", "children") + " with line types: " + collect("lineType", l));
for (GazelleTree t : l) {
if (eq(t.lineType, "temporary fact"))
temporaryFacts.add(printWithIndent("TEMP FACT> ", t.line));
else {
lines.add(printWithIndent("OUT> ", t.line));
if (++nMonologue < maxMonologue)
inputLines.add(t.line);
}
}
}
assertEqualsVerbose(lines, tlft(expectedOutput));
assertEqualsVerbose(asList(temporaryFacts), tlft(expectedTempFacts));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "List inputLines = tlft(sections.get(key));\r\n String expectedOutput...";
}
});
errorCounter.print();
}
public static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
public static boolean checkFields(Object x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1]))
return false;
return true;
}
public static String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
public static String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
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 int l(Object[] a) {
return a == null ? 0 : a.length;
}
public static int l(boolean[] a) {
return a == null ? 0 : a.length;
}
public static int l(byte[] a) {
return a == null ? 0 : a.length;
}
public static int l(short[] a) {
return a == null ? 0 : a.length;
}
public static int l(long[] a) {
return a == null ? 0 : a.length;
}
public static int l(int[] a) {
return a == null ? 0 : a.length;
}
public static int l(float[] a) {
return a == null ? 0 : a.length;
}
public static int l(double[] a) {
return a == null ? 0 : a.length;
}
public static int l(char[] a) {
return a == null ? 0 : a.length;
}
public static int l(Collection c) {
return c == null ? 0 : c.size();
}
public static int l(Map m) {
return m == null ? 0 : m.size();
}
public static int l(CharSequence s) {
return s == null ? 0 : s.length();
}
public static long l(File f) {
return f == null ? 0 : f.length();
}
public static int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
public static int l(MultiSet ms) {
return ms == null ? 0 : ms.size();
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static List reverseInPlace(List l) {
return reverseList(l);
}
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;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
public static List getMatchesX_all(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m)) {
out.add(m);
m = new Matches();
}
return out;
}
public static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
public static List keysList(MultiSet ms) {
return ms == null ? null : keysList(ms.map);
}
public static class dm_gazelle_statementsFromAppliedRules_ByRule {
public String ruleID;
public MultiSet statements = new MultiSet();
}
public static MultiSet dm_gazelle_statementsFromAppliedRules_multiSet() {
List concepts = cloneList((List) dm_requireAndCall("#1021413/AppliedRules", "concepts"));
Map ruleMap = new HashMap();
for (Object c : concepts) {
try {
String judgement = getString("judgement", c);
String struct = getString("matchedRuleStruct", c);
RuleEngine2_MatchedRule mr = (RuleEngine2_MatchedRule) (unstructureUnlessContainsAnonymousClasses(struct));
if (mr == null)
continue;
String ruleID = mr.rule.globalID;
dm_gazelle_statementsFromAppliedRules_ByRule r = getOrCreate_f1(ruleMap, ruleID, new F1() {
public dm_gazelle_statementsFromAppliedRules_ByRule get(String ruleID) {
try {
return nu(dm_gazelle_statementsFromAppliedRules_ByRule.class, "ruleID", ruleID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "nu(dm_gazelle_statementsFromAppliedRules_ByRule, +ruleID)";
}
});
r.statements.addAll(ai_gazelle_statementsFromAppliedRule(mr, judgement));
} catch (Throwable __e) {
_handleException(__e);
}
}
MultiSet out = new MultiSet();
for (dm_gazelle_statementsFromAppliedRules_ByRule r : values(ruleMap)) for (String s : keys(r.statements)) out.add("Rule " + r.ruleID + ": " + s, r.statements.get(s));
return out;
}
public static Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
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(MultiSet ms) {
return ms.keySet();
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static Map> callF_cache = newDangerousWeakHashMap();
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 callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
public static TreeSet asCISet(Iterable c) {
return toCaseInsensitiveSet(c);
}
public static TreeSet asCISet(String... x) {
return toCaseInsensitiveSet(x);
}
public static List matchAny_firstGroups(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (match(pat, s, m))
out.add(m.unq(0));
return out;
}
public static List matchX_any_firstGroups(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m))
out.add(m.unq(0));
return out;
}
public static List listMinusSet(Iterable l, Collection stuff) {
if (empty(stuff))
return asList(l);
Set set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
public static List listMinusSet(Iterable l, Collection stuff, Collection stuff2) {
return listMinusSet(listMinusSet(l, stuff), stuff2);
}
public static Set setIntersection(Set a, Collection b) {
Set set = similarEmptySet(a);
Set bSet = asSet(b);
for (A x : a) if (bSet.contains(x))
set.add(x);
return set;
}
public static MultiMap uniquifyMultiMapValues(MultiMap mm) {
return mm == null ? null : new MultiMap(mapValues("uniquify", mm.data));
}
public static MultiMap pairsToMultiMap(List> l) {
MultiMap mm = new MultiMap();
for (Pair p : unnull(l)) mm.put(p.a, p.b);
return mm;
}
public static List> matchX_any_firstAndSecondGroups(String pat, Iterable l) {
Matches m = new Matches();
List> out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m))
out.add(pair(m.unq(0), m.unq(1)));
return out;
}
public static MultiMap multiMapDiff(MultiMap mm1, MultiMap mm2) {
return pairsToMultiMap(listMinusSet(multiMapToPairs(mm1), multiMapToPairs(mm2)));
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(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 Object safeUnstruct(String s) {
return unstructure(s, true);
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static Set setDiff(Set l, Collection stuff) {
return setMinusSet(l, stuff);
}
public static String ai_gazelle_predictor1_onData(RuleEngine2_MatchedRule r, ai_gazelle_analyzeStatementsForRule_Data data, Object... __) {
boolean debug = boolPar("debug", __);
String prediction = containsAny(keys(r.map), data.varsUsedInBadOnly) ? "bad" : "good";
if (debug)
print("predictor1: " + keys(r.map) + " => " + prediction);
return prediction;
}
public static ThreadLocal saveTiming_last = new ThreadLocal();
public static void saveTiming(long ms) {
print(ms + " ms");
saveTiming_noPrint(ms);
}
public static void saveTiming_noPrint(long ms) {
saveTiming_last.set(ms);
}
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 volatile Object print_preprocess;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
public static void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static boolean isMainProgram() {
return creator() == null;
}
public static void preloadProgramTitle() {
startThread(new Runnable() {
public void run() {
try {
programTitle();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "programTitle();";
}
});
}
public static void stopTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
public static java.util.Timer doLater_daemon(long delay, final Object r) {
final java.util.Timer timer = new java.util.Timer(true);
timer.schedule(timerTask(r, timer), delay);
return timer;
}
public static java.util.Timer doLater_daemon(double delaySeconds, final Object r) {
return doLater_daemon(toMS(delaySeconds), r);
}
public static long toMS(double seconds) {
return (long) (seconds * 1000);
}
public static int serverAutoRestartMD5_timeout = 10000;
public static String serverAutoRestartMD5(String programID) {
return loadPageSilentlyWithTimeout("http://botcompany.de/1010693/raw?id=" + psI(programID), serverAutoRestartMD5_timeout);
}
public static String serverAutoRestartMD5() {
return serverAutoRestartMD5(programID());
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
public static String md5(String text) {
try {
if (text == null)
return "-";
return bytesToHex(md5_impl(toUtf8(text)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String md5(byte[] data) {
if (data == null)
return "-";
return bytesToHex(md5_impl(data));
}
public static MessageDigest md5_md;
public static byte[] md5_impl(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String md5(File file) {
return md5OfFile(file);
}
public static String loadCachedTranspilation(String id) {
try {
return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
} catch (Throwable __e) {
return null;
}
}
public static String autoRestart_localMD5;
public static String autoRestart_localMD5() {
if (autoRestart_localMD5 == null)
autoRestart_localMD5 = md5(loadCachedTranspilation(programID()));
return autoRestart_localMD5;
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
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 String programTitle() {
return getProgramName();
}
public static void restartWithDelay(int delay) {
Object j = getJavaX();
call(j, "preKill");
call(j, "nohupJavax", smartJoin((String[]) get(j, "fullArgs")), call(j, "fullVMArguments"));
sleep(delay);
System.exit(0);
sleep();
}
public static volatile boolean sleep_noSleep;
public static void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void consoleAndDefaultFrameIcon(String icon) {
consoleIcon(icon);
setDefaultFrameIcon(icon);
}
public static boolean headless() {
return isHeadless();
}
public static void setConsoleHeight(int h) {
setFrameHeight(consoleFrame(), h);
}
public static void centerConsole() {
centerConsoleFrame();
}
public static void centerConsole(int w, int h) {
setConsoleSize(w, h);
centerConsoleFrame();
}
public static void typeWriterConsole() {
if (isHeadless())
return;
Font f = typeWriterFont();
consoleFont(f);
consoleInputFont(f);
}
public static String tag(String tag) {
return htag(tag);
}
public static String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
public static String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
public static String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static void setConsoleWidth(int w) {
setFrameWidth(consoleFrame(), w);
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static TreeMap asCIMap(Map map) {
return asCaseInsensitiveMap(map);
}
public static Map minusSignsSections(String text) {
List lines = lines(text);
List l = indicesOfStartingWithTrim(lines, "--");
LinkedHashMap out = new LinkedHashMap();
if (nempty(l))
mapPutIfNemptyValue(out, "", rtrim(lines(subList(lines, 0, first(l)))));
for (int i = 0; i < l(l); i++) {
int i1 = l.get(i);
int i2 = or(get(l, i + 1), l(lines));
String heading = trim(lines.get(i1));
int iHeading = 0;
while (iHeading < l(heading) && heading.charAt(iHeading) == '-') iHeading++;
heading = trim(substring(heading, iHeading));
out.put(heading, lines(subList(lines, i1 + 1, i2)));
}
return out;
}
public static void gazelle_fakery_clean() {
rules.clear();
fulfillments.clear();
}
public static Map keysStartingWith(String x, TreeMap map) {
if (empty(x))
return map;
String lastKey = lexicographicallyNextString(x);
return map.subMap(x, true, lastKey, false);
}
public static Map keysStartingWith(TreeMap map, String x) {
return keysStartingWith(x, map);
}
public static String gazelle_processSquareBracketAnnotations(String ruleText, List comments) {
List lines = tlft(ruleText);
while (isSquareBracketed(last(lines))) comments.add(deSquareBracket(popLast(lines)));
int out = -1;
for (int i = 0; i < l(lines); i++) {
String s = lines.get(i);
Pair p = splitTrailingSquareBracketStuff(s);
if (startsWith(s, "=>"))
out = i;
if (nempty(p.b))
comments.add((out >= 0 ? i == out && i == l(lines) - 1 ? "out" : "out " + (i - out + 1) : "in " + (i + 1)) + " = " + p.b);
lines.set(i, p.a);
}
return lines_rtrim(lines);
}
public static String lines(Iterable lines) {
return fromLines(lines);
}
public static String lines(Object[] lines) {
return fromLines(asList(lines));
}
public static List lines(String s) {
return toLines(s);
}
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 List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static boolean match(String pat, String s) {
return match3(pat, s);
}
public static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
public static boolean match(String pat, List toks, Matches matches) {
return match3(pat, toks, matches);
}
public static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
public static int parseInt(char c) {
return Integer.parseInt(str(c));
}
public static String dropPrefixTrim(String prefix, String s) {
return trim(dropPrefix(prefix, s));
}
public static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
public static Object get(Object o, String field) {
try {
if (o == null)
return null;
if (o instanceof Class)
return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
public static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static Object get(String field, Object o) {
return get(o, field);
}
public static boolean empty(Collection c) {
return c == null || c.isEmpty();
}
public static boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
public static boolean empty(Map map) {
return map == null || map.isEmpty();
}
public static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
public static boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
public static boolean empty(float[] a) {
return a == null || a.length == 0;
}
public static boolean empty(int[] a) {
return a == null || a.length == 0;
}
public static boolean empty(long[] a) {
return a == null || a.length == 0;
}
public static boolean empty(byte[] a) {
return a == null || a.length == 0;
}
public static boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
public static boolean empty(File f) {
return getFileSize(f) == 0;
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static String dm_gazelle_findRuleForStatementCondition(String s) {
for (T3 t : dm_gazelle_allRulesWithComment("in = statement")) {
Pair p = splitAtDoubleArrow_pair(t.a);
if (p == null) {
print("dm_gazelle_findRuleForStatementCondition skipping: " + t.a);
continue;
}
if (eqic(p.a, s))
return t.c;
}
return null;
}
public static A pairA(Pair p) {
return p == null ? null : p.a;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
public static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
public static ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
public static ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
public static ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
public static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
public static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
public static A pnl(A l) {
printNumberedLines(l);
return l;
}
public static void pnl(Map map) {
printNumberedLines(map);
}
public static void pnl(Object[] a) {
printNumberedLines(a);
}
public static void pnl(String s) {
printNumberedLines(lines(s));
}
public static String sfu(Object o) {
return structureForUser(o);
}
public static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
public static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
public static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
public static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
public static 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 List startingWithIC(Collection l, final String prefix) {
return filter(unnull(l), new F1() {
public Boolean get(String s) {
try {
return swic(s, prefix);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "swic(s, prefix)";
}
});
}
public static List startingWithIC(String prefix, Collection l) {
return startingWithIC(l, prefix);
}
public static List replaceIC(List l, String a, String b) {
List l2 = new ArrayList();
for (int i = 0; i < l(l); i++) {
String s = l.get(i);
l2.add(eqic(s, a) ? b : s);
}
return l2;
}
public static String replaceIC(String s, String a, String b) {
return s.replaceAll("(?i)" + patternQuote(a), quoteReplacement(b));
}
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 void gazelle_gatherFulfillments(List lines, List list_out, Object... __) {
Integer maxEntries = (Integer) (optPar("maxEntries", __));
Flag cancel = (Flag) (optPar("cancel", __));
boolean debug = boolPar("debug", __);
GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __));
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_rulesOnFacts());
if (debug)
print("Rules: " + l(ctx.engine.rules));
for (GazelleLine line : lines) {
try {
List children = gazelle_getChildren(new GazelleTree(ctx, line.text), __);
if (debug)
print("line " + line + ": children: " + children);
for (GazelleTree t : gazelle_dropUnsatisfiedEntries(children)) {
try {
if (flagIsUp(cancel) || maxEntries != null && l(list_out) >= maxEntries) {
print("Cancel");
return;
}
GazelleFulfillment f = nu(GazelleFulfillment.class, "line", t.parent.line, "varMap", struct(t.varMap()), "rule", t.ruleID(), "matchedRuleStruct", struct(t.mr), "context", "discord msg " + line.msgID);
if (debug)
printStruct(f);
list_out.add(f);
} catch (Throwable __e) {
_handleException(__e);
}
}
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
public static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
public static List dm_gazelle_reasonAboutChatInput_v2(String userName, String content, Object... __) {
boolean debug = boolPar("debug", __);
boolean debugRules = boolPar("debugRules", __) || debug;
List preContext = (List) (optPar("preContext", __));
GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __));
F0 contextMaker = (F0) (optPar("contextMaker", __));
if (ctx == null && contextMaker != null) {
ctx = contextMaker.get();
if (debugRules)
print("Called contextMaker, got " + n2(ctx.engine.rules, "rule"));
}
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord")));
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
if (debug)
print(" == PROCESSING INPUT: " + content);
ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement", "disable"));
if (acceptablePurposes != null) {
if (debugRules)
print("Purposes: " + acceptablePurposes);
ctx.engine.dropRulesWhere(r -> !acceptablePurposes.contains(unnull(r.purpose)));
if (debugRules)
print("Retaining " + n2(ctx.engine.rules, "rule"));
}
if (debugRules)
print("Have rules: " + collect("globalID", ctx.engine.rules));
gazelle_addHelpers(ctx, __);
Object[] params = litparams("firstConditionOnly", true, "dialogHistory", preContext, "debug", debug, "badComments", optPar("badComments", __), "acceptablePurposes", optPar("acceptablePurposes", __), "respondingToHuman", optPar("respondingToHuman", __), "skipSplitters", optPar("skipSplitters", __));
GazelleTree tree1 = (GazelleTree) (optPar("tree", __));
if (tree1 == null)
tree1 = new GazelleTree(ctx, content);
List l = dm_gazelle_getChildren(tree1, params);
Map inputMap = gazelle_inputMapFromLineAndHistory(content, listPlus(preContext, content));
if (debug)
print("reasonAbout inputMap=" + sfu(asTreeMap(inputMap)));
dm_gazelle_matchAdditionalInput3(l, inputMap, __);
if (nempty(userName) && !boolPar("skipUserName", __)) {
GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content);
if (debug)
print("Tree2: " + tree2);
l.addAll(dm_gazelle_getChildren(tree2, paramsPlus(__, "tree2", true)));
}
Long userID = (Long) (optPar("userID", __));
if (userID != null && userID != 0 && !boolPar("skipUserID", __)) {
GazelleTree tree3 = new GazelleTree(ctx, "user with id " + userID + " says: " + content);
l.addAll(dm_gazelle_getChildren(tree3, paramsPlus(__, "tree3", true)));
}
if (boolPar("skipBad", __, true))
l = filter(l, new F1() {
public Boolean get(GazelleTree t) {
try {
return neq(t.prediction, "bad");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "neq(t.prediction, \"bad\")";
}
});
gazelle_sortChildren(l);
dm_gazelle_matchStatements_v2(l, passParams(__, "debug", "dm_gazelle_matchStatementsDebug"));
for (GazelleTree t : l) t.flush();
int n = l(l);
l = gazelle_dropUnsatisfiedEntries(l);
if (debug)
print("Filtered out " + (n - l(l)) + " unsatisfied entries (keeping " + l(l) + ")");
gazelle_dropMatchedDefaultRules(l);
return l;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], a2) };
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static A printWithIndent(A o) {
return printIndent(o);
}
public static A printWithIndent(String indent, A o) {
return printIndent(indent, o);
}
public static void printWithIndent(int indent, Object o) {
printIndent(indent, o);
}
public static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
public static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((msg != null ? msg + ": " : "") + (y) + " != " + (x));
} else
print("OK: " + (x));
return 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 collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
public static Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
public static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
public static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static RuntimeException fail() {
throw new RuntimeException("fail");
}
public static RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
public static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
public static RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
public static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
public static Object call(Object o) {
return callF(o);
}
public static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
public static Object call(Object o, String method, Object... args) {
return call_cached(o, method, args);
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static List reverseList(List l) {
Collections.reverse(l);
return l;
}
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 boolean matchX(String pat, String s) {
return matchX(pat, s, null);
}
public static boolean matchX(String pat, String s, Matches m) {
if (endsWith(pat, "..."))
return matchStartX(pat, s, m);
if (startsWith(pat, "..."))
return matchEndX(pat, s, m);
return match(pat, s, m);
}
public static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null)
return new ArrayList();
synchronized (mutex) {
return new ArrayList (l);
}
}
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 Object dm_requireAndCall(String moduleLibID, String method, Object... args) {
return dm_requireAndCallModule(moduleLibID, method, args);
}
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 Object unstructureUnlessContainsAnonymousClasses(String s) {
return structContainsAnonymousClasses(s) ? null : unstruct(s);
}
public static B getOrCreate_f1(Map map, A key, F1 create) {
try {
B b = map.get(key);
if (b == null)
mapPut(map, key, b = callF(create, key));
return b;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static List ai_gazelle_statementsFromAppliedRule(RuleEngine2_MatchedRule r, String judgement) {
if (r == null || r.rule == null)
return new ArrayList();
if (nempty(judgement) && neq(judgement, "good"))
judgement = "bad";
String ruleID = r.rule.globalID;
String ruleIn = first(r.rule.in);
if (ruleIn == null)
return new ArrayList();
Map varMap = r.map;
String tokenize = r.tokenizationFunction;
List tok = (List) (callAndMake(tokenize, ruleIn));
List tokC = codeTokens(tok);
Set possibleVars = asCISet(tokC);
List statements = new ArrayList();
for (String a : keys(varMap)) {
String b = varMap.get(a);
statements.add(format("in a * mapping, variable " + quote(a) + " was used", judgement));
statements.add(format("in a * mapping, variable " + quote(a) + " was mapped to " + quote(b), judgement));
}
for (String var : possibleVars) statements.add("possible variable " + quote(var));
statements.add(format("a * mapping is *", judgement, sfu(varMap)));
return statements;
}
public static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
public static Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
public static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
public static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
public static HashMap> callMC_cache = new HashMap();
public static String callMC_key;
public static Method callMC_value;
public static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] { arg });
}
public static Object callMC(String method, Object... args) {
try {
Method me;
if (callMC_cache == null)
callMC_cache = new HashMap();
synchronized (callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null)
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized (callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null)
throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized (callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void callMC_makeCache() {
synchronized (callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
public static TreeSet toCaseInsensitiveSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet();
addAll(set, c);
return set;
}
public static TreeSet toCaseInsensitiveSet(String... x) {
TreeSet set = caseInsensitiveSet();
addAll(set, x);
return set;
}
public static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
public static Set similarEmptySet(Collection m) {
if (m instanceof TreeSet)
return new TreeSet(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet)
return new LinkedHashSet();
return new HashSet();
}
public static List uniquify(Collection l) {
return uniquifyList(l);
}
public static List> multiMapToPairs(MultiMap mm) {
List> out = new ArrayList();
for (A key : keys(mm)) for (B value : mm.get(key)) out.add(pair(key, value));
return out;
}
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 Object unstructure(String text) {
return unstructure(text, false);
}
public static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
public static int structure_internStringsLongerThan = 50;
public static int unstructure_unquoteBufSize = 100;
public static int unstructure_tokrefs;
public abstract static class unstructure_Receiver {
public abstract void set(Object o);
}
public static Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
public static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
print("Warning: unsatisfied token reference " + ref);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("sync")) {
consume();
if (t().equals("tm")) {
consume();
{
parseMap(synchronizedTreeMap(), out);
return;
}
}
if (t().equals("[")) {
parseList(synchroList(), out);
return;
}
{
parseMap(synchronizedMap(), out);
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
this.parseList(new ArrayList(), out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray")) {
parseArray(out);
return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume("c");
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava());
return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + t);
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = "main$" + t;
}
if (c == null) {
if (allDynamic)
c = null;
else
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c != null)
classesMap.put(className, c);
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
final LinkedHashMap fields = new LinkedHashMap();
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ...";
}
});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
setOptAllDyn(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
else
for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ...";
}
});
}
public void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix("main$", name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_x(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
Boolean b = DynamicObject_loading.get();
DynamicObject_loading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
DynamicObject_loading.set(b);
}
}
public static boolean unstructure_debug;
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 Set setMinusSet(Set l, Collection stuff) {
if (empty(stuff))
return l;
Set set = asSet(stuff);
Set l2 = similarEmptySet(l);
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
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 boolean containsAny(Collection a, Collection b) {
if (empty(a) || empty(b))
return false;
Set set = asSet(b);
for (A x : a) if (contains(set, x))
return true;
return false;
}
public static boolean containsAny(Map a, Collection b) {
if (empty(a))
return false;
if (b != null)
for (A x : b) if (a.containsKey(x))
return true;
return false;
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
public static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
public static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable _buf, String s, int max) {
try {
synchronized (_buf) {
_buf.append(s);
if (!(_buf instanceof 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 String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
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 WeakReference creator_class;
public static Object creator() {
return creator_class == null ? null : creator_class.get();
}
public static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
public static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
public static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
public static 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 String loadPageSilentlyWithTimeout(int timeout, String url) {
return loadPageSilentlyWithTimeout(url, timeout);
}
public static String loadPageSilentlyWithTimeout(String url, int timeout) {
try {
url = loadPage_preprocess(url);
URL _url = new URL(url);
return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
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 isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
} else
return false;
}
return true;
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
public static byte[] toUtf8(String s) {
try {
return s.getBytes("UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean md5OfFile_verbose;
public static String md5OfFile(String path) {
return md5OfFile(newFile(path));
}
public static String md5OfFile(File f) {
try {
if (!f.exists())
return "-";
if (md5OfFile_verbose)
print("Getting MD5 of " + f);
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(f);
try {
byte[] buf = new byte[65536];
int l;
while (true) {
l = in.read(buf);
if (l <= 0)
break;
md5.update(buf, 0, l);
}
return bytesToHex(md5.digest());
} finally {
_close(in);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFilePossiblyGZipped(String fileName) {
return loadTextFilePossiblyGZipped(fileName, null);
}
public static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) {
File gz = new File(fileName + ".gz");
return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents);
}
public static String loadTextFilePossiblyGZipped(File fileName) {
return loadTextFilePossiblyGZipped(fileName, null);
}
public static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) {
return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents);
}
public static File getCachedTranspilationFile(String id) {
return newFile(getCodeProgramDir(id), "Transpilation");
}
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 String getProgramName_cache;
public static String getProgramName() {
Lock __1496 = downloadLock();
lock(__1496);
try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally {
unlock(__1496);
}
}
public static void _onLoad_getProgramName() {
startThread(new Runnable() {
public void run() {
try {
getProgramName();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getProgramName();";
}
});
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String smartJoin(String[] args) {
if (args.length == 1)
return args[0];
String[] a = new String[args.length];
for (int i = 0; i < a.length; i++) a[i] = !isJavaIdentifier(args[i]) && !isQuoted(args[i]) ? quote(args[i]) : args[i];
return join(" ", a);
}
public static String smartJoin(List args) {
return smartJoin(toStringArray(args));
}
public static Object sleepQuietly_monitor = new Object();
public static void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void consoleIcon(String imageID) {
frameIcon(consoleFrame(), or2(imageID, javaxDefaultIcon()));
}
public static void setDefaultFrameIcon(String icon) {
setOptMC("makeFrame_defaultIcon", icon);
}
public static Boolean isHeadless_cache;
public static boolean isHeadless() {
if (isHeadless_cache != null)
return isHeadless_cache;
if (isAndroid())
return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless())
return isHeadless_cache = true;
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) {
return isHeadless_cache = true;
}
}
public static JFrame setFrameHeight(JFrame frame, int h) {
frame.setSize(frame.getWidth(), h);
return frame;
}
public static JFrame setFrameHeight(int h, JFrame frame) {
return setFrameHeight(frame, h);
}
public static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
public static void centerConsoleFrame() {
centerFrame(consoleFrame());
}
public static void setConsoleSize(int w, int h) {
setFrameSize(consoleFrame(), w, h);
}
public static Font typeWriterFont() {
return typeWriterFont(iround(14 * getSwingFontScale()));
}
public static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
public static void consoleFont(Font font) {
callOpt(getConsoleTextArea_gen(), "setFont", font);
}
public static void consoleInputFont(final Font f) {
{
swing(new Runnable() {
public void run() {
try {
JTextField input = consoleInputField();
if (input != null) {
input.setFont(f);
revalidateFrame(input);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextField input = consoleInputField();\r\n if (input != null) {\r\n inpu...";
}
});
}
}
public static String htag(String tag) {
return htag(tag, "");
}
public static String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static A setFrameWidth(int w, A c) {
return setFrameWidth(c, w);
}
public static A setFrameWidth(A c, int w) {
JFrame f = getFrame(c);
if (f != null)
f.setSize(w, f.getHeight());
return c;
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static TreeMap asCaseInsensitiveMap(Map map) {
if (isCIMap(map))
return (TreeMap) map;
TreeMap m = ciMap();
m.putAll(map);
return m;
}
public static List indicesOfStartingWithTrim(List l, String prefix) {
List x = new ArrayList();
for (int i = 0; i < l(l); i++) if (startsWith(trim(l.get(i)), prefix))
x.add(i);
return x;
}
public static boolean nempty(Collection c) {
return !empty(c);
}
public static boolean nempty(CharSequence s) {
return !empty(s);
}
public static boolean nempty(Object[] o) {
return !empty(o);
}
public static boolean nempty(byte[] o) {
return !empty(o);
}
public static boolean nempty(int[] o) {
return !empty(o);
}
public static boolean nempty(Map m) {
return !empty(m);
}
public static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
public static boolean nempty(Object o) {
return !empty(o);
}
public static void mapPutIfNemptyValue(Map map, A key, String value) {
if (map != null && key != null && nempty(value))
map.put(key, value);
}
public static String rtrim(String s) {
if (s == null)
return null;
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
return i < s.length() ? s.substring(0, i) : s;
}
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 A or(A a, A b) {
return a != null ? a : b;
}
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 String lexicographicallyNextString(String input) {
final int lastCharPosition = input.length() - 1;
String inputWithoutLastChar = input.substring(0, lastCharPosition);
char lastChar = input.charAt(lastCharPosition);
char incrementedLastChar = (char) (lastChar + 1);
if (incrementedLastChar == ((char) 0))
return input + incrementedLastChar;
return inputWithoutLastChar + incrementedLastChar;
}
public static boolean isSquareBracketed(String s) {
return s != null && s.startsWith("[") && s.endsWith("]");
}
public static A last(List l) {
return empty(l) ? null : l.get(l.size() - 1);
}
public static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s) - 1);
}
public static int last(int[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
public static A last(A[] a) {
return l(a) != 0 ? a[l(a) - 1] : null;
}
public static A last(Iterator it) {
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
public static String deSquareBracket(String s) {
if (startsWith(s, "[") && endsWith(s, "]"))
return substring(s, 1, l(s) - 1);
return s;
}
public static A popLast(List l) {
return liftLast(l);
}
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 String lines_rtrim(Collection lines) {
return rtrim_fromLines(lines);
}
public static String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
public static String fromLines(String... lines) {
return fromLines(asList(lines));
}
public static IterableIterator toLines(File f) {
return linesFromFile(f);
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
public static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
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 boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
public static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
public static List 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 match3(String pat, String s) {
return match3(pat, s, null);
}
public static boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null)
return false;
return match3(pat, parse3_cachedInput(s), matches);
}
public static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
return match3(tokpat, toks, matches);
}
public static boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
if (m == null)
return false;
if (matches != null)
matches.m = m;
return true;
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static String getType(Object o) {
return getClassName(o);
}
public static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
public static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static 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 Pair splitAtDoubleArrow_pair(String s) {
return splitAtDoubleArrow_pair(javaTokWithBrackets(s));
}
public static Pair splitAtDoubleArrow_pair(List tok) {
return listToPair(splitAtDoubleArrow(tok));
}
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 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 boolean structure_showTiming, structure_checkTokenCount;
public static String structure(Object o) {
return structure(o, new structure_Data());
}
public static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
public static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
public static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
public static boolean structure_allowShortening = false;
public static class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing;
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap> fieldsByClass = new HashMap();
public HashMap persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
}
public static void structure_1(final Object o, final structure_Data d) {
try {
if (o == null) {
d.append("null");
return;
}
Class c = o.getClass();
boolean concept = false;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) {
int i = ((Integer) o).intValue();
out.print(i);
d.n += i < 0 ? 2 : 1;
return;
}
if (o instanceof Long) {
long l = ((Long) o).longValue();
out.print(l);
out.print("L");
d.n += l < 0 ? 2 : 1;
return;
}
if (o instanceof Short) {
short s = ((Short) o).shortValue();
d.append("sh ", 2);
out.print(s);
d.n += s < 0 ? 2 : 1;
return;
}
if (o instanceof Float) {
d.append("fl ", 2);
quoteToPrintWriter(str(o), out);
return;
}
if (o instanceof Double) {
d.append("d(", 3);
quoteToPrintWriter(str(o), out);
d.append(")");
return;
}
if (o instanceof BigInteger) {
out.print("bigint(");
out.print(o);
out.print(")");
d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
return;
}
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f");
return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o));
return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath()));
return;
}
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.append("t").app(ref);
return;
}
if (!(o instanceof String))
d.seen.put(o, d.n);
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out);
d.n++;
return;
}
if (o instanceof Set) {
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection && !startsWith(name, "main$")) {
if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList"))
d.append("sync");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta...";
}
});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap)
d.append("lhm");
else if (o instanceof HashMap)
d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap"))
d.append("sync");
else if (name.equals("java.util.Collections$SynchronizedSortedMap")) {
d.append("sync tm", 2);
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
public boolean v;
public Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o)));
return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o)));
return;
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator