Warning : session_start(): open(/var/lib/php/sessions/sess_tgdpcg5jo21fbo6etg5tgjrae6, 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.*;
class main {
static String bla = "\n Always fully apply ((Concept X was touched at Y.) and (Concept X was touched at Z.) and (Y > Z) => (Remove (Concept X was touched at Z.)))\n \n cwvffbyvwmafomuq - Concept X was touched at Y.\n anmgnlmdnkjivliq - Always fully apply (X)\n chjllkocfhtwcgoj - Remove (X)\n eijdjqhyzheusetj - (X) and (Y) and (Z) => (AA)\n wdbphzfoxwlrhdyl - X > Y\n";
public static void main(final String[] args) throws Exception { typeWriterConsole();
centerHigherConsole();
// Set-up & quick evaluator check
myTruth(bla);
assertTrue(callLispEvaluator(englishToLisp("5 > 3")));
assertFalse(callLispEvaluator(englishToLisp("3 > 5")));
// Add information & think
emit_english("Concept cwvffbyvwmafomuq was touched at " + now() + ".");
applyAlwaysRules(100);
// Print
//printLispStatements();
printEnglishStatements();
}
static void centerHigherConsole() {
if (headless()) return;
setConsoleHeight(600);
centerConsole();
}
static void emit_english(String s) {
emit(englishToLisp(s));
}
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 void printEnglishStatements(List l) {
for (Lisp x : unnull(l))
printIndent(lispToEnglish(x));
}
static void printEnglishStatements() {
printEnglishStatements(lispTruth());
}
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 long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static Map _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static long applyAlwaysRules_defaultSteps = 1000;
static void applyAlwaysRules() {
applyAlwaysRules(applyAlwaysRules_defaultSteps);
}
static void applyAlwaysRules(long maxSteps) {
long count = 0, step = 0;
do {
count = lispChangeCount();
applyAlwaysRules_step();
} while (++step < maxSteps && lispChangeCount() != count);
}
static boolean myTruth_verbose, myTruth_persistent = true;
static void loadMyTruthFrom(String dbProgramID) {
loadConceptsFrom(dbProgramID);
loadMyTruth2();
}
static void loadMyTruth() {
if (myTruth_persistent) db();
loadMyTruth2();
}
static void loadMyTruth2() {
tt();
englishToConceptLanguage_hygienicParsing = true;
for (MyTruth t : list(MyTruth.class))
lispAddLocalTruth(t.globalID, t.term);
}
static void myTruth(String bla) {
Pair p = splitConceptsFromStatements(bla);
myTruth(p.a, p.b);
}
static void myTruth(String concepts, String statements) {
useConceptsAndStatements(concepts, statements);
loadMyTruth();
aiStandardHandlers();
printLispStatements();
}
static void fromUser(String head, Object... args) { fromUser(lisp(head, args)); }
static void fromUser(Lisp l) { emit(l, "user"); }
static void emit(Lisp l) { emit(l, ""); }
static void emit(Lisp l, String madeByRule) {
ThoughtSpace ts = thoughtSpace();
if (ts != null) {
ts.addStatement(l);
return;
}
LispStatement s = lispAddLocalTruth(l);
if (s != null) {
new MyTruth(s.globalID, l, madeByRule);
if (myTruth_verbose)
print("emit> " + l);
}
}
static void unemit(Lisp l) {
ThoughtSpace ts = thoughtSpace();
if (ts != null) {
//print("Unemitting from " + ts.globalID + ": " + l);
ts.removeStatement(l);
return;
}
LispStatement s = findLispStatement(l);
if (s == null) return;
removeLispStatement(s);
deleteConcepts(MyTruth.class, "globalID" , s.globalID);
}
static void unemit(String statementID) {
ThoughtSpace ts = thoughtSpace();
if (ts != null) {
ts.removeStatement(statementID);
return;
}
LispStatement s = getLispStatement(statementID);
if (s == null) return;
removeLispStatement(s);
deleteConcepts(MyTruth.class, "globalID" , s.globalID);
}
static Lisp englishToLisp(String s) {
return clParse(englishToConceptLanguage(s));
}
static Object callLispEvaluator(Lisp l) {
F1 e = getLispEvaluator(l.head);
if (e == null) return null;
return e.get(l);
}
static void tt() {
typeWriterConsole();
}
static void centerConsole() {
centerConsoleFrame();
}
static void centerConsole(int w, int h) {
setConsoleSize(w, h);
centerConsoleFrame();
}
static String lispToEnglish(Lisp l) {
return lispToEnglish_prettier(l);
}
// return new statement or null if it existed
static LispStatement lispAddLocalTruth(Lisp l) {
if (lispTrue(l)) return null;
return lispAddLocalTruth_noCheck(aGlobalID(), l);
}
static LispStatement lispAddLocalTruth(String id, Lisp l) {
if (lispTrue(l)) return null;
return lispAddLocalTruth_noCheck(id, l);
}
static LispStatement lispAddLocalTruth_noCheck(String id, Lisp l) {
LispStatement s = new LispStatement(id, l);
lispStatements_cached().put(id, s);
lispChange();
return s;
}
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 LispStatement findLispStatement(Lisp l) {
for (LispStatement s : lispStatementsByHead(l.head))
if (eq(s.term, l)) return s;
return null;
}
static void printIndent(Object o) {
print(indentx(str(o)));
}
static void printIndent(String indent, Object o) {
print(indentx(indent, str(o)));
}
static void printIndent(int indent, Object o) {
print(indentx(indent, str(o)));
}
static void setConsoleHeight(int h) {
setFrameHeight(consoleFrame(), h);
}
static long lispChangeCount() {
ThoughtSpace ts = thoughtSpace();
if (ts != null) return ts.changes;
return lispChange_count.get();
}
static boolean englishToConceptLanguage_dropPunctuation;
static boolean englishToConceptLanguage_hygienicParsing = true;
static String englishToConceptLanguage(String s) {
if (englishToConceptLanguage_hygienicParsing) {
Lisp l = hygienicParse1(s);
if (l != null) return clUnparse(l);
}
{ 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 printLispStatements() {
printNumberedLines(map(new Object() { Object get(LispStatement s) { try { return
"[" + s.globalID + "] " + s.term
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "\"[\" + s.globalID + \"] \" + s.term"; }}, values(lispStatements_cached())));
print();
}
static void useConceptsAndStatements(String concepts, String statements) {
useConcepts(concepts);
useFacts(statements);
}
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, Collection args) {
return new Lisp(head, args);
}
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 List lispTruth() {
return collect(values(lispStatements_cached()), "term");
}
static Map applyAlwaysRules_handlers = new HashMap();
static boolean applyAlwaysRules_step_debug;
// for handlers
static ThreadLocal applyAlwaysRules_ruleID = new ThreadLocal();
static void applyAlwaysRules_step() {
List statements = lispStatements_cloned();
if (applyAlwaysRules_step_debug)
print("applyAlwaysRules_step: " + struct(statements));
for (LispStatement s : statements) {
Lisp l = s.term;
Object handler = applyAlwaysRules_handlers.get(l.head);
if (handler != null) {
applyAlwaysRules_ruleID.set(s.globalID);
if (applyAlwaysRules_step_debug)
print("Calling handler for " + l.head);
try {
callF(handler, /*lispSingleChildOrFull*/(l));
} finally {
applyAlwaysRules_ruleID.set(null);
}
}
}
}
static boolean headless() {
return isHeadless();
}
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); }
static ThreadLocal thoughtSpace_byThread = new ThreadLocal();
// get for current thread
static ThoughtSpace thoughtSpace() {
return thoughtSpace_byThread.get();
}
// set for current thread
static ThoughtSpace thoughtSpace(ThoughtSpace ts) {
thoughtSpace_byThread.set(ts);
return ts;
}
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 Object print_byThread_lock = new Object();
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) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(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 LispStatement getLispStatement(String statementID) {
return lispStatements_cached().get(statementID);
}
static void deleteConcepts(List conceptsOrIDs) {
mainConcepts.deleteConcepts(conceptsOrIDs);
}
static List deleteConcepts(Class c, Object... params) {
List l = findConceptsWhere(c, params);
deleteConcepts(l);
return l;
}
static void aiStandardHandlers() {
alwaysRules_standardHandlers();
lispStandardEvaluators();
lispStandardExecutors();
}
static Pair splitConceptsFromStatements(String text) {
List a = new ArrayList();
List b = new ArrayList();
for (String s : toLinesFullTrim_java(text)) {
List tok = javaTokC(s);
if (possibleGlobalID(get(tok, 0)) && eq(get(tok, 1), "-"))
a.add(s);
else
b.add(s);
}
return pair(joinLines(a), joinLines(b));
}
static F1 getLispEvaluator(String head) {
return addLispEvaluator_map.get(head);
}
static void removeLispStatement(LispStatement s) {
if (s == null) return;
ThoughtSpace ts = thoughtSpace();
if (ts != null) {
ts.removeStatement(s);
return;
}
lispStatements_cached().remove(s.globalID);
lispChange();
}
static void db() {
conceptsAndBot();
}
static String aGlobalID() {
return randomID(16);
}
static String struct(Object o) {
return structure(o);
}
static String lispToEnglish_prettier(Lisp l) {
if (l == null) return "";
String pattern = conceptToNameOpt(lispForwardRawOrSame("omrvwjslbkffaxoj", l.head));
if (empty(pattern)) return clUnparse(l);
List args = map("lispToEnglish_prettier", l.args);
String s = formatXYZ_appendRest(pattern, args);
return s;
}
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 {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static List lispStatements_cloned() {
return cloneList(values(lispStatements_cached()));
}
static WeakHashMap> callF_cache = new WeakHashMap();
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) throw fail("No get method in " + getClassName(c));
if (n == 1) return 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 String joinLines(List lines) {
return fromLines(lines);
}
static String joinLines(String glue, String text) {
return join(glue, toLines(text));
}
static boolean hygienicParse1_debug, hygienicParse1_unquote;
static Lisp hygienicParse1(String s) {
if (hygienicParse1_debug)
print("Parsing: " + s);
// Simple case first
String id = englishToConceptLanguage_simple(s);
if (id != null) return lisp(id);
// Now the pattern matching
List parses = englishToLisp_multi(s);
if (hygienicParse1_debug) {
int i = 0;
for (Lisp l : sortByArgumentHygiene(parses))
printIndent((++i) + ". " + l + " [" + lisp_roundBracketHygieneScore(l) + "]");
}
Lisp l = chooseBestArgumentHygiene(parses);
return l == null ? lispFromJavaTok(s) : hygienicParse1_sub(l);
}
// parse the arguments which are original strings
static Lisp hygienicParse1_sub(Lisp l) {
if (l == null || l.isLeaf()) return l;
Lisp x = lisp(l.head);
for (Lisp a : l.args) {
if (hygienicParse1_unquote) a = lisp(unquote(a.raw()));
x.add(or(hygienicParse1(a.raw()), a));
}
return x;
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static void lispStandardEvaluators() {
// True
addLispEvaluator("zivsiiacmvqrolto", main.f1_const(Boolean.TRUE));
// Not (X)
addLispEvaluator("wynynoujiakixjus", new F1() {
Boolean get(Lisp l) {
return !isTrue(callLispEvaluator(l.get(0)));
}
});
// X <> Y
addLispEvaluator("buahjsodljsaxvaq", new F1() {
Boolean get(Lisp l) {
return l.size() == 2 && neq(l.get(0), l.get(1));
}
});
// X > Y
addLispEvaluator("wdbphzfoxwlrhdyl", new F1() {
Boolean get(Lisp l) {
return l.size() == 2 && eq(compareIfNotNull(lispToBigInt(l.get(0)), lispToBigInt(l.get(1))), 1);
}
});
// I don't know if (X)
addLispEvaluator("mzdvauejerzefagk", new F1() {
Boolean get(Lisp l) {
return l.size() == 1 && notKnownIf(l.get(0));
}
});
// There is no statement with operator X.
addLispEvaluator("zhoulgsatpswstfa", new F1() {
Boolean get(Lisp l) {
return l.size() == 1 && !hasTruthWithHead(l.raw(0));
}
});
// There is no answer to (X).
addLispEvaluator("xikyminwmeahxiws", new F1() {
Boolean get(Lisp l) {
boolean ok = l.size() == 1 && null == lispForward("pxavyqesoqyqbipb", l.get(0));
print("Checking for answer to " + l.get(0) + " => " + ok);
return ok;
}
});
// :- rules
for (final Lisp rule : lispTruth2("sicrogpdrtkiptun"))
addLispEvaluator(rule.raw(0), new F1() {
Boolean get(Lisp l) {
return l.isLeaf() && matchCondition_simple(rule.get(1));
}
});
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static String indentx(String s) {
return indentx(indent_default, s);
}
static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static void lispStandardExecutors() {
// (X)
lispEvaluator("mcoswmplpqlieruo", new F1() {
Boolean get(Lisp l) {
return isTrue(callLispEvaluator(l.get(0)));
}
});
// Assert (X).
lispExecutor("rzryqdohxtczvzgn", new Object() { void get(Lisp l) { try {
l = l.get(0);
if (!isTrue(callLispEvaluator(l)))
throw fail("Not true: " + l);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "l = l.get(0);\r\n if (!isTrue(callLispEvaluator(l)))\r\n fail(\"Not true: \" +..."; }});
// Make an empty thought space X.
lispExecutor("jamvyfwypzbptvle", new Object() { void get(Lisp l) { try {
String name = l.raw(0);
addThoughtSpace(new ThoughtSpace(name));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S name = l.raw(0);\r\n addThoughtSpace(new ThoughtSpace(name));"; }});
// X is empty (thought space)
lispEvaluator("yvmxaacduvvomgqi", new F1() {
Boolean get(Lisp l) {
return isEmpty(getThoughtSpace(l.raw(0)).statements);
}
});
// X contains Y (thought space)
lispEvaluator("unfiqixlxwqnomcs", new F1() {
Boolean get(Lisp l) {
return getThoughtSpace(l.raw(0)).containsStatement(l.get(1));
}
});
// Add (X) to Y. (thought space)
lispExecutor("matnhiruhwprdiir", new Object() { void get(Lisp l) { try {
getThoughtSpace(l.raw(1)).addStatement(l.get(0));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "getThoughtSpace(l.raw(1)).addStatement(l.get(0));"; }});
// Apply always rules in X. (thought space)
lispExecutor("bcypplfticghlkxy", new Object() { void get(Lisp l) { try {
thoughtSpace(getThoughtSpace(l.raw(0)));
try {
applyAlwaysRules(100);
//print("After always rules: " + struct(keys(thoughtSpace().statementsIndex)));
} finally {
thoughtSpace(null);
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "thoughtSpace(getThoughtSpace(l.raw(0)));\r\n try {\r\n applyAlwaysRules(100)..."; }});
// No X where Y
lispEvaluator(ll("bblhpfgfvcyjfwmd", "kxlzhendchftgjqh"), new F1() {
Boolean get(Lisp l) {
String var = l.raw(0), newVar = aGlobalID();
Lisp term = l.get(1);
Lisp newTerm = lispReplaceVars(term, litmap(var, lisp(newVar)));
//print("Evaluating negation: " + newVar + " - " + newTerm);
Map m = new HashMap();
m.put(newVar, null);
m = matchCondition_first(newTerm, m);
//print(" Result: " + struct(m));
return m == null;
}
});
}
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 List findConceptsWhere(Class c, Object... params) {
return filterConcepts(list(c), expandParams(c, params));
}
static List findConceptsWhere(String c, Object... params) {
return filterConcepts(list(c), params);
}
static List findConceptsWhere(Concepts concepts, Class c, Object... params) {
return filterConcepts(concepts.list(c), expandParams(c, params));
}
static List findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
static void typeWriterConsole() {
if (isHeadless()) return;
Font f = typeWriterFont();
consoleFont(f);
consoleInputFont(f);
}
static WeakAssoc, Map> lispStatements_cache = new WeakAssoc("statementsToLisp");
static Map lispStatements_global;
static Map lispStatements_cached() {
ThoughtSpace ts = thoughtSpace();
if (ts != null) return ts.statements;
if (lispStatements_global != null) return lispStatements_global;
return lispStatements_cache.get(loadTruth_cached());
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static void useConcepts(String concepts) {
useConceptsDump(concepts);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
// avoid XYZ vars in this step - seems useful, now on by default
static boolean englishToConceptLanguage_simple_noXYZ = true;
static String englishToConceptLanguage_simple(String s) {
for (AIConcept c : englishToConceptLanguage_concepts()) {
List tok = javaTokC(c.name);
if (tok.contains("*")) continue;
if (englishToConceptLanguage_simple_noXYZ && containsXYZVariables_c(tok)) continue;
if (match_noEllipsis(c.name, s))
return c.globalID;
}
return null;
}
static void alwaysRules_standardHandlers() {
// Remove (X)
addAlwaysRuleHandler("chjllkocfhtwcgoj", new Object() { void get(Lisp l) { try {
//print("Remove " + l.get(0) + ", ts=" + thoughtSpace());
unemit(l);
unemit(l.get(0));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "//print(\"Remove \" + l.get(0) + \", ts=\" + thoughtSpace());\r\n unemit(l);\r\n u..."; }});
// Always fully apply X
addAlwaysRuleHandler(ll("anmgnlmdnkjivliq", "anmjmlkwmjbzbiss"), new Object() { void get(Lisp l) { try {
l = l.get(0);
applyRule_all(l, applyAlwaysRules_ruleID());
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "l = l.get(0);\r\n applyRule_all(l, applyAlwaysRules_ruleID());"; }});
// Fire once: X - not try to apply once, but actually fire once
addAlwaysRuleHandler("wrqnygxvjvtpyiwc", new Object() { void get(Lisp l) { try {
String ruleID = applyAlwaysRules_ruleID();
//print("Trying to fire " + l.get(0));
if (applyRule_first(l.get(0), ruleID))
unemit(ruleID);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S ruleID = applyAlwaysRules_ruleID();\r\n //print(\"Trying to fire \" + l.get(0))..."; }});
}
static Map> addLispEvaluator_map = new HashMap();
static void addLispEvaluator(String head, F1 evaluator) {
addLispEvaluator_map.put(head, (F1) evaluator);
}
static boolean lispTrue(String head, Object... args) {
return lispTrue(lisp(head, args));
}
static boolean lispTrue(Lisp l) {
for (Lisp x : lispTruthByHead(l.head))
if (eq(x, l)) return true;
return false;
}
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)));
}
}
volatile static boolean conceptsAndBot_running;
static void conceptsAndBot() {
conceptsAndBot(null);
}
static void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running) return;
conceptsAndBot_running = true;
ensureBotIsNotAlreadyRunning(dbBotStandardName());
if (autoSaveInterval != null)
loadAndAutoSaveConcepts(autoSaveInterval);
else
loadAndAutoSaveConcepts();
dbBot();
}
static boolean englishToConceptLanguage_xyz_debug, englishToConceptLanguage_useBrackets = true;
static boolean englishToConceptLanguage_unquote;
static ThreadLocal englishToConceptLanguage_xyz_level = new ThreadLocal();
static String englishToConceptLanguage_xyz(String s, Object preprocess) {
assertNotNull("Input", s);
/*int level = englishToConceptLanguage_xyz_level.get();
if (level >= englishToConceptLanguage_xyz_maxLevel) fail("max level");
englishToConceptLanguage_xyz_level.set(level+1);
try {*/
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 name, String original, String s) {
if (englishToConceptLanguage_unquote) s = unquote(s);
if (l(s) >= l(original)) throw fail("Bad sub: " + quote(name) + " " + quote(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 (l(tok) < 2) return null;
//replace(tok, "*", "\\*");
if (tok.contains("*")) return null;
int n = numberOfXYZVars_c(tok);
if (n == 0) return null;
String pat = formatXYZ(name, rep(n, "*"));
boolean yes = flexMatchIC2(pat, s, m, false);
if (englishToConceptLanguage_xyz_debug && yes)
print("xyz: " + n + " " + pat + " - " + s + " => " + (yes ? struct(m) : "-"));
if (!yes) return null;
if (n != l(m.m)) return null;
TreeMap map = new TreeMap();
for (int i = 0; i < l(tok); i++) {
int x = xyzVarToIndex(tok.get(i));
if (x != 0)
map.put(i, englishToConceptLanguage_xyz_sub(name, s, m.m[x-1]));
}
return aiUsing(id) + " " + join(" ", values(map));
}
static List collect(Collection c, String field) {
return collectField(c, field);
}
static List collect(String field, Collection c) {
return collectField(c, field);
}
static List collect(Class c, String field) {
return collect(list(c), field);
}
static AtomicLong lispChange_count = new AtomicLong();
static void lispChange() {
lispChange_count.incrementAndGet();
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static List printNumberedLines(List l) {
printNumberedLines((Collection ) l);
return l;
}
static void printNumberedLines(Map map) {
printNumberedLines(mapToLines(map));
}
static Collection printNumberedLines(Collection l) {
int i = 0;
if (l != null) for (A a : l) print((++i) + ". " + str(a));
return l;
}
static void printNumberedLines(Object[] l) {
printNumberedLines(asList(l));
}
static void printNumberedLines(Object o) {
printNumberedLines(lines(str(o)));
}
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());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(ping_actions) {
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 Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static void centerConsoleFrame() {
centerFrame(consoleFrame());
}
static List lispStatementsByHead(final String... heads) {
return aiUsing(filter(values(lispStatements_cached()) , new Object() { Object get(LispStatement s) { try { return s.term.is(heads) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "s.term.is(heads)"; }}));
}
static List toLinesFullTrim_java(String text) {
return toLinesFullTrim(joinLines(map("javaDropComments", toLinesFullTrim(text))));
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
// get purpose 1: access a list/array/map (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;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : 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;
}
// 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 (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
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 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(callF(f, o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, 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(callF(f, e.getKey(), e.getValue()));
}
return x;
}
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 void setConsoleSize(int w, int h) {
setFrameSize(consoleFrame(), w, h);
}
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 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 List clUnparse(List l) {
return map("clUnparse", l);
}
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 boolean possibleGlobalID(String s) {
return l(s) == 16 && allLowerCaseCharacters(s);
}
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)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static int l(Lisp l) { return l == null ? 0 : l.size(); }
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static boolean aiUsing_enabled;
static Set aiUsing_set = synchroTreeSet();
static String aiUsing(String s) {
if (aiUsing_enabled)
aiUsing_set.addAll(aggressivelyCollectPossibleGlobalIDs(s));
return s;
}
static void aiUsing(Object o) {
// TODO
}
static List aiUsing(List l) {
if (aiUsing_enabled)
for (Object li : unnull(l)) aiUsing(li);
return l;
}
static Lisp aiUsing(Lisp l) {
if (aiUsing_enabled && 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 void useFacts(String facts) {
List statements = linesToCL(facts);
useFacts_cl(statements);
}
// use facts in CL
static void useFacts_cl(List statements) {
ai();
// trueStatements_cached_autoClearInterval = 0;
trueStatements_cached_cache.set(new LinkedHashSet(statements));
loadTruth_cached_cache.set(aiMakeStatements(statements));
}
static void useFacts_cl(String statements) {
useFacts_cl(toLinesFullTrim(statements));
}
static Font typeWriterFont() {
return typeWriterFont(14);
}
static Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static void ensureBotIsNotAlreadyRunning(String name) {
if (hasBot(name))
throw fail("Bot already running [" + name + "]");
}
static final HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) return callMC_value.invoke(null, args);
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
return me.invoke(null, args);
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return me.invoke(null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
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 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((int) (l(s)*1.5+2));
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('"');
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static BigInteger lispToBigInt(Lisp l) { return lispToInt(l); }
static Thread currentThread() {
return Thread.currentThread();
}
// 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 void ai() {
aiEnhancements();
}
static boolean isProperlyQuoted(String s) {
return s.length() >= 2
&& s.startsWith("\"")
&& s.endsWith("\"")
&& (!s.endsWith("\\\"") || s.endsWith("\\\\\""));
}
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 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 quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static List linesToCL(String text) {
return listToCL(linesToCL_prepare(text));
}
static List linesToCL_prepare(String text) {
return toLinesFullTrim_java(text);
}
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
static int numberOfXYZVars(String s) {
return numberOfXYZVars_c(javaTokC(s));
}
static int numberOfXYZVars_c(List ctok) {
int m = 0;
for (String t : ctok) m = max(m, xyzVarToIndex(t));
return m;
}
static int numberOfXYZVars(List tok) {
int m = 0;
for (int i = 1; i < l(tok); i += 2)
m = max(m, xyzVarToIndex(tok.get(i)));
return m;
}
// 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
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
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 JFrame centerFrame(Component c) {
JFrame frame = getFrame(c);
if (frame != null)
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_cached(unnull(s)), m);
}
static boolean flexMatchIC2(String pat, String s, Matches m, boolean joinBrackets) {
return flexMatchIC2(javaTok(pat), javaTok_cached(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 __javax;
static Class getJavaX() {
return __javax;
}
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 List collectField(Collection c, String field) {
List l = new ArrayList();
for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static Map matchCondition_first(Lisp condition, Map m) {
List facts = lispTruth();
Object evaluator = getLispEvaluator(condition.head);
if (evaluator != null)
return isTrue(callF(evaluator, lispReplaceVars(condition, m))) ? m : null;
List> candidates = new ArrayList();
for (Lisp fact : facts) {
Map m2 = cloneMap(m);
if (lispMatchIC_xyzVars_sub(condition, fact, m2))
return m2;
}
return null;
}
static Lisp lispFromJavaTok(String s) {
List tok = javaTokC(s);
if (empty(tok)) return lisp("");
else return lisp(first(tok), dropFirst(tok));
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static Lisp lispForward(String relation, Lisp argument) {
return first(followForwardRelation(relation, argument));
}
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 empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String s) { return s == null || s.length() == 0; }
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 empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] 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 boolean englishToLisp_multi_debug;
static boolean englishToLisp_multi_left = true;
static ThreadLocal englishToLisp_multi_level = new ThreadLocal();
static List englishToLisp_multi(String s) {
return englishToLisp_multi(s, null);
}
static List englishToLisp_multi(String s, Object preprocess) {
List c = new ArrayList();
englishToLisp_multi(listCollector(c), s, preprocess);
return c;
}
static void englishToLisp_multi(Collector out, String s, Object preprocess) {
assertNotNull("Input", s);
/*int level = englishToLisp_multi_level.get();
if (level >= englishToLisp_multi_maxLevel) fail("max level");
englishToLisp_multi_level.set(level+1);
try {*/
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);
englishToLisp_multi_with(out, c.globalID, name, s);
if (out.full()) return;
}
// no full string match. go word by word
/*
L tok = javaTok(s);
if (l(tok) <= 3) ret;
for (int i = 1; i < l(tok); i += 2) {
S x = englishToLisp(unquote(tok.get(i)));
if (nempty(x)) tok.set(i, conceptQuote(x));
}
S x = join(tok);
if (neq(x, s)) out.add(x);
*/
}
static void englishToLisp_multi_with(Collector out, String id, String name, String s) {
List originalTok = javaTok(name), tok = cloneList(originalTok);
if (l(tok) < 5) return; // need 2 code tokens
/*if (englishToLisp_multi_debug)
print("xyz name " + name + " originalTok1 " + struct(originalTok));*/
boolean stars = tok.contains("*");
if (stars)
tok = replace(tok, "*", "**");
/*if (englishToLisp_multi_debug)
print("xyz name " + name + " originalTok2 " + struct(originalTok));*/
int n = numberOfXYZVars(tok);
if (n == 0) return;
tok = formatXYZ(tok, rep(n, "*"));
List toks = javaTok_cached(s);
if (stars)
toks = replace(cloneList(toks), "*", "**");
for (Matches m : flexMatchIC2_left_multi(tok, toks)) {
if (englishToLisp_multi_debug)
print("xyz: " + n + " " + struct(tok) + " - " + struct(toks) + " => " + struct(m));
if (n != l(m.m)) return; // that's really wrong
TreeMap map = new TreeMap();
if (englishToLisp_multi_debug)
print("xyz originalTok " + struct(originalTok));
for (int i = 1; i < l(originalTok); i += 2) {
String t = originalTok.get(i);
int x = xyzVarToIndex(t);
if (englishToLisp_multi_debug)
print("xyz " + t + " => " + x);
if (x != 0) {
//S sub = english+ToConceptLanguage_multi_sub(name, s, m.m[x-1]);
String sub = m.m[x-1];
map.put(i, sub);
}
}
if (out.add(aiUsing(lisp(id, values(map))))) return;
}
}
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 List rep(int n, A a) {
return repeat(n, a);
}
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 boolean matchCondition_simple(Lisp condition) {
//print("matchCondition " + condition);
Object evaluator = getLispEvaluator(condition.head);
if (evaluator != null)
return isTrue(callF(evaluator, condition));
return lispTrue(condition);
}
static String lispForwardRawOrSame(String relation, String argument) {
return or(lispForwardRaw(relation, argument), argument);
}
static ArrayList list(A[] a) {
return asList(a);
}
static ArrayList list(int[] a) {
return asList(a);
}
static ArrayList list(Set s) {
return asList(s);
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static int lisp_roundBracketHygieneScore(Lisp l) {
if (l == null) return 0;
int score = 0;
for (Lisp arg : l)
if (arg.isLeaf() && !hasRoundBracketHygiene(arg.unq()))
--score;
return score;
}
static void lispExecutor(String head, Object executor) {
addLispExecutor(head, executor);
}
static List findAIConcepts(String ids) {
return findAIConcepts(javaTokC(ids));
}
static List findAIConcepts(Iterable ids) {
List l = new ArrayList();
for (Object id : ids)
if (id instanceof String)
addIfNotNull(l, aiConceptsMap_cached().get((String) id));
else if (id instanceof AIConcept)
l.add((AIConcept) id);
return l;
}
// usually L
static String fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines)
buf.append(str(line)).append('\n');
return buf.toString();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static void lispEvaluator(String head, F1 evaluator) {
addLispEvaluator(head, evaluator);
}
static void lispEvaluator(List heads, F1 evaluator) {
for (String head : heads)
addLispEvaluator(head, evaluator);
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static A postProcess(Object f, A a) {
return callPostProcessor(f, a);
}
static String conceptQuote(String s) {
if (isIdentifier(s) || isInteger(s) || isProperlyQuoted(s)) return s;
return quote(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 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 A setFrameSize(A c, int w, int h) {
JFrame f = getFrame(c);
if (f != null)
f.setSize(w, h);
return c;
}
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 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 int xyzVarToIndex(String s) { return formatXYZ_varToIndex(s); }
static boolean containsXYZVariables_c(List tokC) {
for (String t : tokC)
if (formatXYZ_varToIndex(t) != 0)
return true;
return false;
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static F1 f1_const(final B b) {
return new F1 () {
B get(A a) { return b; }
};
}
static void addAlwaysRuleHandler(String head, Object handler) {
applyAlwaysRules_handlers.put(head, handler);
}
static void addAlwaysRuleHandler(List heads, Object handler) {
for (String head : heads)
addAlwaysRuleHandler(head, handler);
}
static List cloneList(Collection l) {
if (l == null) return new ArrayList();
// assume collection's 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 Map litmap(Object... x) {
TreeMap map = new TreeMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static Lisp chooseBestArgumentHygiene(List l) {
Best best = new Best();
for (Lisp x : l)
best.put(x, lisp_roundBracketHygieneScore(x));
return best.get();
}
static List lispTruthByHead(String... heads) {
return collect(lispStatementsByHead(heads), "term");
}
static String conceptToNameOpt(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null ? null : unnull(c.name);
}
static List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map))
l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static boolean applyRule_all_debug;
static void applyRule_all(String ruleID) {
// process the rule
Lisp rule = getLispTruth(ruleID);
if (rule == null) { print("Rule not found: " + ruleID); return; }
//print("Applying rule " + ruleID);
if (applyRule_all_debug) print_setPrefixForThread(ruleID + "> ");
try {
applyRule_all(rule, ruleID);
} finally {
if (applyRule_all_debug) print_setPrefixForThread("");
}
}
static void applyRule_all(Lisp rule, String ruleID) {
List conditions = dropLast(rule.args);
Lisp out = last(rule.args);
//for (Lisp cond : conditions) print("Condition: " + cond);
List> results = matchConditions_all(conditions, new HashMap());
if (applyRule_all_debug) {
print("Got " + n(results, "results"));
if (empty(results))
print(" " + n(matchConditions_random(conditions, new HashMap()), "conditions") + " met of " + l(conditions));
}
for (Map matches : results) {
if (applyRule_all_debug) print("Yo! " + struct(matches));
out = lispReplaceVars(out, matches);
if (lispTrue(out)) {
if (applyRule_all_debug) print("Already had: " + out);
} else {
if (applyRule_all_debug) print("Defining: " + lispToEnglish_prettier(out));
emit(out, ruleID);
}
}
}
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 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 Integer compareIfNotNull(BigInteger a, BigInteger b) {
return a == null || b == null ? null : a.compareTo(b);
}
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 List ll(A... a) {
return litlist(a);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
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"));
ai();
}
static Class mc() {
return main.class;
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static String applyAlwaysRules_ruleID() {
return applyAlwaysRules_ruleID.get();
}
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, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
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) {
return a == null ? -1 : a.indexOf(b);
}
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;
}
static List filterConcepts(List list, Object... params) {
List l = new ArrayList();
for (A x : list)
if (checkConceptFields(x, params))
l.add(x);
return l;
}
static List lispTruth2(String... heads) {
List out = new ArrayList();
for (Lisp l : lispTruthByHead(heads))
if (l.size() == 2) out.add(l);
return out;
}
static List aiMakeStatements(List statements) {
return map(new Object() { Object get(String s) { try {
Statement st = unlisted(Statement.class);
String id = getGlobalIDPrefix(s);
if (id == null) {
st.globalID = aGlobalID();
st.text = s;
} else {
st.globalID = id;
st.text = dropGlobalIDPrefix(s);
}
return st;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Statement st = unlisted(Statement);\r\n S id = getGlobalIDPrefix(s);\r\n if (i..."; }}, statements);
}
static String formatXYZ_appendRest(String pattern, List args) {
List tok = javaTokC(pattern);
List restArgs = cloneList(args);
for (int idx : (List) reverseSorted(map("formatXYZ_varToIndex_maybeQuoted", tok)))
remove(restArgs, idx-1);
return join(" ", concatLists(
ll(formatXYZ(pattern, args)),
restArgs));
}
static boolean hasTruthWithHead(String... heads) {
return nempty(lispStatementsByHead(heads));
}
static List sortByArgumentHygiene(List l) {
IdentityHashMap scores = new IdentityHashMap();
for (Lisp x : l)
scores.put(x, lisp_roundBracketHygieneScore(x));
return sortByDescScore(l, scores);
}
static boolean match_noEllipsis(String pat, String s) {
return match_noEllipsis(pat, s, null);
}
static boolean match_noEllipsis(String pat, String s, Matches matches) {
String[] m = match2_match(parse3(pat), parse3_cached(s));
if (m == null) return false;
if (matches != null) matches.m = m; return true;
}
// returns true if it fired
static boolean applyRule_first(String ruleID) {
// process the rule
Lisp rule = getLispTruth(ruleID);
if (rule == null) { print("Rule not found: " + ruleID); return false; }
//print("Applying rule " + ruleID);
print_setPrefixForThread(ruleID + "> ");
try {
return applyRule_first(rule, ruleID);
} finally {
print_setPrefixForThread("");
}
}
// ruleID is just as an info parameter to emit()
static boolean applyRule_first(Lisp rule, String ruleID) {
List conditions = dropLast(rule.args);
Lisp out = last(rule.args);
List> results = matchConditions_all(conditions, new HashMap()); // can be optimized
//print("Got " + n(results, "results"));
if (empty(results)) return false;
Map matches = first(results);
//print("Yo! " + struct(matches));
out = lispReplaceVars(out, matches);
//print("Possibly defining: " + lispToEnglish_prettier(out));
emit(out, ruleID);
return true;
}
static void addThoughtSpace(ThoughtSpace ts) {
getThoughtSpace_map.put(ts.globalID, ts);
if (!aiConceptsMap_cached().containsKey(ts.globalID)) {
AIConcept c = unlisted(AIConcept.class);
c.globalID = ts.globalID;
c.name = "-> a thought space";
aiConceptsMap_cached().put(c.globalID, c);
}
}
static HashMap getThoughtSpace_map = new HashMap();
static ThoughtSpace getThoughtSpace(String name) {
return assertNotNull(getThoughtSpace_map.get(name));
}
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;
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection 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 String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static int indent_default = 2;
static String indent(int indent) {
return repeat(' ', indent);
}
static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
static String indent(String s) {
return indent(indent_default, s);
}
static List indent(String indent, List lines) {
List l = new ArrayList();
for (String s : lines)
l.add(indent + s);
return l;
}
static volatile Android3 dbBot_instance;
static Android3 dbBot() {
return dbBot(dbBotStandardName());
}
static Android3 dbBot(String name) {
ensureBotIsNotAlreadyRunning(name);
assertNotNull(mainConcepts);
return dbBot_instance = methodsBot2(name, mainConcepts, exposedDBMethods, mainConcepts.lock);
}
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 boolean notKnownIf(Lisp l) {
// check fact and negation
return !lispTrue(l)
&& !lispTrue(lisp("zxucpbfzmexohoiv", l));
}
static String dbBotStandardName() {
return dbBotName(getDBProgramID()) + ".";
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static boolean formatXYZ_quotedVars;
static String formatXYZ(String pattern, List args) {
return join(formatXYZ(javaTok(pattern), args));
}
// modifies tok!
static List formatXYZ(List tok, List args) {
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (formatXYZ_quotedVars && isQuoted(t)) {
int idx = formatXYZ_varToIndex(unquote(t))-1;
if (idx >= 0 && l(args) > idx)
tok.set(i, quote(args.get(idx)));
}
int idx = formatXYZ_varToIndex(t)-1;
if (idx >= 0 && l(args) > idx)
tok.set(i, args.get(idx));
}
return tok;
}
static String formatXYZ(String pattern, String... args) {
return formatXYZ(pattern, asList(args));
}
static Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static void consoleFont(Font font) {
callOpt(getConsoleTextArea_gen(), "setFont", font);
}
static A or(A a, A b) {
return a != null ? a : b;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
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 class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
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) {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof 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; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof 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;
}
String name = c.getName();
if (o instanceof Collection
&& !startsWith(name, "main$")
/* && 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())\r\n d.append(\"]\");\r\n else {\r\n d.stack...."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
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())\r\n d.append(\")\");\r\n else {\r\n d...."; }});
return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
String dynName = shortDynamicClassName(o);
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());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
cc = cc.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);
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
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 name = c.getName();
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 = shortDynamicClassName(o);
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()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else {\r..."; }});
}
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 void consoleInputFont(final Font f) {
{ swingAndWait(new Runnable() { public void run() { try {
JTextField input = consoleInputField();
if (input != null) {
input.setFont(f);
revalidateFrame(input);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JTextField input = consoleInputField();\r\n if (input != null) {\r\n input.s..."; }}); }
}
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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static Set followForwardRelation(String relation, String argument) {
return followForwardRelation(relation, lisp(argument));
}
static Set followForwardRelation(String relation, Lisp argument) {
HashSet out = new HashSet();
for (Lisp l : lispTruthByHead(relation))
if (eq(l.get(0), argument))
out.add(l.get(1));
return out;
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
// if match: returns -1
// if no match: returns how many conditions were met
static int matchConditions_random(List conditions, Map m) {
if (empty(conditions)) return -1;
Lisp condition = first(conditions);
Map m2 = cloneMap(m);
if (!matchCondition_random(condition, m2)) {
print("Condition failed: " + condition);
return 0;
}
print("Condition matched, " + struct(m2));
int n = matchConditions_random(dropFirst(conditions), m2);
if (n == -1) {
m.putAll(m2);
return -1;
}
return n+1; // failure
}
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 "'\\\\'";
if (c == '\r') return "'\\r'";
if (c == '\n') return "'\\n'";
if (c == '\t') return "'\\t'";
return "'" + c + "'";
}
static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static Lisp getLispTruth(String id) {
LispStatement s = lispStatements_cached().get(id);
return s == null ? null : s.term;
}
static boolean aiConceptsMap_fastLoad, aiConceptsMap_silent;
static List aiConceptsMap_list;
static Map aiConceptsMap() {
long time = sysNow();
List concepts = aiConceptsMap_fastLoad ? fastLoadAIConcepts() : loadAIConcepts();
aiConceptsMap_list = concepts;
Map map = indexByField(concepts, "globalID");
if (!aiConceptsMap_silent)
sysDone(time, "load ai concepts");
return map;
}
static String getType(Object o) {
return getClassName(o);
}
// 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 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 boolean hasRoundBracketHygiene(String s) {
return hasBracketHygiene(s, "(", ")");
}
static Map cloneMap(Map map) {
if (map == null) return litmap();
// assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(map) {
return map instanceof TreeMap ? new TreeMap(map)
: map instanceof LinkedHashMap ? new LinkedHashMap(map)
: new HashMap(map);
}
}
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 String n(long l, String name) {
return l + " " + trim(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 String lispForwardRaw(String relation, String argument) {
return first(followForwardRelation_raw(relation, argument));
}
static String lispForwardRaw(String relation, Lisp argument) {
return first(followForwardRelation_raw(relation, argument));
}
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 List flexMatchIC2_left_multi(List tokpat, List toks) {
List out = new ArrayList();
if (l(tokpat) == 7 && eq(tokpat.get(1), "*") && neq(tokpat.get(3), "*") && eq(tokpat.get(5), "*")) {
String middle = tokpat.get(3);
for (int i : reverseIndexesOf(toks, middle))
if (i > 1 && i < l(toks)-2)
out.add(new Matches(join(subList(toks, 1, i-1)), join(subList(toks, i+2, l(toks)-1))));
} else {
Matches m = new Matches();
if (flexMatchIC2_left(tokpat, toks, m, false))
out.add(m);
}
return out;
}
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
static String javaTok_cached_s;
static List javaTok_cached_l;
static synchronized List javaTok_cached(String s) {
if (neq(s, javaTok_cached_s))
javaTok_cached_l = javaTok(javaTok_cached_s = s);
return javaTok_cached_l;
}
static String getGlobalIDPrefix(String s) {
List tok = javaTok(s);
if (eq(get(tok, 1), "[") && eq(get(tok, 5), "]") && possibleGlobalID(get(tok, 3)))
return get(tok, 3);
return null;
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
if (startsWith(s, "'") || startsWith(s, "\"")) return true;
return isMultilineQuoted(s);
}
static int formatXYZ_varToIndex(String t) {
if (l(t) == 1 && eqOneOf(t, "X", "Y", "Z"))
return 1 + charDiff(t.charAt(0), 'X');
else if (l(t) == 2 && t.startsWith("A")) {
char c = t.charAt(1);
if (c >= 'A' && c <= 'Z')
return 4 + charDiff(t.charAt(1), 'A');
}
return 0;
}
static A last(List l) {
return l.isEmpty() ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static String dbBotName(String progID) {
return fsI(progID) + " Concepts";
}
// 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);
}
}
static List conceptsFromDump(String s) {
List < List < String > > l = new ArrayList();
if (neq(first(javaTokC(s)), "[")) {
for (String line : toLinesFullTrim(s)) {
int i = line.indexOf(" - ");
if (i > 0) {
String id = trim(substring(line, 0, i));
if (!possibleGlobalID(id)) warn("no id: " + id);
else
l.add(ll(id, trim(substring(line, i+3))));
}
}
} else
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 String dropGlobalIDPrefix(String s) {
List tok = javaTok(s);
if (eq(get(tok, 1), "[") && eq(get(tok, 5), "]") && possibleGlobalID(get(tok, 3)))
return join(subList(tok, 7));
return s;
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static void remove(Collection l, A a) {
if (l != null) l.remove(a);
}
static void addIfNotNull(Collection l, A a) {
if (a != null) l.add(a);
}
static List> matchConditions_all(List conditions) {
return matchConditions_all(conditions, new HashMap());
}
static List> matchConditions_all(List conditions, Map m) {
if (empty(conditions)) return ll(m);
Lisp condition = first(conditions);
List> candidates = matchCondition_all(condition, m);
if (empty(candidates)) return candidates; // first condition failed
LinkedHashSet < Map < String , Lisp > > results = new LinkedHashSet();
for (Map m2 : candidates)
results.addAll(matchConditions_all(dropFirst(conditions), m2));
return asList(results);
}
static boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2)
if (neq(cget(x, (String) data[i]), deref(data[i+1])))
return false;
return true;
}
static String makeRandomID(int length) {
Random random = new Random();
char[] id = new char[length];
for (int i = 0; i < id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static boolean containsIgnoreCase(List l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static JTextField consoleInputField() {
return (JTextField) getOpt(get(getJavaX(), "console"), "tfInput");
}
static boolean lispMatchIC_xyzVars_debug;
static Map