Warning: session_start(): open(/var/lib/php/sessions/sess_g3tud429b57nnetd84lebp6rno, 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.*;
public class main {
static class PNGFile extends Concept {}
static PNGFile fastLoadPNGFile(Object o) { return null; }
static String questions = "\n Is your product software?\n Is your product hardware?\n Is your product a fluffy penguin?\n";
static String facts = "\n My product is a C compiler\n A C compiler is software\n";
static String rules = "\n Always: (Q: Is your product X?) & (My product is Y) & (Y is X) => A: Yes\n Always: (Q: X) & (There is no statement with operator nywfcwkkcknzhmdy.) => A: I don't know\n\n anmjmlkwmjbzbiss - Always: X\n ufzlismnlhvbjqoj - (X) and (Y) and (Z) and (AA) and (AB) => (AC)\n phkdhqkhzytkwdpb - (X) and (Y) and (Z) and (AA) => (AB)\n cntevdawguaaxqmn - (X) and (Y) and (Z) => (AB)\n eijdjqhyzheusetj - (X) and (Y) and (Z) => (AA)\n jkbzwuwirpbvfzhy - (X) & (Y) & (Z) => AA\n mwpbetwhkuuuupws - X and Y and Z => AA\n txsysipmstxmjhmi - (X) and (Y) => (Z)\n cuutddpitkuswthu - While (X) => (Y)\n kecvwixuouqlpzhu - (X) and (Y) => Z\n tusgcjefvtgebzba - (X) & (Y) => Z\n wziyypnyayfphdxs - (X) => (Y)\n chkfkshhwshoauan - X => Y\n mcoswmplpqlieruo - (X)\n zhoulgsatpswstfa - There is no statement with operator X.\n \n vouwrrhtmajsgaby - Q: X\n nywfcwkkcknzhmdy - A: X\n \n ypenmdohuvmyfabd - Is your product X?\n wcwlqvvrpdwjzfms - X is Y\n kxlzhendchftgjqh - No X where (Y)\n zhahnerfmvfdqkxd - It's X\n zqxoghyhhhfgziob - I don't know\n";
public static void main(final String[] args) throws Exception {
myTruthNonPersist(facts + rules);
lispSolveQuestionsVerbose(questions);
}
static void myTruthNonPersist(String bla) {
myTruth_persistent = false;
myTruth(bla);
}
static void lispSolveQuestionsVerbose(String questions) {
for (String q : toLinesFullTrim_java(questions))
lispSolveQuestionVerbose(q);
}
static Map _registerThread_threads = synchroMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static boolean myTruth_verbose, myTruth_persistent = true;
static class MyTruth extends Concept {
static String _fieldOrder = "globalID term madeByRule globalID term";
String globalID;
Lisp term;
String madeByRule;
MyTruth() {}
MyTruth(String globalID, Lisp term, String madeByRule) {
this.madeByRule = madeByRule;
this.term = term;
this.globalID = globalID; change(); }
}
static void loadMyTruth() {
tt();
if (myTruth_persistent) db();
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 List toLinesFullTrim_java(String text) {
return toLinesFullTrim(joinLines(map("javaDropComments", toLinesFullTrim(text))));
}
static void lispSolveQuestionVerbose(String q) {
Lisp l = englishToLisp(q);
print(q);
openThoughtSpace();
fromUser(lisp("vouwrrhtmajsgaby", l)); // emit question
//set applyAlwaysRules_step_debug;
applyRules();
printEnglishStatements(lispTruth1("nywfcwkkcknzhmdy"));
//printLispStatements();
thoughtSpace(null);
}
static void tt() {
typeWriterConsole();
}
// 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 joinLines(List lines) {
return fromLines(lines);
}
static String joinLines(String glue, String text) {
return join(glue, toLines(text));
}
static LispStatement findLispStatement(Lisp l) {
for (LispStatement s : lispStatementsByHead(l.head))
if (eq(s.term, l)) return s;
return null;
}
static void printEnglishStatements(List l) {
for (Lisp x : unnull(l))
printIndent(lispToEnglish(x));
}
static Lisp englishToLisp(String s) {
return clParse(englishToConceptLanguage(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 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 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 void useConceptsAndStatements(String concepts, String statements) {
useConcepts(concepts);
useFacts(statements);
}
static ThoughtSpace openThoughtSpace() {
ThoughtSpace ts = new ThoughtSpace();
ts.addLispStatements(values(lispStatements_cached()));
thoughtSpace(ts);
return ts;
}
static List lispTruth1(String... heads) {
List out = new ArrayList();
for (Lisp l : lispTruthByHead(heads))
if (l.size() == 1) out.add(l);
return out;
}
// 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 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 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 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 void applyRules() {
applyAlwaysRules();
}
static void applyRules(long maxSteps) {
applyAlwaysRules(maxSteps);
}
static LispStatement getLispStatement(String statementID) {
return lispStatements_cached().get(statementID);
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 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 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 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 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 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 Object mc() {
return getMainClass();
}
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;
}
});
}
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));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
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 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);
}
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 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 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 lispTruthByHead(String... heads) {
return collect(lispStatementsByHead(heads), "term");
}
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 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 String lispToEnglish(Lisp l) {
return lispToEnglish_prettier(l);
}
static List printNumberedLines(List l) {
int i = 0;
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(mc()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
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;
}
// usually L
static String fromLines(List 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 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)"; }}));
}
// get purpose 1: access a list/array (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// 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 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 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 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;
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
try {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
return loadTextFile(fileName.getPath(), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static 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 Pair pair(A a, B b) {
return new Pair(a, b);
}
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 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 A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static long lispChangeCount() {
ThoughtSpace ts = thoughtSpace();
if (ts != null) return ts.changes;
return lispChange_count.get();
}
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);
}
// 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();
}
static F1 f1_const(final B b) {
return new F1() {
B get(A a) { return b; }
};
}
// 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 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 void ai() {
aiEnhancements();
}
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 Lisp lispReplaceVars(Lisp l, Map map) {
if (l.isLeaf()) {
Lisp x = map.get(l.head);
if (x != null) return x;
}
Lisp x = lisp(l.head);
for (Lisp a : l.args)
x.add(lispReplaceVars(a, map));
return x;
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
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);
}
// 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 Map> addLispEvaluator_map = new HashMap();
static void addLispEvaluator(String head, F1 evaluator) {
addLispEvaluator_map.put(head, (F1) evaluator);
}
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 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