Warning : session_start(): open(/var/lib/php/sessions/sess_ug16m0gqd6nrecas9rdt278seg, 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 org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.Timer;
public class main {
static String theFacts = "\n\n Fibonacci number n is Fibonacci number n-1 plus Fibonacci number n-2 if n > 2.\n There is no Fibonacci number with a negative index.\n There is no Fibonacci number 0.\n Fibonacci number 1 is 1.\n Fibonacci number 2 is 1.\n\n // Some technical stuff\n gmtzfidalveipfyx feyhbrhdeovmbvaw amcmxkgwhivbouqs\n pqnfhkzxoqkaoyqk sppxbuuqeetjmzuo\n";
static String theRiddle = "\n What is Fibonacci number 0?\n What is Fibonacci number 1?\n What is Fibonacci number 2?\n What is Fibonacci number 3?\n What is Fibonacci number 4?\n";
static String concepts = "\n [\"feyhbrhdeovmbvaw\", \"There is no X.\"],\n [\"mtsrzasaoxrmicch\", \"X is Y if Z.\"],\n [\"fgvvrzypbkqomktd\", \"X is Y.\"],\n [\"sppxbuuqeetjmzuo\", \"X plus Y\"],\n [\"devwldetfsfylnod\", \"X with a negative index\"],\n [\"rgsamtbrhpcqowko\", \"Fibonacci number X\"],\n [\"jxcubqjtqykhfvyo\", \"X - Y\", \"as in minus\"],\n [\"wdbphzfoxwlrhdyl\", \"X > Y\"],\n [\"urfkhwfasdaqqqse\", \"What is X?\"],\n [\"pqnfhkzxoqkaoyqk\", \"Operation X should be expanded.\"],\n [\"amcmxkgwhivbouqs\", \"Something that doesn't exist\"],\n [\"yissyloatogavyuu\", \"Fibonacci number\"],\n [\"gmtzfidalveipfyx\", \"Marker X implies label Y.\"]\n";
static class WebNode {
Web web;
List labels = new ArrayList();
WebNode() {}
WebNode(Web web) {
this.web = web;}
void addLabel(String label) {
addLabel(clParse(label));
}
void addLabel(Lisp label) {
if (setAdd(labels, label) && web != null)
web.index(label, this);
}
boolean hasLabel(Lisp label) { return labels.contains(label); }
public String toString() { return str(labels); }
int count() { return 1 + l(labels); }
}
static class Web {
List nodes = new ArrayList();
Map, WebNode> relations = new HashMap();
MultiMap index = new MultiMap();
Map> pots = new HashMap();
transient Lock lock = reentrantLock(true);
boolean potNotEmpty(String pot) { return nempty(getPot(pot)); }
List clearPot(String pot) {
List l = getPot(pot);
List l2 = cloneList(l);
l.clear();
return l2;
}
List getPot(String pot) {
List l = pots.get(pot);
if (l == null)
pots.put(pot, l = cloneList(nodes));
return l;
}
void relation(Lisp l) {
if (l(l) == 1) {
findNode(l.get(0)).addLabel(lisp("wvuyakuvuelmxpwp", l.head));
} else if (l(l) == 2) {
String a = lisp2label(l.get(0)), b = lisp2label(l.get(1));
if (l.is("fgvvrzypbkqomktd")) { // X is Y.
findNode(a).addLabel(b);
findNode(b).addLabel(a);
}
getRelation(a, b).addLabel(l.head);
}
}
void relations(List l) {
for (Lisp li : l) relation(li);
}
WebNode getRelation(String a, String b) {
Pair p = pair(findNode(a), findNode(b));
WebNode r = relations.get(p);
if (r == null) relations.put(p, r = new WebNode());
return r;
}
WebNode newNode() {
WebNode node = new WebNode(this);
nodes.add(node);
for (List l : values(pots)) l.add(node);
return node;
}
WebNode node(String s) { return findNode(s); }
WebNode node(Lisp l) { return findNode(l); }
WebNode findNode(String s) {
return findNode(clParse(s));
}
WebNode findNode(Lisp l) {
WebNode n = findNodeOpt(l);
return n != null ? n : newNode(l);
}
WebNode findNodeOpt(Lisp l) {
return first(index.get(l));
/*for (WebNode n : nodes)
if (n.labels.contains(l))
ret n;
null;*/
}
WebNode newNode(String... labels) {
WebNode n = newNode();
for (String label : labels) n.addLabel(label);
return n;
}
WebNode newNode(Lisp... labels) {
WebNode n = newNode();
for (Lisp label : labels) n.addLabel(label);
return n;
}
public String toString() { return webToString(this); }
int count() {
int count = 0;
for (WebNode n : nodes) count += n.count();
for (WebNode n : values(relations)) count += n.count();
return count;
}
void index(Lisp label, WebNode n) {
index.put(label, n);
}
}
static int saveInterval = 60000;
static Web web = new Web();
static List facts;
static long lastSave, sizeSaved;
public static void main(final String[] args) throws Exception { typeWriterConsole();
setConsoleTitle(programTitle());
load("web"); lastSave = sysNow();
setFrameHeight(consoleFrame(), 400);
centerConsole();
//magellan();
//graphite();
//mistAqua();
//moderateTheme();
sahara();
{ swingAndWait(new Runnable() { public void run() { try {
setConsoleInput("What is Fibonacci number 500?");
consoleAddAskButton();
focusConsole();
final JLabel lblBrainSize = jRightAlignedLabel();
addToConsole(lblBrainSize);
awtEvery(lblBrainSize, 1000, new Runnable() { public void run() { try {
lblBrainSize.setText("Brain Size: " + toM(fileSize(programFile("web.structure")), 1) + "MB");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lblBrainSize.setText(\"Brain Size: \" + toM(fileSize(programFile(\"web.structure\"))..."; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setConsoleInput(\"What is Fibonacci number 500?\");\n consoleAddAskButton();\n ..."; }}); }
aiEnhancements();
aiConcepts_noAutoClear();
useConceptsDump(concepts);
englishToConceptLanguage_useBrackets = true;
facts = clParse(linesToCL(theFacts));
print(theFacts);
useFacts(theFacts);
//printNumberedLines(facts);
print();
for (String rid : toLinesFullTrim(theRiddle)) {
print("? " + rid);
print(" " + answer(rid));
}
makeBot();
notDone();
}
static String answer(String rid) {
if (eq(rid, "web")) { print(web); return "OK"; }
Lisp riddle = clParse(englishToConceptLanguage(rid));
//print("# " + riddle);
if (!riddle.is("urfkhwfasdaqqqse", "mrhggsmuykeceghd")) return "huh?"; // What is X? // What is the decimal representation of X?
Lisp mainConcept = riddle.get(0);
// Make web
web.node(mainConcept);
web.relations(facts);
int webSize = web.count();
int cursor = 0;
while (licensed()) {
//print("Web size: " + webSize);
if (webSize != sizeSaved && sysNow() >= lastSave+saveInterval) {
printWithoutNL("S");
save("web");
sizeSaved = webSize;
lastSave = sysNow();
} else
printWithoutNL(".");
if ((++cursor % 60) == 0) print();
CriticalAction action = beginCriticalAction("Web Update");
try {
web_expandMarkers(web);
web_expandOperations(web);
for (Lisp rule : trueStatementsByHead("mtsrzasaoxrmicch")) {
Lisp x = rule.get(0);
for (WebNode node : cloneList(web.nodes)) {
for (Lisp lbl : cloneList(node.labels)) {
//print("Matching " + x + " and " + lbl);
Map matches = lispMatch(x, lbl, ll("n"));
if (matches != null) {
//print("Rule match: " + struct(matches));
Lisp bla = lispReplaceVars(rule.get(2), matches);
if (checkACondition(bla)) {
bla = lispReplaceVars(rule.get(1), matches);
bla = lispCalculateDeep(bla);
bla = web_insertNumbers(web, bla);
//print("bla: " + bla);
bla = lispCalculateDeep(bla);
if (lispIsInt(bla))
node.addLabel(bla); // Found!
else {
//print("Condition OK! Evaluating: " + bla);
web.node(bla);
}
}
}
}
}
//print("Node: " + node + ", condition: " + condition);
}
} finally {
action.done();
}
int n = web.count();
if (n == webSize) break;
webSize = n;
}
print();
// print question again
if (cursor / 60 >= 10)
print("? " + rid);
// Answer question
List l = listWithout(web.findNode(mainConcept).labels, mainConcept);
//print("Labels: " + l);
String s = chooseALabelToReturn(l);
s = or2(conceptLanguageToEnglish(unquote(s)), "I don't know");
return s;
}
static String chooseALabelToReturn(List ll) {
List l = map("clUnparse", ll);
//print(" Labels: " + l);
String s = findInteger(l);
if (s == null) s = firstGlobalID(l);
//if (s == null) s = random(l);
if (s == null) return s = first(l);
return s;
}
static boolean checkACondition(Lisp l) { try {
return lispCalculateDeep(l).is("true");
} catch (Throwable __e) { return false; } }
static void cleanMeUp() {
while (criticalActionsInFlight()) sleep(5);
if (sizeSaved != web.count())
save("web");
}
static List ll(A... a) {
return litlist(a);
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static List beginCriticalAction_inFlight = synchroList();
static class CriticalAction {
String description;
CriticalAction() {}
CriticalAction(String description) {
this.description = description;}
void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) { printStackTrace(__e); }
}
sleepInCleanUp(10);
}
}
static void useConceptsDump(String concepts) {
List usedConcepts = conceptsFromDump(concepts);
//dumpConcepts2(findAIConcepts(conceptsUsed));
//printAIConcepts(usedConcepts);
setOpt(mc(), "englishToConceptLanguage_concepts_global", usedConcepts);
aiConceptsMap_cached_autoClearInterval = 0;
aiConceptsMap_cached_cache.set(indexByField(usedConcepts, "globalID"));
}
static String webToString(Web web) {
List out = new ArrayList();
Map index = new HashMap();
for (int i = 0; i < l(web.nodes); i++) {
out.add("Node " + (i+1) + ": " + web.nodes.get(i));
index.put(web.nodes.get(i), i+1);
}
for (Pair p : keys(web.relations))
out.add(index.get(p.a) + " -> " + index.get(p.b) + " = " + web.relations.get(p));
return fromLines(out);
}
static void setConsoleInput(String text) {
consoleSetInput(text);
}
static void web_expandMarkers(Web web) {
for (Lisp rule : trueStatementsByHead("razrxqstbnzeahwg"))
web_labelToLabel(web, lisp("wvuyakuvuelmxpwp", rule.get(0)),
lisp("wvuyakuvuelmxpwp", rule.get(1)));
for (Lisp rule : trueStatementsByHead("gmtzfidalveipfyx"))
web_labelToLabel(web, lisp("wvuyakuvuelmxpwp", rule.get(0)), rule.get(1));
}
static void setConsoleTitle(String title) {
callOpt(consoleFrame_gen(), "setTitle", title);
}
static void web_expandOperations(Web web) {
for (Lisp rule : trueStatementsByHead("pqnfhkzxoqkaoyqk")) {
String toExpand = rule.s(0);
//print("Expanding " + toExpand);
for (WebNode node : cloneList(web.nodes))
for (Lisp lbl : node.labels)
if (lbl.is(toExpand)) {
//print(" Expanding " + lbl);
for (Lisp child : lbl)
web.node(child);
}
}
}
static boolean lispIsInt(Lisp x) {
return x != null && x.isLeaf() && isInteger(x.head);
}
static File programFile(String name) {
return prepareProgramFile(name);
}
static File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static List listWithout(List a, Object... b) {
return minus(a, b);
}
static boolean criticalActionsInFlight() {
return nempty(beginCriticalAction_inFlight);
}
static ReentrantLock reentrantLock(boolean fair) {
return new ReentrantLock(fair);
}
static String conceptLanguageToEnglish(String s) {
if (s == null) return null;
try {
return conceptLanguageToEnglish_xyz(s);
} catch (Throwable __e) { printStackTrace(__e); }
return s;
}
static Lisp clParse(String s) {
List tok = tok_groupRoundBrackets(s);
if (l(tok) == 1) return null;
Lisp l = lisp(unquote(tok.get(1)));
for (int i = 3; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("(") && t.endsWith(")"))
l.add(assertNotNull(clParse(dropFirstAndLast(t))));
else
l.add(lisp(aiUsing(unquote(t))));
}
return l;
}
static List clParse(List l) {
return map("clParse", l);
}
// make a lisp form
static Lisp lisp(String head, Object... args) {
Lisp l = new Lisp(head);
for (Object o : args)
l.add(o);
return l;
}
static Lisp lisp(String head, List args) {
return new Lisp(head, args);
}
static List cloneList(Collection l) {
if (l == null) return new ArrayList();
//O mutex = getOpt(l, "mutex");
/*if (mutex != null)
synchronized(mutex) {
ret new ArrayList (l);
}
else
ret new ArrayList (l);*/
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(l) {
return new ArrayList (l);
}
}
static void aiEnhancements() {
conceptLanguageToolTips();
}
static boolean eq(Object a, Object b) {
if (a == null) return b == null;
if (a.equals(b)) return true;
if (a instanceof BigInteger) {
if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
}
return false;
}
static Lisp lispReplaceVars(Lisp l, Map map) {
if (l.isLeaf()) {
Lisp x = map.get(l.head);
if (x != null) return x;
}
Lisp x = lisp(l.head);
for (Lisp a : l.args)
x.add(lispReplaceVars(a, map));
return x;
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static void notDone() {
sleep();
}
static String str(Object o) {
return String.valueOf(o);
}
static String str(char[] c) {
return new String(c);
}
static Lisp web_insertNumbers(final Web web, Lisp x) {
return lispMap_after(x, new Object() { Object get(Lisp l) { try {
WebNode node = web.findNodeOpt(l);
if (node != null)
return firstLispInt(node.labels);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "WebNode node = web.findNodeOpt(l);\n if (node != null)\n ret firstLispInt(..."; }});
}
static long toM(long l) {
return (l+1024*1024-1)/(1024*1024);
}
static String toM(long l, int digits) {
return formatDouble(toM_double(l), digits);
}
static List toLinesFullTrim(String s) {
List l = toLines(s);
for (ListIterator i = l.listIterator(); i.hasNext(); ) {
String line = i.next().trim();
if (line.length() == 0)
i.remove();
else
i.set(line);
}
return l;
}
static List toLinesFullTrim(File f) {
return toLinesFullTrim(loadTextFile(f));
}
static String firstGlobalID(List l) {
for (String s : l) if (possibleGlobalID(s)) return s; return null;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static List trueStatementsByHead(String head) {
return aiUsing(filterByHead(head, parsedTrueStatements_cached()));
}
static List linesToCL(String text) {
return listToCL(toLinesFullTrim(joinLines(map("javaDropComments", toLinesFullTrim(text)))));
}
static void centerConsole() {
centerConsoleFrame();
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static void save(String varName) {
saveLocally(varName);
}
static void save(String progID, String varName) {
saveLocally(progID, varName);
}
static String findInteger(List l) {
for (String s : unnull(l))
if (isInteger(s)) return s;
return null;
}
static boolean lispCalculateDeep_debug;
static class lispCalculateDeep_Op {
int arity;
Method method;
lispCalculateDeep_Op() {}
lispCalculateDeep_Op(int arity, Method method) {
this.method = method;
this.arity = arity;}
}
static Map lispCalculateDeep_ops = new HashMap();
static boolean lispCalculateDeep_inited;
static void lispCalculateDeep_init() {
synchronized(lispCalculateDeep_ops) {
if (!lispCalculateDeep_inited) {
lispCalculateDeep_inited = true;
lispCalculateDeep_op("plus", BigInteger.class, BigInteger.class, "sppxbuuqeetjmzuo", "jcnbmtmfzktxhzyf");
lispCalculateDeep_op("minus", BigInteger.class, BigInteger.class, "jxcubqjtqykhfvyo");
lispCalculateDeep_op("bigIntBiggerThan", BigInteger.class, BigInteger.class, "wdbphzfoxwlrhdyl");
}
}
}
// evaluate anywhere in the tree (e.g. Fib number 2-1 => Fib number 1)
static Lisp lispCalculateDeep(Lisp x) {
lispCalculateDeep_init();
return lispMap_after(x, new Object() { Object get(Lisp l) { try {
if (lispCalculateDeep_debug) print("lispCalculateDeep: " + l);
lispCalculateDeep_Op op = lispCalculateDeep_ops.get(l.head);
if (op == null) return null;
int n = op.arity;
if (n != l.size()) return null;
for (Lisp arg : l) if (!lispIsInt(arg)) return null;
Object[] args = new Object[n];
for (int i = 0; i < n; i++) args[i] = lispToInt(l.get(i));
Object o = op.method.invoke(null, args);
// if (o == null) null;
if (o instanceof BigInteger) return lispInt((BigInteger) o);
if (o instanceof Boolean) return lispBool((Boolean) o);
warn("lispCalculateDeep badly defined operation: " + l.head);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (lispCalculateDeep_debug) print(\"lispCalculateDeep: \" + l);\n \n lispCalc..."; }});
}
static void lispCalculateDeep_op(String function, final Class arg1, final Class arg2, String... names) {
List methods = filter(findMethodsNamed(mc(), function)
, new Object() { Object get(Method m) { try { return arraysEqual(m.getParameterTypes(), new Class[] {arg1, arg2}) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "arraysEqual(m.getParameterTypes(), new Class[] {arg1, arg2})"; }});
if (l(methods) != 1) warn("lispCalculateDeep: Method " + function + " found " + l(methods) + " times");
if (nempty(methods))
putWithAllKeys(lispCalculateDeep_ops, names, new lispCalculateDeep_Op(2, first(methods)));
}
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static long sysNow() {
return System.nanoTime()/1000000;
}
static void load(String varName) {
readLocally(varName);
}
static void load(String progID, String varName) {
readLocally(progID, varName);
}
static void consoleAddAskButton() {
awtReplaceComponent(consoleInputField(), new Object() { Object get(Component c) { try { return
centerAndEast(c, withMargin(jbutton("Ask", "consoleSend")))
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "centerAndEast(c, withMargin(jbutton(\"Ask\", f consoleSend)))"; }});
}
static JLabel jRightAlignedLabel() {
return jrightAlignedLabel();
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(getProgramTitle() + ".");
}
static OccTree2 findNode(OccTree2 tree, E e) {
if (eq(tree.e, e)) return tree;
for (OccTree2 n : tree.next) {
OccTree2 t = findNode(n, e);
if (t != null) return t;
}
return null;
}
static boolean englishToConceptLanguage_dropPunctuation;
static String englishToConceptLanguage(String s) {
{ String _a_1 = englishToConceptLanguage_simple(s); if (!empty(_a_1)) return _a_1; }
{ String _a_2 = englishToConceptLanguage_xyz(s, null); if (!empty(_a_2)) return _a_2; }
if (englishToConceptLanguage_dropPunctuation)
{ String _a_3 = englishToConceptLanguage_xyz(s, "dropPunctuation"); if (!empty(_a_3)) return _a_3; }
return s;
}
static void printWithoutNL(Object o) {
printNoNewLine(o);
}
static boolean setAdd(Collection c, A a) {
if (c.contains(a)) return false;
c.add(a);
return true;
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = new ArrayList();
Object mc = mc();
for (Object o : unnull(l))
x.add(callFunction(f, o));
return x;
}
static List map(Object f, Object[] l) {
return map(f, asList(l));
}
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Map map, Object f) {
List x = new ArrayList();
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callFunction(f, e.getKey(), e.getValue()));
}
return x;
}
public static String unquote(String s) {
if (s == null) return null;
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
return s; // not quoted - return original
}
static JFrame setFrameHeight(JFrame frame, int h) {
frame.setSize(frame.getWidth(), h);
return frame;
}
static JFrame setFrameHeight(int h, JFrame frame) {
return setFrameHeight(frame, h);
}
static boolean addToConsole(final Component c) {
final JFrame frame = consoleFrame();
if (frame == null) return false;
swingLater(new Runnable() { public void run() { try {
addToWindow(frame, c);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "addToWindow(frame, c);"; }});
return true;
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static void focusConsole() {
JTextField tf = consoleInputField();
if (tf != null) {
//print("Focusing console");
//getFrame(tf).requestFocus();
tf.requestFocus();
}
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: l((Collection) o); // incomplete
}
static int l(Lisp l) { return l == null ? 0 : l.size(); }
static void aiConcepts_noAutoClear() {
setOpt(mc(), "aiConceptsMap_cached_autoClearInterval", 0);
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static String programTitle() {
return getProgramName();
}
static void awtEvery(JComponent component, long delay, Runnable r) {
swingEvery(component, delay, r);
}
static void awtEvery(JComponent component, long delay, long firstDelay, Runnable r) {
swingEvery(component, delay, firstDelay, r);
}
static void awtEvery(RootPaneContainer frame, long delay, Runnable r) {
swingEvery(frame, delay, r);
}
static void sahara() {
substanceLAF("Sahara");
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static volatile ThreadLocal print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
Object f = print_byThread.get();
if (f != null)
if (isFalse(callF(f, s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
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);
}
}
}
static void useFacts(String facts) {
List statements = linesToCL(facts);
// trueStatements_cached_autoClearInterval = 0;
trueStatements_cached_cache.set(new LinkedHashSet(statements));
loadTruth_cached_cache.set(aiMakeStatements(statements));
}
static boolean lispMatch_debug;
static Map lispMatch(Lisp pat, Lisp nl, Collection variables) {
Map matches = new HashMap();
return lispMatch_sub(pat, nl, variables, matches) ? matches : null;
}
static boolean lispMatch_sub(Lisp pat, Lisp nl, Collection variables, Map m) {
if (pat == null || nl == null) return false;
if (pat.isLeaf() && variables.contains(pat.head)) {
if (lispMatch_debug) print("Var: " + pat.head + " => " + nl);
return lispMatch_putMatch(m, pat.head, nl);
}
if (neq(pat.head, nl.head)) return false;
// heads identical, proceed to children
int n = pat.size();
if (n != nl.size()) return false;
for (int i = 0; i < n; i++) {
if (lispMatch_debug) print("Sub " + i + ": " + pat.get(i) + " => " + nl.get(i));
if (!lispMatch_sub(pat.get(i), nl.get(i), variables, m))
return false;
}
return true;
}
static boolean lispMatch_putMatch(Map matches, String key, Lisp val) {
if (matches.containsKey(key)) {
if (neq(matches.get(key), val))
return false;
//fail("multi-matching not implemented");
} else
matches.put(key, val);
return true;
}
static String lisp2label(Lisp l) {
return l.isLeaf() ? l.head : clUnparse(l);
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static JPanel centerAndEast(Component c, Component e) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.EAST, wrap(e));
return panel;
}
static Object callF(Object f, Object... args) {
return callF_cached(f, args);
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static ArrayList asList(A[] a) {
return new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
ArrayList l = new ArrayList();
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static String join(String glue, Iterable strings) {
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static List dropFirstAndLast(int n, List l) {
return new ArrayList(subList(l, n, l(l)-n));
}
static String dropFirstAndLast(String s) {
return substring(s, 1, l(s)-1);
}
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isTrue(callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread"));
}
static void sleepInCleanUp(long ms) { try {
if (ms < 0) return;
Thread.sleep(ms);
} catch (Exception __e) { throw rethrow(__e); } }
static boolean arraysEqual(Object[] a, Object[] b) {
if (a.length != b.length) return false;
for (int i = 0; i < a.length; i++)
if (neq(a[i], b[i])) return false;
return true;
}
static WeakAssoc, List> parsedTrueStatements_cached_cache = new WeakAssoc(new Object() { Object get(Set statements) { try { return map("clParse", statements) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "map(f clParse, statements)"; }});
static List parsedTrueStatements_cached() {
return parsedTrueStatements_cached_cache.get(trueStatements_cached());
}
static Lisp lispInt(BigInteger x) {
return lisp(str(x));
}
// TODO: WeakAssoc from loadTruth_cached()
static Cache> trueStatements_cached_cache = new Cache(new Object() { Object get() { try { return collectTreeSet(loadTruth_cached(), "text") ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "collectTreeSet(loadTruth_cached(), \"text\")"; }});
static Set trueStatements_cached() {
return trueStatements_cached_cache.get();
}
static void trueStatements_clearCache() {
trueStatements_cached_cache.clear();
}
// clear cache if older than x seconds
static void trueStatements_clearCache(double seconds) {
trueStatements_cached_cache.clear(seconds);
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static String englishToConceptLanguage_simple(String s) {
for (AIConcept c : englishToConceptLanguage_concepts())
if (!javaTokC(c.name).contains("*") && match(c.name, s))
return c.globalID;
return null;
}
static boolean aiConceptsMap_fastLoad;
static Map aiConceptsMap() {
long time = sysNow();
List concepts = aiConceptsMap_fastLoad ? fastLoadAIConcepts() : loadAIConcepts();
Map map = indexByField(concepts, "globalID");
sysDone(time, "load ai concepts");
return map;
}
static List filterByHead(List l, final String head) {
return filter(l , new Object() { Object get(Lisp x) { try { return x.is(head) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "x.is(head)"; }});
}
static List filterByHead(String head, List l) {
return filterByHead(l, head);
}
static void addToWindow(Component c, Component toAdd) {
if (toAdd == null) return;
JFrame frame = getFrame(c);
Container cp = frame.getContentPane();
JPanel newCP = new JPanel();
newCP.setLayout(new BorderLayout());
newCP.add(BorderLayout.CENTER, cp);
newCP.add(BorderLayout.SOUTH, toAdd);
frame.setContentPane(newCP);
// magic combo to actually relayout and repaint
frame.revalidate();
frame.repaint();
}
static Lisp firstLispInt(List l) {
for (Lisp x : l) if (lispIsInt(x)) return x; return null;
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static List minus(List a, Object... b) {
Set set = asSet(b);
List l = new ArrayList();
for (Object s : a)
if (!set.contains(s))
l.add(s);
return l;
}
static BigInteger minus(BigInteger a, BigInteger b) {
return a.subtract(b);
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// returns true if it did anything
static boolean ping() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(mc()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Lisp lispBool(boolean b) {
return lisp(b ? "true" : "false");
}
static ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
// get purpose 1: access a list/array (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
static Class get_dynamicObject = DynamicObject.class;
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
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 (get_dynamicObject != null && get_dynamicObject.isInstance(o))
return call(get_raw(o, "fieldValues"), "get", field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(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);
}
}
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);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static String conceptLanguageToEnglish_xyz(String s) {
List tok = javaTokC(s);
if (empty(tok)) return s;
String pattern = conceptToNameOpt(first(tok));
if (empty(pattern)) return s;
s = formatXYZ_appendRest(pattern, map(new Object() { Object get(String s) { try { return conceptQuote(conceptToName(s)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "conceptQuote(conceptToName(s))"; }}, dropFirst(tok)));
// Crazy English Fixing
s = jreplace(s, "A", "a");
s = jreplace(s, "a a", "a");
return firstToUpper(s);
}
static List toLines(File f) {
return toLines(loadTextFile(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;
}
private 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;
}
static void web_labelToLabel(Web web, Lisp in, Lisp out) {
web_labelToLabel(web, web.nodes, in, out);
}
static void web_labelToLabel(Web web, List nodes, Lisp in, Lisp out) {
//print("labelToLabel " + in + " => " + out);
for (WebNode node : nodes)
if (node.hasLabel(in)) {
node.addLabel(out);
//print("labelToLabel " + node);
}
}
static Class __javax;
static Class getJavaX() {
return __javax;
}
static boolean conceptLanguageToolTips_enabled;
static void conceptLanguageToolTips() { swingAndWait(new Runnable() { public void run() { try {
if (conceptLanguageToolTips_enabled) return;
conceptLanguageToolTips_enabled = true;
{ /*nt*/ Thread _t_0 = new Thread("conceptLanguageToolTips") {
public void run() { /* in run */ try { /* in thread */
while (licensed()) { try {
Component c = componentAtMouse();
if (c instanceof JComponent) {
String word = wordAtMouse(), msg = "";
if (possibleGlobalID(word)) {
String name = conceptToName(word); // This reloads AI concepts
if (neq(name, word))
msg = word + ": " + name;
}
setToolTipText((JComponent) c, msg);
}
} catch (Throwable __e) { printStackTrace(__e); } sleep(500); }
/* in thread */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ }
};
_t_0.start(); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (conceptLanguageToolTips_enabled) return;\n conceptLanguageToolTips_enabled =..."; }}); }
static void swingEvery(JComponent component, long delay, Runnable r) {
installTimer(component, delay, r);
}
static void swingEvery(JComponent component, long delay, long firstDelay, Runnable r) {
installTimer(component, r, delay, firstDelay);
}
static void swingEvery(RootPaneContainer frame, long delay, Runnable r) {
installTimer(frame, delay, r);
}
static String formatDouble(double d, int digits) {
String format = "0." + rep(digits, '#');
return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}
static BigInteger lispToInt(Lisp x) {
return lispIsInt(x) ? bigint(x.head) : null;
}
static double toM_double(long l) {
return l/(1024*1024.0);
}
// makeNewComponent: func(Component) -> Component
static Component awtReplaceComponent(Component c, Object makeNewComponent) {
Container parent = c.getParent();
assertNotNull("woot", parent);
Component[] l = parent.getComponents();
LayoutManager layout = parent.getLayout();
if (!(layout instanceof BorderLayout))
warn("awtReplaceComponent only tested for BorderLayout");
int idx = indexOf(l, c);
if (idx < 0) throw fail("component not found in parent");
//print("idx: " + idx);
//print("Parent: " + parent);
Object constraints = callOpt(layout, "getConstraints", c);
//print("Constraints: " + constraints);
// remove
parent.remove(c);
// add new component
Component newComponent = (Component) ( callF(makeNewComponent, c));
parent.add(newComponent, constraints, idx);
validateFrame(parent);
return newComponent;
}
static String n(long l, String name) {
return l + " " + (l == 1 ? singular(name) : getPlural(name));
}
static String n(Collection l, String name) {
return n(l(l), name);
}
static String n(Map m, String name) {
return n(l(m), name);
}
static String n(Object[] a, String name) {
return n(l(a), name);
}
static Set aiUsing_set = synchroTreeSet();
static String aiUsing(String s) {
aiUsing_set.addAll(aggressivelyCollectPossibleGlobalIDs(s));
return s;
}
static void aiUsing(Object o) {
// TODO
}
static List aiUsing(List l) {
for (Object li : unnull(l)) aiUsing(li);
return l;
}
static Lisp aiUsing(Lisp l) {
if (l != null) {
aiUsing(l.head);
for (Lisp sub : l) aiUsing(sub);
}
return l;
}
static void aiUsing_print() {
aiUsing_print(null);
}
static void aiUsing_print(List priorityConcepts) {
//print("\nAI concepts used: " + aiUsing_set);
print("\nAI concepts used: ");
dumpConcepts2(findAIConcepts(prioritizeList(aiUsing_set, priorityConcepts)));
}
static JLabel jrightAlignedLabel() {
return new JLabel(" ", JLabel.RIGHT);
}
static File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static Cache> loadTruth_cached_cache = new Cache("loadTruth");
static List loadTruth_cached() {
return loadTruth_cached_cache.get();
}
static void loadTruth_clearCache() {
loadTruth_cached_cache.clear();
}
static void loadTruth_clearCache(double seconds) {
loadTruth_cached_cache.clear(seconds);
}
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
print("[bot] " + a.greeting);
if (a.console && makeAndroid3_consoleInUse()) a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() { try {
List history = new ArrayList();
String line;
while ((line = readLine()) != null) {
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { printStackTrace(__e); } }
};
_t_0.start(); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
print("> " + shorten(originalAnswer, a.answerPrintLimit));
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static String joinLines(List lines) {
return fromLines(lines);
}
static String joinLines(String glue, String text) {
return join(glue, toLines(text));
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
static boolean empty(Map map) {
return map == null || map.isEmpty();
}
static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean isInteger(String s) {
if (s == null) return false;
int n = l(s);
if (n == 0) return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n) return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static void putWithAllKeys(Map map, A[] keys, B value) {
for (A a : keys) map.put(a, value);
}
static Object mc() {
return getMainClass();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
// finds static and non-static methods.
static List findMethodsNamed(Object obj, String method) {
if (obj == null) return null;
return findMethodsNamed(_getClass(obj), method);
}
static List findMethodsNamed(Class c, String method) {
List l = new ArrayList();
while (c != null) {
for (Method m : c.getDeclaredMethods())
if (m.getName().equals(method)) {
m.setAccessible(true);
l.add(m);
}
c = c.getSuperclass();
}
return l;
}
static String getProgramTitle() {
return getProgramName();
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
}
static List aiMakeStatements(List statements) {
return map(new Object() { Object get(String s) { try {
Statement st = unlisted(Statement.class);
st.globalID = aGlobalID();
st.text = s;
return st;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Statement st = unlisted(Statement);\n st.globalID = aGlobalID();\n st.text =..."; }}, statements);
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static void saveLocally(String variableName) {
saveLocally(programID(), variableName);
}
static void saveLocally(String progID, String variableName) {
saveLocally2(mc(), progID, variableName);
}
static void saveLocally2(Object obj, String variableName) {
saveLocally2(obj, programID(), variableName);
}
static synchronized void saveLocally2(Object obj, String progID, String variableName) {
File textFile = new File(programDir(progID), variableName + ".text");
File structureFile = new File(programDir(progID), variableName + ".structure");
Object x = get(obj, variableName);
if (x == null) {
textFile.delete();
structureFile.delete();
} else if (x instanceof String) {
saveTextFile(textFile, (String) x);
structureFile.delete();
} else {
saveTextFile(structureFile, javaTokWordWrap(structure(x)));
textFile.delete();
}
}
static boolean warn_on = true;
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
static List tok_groupRoundBrackets(String s) {
List tok = javaTok(s);
while (true) {
int i = tok.lastIndexOf("(");
if (i < 0) return tok;
int j = indexOf(tok, ")", i);
if (j < 0) return tok;
tok.set(i, join(subList(tok, i, j+1)));
tok.subList(i+1, j+1).clear();
assertTrue(odd(l(tok)));
}
}
static List conceptsFromDump(String s) {
List> l = (List) safeUnstructure("[" + s + "]");
List out = new ArrayList();
for (List x : l) {
AIConcept c = unlisted(AIConcept.class);
String id = makeNewID(get(x, 0));
cset(c, "globalID" , id, "name" , unnull(get(x, 1)), "comment" , unnull(get(x, 2)));
out.add(c);
}
return out;
}
static void consoleSetInput(final String text) {
if (headless()) return;
setTextAndSelectAll(consoleInputField(), text);
}
static List collect(Collection c, String field) {
return collectField(c, field);
}
static boolean englishToConceptLanguage_xyz_debug, englishToConceptLanguage_useBrackets = true;
static String englishToConceptLanguage_xyz(String s, Object preprocess) {
assertNotNull("Input", s);
s = postProcess(preprocess, s);
// pattern matching all concepts against full string
for (AIConcept c : englishToConceptLanguage_concepts()) {
if (empty(c.name)) {
print("Warning, empty name: " + c.globalID);
continue;
}
String name = postProcess(preprocess, c.name);
{ String _a_4 = englishToConceptLanguage_xyz_with(c.globalID, name, s); if (!empty(_a_4)) return _a_4; }
}
// no full string match. go word by word
List tok = javaTok(s);
if (l(tok) <= 3) return null;
for (int i = 1; i < l(tok); i += 2) {
String x = englishToConceptLanguage(unquote(tok.get(i)));
if (nempty(x)) tok.set(i, conceptQuote(x));
}
String x = join(tok);
return eq(x, s) ? null : x;
}
static String englishToConceptLanguage_xyz_sub(String s) {
String s2 = or2(englishToConceptLanguage(s), s);
if (englishToConceptLanguage_xyz_debug)
print("xyz_sub " + quote(s) + " => " + quote(s2));
if (englishToConceptLanguage_useBrackets)
return isIdentifier(s2) || isInteger(s2) || isProperlyQuoted(s2) ? s2 : "(" + s2 + ")";
return conceptQuote(s2);
}
static String englishToConceptLanguage_xyz_with(String id, String s) {
return englishToConceptLanguage_xyz_with(getAIConcept(id), s);
}
static String englishToConceptLanguage_xyz_with(AIConcept c, String s) {
if (c == null) return null;
return englishToConceptLanguage_xyz_with(c.globalID, c.name, s);
}
static String englishToConceptLanguage_xyz_with(String id, String name, String s) {
Matches m = new Matches();
List tok = javaTokC(name);
if (tok.contains("*")) return null; // Don't want those, use X and Y here
int iX = tok.indexOf("X");
if (iX >= 0) {
int iY = tok.indexOf("Y");
if (iY >= 0) {
int iZ = tok.indexOf("Z");
if (iZ >= 0) {
// X and Y and Z
String pat = formatXYZ(name, "*", "*", "*");
boolean yes = flexMatchIC2(pat, s, m, false);
if (englishToConceptLanguage_xyz_debug && yes)
print("xyz: " + pat + " - " + s + " => " + (yes ? struct(m) : "-"));
if (yes) {
assertEquals(name, 3, l(m.m));
TreeMap map = new TreeMap();
map.put(iX, englishToConceptLanguage_xyz_sub(m.m[0]));
map.put(iY, englishToConceptLanguage_xyz_sub(m.m[1]));
map.put(iZ, englishToConceptLanguage_xyz_sub(m.m[2]));
return aiUsing(id) + " " + join(" ", values(map));
}
} else {
// X and Y
String pat = formatXYZ(name, "*", "*");
boolean complicated = containsSubList(tok, "X", "Y");
boolean yes = complicated ? jmatch(pat, s, m) : flexMatchIC2(pat, s, m, false);
if (englishToConceptLanguage_xyz_debug && yes)
print("xyz: " + pat + " - " + s + " => " + (yes ? struct(m) : "-"));
if (yes) {
assertEquals(name, 2, l(m.m));
String a = englishToConceptLanguage_xyz_sub(m.m[0]);
String b = englishToConceptLanguage_xyz_sub(m.m[1]);
return aiUsing(id) + " " +
(iX < iY ? a + " " + b : b + " " + a);
}
}
} else {
// X only
String pat = formatXYZ(name, "*");
if (flexMatchIC2(pat, s, m, false)) {
assertEquals(name, 1, l(m.m));
String a = englishToConceptLanguage_xyz_sub(m.m[0]);
return aiUsing(id) + " " + a;
}
}
}
return null;
}
static Object consoleFrame_gen() {
return getOpt(getOpt(getJavaX(), "console"), "frame");
}
static Set keys(Map map) {
return map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static void centerConsoleFrame() {
centerFrame(consoleFrame());
}
static String fromLines(List lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (String line : lines)
buf.append(line).append('\n');
return buf.toString();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static String substanceLAF_defaultSkin = "Creme";
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try {
enableSubstance_impl(or2(skinName, substanceLAF_defaultSkin));
} catch (Throwable __e) { printStackTrace(__e); }
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static void sleepQuietly() { try {
assertFalse(isAWTThread());
synchronized(main.class) { main.class.wait(); }
} catch (Exception __e) { throw rethrow(__e); } }
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static List listToCL(List l) {
return map("englishToConceptLanguage", l);
}
static void readLocally(String progID, String varNames) {
readLocally2(mc(), progID, varNames);
}
static void readLocally(String varNames) {
readLocally2(mc(), programID(), varNames);
}
static void readLocally2(Object obj, String varNames) {
readLocally2(obj, programID(), varNames);
}
static int readLocally_stringLength;
static ThreadLocal readLocally2_allDynamic = new ThreadLocal();
// read a string variable from standard storage
// does not overwrite variable contents if there is no file
static void readLocally2(Object obj, String progID, String varNames) { try {
boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic));
for (String variableName : javaTokC(varNames)) {
File textFile = new File(programDir(progID), variableName + ".text");
String value = loadTextFile(textFile);
if (value != null)
set(main.class, variableName, value);
else {
File structureFile = new File(programDir(progID), variableName + ".structure");
value = loadTextFile(structureFile);
if (value == null) {
File structureGZFile = new File(programDir(progID), variableName + ".structure.gz");
if (!structureGZFile.isFile()) return;
//value = loadGZTextFile(structureGZFile);
InputStream fis = new FileInputStream(structureGZFile);
try {
GZIPInputStream gis = new GZIPInputStream(fis);
InputStreamReader reader = new InputStreamReader(gis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
//O o = unstructure_reader(bufferedReader);
Object o = unstructure_tok(javaTokC_onReader(bufferedReader), allDynamic, null);
readLocally_set(obj, variableName, o);
} finally {
fis.close();
}
return;
}
readLocally_stringLength = l(value);
if (value != null)
readLocally_set(obj, variableName, allDynamic ? safeUnstructure(value) : unstructure(value));
}
}
} catch (Exception __e) { throw rethrow(__e); } }
static void readLocally_set(Object c, String varName, Object value) {
Object oldValue = get(c, varName);
if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) {
// Assume it's a synchroList.
value = synchroList((List) value);
}
set(c, varName, value);
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
try {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
return loadTextFile(fileName.getPath(), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static String clUnparse(Lisp l) {
if (l == null) return "";
return join(" ", (List) concatLists(ll(conceptQuote(l.head)), map("clUnparse_sub", l)));
}
static String clUnparse_sub(Lisp l) {
return l.empty() ? clUnparse(l) : "(" + clUnparse(l) + ")";
}
static boolean possibleGlobalID(String s) {
return l(s) == 16 && allLowerCaseCharacters(s);
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static JTextField consoleInputField() {
return (JTextField) getOpt(get(getJavaX(), "console"), "tfInput");
}
static void printNoNewLine(Object o) {
print_noNewLine(str(o));
}
// does not store null values
static Map indexByField(Collection c, String field) {
HashMap map = new HashMap();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
map.put(val, a);
}
return map;
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
return new Responder() {
String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
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 new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String getProgramName_cache;
static synchronized String getProgramName() {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
}
// f: func(Lisp) -> Lisp; may return null
static Lisp lispMap_after(Lisp l, Object f) {
if (l == null) return null;
Lisp l2 = lisp(l.head);
for (Lisp child : l)
l2.add(lispMap_after(child, f));
return (Lisp) callPostProcessor2(f, l2);
}
static String aGlobalID() {
return randomID(16);
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder out = new StringBuilder();
quote_impl(s, out);
return out.toString();
}
static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else
out.append(c);
}
out.append('"');
}
static List record_list = synchroList();
static void record(Object o) {
record_list.add(o);
}
static Thread currentThread() {
return Thread.currentThread();
}
static List getPlural_specials = ll("sheep", "fish");
static String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s)) return s;
if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
static void printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}
static boolean containsSubList(List x, List y) {
return indexOfSubList(x, y) >= 0;
}
static boolean containsSubList(List x, A... y) {
return containsSubList(x, asList(y));
}
static boolean isProperlyQuoted(String s) {
return s.length() >= 2
&& s.startsWith("\"")
&& s.endsWith("\"")
&& (!s.endsWith("\\\"") || s.endsWith("\\\\\""));
}
static void removeFromMultiPort(long vport) {
if (vport == 0) return;
for (Object port : getMultiPorts())
call(port, "removePort", vport);
}
static JTextField setTextAndSelectAll(final JTextField tf, final String text) {
{ swingAndWait(new Runnable() { public void run() { try {
tf.setText(text);
tf.selectAll();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tf.setText(text);\n tf.selectAll();"; }}); }
return tf;
}
static WeakHashMap> callF_cache = new WeakHashMap();
static Object callF_cached(Object f, Object... args) { try {
if (f == null) return null;
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f instanceof String)
return call(mc(), (String) f, args);
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 methods.get(0).invoke(f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return m.invoke(f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static List fastLoadAIConcepts() {
print("fast-loading ai concepts");
Class main = getBotMainClass(dbBotName(aiConceptsProgram()));
Object concepts = get(main, "mainConcepts");
return map("fastLoadAIConcept", (List) call(concepts, "list", "AIConcept"));
}
static String getType(Object o) {
return getClassName(o);
}
// Substance
// Trident (required by Substance)
static void enableSubstance_impl(final String skinName) { swingAndWait(new Runnable() { public void run() { try {
if (!substanceLookAndFeelEnabled())
enableSubstance_impl_2(skinName);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!substanceLookAndFeelEnabled())\n enableSubstance_impl_2(skinName);"; }}); }
static void enableSubstance_impl_2(String skinName) { try {
ClassLoader cl = main.class.getClassLoader();
UIManager.getDefaults().put("ClassLoader", cl);
Thread.currentThread().setContextClassLoader(cl);
String skinClassName = "org.pushingpixels.substance.api.skin." + addSuffix(skinName, "Skin");
SubstanceSkin skin = (SubstanceSkin) nuObject(cl.loadClass(skinClassName));
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
updateLookAndFeelOnAllWindows();
if (substanceLookAndFeelEnabled())
print("Substance L&F enabled.");
else
print("Could not enable Substance L&F?");
} catch (Exception __e) { throw rethrow(__e); } }
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine");
static String singular(String s) {
if (s == null) return null;
{ String _a_5 = singular_specials.get(s); if (!empty(_a_5)) return _a_5; }
if (singular_specials2.contains(dropSuffix("s", s)))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
static Object addToMultiPort_responder;
static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List history) {
String answer = (String) ( callOpt(getMainClass(), "answer", s, history));
if (answer != null) return answer;
answer = (String) callOpt(getMainClass(), "answer", s);
if (answer != null) return answer;
if (match3("get injection id", s))
return getInjectionID();
return null;
}
});
}
static long addToMultiPort(final String botName, final Object responder) {
//print(botName);
addToMultiPort_responder = responder;
startMultiPort();
List ports = getMultiPorts();
if (ports == null) return 0;
if (ports.isEmpty())
throw fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
Object responder2 = new Object() {
public String answer(String s, List history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
};
record(responder2);
return (Long) call(port, "addResponder", botName, responder2);
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;
static List javaTok(String s) {
return javaTok(s, null);
}
static List javaTok(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTok(join(tok), tok);
}
static boolean javaTok_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static Object unstructure(String text) {
return unstructure(text, false);
}
static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static int structure_internStringsLongerThan = 50;
static int unstructure_tokrefs; // stats
abstract static class unstructure_Receiver {
abstract void set(Object o);
}
// classFinder: func(name) -> class (optional)
static Object unstructure(String text, boolean allDynamic,
Object classFinder) {
if (text == null) return null;
return unstructure_tok(javaTokC_iterator(text), allDynamic, classFinder);
}
static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_onReader(reader), false, null);
}
static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object classFinder) {
final boolean debug = unstructure_debug;
final class X {
int i = -1;
HashMap refs = new HashMap();
HashMap tokrefs = new HashMap();
HashSet concepts = new HashSet();
HashMap classesMap = new HashMap();
List stack = new ArrayList();
String curT;
// look at current token
String t() {
return curT;
}
// get current token, move to next
String tpp() {
String t = curT;
consume();
return t;
}
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;
// if (debug) print("parse: " + quote(t));
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
// if (debug) print("parse_inner: " + quote(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("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 (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t));
if (isLongConstant(t)) {
out.set(parseLong(t)); return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
if (debug)
print("l=" + l + ", isInt: " + isInt);
out.set(isInt ? (Object) new Integer((int) l) : (Object) new Long(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("treeset")) {
parseTreeSet(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("{")) {
parseMap(out); return;
}
if (t.equals("[")) {
parseList(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 (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
// any other class name
if (c == null) {
// First, find class
if (allDynamic) c = null;
else if (classFinder != null)
c = (Class) callF(classFinder, t);
else
c = findClass(t);
if (c != null)
classesMap.put(t, c);
}
// Check if it has an outer reference
consume();
boolean hasBracket = eq(t(), "(");
if (hasBracket) consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
if (c != null)
o = hasOuter ? nuStubInnerObject(c) : nuEmptyObject(c);
else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = t;
if (debug) print("Made dynamic object " + t + " " + shortClassName(dO));
}
// Save in references list early because contents of object
// might link back to main object
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
// NOW parse the fields!
final LinkedHashMap fields = new LinkedHashMap(); // preserve order
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());
consume("=");
stack.add(this);
parse(new unstructure_Receiver() {
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(), \")\")) {\n consume(\")\");\n objRead(_o, _dO, field..."; }});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
if (debug)
printStructure("setOptAllDyn", fields);
setOptAllDyn(dO, fields);
} else
setOptAll(o, fields);
else for (String field : keys(fields))
dO.fieldValues.put(field.intern(), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
void parseSet(final Set set, final unstructure_Receiver out) {
parseList(new unstructure_Receiver() {
void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
void parseLisp(final unstructure_Receiver out) {
consume("l");
consume("(");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), ")")) {
consume(")");
out.set(newObject("main$Lisp", (String) list.get(0), subList(list, 1)));
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\n consume(\")\");\n out.set(newObject(\"main$Li..."; }});
}
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() {
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(), \"}\")) {\n consume(\"}\");\n out.set(bs);\n } els..."; }});
}
void parseList(final unstructure_Receiver out) {
consume("[");
final ArrayList list = new ArrayList();
stack.add(new Runnable() { public void run() { try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
//if (debug) print("List element type: " + getClassName(o));
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\n consume(\"]\");\n out.set(list);\n } e..."; }});
}
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() {
void set(Object o) {
list.add(o);
if (eq(t(), ",")) consume();
}
});
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\n consume(\"}\");\n out.set(type.equals(\"intar..."; }});
}
Object parseClass() {
consume("class");
consume("(");
String name = tpp();
consume(")");
Class c = allDynamic ? null : findClass(name);
if (c != null) return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
dO.fieldValues.put("name", name);
return dO;
}
Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
boolean v;
Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
consume("=");
parse(new unstructure_Receiver() {
void set(Object value) {
map.put(key, value);
if (debug)
print("parseMap: Got value " + getClassName(value) + ", next token: " + quote(t()));
if (eq(t(), ",")) consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
void set(Object o) {
key = o;
}
});
}
} // if v else
} // run()
});
}
/*void parseSub(unstructure_Receiver out) {
int n = l(stack);
parse(out);
while (l(stack) > n)
stack
}*/
void consume() { curT = tok.next(); ++i; }
void consume(String s) {
if (!eq(t(), s)) {
/*S prevToken = i-1 >= 0 ? tok.get(i-1) : "";
S nextTokens = join(tok.subList(i, Math.min(i+2, tok.size())));
fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");*/
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
void parse_x(unstructure_Receiver out) {
consume(); // get first token
parse(out);
while (nempty(stack))
popLast(stack).run();
}
}
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
void set(Object o) { v.set(o); }
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
}
static boolean unstructure_debug;
static JFrame centerFrame(JFrame frame) {
frame.setLocationRelativeTo(null); // magic trick
return frame;
}
static boolean flexMatchIC2_debug;
static boolean flexMatchIC2(String pat, String s) {
return flexMatchIC2(pat, s, null);
}
static boolean flexMatchIC2(String pat, String s, Matches m) {
return flexMatchIC2(javaTok(pat), javaTok(unnull(s)), m);
}
static boolean flexMatchIC2(String pat, String s, Matches m, boolean joinBrackets) {
return flexMatchIC2(javaTok(pat), javaTok(unnull(s)), m, joinBrackets);
}
static boolean flexMatchIC2(List tokpat, List tokfull, Matches m) {
return flexMatchIC2(tokpat, tokfull, m, true);
}
static boolean flexMatchIC2(List tokpat, List tokfull, Matches m, boolean joinBrackets) {
tokpat = codeTokens(joinBrackets ? joinBrackets(tokpat) : tokpat);
for (int i = 0; i < l(tokpat); i++)
if (eq(tokpat.get(i), "*"))
tokpat.add(i++, "!*"); // insert single-token wildcard in front to avoid empty matches
if (joinBrackets) tokfull = joinBrackets(tokfull);
List tok = codeTokens(tokfull);
BitSet bla = new BitSet();
BitSet bla2 = new BitSet();
if (!flexMatchIC2_impl(tokpat, 0, tok, 0, bla, bla2)) return false;
if (m != null) {
List l = new ArrayList();
for (int i = 1; i < l(tokfull); i += 2) {
if (bla.get(i/2)) {
int j = i;
while (j < l(tokfull) && bla.get(j/2)) j += 2;
l.add(join(subList(tokfull, i, j-1)));
i = j-2;
} else if (bla2.get(i/2))
l.add(tokfull.get(i));
}
m.m = toStringArray(l);
}
return true;
}
static boolean flexMatchIC2_impl(List pat, int ipat, List tok, int itok, BitSet bla, BitSet bla2) {
if (flexMatchIC2_debug)
print("flexMatchIC2 pat=" + structure(subList(pat, ipat)) + " tok=" + structure(subList(tok, itok)) + " " + structure(bla));
if (ipat >= l(pat))
return itok >= l(tok);
String t = pat.get(ipat);
if (eq(t, "*")) { // the flex wildcard (0 or more tokens)
if (flexMatchIC2_debug) print("Trying zero tokens");
if (flexMatchIC2_impl(pat, ipat+1, tok, itok, bla, bla2)) {
if (flexMatchIC2_debug) print("Success!");
return true;
}
bla.set(itok);
if (itok < l(tok)) {
if (flexMatchIC2_debug) print("Trying one or more tokens");
if (flexMatchIC2_impl(pat, ipat, tok, itok+1, bla, bla2)) {
if (flexMatchIC2_debug) print("Success!");
return true; // success, leave mark
}
}
if (flexMatchIC2_debug) print("Failed * matching");
bla.clear(itok); // fail, undo marking
return false;
}
if (itok >= l(tok)) {
if (flexMatchIC2_debug)
print("too much pattern");
return false;
}
if (eq(t, "!*")) { // the single-token wildcard
bla.set(itok);
if (flexMatchIC2_impl(pat, ipat+1, tok, itok+1, bla, bla2))
return true; // success, leave mark
bla.clear(itok); // fail, undo marking
return false;
}
String realt = tok.get(itok);
if (t.startsWith("(") && t.endsWith(")")) {
// quick pre-check
if (flexMatchIC2_debug)
print("flexMatchIC2 precheck " + t + " " + realt);
if (!containsIgnoreCase(t, realt)) return false;
// real check
List list = splitAt(dropFirstAndLast(t), "|");
if (flexMatchIC2_debug)
print("flexMatchIC2 real check " + struct(list));
if (!containsIgnoreCase(list, realt)) return false;
bla2.set(itok);
} else if (neqic(realt, t)) {
if (flexMatchIC2_debug)
print("mismatch");
return false;
}
// it is a token match. consume and proceed
if (flexMatchIC2_impl(pat, ipat+1, tok, itok+1, bla, bla2))
return true;
else {
bla2.clear(itok);
return false;
}
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(List l, int startIndex, int endIndex) {
startIndex = max(0, min(l(l), startIndex));
endIndex = max(0, min(l(l), endIndex));
if (startIndex > endIndex) return litlist();
return l.subList(startIndex, endIndex);
}
static void set(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static List collectField(Collection c, String field) {
List l = new ArrayList();
for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Object call(Object o) {
return callFunction(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
try {
if (o instanceof Class) {
Method m = call_findStaticMethod((Class) o, method, args, false);
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = call_findMethod(o, method, args, false);
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
}
static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && call_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
}
private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
// hmm, this shouldn't call functions really. That was just
// for coroutines.
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
return ((Boolean) callF(o)).booleanValue();
}
static boolean isTrue(Object pred, Object arg) {
return booleanValue(callF(pred, arg));
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane)
return new JScrollPane(c);
return c;
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
callOpt(getClass("javax.swing.SwingUtilities"), "isEventDispatchThread");
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
// class Matches is added by #752
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (s == null) return false;
return match3(pat, parse3_cached(s), matches);
}
static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3(pat);
return match3(tokpat,toks,matches);
}
static boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swingAndWait(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\n if (neq(s, c.getToolTipText()))\n ..."; }}); }
return c;
}
static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
static boolean jmatch(String pat, String s, Matches matches) {
if (s == null) return false;
return jmatch(pat, javaTok(s), matches);
}
static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static File programDir_mine; // set this to relocate program's data
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
if (programDir_mine != null && sameSnippetID(snippetID, programID()))
return programDir_mine;
return new File(javaxDataDir(), formatSnippetID(snippetID));
}
static String rep(int n, char c) {
return repeat(c, n);
}
static String rep(char c, int n) {
return repeat(c, n);
}
static List rep(A a, int n) {
return repeat(a, n);
}
static String wordAtMouse() {
return (String) swing(new Object() { Object get() { try {
Component c = componentAtMouse();
if (c instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) ( c);
Point d = mouseToComponent(c);
int idx = tc.viewToModel(d);
String text = tc.getText();
return wordAroundIndex(text, idx);
}
return "";
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Component c = componentAtMouse();\n if (c instanceof JTextComponent) {\n J..."; }});
}
static Set aggressivelyCollectPossibleGlobalIDs(String s) {
LinkedHashSet ids = new LinkedHashSet();
if (s == null) return ids;
for (int i = 0; i < l(s); i++) {
int j = i;
while (j < l(s) && Character.isLowerCase(s.charAt(j))) ++j;
if (j-i == 16)
ids.add(substring(s, i, j));
i = j;
}
return ids;
}
static String getInjectionID() {
return (String) call(getJavaX(), "getInjectionID", getMainClass());
}
// make concept instance that is not connected to DB
static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
/** writes safely (to temp file, then rename) */
static void saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists()) try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) { printStackTrace(e); }
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
} finally {
action.done();
}
}
static void saveTextFile(File fileName, String contents) { try {
saveTextFile(fileName.getPath(), contents);
} catch (Exception __e) { throw rethrow(__e); } }
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) // is null if file is in current dir
dir.mkdirs();
return file;
}
static List findAIConcepts(String ids) {
return findAIConcepts(javaTokC(ids));
}
static List findAIConcepts(Collection ids) {
List l = new ArrayList();
for (String id : ids)
addIfNotNull(l, aiConceptsMap_cached().get(id));
return l;
}
static AtomicInteger dialogServer_clients = new AtomicInteger();
static boolean dialogServer_printConnects;
static Set dialogServer_knownClients = synchroTreeSet();
static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler))
++port;
return port;
}
static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true))
++port;
return port;
}
static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
static ServerSocket startDialogServer_serverSocket;
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// probably the port number is used - let's assume there already is a chat server.
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) { public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
// This should be the same as #1001076 (talkTo)
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) { throw rethrow(__e); } }
String readLineImpl() { try {
return in.readLine();
} catch (Exception __e) { throw rethrow(__e); } }
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
//print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
}
}
}; // Thread t2
t2.setDaemon(true); // ?
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}};
if (daemon) thread.setDaemon(true);
thread.start();
print("Dialog server on port " + port + " started.");
return true;
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static void installTimer(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
return (Timer) swingAndWait(new Object() { Object get() { try {
Timer timer = new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
if (!allPaused())
callF(r);
} catch (Throwable __e) { printStackTrace(__e); }
}});
timer.setInitialDelay(toInt(firstDelay));
timer.setRepeats(repeats);
bindTimerToComponent(timer, component);
return timer;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Timer timer = new Timer(toInt(delay), actionListener {\n pcall {\n if ..."; }});
}
static Timer installTimer(JFrame frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), r, delay, firstDelay);
}
static A postProcess(Object f, A a) {
return callPostProcessor(f, a);
}
static String programID() {
return getProgramID();
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static String conceptToName(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null || empty(c.name) ? s : c.name;
}
static String conceptQuote(String s) {
if (isIdentifier(s) || isInteger(s) || isProperlyQuoted(s)) return s;
return quote(s);
}
static BufferedReader readLine_reader;
static String readLine() {
return (String) call(getJavaX(), "readLine");
}
static void validateFrame(Component c) {
revalidateFrame(c);
}
static boolean headless() {
return isHeadless();
}
static AIConcept getAIConcept(String id) {
return aiConceptsMap_cached().get(id);
}
static boolean allLowerCaseCharacters(String s) {
for (int i = 0; i < l(s); i++)
if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false;
return true;
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static List dropFirst(int n, List l) {
return new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static String dropFirst(int n, String s) {
return substring(s, n);
}
static String struct(Object o) {
return structure(o);
}
static String shorten(String s, int max) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static String shorten(int max, String s) { return shorten(s, max); }
static TreeSet collectTreeSet(Collection c, String field) {
TreeSet set = new TreeSet();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
set.add(val);
}
return set;
}
static Object safeUnstructure(String s) {
return unstructure(s, true);
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static String conceptToNameOpt(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null ? null : unnull(c.name);
}
static void assertTrue(Object o) {
assertEquals(true, o);
}
static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(Collection l) {
HashSet set = new HashSet();
for (A o : l)
if (o != null)
set.add(o);
return set;
}
static List javaTokC(String s) {
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(quickSubstring(s, i, j));
i = j;
}
return tok;
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
static String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
jreplace(tok, in, out, condition);
return join(tok);
}
// leaves tok properly tokenized
// returns true iff anything was replaced
static boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
static boolean jreplace(List tok, String in, String out, Object condition) {
return jreplace(tok, in, out, false, true, condition);
}
static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
boolean anyChange = false;
for (int n = 0; n < 10000; n++) {
int i = findCodeTokens(tok, 1, ignoreCase, toStringArray(codeTokensOnly(tokin)), condition);
if (i < 0)
return anyChange;
List subList = tok.subList(i-1, i+l(tokin)-1); // N to N
String expansion = jreplaceExpandRefs(out, subList);
int end = i+l(tokin)-2;
clearAllTokens(tok, i, end); // C to C
tok.set(i, expansion);
if (reTok) // would this ever be false??
reTok(tok, i, end);
anyChange = true;
}
throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
}
static boolean jreplace_debug;
static Producer javaTokC_onReader(final BufferedReader r) {
final class X implements Producer {
StringBuilder buf = new StringBuilder(); // stores from "i"
char c, d, e = 'x'; // just not '\0'
X() {
// fill c, d and e
nc();
nc();
nc();
}
// get next character(s) into c, d and e
void nc() { try {
c = d;
d = e;
if (e == '\0') return;
int i = r.read();
e = i < 0 ? '\0' : (char) i;
} catch (Exception __e) { throw rethrow(__e); } }
void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
// scan for whitespace
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc(); nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0') return null;
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') { // end at \n to not propagate unclosed string literal errors
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L') ncSave(); // Long constants like 1L
} else if (c == '[' && d == '[') {
do ncSave(); while (c != '\0' && !(c == ']' && d == ']'));
ncSave(); ncSave();
} else if (c == '[' && d == '=' && e == '[') {
do ncSave(); while (c != '\0' && !(c == ']' && d == '=' && e == ']'));
ncSave(); ncSave(); ncSave();
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
// action can be Runnable or a function name
static JButton newButton(String text, final Object action) {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
callFunction(action);
}});
return btn;
}
static List prioritizeList(Collection c, List prioritizer) {
List l = new ArrayList();
Set set = asSet(c);
for (A a : prioritizer) {
if (set.contains(a)) {
set.remove(a);
l.add(a);
}
}
l.addAll(set);
return l;
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static Class getClass(Object realm, String name) { try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
for (int i = startIndex; i < l(l); i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static String formatXYZ_appendRest(String pattern, List args) {
List tok = javaTokC(pattern);
List restArgs = cloneList(args);
for (int idx : (List) reverseSorted(map("formatXYZ_varToIndex", tok)))
remove(restArgs, idx-1);
return join(" ", concatLists(
ll(formatXYZ(pattern, args)),
restArgs));
}
static Component componentAtMouse() {
return (Component) swing(new Object() { Object get() { try {
Point p = MouseInfo.getPointerInfo().getLocation();
Window window = locationToWindow(p);
if (window == null) return null;
SwingUtilities.convertPointFromScreen(p, window);
return SwingUtilities.getDeepestComponentAt(window, p.x, p.y);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Point p = MouseInfo.getPointerInfo().getLocation();\n Window window = location..."; }});
}
static long sysDone(long startTime, String desc) {
return done2(startTime, desc);
}
static long sysDone(String desc, long startTime) {
return done2(desc, startTime);
}
static long sysDone(long startTime) {
return done2(startTime);
}
static List concatLists(List ... lists) {
List l = new ArrayList();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection> lists) {
List l = new ArrayList();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static String javaTokWordWrap(String s) {
int cols = 120, col = 0;
List tok = javaTok(s);
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && col >= cols && !containsNewLine(t))
tok.set(i, t += "\n");
int idx = t.lastIndexOf('\n');
if (idx >= 0) col = l(t)-(idx+1);
else col += l(t);
}
return join(tok);
}
static JFrame getFrame(Object o) {
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
}
static void assertFalse(Object o) {
assertEquals(false, o);
}
static boolean assertFalse(boolean b) {
if (b) throw fail("oops");
return b;
}
static boolean assertFalse(String msg, boolean b) {
if (b) throw fail(msg);
return b;
}
static final WeakHashMap> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker
static {
getOpt_cache.put(Class.class, getOpt_special);
getOpt_cache.put(String.class, getOpt_special);
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
getOpt_cache.put(c, map);
return map;
}
static String formatXYZ(String pattern, List args) {
List tok = javaTok(pattern);
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
int idx = formatXYZ_varToIndex(t)-1;
if (idx >= 0 && l(args) > idx)
tok.set(i, args.get(idx));
}
return join(tok);
}
static String formatXYZ(String pattern, String... args) {
return formatXYZ(pattern, asList(args));
}
static BigInteger bigint(String s) {
return new BigInteger(s);
}
static BigInteger bigint(long l) {
return BigInteger.valueOf(l);
}
static String processID_cached;
// try to get our current process ID
static String getPID() {
if (processID_cached == null) {
String name = ManagementFactory.getRuntimeMXBean().getName();
processID_cached = name.replaceAll("@.*", "");
}
return processID_cached;
}
static boolean match(String pat, String s) {
return match3(pat, s);
}
static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static String callStaticAnswerMethod(List bots, String s) {
for (Object c : bots) try {
String answer = callStaticAnswerMethod(c, s);
if (!empty(answer)) return answer;
} catch (Throwable e) {
print("Error calling " + getProgramID(c));
e.printStackTrace();
}
return null;
}
static String callStaticAnswerMethod(Object c, String s) {
String answer = (String) callOpt(c, "answer", s, litlist(s));
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
static String callStaticAnswerMethod(String s) {
return callStaticAnswerMethod(mc(), s);
}
static String callStaticAnswerMethod(String s, List history) {
return callStaticAnswerMethod(mc(), s, history);
}
static String callStaticAnswerMethod(Object c, String s, List history) {
String answer = (String) callOpt(c, "answer", s, history);
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
static String makeNewID(String id) {
return empty(id) || eq(id, "?") ? aGlobalID() : id;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
f.setAccessible(true);
// take care of common case (long to int)
if (f.getType() == int.class && value instanceof Long)
value = ((Long) value).intValue();
try {
f.set(o, value);
} catch (Exception e) {
try {
if (f.getType().getName().equals("main$Concept$Ref")) {
f.set(o, nuObject("main$Concept$Ref", o, value));
return;
}
if (o.getClass().getName().equals("main$Concept$Ref")) {
f.set(o, call(o, "get"));
return;
}
} catch (Throwable _e) {}
throw e;
}
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
structure_Data d = new structure_Data();
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;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static int structure_shareStringsLongerThan = 20;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
IdentityHashMap seen = new IdentityHashMap();
BitSet refd = new BitSet();
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
Class conceptClass = findClass("Concept");
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) {
final PrintWriter out = d.out;
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
String name = c.getName();
String dynName = shortDynamicClassName(o);
boolean concept = d.conceptClass != null && d.conceptClass.isInstance(o);
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
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 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;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.refd.set(ref);
d.append("t").app(ref); return;
}
ref = d.n; //d.seen.size()+1;
d.seen.put(o, ref);
//d.append("m").app(ref).app(" "); // marker
if (o instanceof String) {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (l(s) >= structure_shareStringsLongerThan)
d.strings.put(s, ref);
quoteToPrintWriter(s, out); d.n++; return;
}
if (o instanceof HashSet) {
d.append("hashset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof Collection && neq(name, "main$Concept$RefL")) {
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())\n d.append(\"]\");\n else {\n d.stack.add..."; }});
return;
}
if (o instanceof Map) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v;
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[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
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;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
if (o instanceof Lisp) {
d.append("l(", 2);
final Lisp lisp = (Lisp) ( o);
structure_1(lisp.head, d);
final Iterator it = lisp.args.iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append(")");
else {
d.stack.add(this);
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\n d.append(\")\");\n else {\n d.sta..."; }});
return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
while (c != Object.class) {
for (Field field : getDeclaredFields_cached(c)) {
if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
c = c.getSuperclass();
}
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
}
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null)
fv.put(f.getName(), value);
}
String shortName = dropPrefix("main$", name);
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = dynName;
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\n if (d.n != l)\n d.append(\")\");\n } else {\n ..."; }});
}
static boolean loadAIConcepts_alwaysFromDisk;
static List loadAIConcepts() {
Concepts c = new Concepts("#1006463");
if (loadAIConcepts_alwaysFromDisk) c.loadFromDisk(); else c.load();
return list(c, AIConcept.class);
}
static String firstToUpper(String s) {
if (s.length() == 0) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static ThreadLocal < List < AIConcept > > englishToConceptLanguage_concepts = new ThreadLocal();
static volatile List englishToConceptLanguage_concepts_global;
static List englishToConceptLanguage_concepts() {
List l = englishToConceptLanguage_concepts.get();
if (l != null) return l;
l = englishToConceptLanguage_concepts_global;
if (l != null) return l;
return aiConceptsPrioritized();
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static A callPostProcessor2(Object f, A a) {
return f == null ? a : or((A) callF(f, a), a);
}
static int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static String dumpConcepts2(List concepts) {
List l = new ArrayList();
for (AIConcept c : concepts) {
List x = ll(c.globalID, c.name);
addIfNempty(x, c.comment);
l.add(" " + struct(x));
}
return print("[[\n" + join(",\n", l) + "\n]]");
}
static boolean neqic(String a, String b) {
return !eqic(a, b);
}
static Cache> aiConceptsMap_cached_cache = new Cache("aiConceptsMap");
static double aiConceptsMap_cached_autoClearInterval = 30;
static Map aiConceptsMap_cached() {
aiConceptsMap_cached_cache.clear(aiConceptsMap_cached_autoClearInterval);
return aiConceptsMap_cached_cache.get();
}
static void aiConceptsMap_clearCache() {
aiConceptsMap_cached_cache.clear();
}
// clear cache if older than x seconds
static void aiConceptsMap_clearCache(double seconds) {
aiConceptsMap_cached_cache.clear(seconds);
}
static String quoteCharacter(char c) {
if (c == '\'') return "'\\''";
if (c == '\\') return "'\\\\'";
return "'" + c + "'";
}
// "$1" is first code token, "$2" second code token etc.
static String jreplaceExpandRefs(String s, List tokref) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) {
String x = tokref.get(-1+parseInt(tok.get(i).substring(1))*2);
tok.set(i, x);
}
}
return join(tok);
}
static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static HashSet litset(A... items) {
return lithashset(items);
}
static byte[] hexToBytes(String s) {
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
String hex = substring(s, i*2, i*2+2);
try {
bytes[i] = (byte) parseHexByte(hex);
} catch (Throwable _e) {
throw fail("Bad hex byte: " + quote(hex) + " at " + i*2 + "/" + l(s));
}
}
return bytes;
}
static boolean allPaused() {
return ping_pauseAll;
}
static HashMap nuEmptyObject_cache = new HashMap();
static A nuEmptyObject(Class c) { try {
Constructor ctr;
synchronized(nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
ctr.setAccessible(true);
}
}
return (A) ctr.newInstance();
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
static boolean setOptAllDyn_debug;
static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null) return;
for (String field : keys(fields)) {
Object val = fields.get(field);
boolean has = hasField(o, field);
if (has)
setOpt(o, field, val);
else {
o.fieldValues.put(field.intern(), val);
if (setOptAllDyn_debug) print("setOptAllDyn added dyn " + field + " to " + o + " [value: " + val + ", fieldValues = " + systemHashCode(o.fieldValues) + ", " + struct(keys(o.fieldValues)) + "]");
}
}
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
// TODO: returns empty first, but not empty last
static List splitAt(String s, String splitter) {
List parts = new ArrayList();
int i = 0;
if (s != null)
while (i < l(s)) {
int j = indexOf(s, splitter, i);
if (j < 0) j = l(s);
parts.add(substring(s, i, j));
i = j+l(splitter);
}
return parts;
}
static String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static boolean structure_isMarker(String s, int i, int j) {
if (i >= j) return false;
if (s.charAt(i) != 'm') return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static Object newObject(Class c, Object... args) {
return nuObject(c, args);
}
static Object newObject(String className, Object... args) {
return nuObject(className, args);
}
static List reTok(List tok) {
replaceCollection(tok, javaTok(tok));
return tok;
}
static List reTok(List tok, int i) {
return reTok(tok, i, i+1);
}
static List reTok(List tok, int i, int j) {
// extend i to an "N" token
// and j to "C" (so j-1 is an "N" token)
i = i & ~1;
j = j | 1;
List t = javaTok(join(subList(tok, i, j)));
replaceListPart(tok, i, j, t);
// fallback to safety
// reTok(tok);
return tok;
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static HashMap getDeclaredFields_cache = new HashMap();
static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized(getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields)
f.setAccessible(true);
}
}
return fields;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List pat, List tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList(pat); // We're modifying it, so copy first
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i+1, ""); // doesn't matter
}
return match2_match(pat, tok);
}
static String[] match2_match(List pat, List tok) {
List result = new ArrayList