Warning : session_start(): open(/var/lib/php/sessions/sess_086dnkhj5e09nju329qpg5a660, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import org.pushingpixels.substance.api.*;
import org.pushingpixels.substance.api.skin.*;
import java.awt.datatransfer.StringSelection;
public class main {
static boolean killDB = false;
static int defaultMax = 1000; // steps to run
static String facts = "\n We want to find out what is more correct than what.\n \n \"not correct\" is a candidate.\n \"maybe quite correct\" is a candidate.\n \"really really correct\" is a candidate.\n \"buggy\" is a candidate.\n \"total garbage\" is a candidate.\n \"incorrect\" is a candidate.\n \"almost correct\" is a candidate.\n \"absolutely correct\" is a candidate.\n \"very correct\" is a candidate.\n \n [nfhwfngqkgoqtngs] (no question) and (X is a candidate.) and (Y is a candidate.) and (X <> Y) and (There is no answer to (Is X # more correct than Y?).) => (Ask (Is X # more correct than Y?))\n // Note: The # is just a filler for parsing, we'll get rid of that in time. Also, you will be able to write stuff without brackets of course.\n \n Always apply rule nfhwfngqkgoqtngs.\n \n // Interpret answers\n [iprphzfmwithvdfb] (The answer to (Is X # Y than Z?) is (yes).) => (X is Y than Z.)\n Always apply rule iprphzfmwithvdfb.\n [udsmtmbiedmxtxci] (The answer to (Is X # Y than Z?) is (no).) => (Z is Y than X.)\n Always apply rule udsmtmbiedmxtxci.\n \n // Transitivity!\n [pglcuchrtxdmlfvh] (X is AA than Y.) and (Y is AA than Z.) => (X is AA than Z.)\n Always apply rule pglcuchrtxdmlfvh.\n \n [ijziyiplzanfwvqx] (Ask (X)) and (The answer to (X) is (Y).) => (Remove (Ask (X)))\n Always apply rule ijziyiplzanfwvqx.\n \n no question :- There is no statement with operator fxxathfdlfzgmaov.\n \n // Just a pretty-printing statement\n omrvwjslbkffaxoj hszwyiyetuuhcfwz acwmbrxqrlaplyqu\n";
static String concepts = "\n ufzlismnlhvbjqoj - (X) and (Y) and (Z) and (AA) and (AB) => (AC)\n phkdhqkhzytkwdpb - (X) and (Y) and (Z) and (AA) => (AB)\n txsysipmstxmjhmi - (X) and (Y) => (Z)\n wziyypnyayfphdxs - (X) => (Y)\n xikyminwmeahxiws - There is no answer to (X).\n pxavyqesoqyqbipb - The answer to (X) is (Y).\n cdzttdbxadjreorm - We want to find out what is X than what.\n ogqdgzepqbunuuht - X is a candidate.\n hszwyiyetuuhcfwz - Is X # Y than Z?\n acwmbrxqrlaplyqu - Is \"X\" Y than \"Z\"?\n qgxjwufpfzkqvmxb - X is Y than Z.\n ylvaoplzguvhegka - X is not Y than Z.\n zxucpbfzmexohoiv - It is not true that (X).\n buahjsodljsaxvaq - X <> Y\n fxxathfdlfzgmaov - Ask (X)\n chjllkocfhtwcgoj - Remove (X)\n mzdvauejerzefagk - I don't know if (X)\n omrvwjslbkffaxoj - Format operator X as template Y.\n houyieutcmfdvgmz - Execute (X)\n hzmtabxcmkrtffgh - Apply X\n zvknqzxlrmuobnzx - Always apply rule X.\n plprefzezbluijrw - no question\n jexyjrtbtilmsmfw - setQuestion(X)\n cuutddpitkuswthu - While (X) => (Y)\n sicrogpdrtkiptun - X :- Y\n zhoulgsatpswstfa - There is no statement with operator X.\n ltyqczktgtjxrtlf - more correct\n zveeggveflecjwvr - total garbage\n wolealpbqkkqkvqq - not correct\n tomkbzlqlpeiekvu - maybe quite correct\n dnxyynujqydgcxcd - really really correct\n trajdgvqepyhsumb - buggy\n lwikikhkydtewtjc - incorrect\n muxjpepnjiyjghwj - almost correct\n wtnpjovqqiswlyay - absolutely correct\n bmliokweerblfxco - very correct\n";
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 Map> evaluators = new HashMap();
static Lisp currentQuestion;
public static void main(final String[] args) throws Exception { typeWriterConsole();
centerHigherConsole();
substance();
// customize parsing and printing
hygienicParse1_unquote = true;
hygienicParse1_debug = true;
englishToConceptLanguage_simple_noXYZ = true;
formatXYZ_quotedVars = true;
// load predefined & learned statements
useConceptsAndStatements(concepts, facts);
if (killDB) deleteDB();
db();
for (MyTruth t : list(MyTruth.class))
lispAddLocalTruth(t.globalID, t.term);
printLispStatements();
// create evaluators
// X <> Y
evaluators.put("buahjsodljsaxvaq", new F1() {
Boolean get(Lisp l) {
return l.size() == 2 && neq(l.get(0), l.get(1));
}
});
// I don't know if (X)
evaluators.put("mzdvauejerzefagk", new F1() {
Boolean get(Lisp l) {
return l.size() == 1 && notKnownIf(l.get(0));
}
});
// There is no statement with operator X.
evaluators.put("zhoulgsatpswstfa", new F1() {
Boolean get(Lisp l) {
return l.size() == 1 && !hasTruthWithHead(l.raw(0));
}
});
// There is no answer to (X).
evaluators.put("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"))
evaluators.put(rule.raw(0), new F1() {
Boolean get(Lisp l) {
return l.isLeaf() && matchCondition(rule.get(1));
}
});
bot();
//applyRule("nfhwfngqkgoqtngs");
//applyAlwaysRules();
//runInstruction("yrgkrfrcwubpevzu");
}
static String answer(String s) {
final Matches m = new Matches();
if (match("lisp", s)) { printLispStatements(); return "ok"; }
if (match("print", s)) { printPrettyFacts(); return "ok"; }
if (match("rule *", s, m)) { applyRule(m.unq(0)); return "ok"; }
if (match("step", s)) { applyAlwaysRules_step(); return "ok"; }
if (match("run", s)) { applyAlwaysRules(defaultMax); return "ok"; }
if (match("force", s)) { force(defaultMax); return "ok"; }
return null;
}
static void showQuestion() {
List l = lispTruth1("fxxathfdlfzgmaov");
if (l(l) > 1) warn("Multiple open questions");
if (nempty(l)) {
final Lisp q = first(l).get(0);
if (eq(currentQuestion, q)) return;
currentQuestion = q;
print("Question: " + q);
{ swingAndWait(new Runnable() { public void run() { try {
showControls2(
centerAndSouth(
withBottomMargin(jcenteredBoldLabel(lispToEnglish_prettier(q))),
jcenteredline(answerButton("Yes"), answerButton("No"), answerButton("I don't know"))));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showControls2(\n centerAndSouth(\n withBottomMargin(jcenteredBoldL..."; }}); }
}
}
static void runInstruction(String instructionID) {
Lisp rule = getLispTruth(instructionID);
if (rule == null) { print("Instruction not found: " + instructionID); return; }
runInstruction(rule);
}
static void runInstruction(Lisp rule) {
print("runInstruction: " + rule);
if (rule.is("hzmtabxcmkrtffgh", 1)) // Apply X
applyRule(rule.raw(0));
else if (rule.is("cuutddpitkuswthu", 2)) { // While (X) => (Y)
while (ping() && matchCondition(rule.get(0)))
runInstruction(rule.get(1));
} /*else if (rule.is("houyieutcmfdvgmz", 1))
execute(rule.get(0));
/*else if (rule.is("jexyjrtbtilmsmfw", 1)) // setQuestion(X)
setQuestion(rule.get(0));*/
else print("Unknown instruction type: " + rule);
}
static void applyRule(String ruleID) {
// process the rule
Lisp rule = getLispTruth(ruleID);
if (rule == null) { print("Rule not found: " + ruleID); return; }
//print("Applying rule " + ruleID);
print_setPrefixForThread(ruleID + "> ");
try {
List conditions = dropLast(rule.args);
Lisp out = last(rule.args);
//for (Lisp cond : conditions) print("Condition: " + cond);
Map matches = new HashMap();
int n = matchConditions_random(conditions, matches);
if (n == -1) {
print("Yo! " + struct(matches));
out = lispReplaceVars(out, matches);
if (lispTrue(out))
print("Already had: " + out);
else {
print("Defining: " + lispToEnglish_prettier(out));
emit(out, ruleID);
}
} else
print("Only " + n + " of " + n(conditions, "condition") + " met");
} finally {
print_setPrefixForThread("");
}
}
// 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 boolean matchCondition(Lisp condition) {
print("matchCondition " + condition);
Object evaluator = evaluators.get(condition.head);
if (evaluator != null)
return isTrue(callF(evaluator, condition));
return lispTrue(condition);
}
static boolean matchCondition_random(Lisp condition, Map m) {
List facts = lispTruth();
Object evaluator = evaluators.get(condition.head);
if (evaluator != null)
return isTrue(callF(evaluator, lispReplaceVars(condition, m)));
List> candidates = new ArrayList();
for (Lisp fact : facts) {
Map m2 = cloneMap(m);
if (lispMatchIC_xyzVars_sub(condition, fact, m2))
candidates.add(m2);
}
//print("Have " + n(candidates, "candidate"));
if (empty(candidates)) return false;
m.putAll(random(candidates));
return true;
}
static void force(long steps) {
for (long step = 0; step < steps; step++)
applyAlwaysRules_step();
}
static void applyAlwaysRules(long maxSteps) {
long count = 0, step = 0;
do {
count = lispChangeCount();
applyAlwaysRules_step();
} while (++step < maxSteps && lispChangeCount() != count);
}
static void applyAlwaysRules_step() {
for (Lisp l : lispTruth1("zvknqzxlrmuobnzx"))
applyRule(l.raw(0)); // TODO: not only random application
for (Lisp l : lispTruth1("chjllkocfhtwcgoj")) { // Remove (X)
unemit(l);
unemit(l.get(0));
}
for (Lisp l : lispTruth1("hzmtabxcmkrtffgh")) { // Apply X
unemit(l);
applyRule(l.raw(0));
}
showQuestion();
}
static void emit(Lisp l, String madeByRule) {
LispStatement s = lispAddLocalTruth(l);
if (s != null)
new MyTruth(s.globalID, l, madeByRule);
}
static void unemit(Lisp l) {
LispStatement s = findLispStatement(l);
if (s == null) return;
removeLispStatement(s);
deleteConcepts(MyTruth.class, "globalID" , s.globalID);
}
static JButton answerButton(final String text) {
return jbutton(text, new Runnable() { public void run() { try {
emit(lisp("pxavyqesoqyqbipb", currentQuestion, englishToLisp(text)), "button");
applyAlwaysRules(defaultMax);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "emit(lisp(\"pxavyqesoqyqbipb\", currentQuestion, englishToLisp(text)), \"button\");\n..."; }});
}
// hygienic parsing
static String englishToConceptLanguage(String s) {
Lisp l = assertNotNull(hygienicParse1(s));
return clUnparse(l);
}
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 JComponent showControls2_controls;
static void showControls2(final JComponent controls) {
{ swingAndWait(new Runnable() { public void run() { try {
hideControls2();
JComponent _controls = withMargin(controls);
showControls2_controls = _controls;
addToConsole3(showControls2_controls);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "hideControls2();\r\n JComponent _controls = withMargin(controls);\r\n showCont..."; }}); }
}
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 LispStatement findLispStatement(Lisp l) {
for (LispStatement s : lispStatementsByHead(l.head))
if (eq(s.term, l)) return s;
return null;
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
static boolean empty(Map map) {
return map == null || map.isEmpty();
}
static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean 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 void centerHigherConsole() {
if (headless()) return;
setConsoleHeight(600);
centerConsole();
}
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);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static void printPrettyFacts() {
printNumberedLines(map(new Object() { Object get(LispStatement s) { try { return
"[" + s.globalID + "] " + lispToEnglish_prettier(s.term)
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "\"[\" + s.globalID + \"] \" + lispToEnglish_prettier(s.term)"; }}, values(lispStatements_cached())));
print();
}
static long lispChangeCount() {
ThoughtSpace ts = thoughtSpace();
if (ts != null) return ts.changes;
return lispChange_count.get();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
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 lispTruth1(String... heads) {
List out = new ArrayList();
for (Lisp l : lispTruthByHead(heads))
if (l.size() == 1) out.add(l);
return out;
}
static List lispTruth2(String... heads) {
List out = new ArrayList();
for (Lisp l : lispTruthByHead(heads))
if (l.size() == 2) out.add(l);
return out;
}
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;
}
// 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 boolean hasTruthWithHead(String... heads) {
return nempty(lispStatementsByHead(heads));
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
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 boolean warn_on = true;
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
static void deleteDB() {
deleteAllConceptsOfProgram(dbProgramID());
}
static Lisp getLispTruth(String id) {
LispStatement s = lispStatements_cached().get(id);
return s == null ? null : s.term;
}
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 void deleteConcepts(List conceptsOrIDs) {
mainConcepts.deleteConcepts(conceptsOrIDs);
}
static List deleteConcepts(Class c, Object... params) {
List l = findConceptsWhere(c, params);
deleteConcepts(l);
return l;
}
static JPanel jcenteredline(Component... components) {
//ret new CenteredLine(components);
return jFullCenter(hstackWithSpacing(components));
}
static JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
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 int bot(String greeting) {
return makeBot(greeting);
}
static Android3 bot(Android3 a) {
return makeBot(a);
}
static Android3 bot(String greeting, Object responder) {
return makeBot(greeting, responder);
}
static Android3 bot() {
return makeBot();
}
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); } }
// 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 JPanel centerAndSouth(Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
return oneOf(asList(c));
}
static boolean notKnownIf(Lisp l) {
// check fact and negation
return !lispTrue(l)
&& !lispTrue(lisp("zxucpbfzmexohoiv", l));
}
// 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 void useConceptsAndStatements(String concepts, String statements) {
useConcepts(concepts);
useFacts(statements);
}
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 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 void substance() {
substanceLAF();
}
static void substance(String skinName) {
substanceLAF(skinName);
}
static Map _registerThread_threads = synchroMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static void print_setPrefixForThread(final String prefix) {
interceptPrintInThisThread(empty(prefix) ? null
: new _PrintIndent(prefix));
}
static List lispTruth() {
return collect(values(lispStatements_cached()), "term");
}
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 String n(long l, String name) {
return l + " " + (l == 1 ? singular(name) : getPlural(name));
}
static String n(Collection l, String name) {
return n(l(l), name);
}
static String n(Map m, String name) {
return n(l(m), name);
}
static String n(Object[] a, String name) {
return n(l(a), name);
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static boolean lispMatchIC_xyzVars_debug;
static Map lispMatchIC_xyzVars(Lisp pat, Lisp nl) {
Map matches = new HashMap();
return lispMatchIC_xyzVars_sub(pat, nl, matches) ? matches : null;
}
// put additional vars in m with value = null
static boolean lispMatchIC_xyzVars_sub(Lisp pat, Lisp nl, Map m) {
if (pat == null || nl == null) return false;
if (pat.isLeaf() && (isXYZVar(pat.head) || m.containsKey(pat.head))) {
if (lispMatchIC_xyzVars_debug) print("Var: " + pat.head + " => " + nl);
return lispMatchIC_xyzVars_putMatch(m, pat.head, nl);
}
if (neqic(pat.head, nl.head)) return false;
// heads identical, proceed to children
int n = pat.size();
if (n != nl.size()) return false;
for (int i = 0; i < n; i++) {
if (lispMatchIC_xyzVars_debug) print("Sub " + i + ": " + pat.get(i) + " => " + nl.get(i));
if (!lispMatchIC_xyzVars_sub(pat.get(i), nl.get(i), m))
return false;
}
return true;
}
static boolean lispMatchIC_xyzVars_putMatch(Map matches, String key, Lisp val) {
Lisp oldValue = matches.get(key);
if (oldValue != null) {
if (!lispEqic(oldValue, val))
return false;
//fail("multi-matching not implemented");
} else
matches.put(key, val);
return true;
}
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 Lisp lispForward(String relation, Lisp argument) {
return first(followForwardRelation(relation, argument));
}
static JLabel jcenteredBoldLabel(String text) {
JLabel l = jboldLabel(text);
l.setHorizontalAlignment(JLabel.CENTER);
return l;
}
static JLabel jcenteredBoldLabel() {
return jcenteredBoldLabel("");
}
static void db() {
conceptsAndBot();
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static int withBottomMargin_defaultWidth = 6;
static JPanel withBottomMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withBottomMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
p.add(c);
return p;
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static String dropFirst(int n, String s) {
return substring(s, n);
}
static String aGlobalID() {
return randomID(16);
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static boolean neqic(String a, String b) {
return !eqic(a, b);
}
static void interceptPrintInThisThread(F1 f) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
print_byThread.set(f);
}
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 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 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 JLabel jboldLabel(String text) {
return makeLabelBold(jlabel(text));
}
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);
}
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);
}
// 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 Thread currentThread() {
return Thread.currentThread();
}
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 List getPlural_specials = ll("sheep", "fish");
static String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s)) return s;
if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
static 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 void useConcepts(String concepts) {
useConceptsDump(concepts);
}
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 Lisp chooseBestArgumentHygiene(List l) {
Best best = new Best();
for (Lisp x : l)
best.put(x, lisp_roundBracketHygieneScore(x));
return best.get();
}
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 String getType(Object o) {
return getClassName(o);
}
static List lispTruthByHead(String... heads) {
return collect(lispStatementsByHead(heads), "term");
}
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine");
static String singular(String s) {
if (s == null) return null;
{ String _a_1 = singular_specials.get(s); if (!empty(_a_1)) return _a_1; }
if (singular_specials2.contains(dropSuffix("s", s)))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static String conceptToNameOpt(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null ? null : unnull(c.name);
}
static List printNumberedLines(List l) {
printNumberedLines((Collection ) l);
return l;
}
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 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 void setConsoleHeight(int h) {
setFrameHeight(consoleFrame(), h);
}
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 hideControls2() {
{ swingAndWait(new Runnable() { public void run() { try {
removeFromConsole3(showControls2_controls);
showControls2_controls = null;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "removeFromConsole3(showControls2_controls);\r\n showControls2_controls = null;"; }}); }
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(getProgramTitle() + ".");
}
static 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 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 Lisp lispFromJavaTok(String s) {
List tok = javaTokC(s);
if (empty(tok)) return lisp("");
else return lisp(first(tok), dropFirst(tok));
}
static boolean lispEqic(Lisp a, Lisp b) {
if (a == null) return b == null;
if (neqic(a.head, b.head)) return false;
int n = l(a.args);
if (n != l(b.args)) return false;
for (int i = 0; i < n; i++)
if (!lispEqic(a.args.get(i), b.args.get(i))) return false;
return true;
}
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;
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
callFunction(action);
}});
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n if (action != null)\r\n btn.addActionLi..."; }});
}
// c = JComponent or something implementing swing()
static JComponent wrap(Object swingable) {
if (swingable == null) return null;
JComponent c = (JComponent) ( swingable instanceof JComponent ? swingable : callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane)
return new JScrollPane(c);
return c;
}
static List ll(A... a) {
return litlist(a);
}
static void deleteAllConceptsOfProgram(String progID) {
deleteFile(getProgramFile(progID, "concepts.structure"));
deleteFile(getProgramFile(progID, "concepts.structure.gz"));
}
static JPanel jFullCenter(Component c) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
}
static ArrayList toList(A[] a) { return asList(a); }
static ArrayList toList(int[] a) { return asList(a); }
static ArrayList toList(Set s) { return asList(s); }
static ArrayList toList(Iterable s) { return asList(s); }
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static String oneOf(String... l) {
return oneOf(asList(l));
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 Object mc() {
return getMainClass();
}
static boolean isXYZVar(String s) { return formatXYZ_varToIndex(s) != 0; }
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static String formatXYZ_appendRest(String pattern, List args) {
List tok = javaTokC(pattern);
List restArgs = cloneList(args);
for (int idx : (List) reverseSorted(map("formatXYZ_varToIndex_maybeQuoted", tok)))
remove(restArgs, idx-1);
return join(" ", concatLists(
ll(formatXYZ(pattern, args)),
restArgs));
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static List sortByArgumentHygiene(List l) {
IdentityHashMap scores = new IdentityHashMap();
for (Lisp x : l)
scores.put(x, lisp_roundBracketHygieneScore(x));
return sortByDescScore(l, scores);
}
static String lispForwardRawOrSame(String relation, String argument) {
return or(lispForwardRaw(relation, argument), argument);
}
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;
}
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 String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static List collect(Collection c, String field) {
return collectField(c, field);
}
static AtomicLong lispChange_count = new AtomicLong();
static void lispChange() {
lispChange_count.incrementAndGet();
}
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 Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length-n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static void centerConsole() {
centerConsoleFrame();
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static String substanceLAF_defaultSkin = "Creme";
static void substanceLAF() {
substanceLAF(null);
}
static void substanceLAF(String skinName) {
try {
enableSubstance_impl(or2(skinName, substanceLAF_defaultSkin));
} catch (Throwable __e) { printStackTrace2(__e); }
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static int hstackWithSpacing_spacing = 10;
// first part can be spacing value
static JPanel hstackWithSpacing(Object... parts) {
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(Box.createRigidArea(new Dimension(0, 0)), gbc);
return panel;
}
public static String unquote(String s) {
if (s == null) return null;
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
return s; // not quoted - return original
}
static A or(A a, A b) {
return a != null ? a : b;
}
static String conceptQuote(String s) {
if (isIdentifier(s) || isInteger(s) || isProperlyQuoted(s)) return s;
return quote(s);
}
static String dbProgramID() {
return getDBProgramID();
}
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 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;
IdentityHashMap seen = new IdentityHashMap();
BitSet refd = new BitSet();
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
Class conceptClass = findClass("Concept");
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) {
final PrintWriter out = d.out;
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
String name = c.getName();
String dynName = shortDynamicClassName(o);
boolean concept = d.conceptClass != null && d.conceptClass.isInstance(o);
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.refd.set(ref);
d.append("t").app(ref); return;
}
ref = d.n; //d.seen.size()+1;
if (d.shareStringsLongerThan < Integer.MAX_VALUE || !(o instanceof String))
d.seen.put(o, ref);
//d.append("m").app(ref).app(" "); // marker
if (o instanceof String) {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, ref);
quoteToPrintWriter(s, out); d.n++; return;
}
if (o instanceof HashSet) {
d.append("hashset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof Collection && neq(name, "main$Concept$RefL")) {
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack...."; }});
return;
}
if (o instanceof Map) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
if (o instanceof Lisp) {
d.append("l(", 2);
final Lisp lisp = (Lisp) ( o);
structure_1(lisp.head, d);
final Iterator it = lisp.args.iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append(")");
else {
d.stack.add(this);
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\")\");\r\n else {\r\n d...."; }});
return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
while (c != Object.class) {
for (Field field : getDeclaredFields_cached(c)) {
if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
c = c.getSuperclass();
}
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
}
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null)
fv.put(f.getName(), value);
}
String shortName = dropPrefix("main$", name);
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = dynName;
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else {\r..."; }});
}
static boolean headless() {
return isHeadless();
}
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 void addToConsole3(Component toAdd) {
JFrame frame = consoleFrame();
if (frame == null) return;
Container cp = frame.getContentPane();
Container cp2 = (Container) getCenterComponent(cp);
Container cp3 = (Container) getCenterComponent(cp2);
replaceCenterComponent(cp2, centerAndSouth(cp3, toAdd));
validateFrame(frame);
}
static void ensureBotIsNotAlreadyRunning(String name) {
if (hasBot(name))
throw fail("Bot already running [" + name + "]");
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
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;
}
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('"');
}
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 void replaceCenterComponent(Container container, Component c) {
Component old = getCenterComponent(container);
if (old != null)
container.remove(old);
container.add(c, BorderLayout.CENTER);
}
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 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 String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
static HashSet litset(A... items) {
return lithashset(items);
}
// 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 String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
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));
}
// Substance
// Trident (required by Substance)
static void enableSubstance_impl(final String skinName) { swingAndWait(new Runnable() { public void run() { try {
if (!substanceLookAndFeelEnabled())
enableSubstance_impl_2(skinName);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!substanceLookAndFeelEnabled())\r\n enableSubstance_impl_2(skinName);"; }}); }
static void enableSubstance_impl_2(String skinName) { try {
ClassLoader cl = main.class.getClassLoader();
UIManager.getDefaults().put("ClassLoader", cl);
Thread.currentThread().setContextClassLoader(cl);
String skinClassName = "org.pushingpixels.substance.api.skin." + addSuffix(skinName, "Skin");
SubstanceSkin skin = (SubstanceSkin) nuObject(cl.loadClass(skinClassName));
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
updateLookAndFeelOnAllWindows();
if (substanceLookAndFeelEnabled())
print("Substance L&F enabled.");
else
print("Could not enable Substance L&F?");
} catch (Exception __e) { throw rethrow(__e); } }
static List linesToCL(String text) {
return listToCL(linesToCL_prepare(text));
}
static List linesToCL_prepare(String text) {
return toLinesFullTrim_java(text);
}
static String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : 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;
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;
static List javaTok(String s) {
return javaTok(s, null);
}
static List javaTok(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTok(join(tok), tok);
}
static boolean javaTok_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static 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 Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static List collectField(Collection c, String field) {
List l = new ArrayList();
for (Object a : c)
l.add(getOpt(a, field));
return l;
}
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 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 HashMap getDeclaredFields_cache = new HashMap();
static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized(getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields)
f.setAccessible(true);
}
}
return fields;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
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 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 Cache> loadTruth_cached_cache = new Cache("loadTruth");
static List loadTruth_cached() {
return loadTruth_cached_cache.get();
}
static void loadTruth_clearCache() {
loadTruth_cached_cache.clear();
}
static void loadTruth_clearCache(double seconds) {
loadTruth_cached_cache.clear(seconds);
}
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { printStackTrace2(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && makeAndroid3_consoleInUse()) a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
if (!a.quiet)
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() { try {
List history = new ArrayList();
String line;
while ((line = readLine()) != null) {
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { printStackTrace2(__e); } }
};
startThread(_t_0); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
print("> " + shorten(originalAnswer, a.answerPrintLimit));
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static JLabel makeLabelBold(final JLabel l) {
if (l != null) { swingAndWait(new Runnable() { public void run() { try {
l.setFont(l.getFont().deriveFont(Font.BOLD));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "l.setFont(l.getFont().deriveFont(Font.BOLD));"; }}); }
return l;
}
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();
}
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 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 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 String getProgramTitle() {
return getProgramName();
}
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 void removeFromConsole3(Component c) {
JFrame frame = getFrame(c);
if (frame == null) return;
Container cp = frame.getContentPane(); // This is our BorderLayout
Container cp2 = (Container) getCenterComponent(cp);
Container cp3 = (Container) getCenterComponent(cp2);
if (cp3 != c.getParent()) { print("removeFromConsole3 fail"); return; }
cp3.remove(c); // free our component
Container mainC = (Container) cp3.getComponents()[0];
cp3.remove(mainC);
replaceCenterComponent(cp2, mainC);
validateFrame(frame);
}
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 List tok_groupRoundBrackets(String s) {
List tok = javaTok(s);
while (true) {
int i = tok.lastIndexOf("(");
if (i < 0) return tok;
int j = indexOf(tok, ")", i);
if (j < 0) return tok;
tok.set(i, join(subList(tok, i, j+1)));
tok.subList(i+1, j+1).clear();
assertTrue(odd(l(tok)));
}
}
static void centerConsoleFrame() {
centerFrame(consoleFrame());
}
static void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static String lines(List lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static A postProcess(Object f, A a) {
return callPostProcessor(f, a);
}
static boolean deleteFile(File file) {
return file != null && file.delete();
}
static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
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 void validateFrame(Component c) {
revalidateFrame(c);
}
static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
static Responder makeResponder(final Object bot) {
if (bot instanceof Responder) return (Responder) bot;
return new Responder() {
String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
static A popLast(List l) {
return liftLast(l);
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static List reverseSorted(Collection c, final Object comparator) {
return sortedDesc(c, comparator);
}
static List reverseSorted(Collection c) {
return sortedDesc(c);
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
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;
}
static List sortByDescScore(Collection c, Map map) {
List l = cloneList(c);
sort(l, mapComparatorDesc(map));
return l;
}
static String shorten(String s, int max) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
static String shorten(int max, String s) { return shorten(s, max); }
static String dropPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
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 HashMap findClass_cache = new HashMap();
// currently finds only inner classes of class "main"
// returns null on not found
// this is the simple version that is not case-tolerant
static Class findClass(String name) {
synchronized(findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name)) return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
// collects into l
// 1 billion entries are enough for everyone
static Collector listCollector(final Collection l) {
return limitedListCollector(l, 1024*1024*1024);
}
static Component wrapForSmartAdd(Object o) {
if (o == null) return new JPanel();
if (o instanceof String) return jlabel((String) o);
return wrap(o);
}
static ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
static JFrame setFrameHeight(JFrame frame, int h) {
frame.setSize(frame.getWidth(), h);
return frame;
}
static JFrame setFrameHeight(int h, JFrame frame) {
return setFrameHeight(frame, h);
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static int max(int a, int b) {
return Math.max(a, b);
}
static int max(int a, int b, int c) {
return max(max(a, b), c);
}
static long max(int a, long b) {
return Math.max((long) a, b);
}
static long max(long a, long b) {
return Math.max(a, b);
}
static double max(int a, double b) {
return Math.max((double) a, b);
}
static float max(float a, float b) {
return Math.max(a, b);
}
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static String getDBProgramID_id;
static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programID();
}
static List javaTokC(String s) {
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(quickSubstring(s, i, j));
i = j;
}
return tok;
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static 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 List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++)
if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static Component getCenterComponent(Container container) {
return ((BorderLayout) container.getLayout()).getLayoutComponent(BorderLayout.CENTER);
}
static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static void quoteToPrintWriter(String s, PrintWriter out) {
if (s == null) { out.print("null"); return; }
out.print('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"') {
out.print('\\'); out.print(c);
} else if (c == '\r')
out.print("\\r");
else if (c == '\n')
out.print("\\n");
else
out.print(c);
}
out.print('"');
}
static List filterConcepts(List list, Object... params) {
List l = new ArrayList();
for (A x : list)
if (checkConceptFields(x, params))
l.add(x);
return l;
}
// extended over Class.isInstance() to handle primitive types
static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class) return arg instanceof Boolean;
if (type == int.class) return arg instanceof Integer;
if (type == long.class) return arg instanceof Long;
if (type == float.class) return arg instanceof Float;
if (type == short.class) return arg instanceof Short;
if (type == char.class) return arg instanceof Character;
if (type == byte.class) return arg instanceof Byte;
if (type == double.class) return arg instanceof Double;
return type.isInstance(arg);
}
static 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 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;
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static Android3 dbBot() {
return dbBot(dbBotStandardName());
}
static Android3 dbBot(String name) {
ensureBotIsNotAlreadyRunning(name);
assertNotNull(mainConcepts);
return methodsBot2(name, mainConcepts, exposedDBMethods, mainConcepts.lock);
}
static JLabel jlabel(String text) {
final JLabel l = new JLabel(text) {
@Override
public void setText(String text) {
super.setText(text);
setToolTipText(text);
}
};
componentPopupMenu(l, new Object() { void get(JPopupMenu menu) { try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(l.getText());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(l.getText());"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(l.get..."; }});
return l;
}
static JLabel jlabel() {
return jlabel(" ");
}
static String dbBotStandardName() {
return dbBotName(getDBProgramID()) + ".";
}
static ImageIcon imageIcon(String imageID) { try {
return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(BufferedImage img) {
return new ImageIcon(img);
}
static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
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 int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
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 int isAndroid_flag;
static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
static int stdcompare(String a, String b) {
return cmp(a, b);
}
static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
static List record_list = synchroList();
static void record(Object o) {
record_list.add(o);
}
static Throwable printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static void printStackTrace(String indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace(e));
}
static void removeFromMultiPort(long vport) {
if (vport == 0) return;
for (Object port : getMultiPorts())
call(port, "removePort", vport);
}
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 File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (f == null)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
static Object addToMultiPort_responder;
static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List history) {
String answer = (String) ( callOpt(getMainClass(), "answer", s, history));
if (answer != null) return answer;
answer = (String) callOpt(getMainClass(), "answer", s);
if (answer != null) return answer;
if (match3("get injection id", s))
return getInjectionID();
return null;
}
});
}
static long addToMultiPort(final String botName, final Object responder) {
//print(botName);
addToMultiPort_responder = responder;
startMultiPort();
List ports = getMultiPorts();
if (ports == null) return 0;
if (ports.isEmpty())
throw fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
Object responder2 = new Object() {
public String answer(String s, List history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
};
record(responder2);
return (Long) call(port, "addResponder", botName, responder2);
}
static A liftLast(List l) {
if (l.isEmpty()) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
static String programID;
static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static boolean hasBracketHygiene(String s, String op, String close, Var msg) {
return testBracketHygiene(s, op, close, msg);
}
static boolean hasBracketHygiene(String s, String op, String close) {
return testBracketHygiene(s, op, close, null);
}
static JFrame centerFrame(JFrame frame) {
frame.setLocationRelativeTo(null); // magic trick
return frame;
}
static class componentPopupMenu_Maker {
List menuMakers = new ArrayList();
}
static Map componentPopupMenu_map = new WeakHashMap();
static ThreadLocal componentPopupMenu_mouseEvent = new ThreadLocal();
// menuMaker = voidfunc(JPopupMenu)
static void componentPopupMenu(final JComponent component, final Object menuMaker) {
swingNowOrLater(new Runnable() { public void run() { try {
componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);
if (maker == null) {
componentPopupMenu_map.put(component, maker = new componentPopupMenu_Maker());
component.addMouseListener(new componentPopupMenu_Adapter(maker));
}
maker.menuMakers.add(menuMaker);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "componentPopupMenu_Maker maker = componentPopupMenu_map.get(component);\n if (..."; }});
}
static class componentPopupMenu_Adapter extends MouseAdapter {
componentPopupMenu_Maker maker;
componentPopupMenu_Adapter(componentPopupMenu_Maker maker) {
this.maker = maker;}
public void mousePressed(MouseEvent e) { displayMenu(e); }
public void mouseReleased(MouseEvent e) { displayMenu(e); }
void displayMenu(MouseEvent e) {
if (e.isPopupTrigger()) displayMenu2(e);
}
void displayMenu2(MouseEvent e) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
componentPopupMenu_mouseEvent.set(e);
for (Object menuMaker : maker.menuMakers)
pcallF(menuMaker, menu);
// show menu if any items in it
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
static boolean flexMatchIC2_left_debug;
static boolean flexMatchIC2_left(String pat, String s) {
return flexMatchIC2_left(pat, s, null);
}
static boolean flexMatchIC2_left(String pat, String s, Matches m) {
return flexMatchIC2_left(javaTok(pat), javaTok_cached(unnull(s)), m);
}
static boolean flexMatchIC2_left(String pat, String s, Matches m, boolean joinBrackets) {
return flexMatchIC2_left(javaTok(pat), javaTok_cached(unnull(s)), m, joinBrackets);
}
static boolean flexMatchIC2_left(List tokpat, List tokfull, Matches m) {
return flexMatchIC2_left(tokpat, tokfull, m, true);
}
static boolean flexMatchIC2_left(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_left_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_left_impl(List pat, int ipat, List tok, int itok, BitSet bla, BitSet bla2) {
if (flexMatchIC2_left_debug)
print("flexMatchIC2_left 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)
bla.set(itok);
if (itok < l(tok)) {
if (flexMatchIC2_left_debug) print("Trying one or more tokens");
if (flexMatchIC2_left_impl(pat, ipat, tok, itok+1, bla, bla2)) {
if (flexMatchIC2_left_debug) print("Success!");
return true; // success, leave mark
}
}
bla.clear(itok); // fail, undo marking
if (flexMatchIC2_left_debug) print("Trying zero tokens");
if (flexMatchIC2_left_impl(pat, ipat+1, tok, itok, bla, bla2)) {
if (flexMatchIC2_left_debug) print("Success!");
return true;
}
if (flexMatchIC2_left_debug) print("Failed * matching");
return false;
}
if (itok >= l(tok)) {
if (flexMatchIC2_left_debug)
print("too much pattern");
return false;
}
if (eq(t, "!*")) { // the single-token wildcard
bla.set(itok);
if (flexMatchIC2_left_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_left_debug)
print("flexMatchIC2_left precheck " + t + " " + realt);
if (!containsIgnoreCase(t, realt)) return false;
// real check
List list = splitAt(dropFirstAndLast(t), "|");
if (flexMatchIC2_left_debug)
print("flexMatchIC2_left real check " + struct(list));
if (!containsIgnoreCase(list, realt)) return false;
bla2.set(itok);
} else if (neqic(realt, t)) {
if (flexMatchIC2_left_debug)
print("mismatch");
return false;
}
// it is a token match. consume and proceed
if (flexMatchIC2_left_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 Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static String copyTextToClipboard(String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
return text;
}
// class Matches is added by #752
static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static boolean match3(String pat, String s, Matches matches) {
if (s == null) return false;
return match3(pat, parse3_cached(s), matches);
}
static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3(pat);
return match3(tokpat,toks,matches);
}
static boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null) return false;
if (matches != null) matches.m = m; return true;
}
static A setToolTipText(final A c, final Object toolTip) {
if (c == null) return null;
{ swingAndWait(new Runnable() { public void run() { try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ..."; }}); }
return c;
}
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;
}
// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
if (s.startsWith("'") || s.startsWith("\"")) return true;
if (!s.startsWith("[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
//return Pattern.compile("^\\[=*\\[").matcher(s).find();
}
static Set aggressivelyCollectPossibleGlobalIDs(String s) {
LinkedHashSet ids = new LinkedHashSet();
if (s == null) return ids;
for (int i = 0; i < l(s); i++) {
int j = i;
while (j < l(s) && Character.isLowerCase(s.charAt(j))) ++j;
if (j-i == 16)
ids.add(substring(s, i, j));
i = j;
}
return ids;
}
static String getInjectionID() {
return (String) call(getJavaX(), "getInjectionID", getMainClass());
}
static List reverseIndexesOf(List l, A a) {
return reverseList(indexesOf(l, a));
}
static String dbBotName(String progID) {
return fsI(progID) + " Concepts";
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
// 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 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;
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
// 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 AtomicInteger dialogServer_clients = new AtomicInteger();
static boolean dialogServer_printConnects;
static Set dialogServer_knownClients = synchroTreeSet();
static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler))
++port;
return port;
}
static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true))
++port;
return port;
}
static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
static ServerSocket startDialogServer_serverSocket;
static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// probably the port number is used - let's assume there already is a chat server.
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) { public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
// This should be the same as #1001076 (talkTo)
boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
boolean isStillConnected() {
return !(eos || s.isClosed());
}
void sendLine(String line) { try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) { throw rethrow(__e); } }
String readLineImpl() { try {
return in.readLine();
} catch (Exception __e) { throw rethrow(__e); } }
void close() {
try {
s.close();
} catch (IOException e) {
// whatever
}
}
Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
//print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
}
}
}; // Thread t2
t2.setDaemon(true); // ?
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}};
if (daemon) thread.setDaemon(true);
thread.start();
print("Dialog server on port " + port + " started.");
return true;
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static String shortClassName(Object o) {
if (o == null) return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
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 programID() {
return getProgramID();
}
static Comparator mapComparatorDesc(final Map map) {
return new Comparator () {
public int compare(A a, A b) {
return cmp(map.get(b), map.get(a));
}
};
}
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 BufferedReader readLine_reader;
static String readLine() {
return (String) call(getJavaX(), "readLine");
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
// does not store null values
static Map indexByField(Collection c, String field) {
HashMap map = new HashMap();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
map.put(val, a);
}
return map;
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static 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 Set followForwardRelation_raw(String relation, String argument) {
return rawOnly(followForwardRelation(relation, argument));
}
static Set followForwardRelation_raw(String relation, Lisp argument) {
return rawOnly(followForwardRelation(relation, argument));
}
static TreeSet collectTreeSet(Collection c, String field) {
TreeSet set = new TreeSet();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
set.add(val);
}
return set;
}
static void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(r);
} catch (Exception __e) { throw rethrow(__e); } }
static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() { public void run() { try {
result.set(callF(f));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }});
return result.get();
}
}
static byte[] boolArrayToBytes(boolean[] a) {
byte[] b = new byte[(l(a)+7)/8];
for (int i = 0; i < l(a); i++)
if (a[i])
b[i/8] |= 1 << (i & 7);
return b;
}
static boolean substanceLookAndFeelEnabled() {
return startsWith(getLookAndFeel(), "org.pushingpixels.");
}
static void aiEnhancements() {
conceptLanguageToolTips();
}
static boolean odd(int i) {
return (i & 1) != 0;
}
static void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static boolean isJavaIdentifier(String s) {
if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static boolean endsWithIgnoreCase(String a, String b) {
return a != null && l(a) >= l(b) && a.regionMatches(true, l(a)-l(b), b, 0, l(b));
}
static String addSuffix(String s, String suffix) {
return s.endsWith(suffix) ? s : s + suffix;
}
static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static int cmp(String a, String b) {
return a == null ? b == null ? 0 : -1 : a.compareTo(b);
}
static int cmp(Object a, Object b) {
if (a == null) return b == null ? 0 : -1;
if (b == null) return 1;
return ((Comparable) a).compareTo(b);
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static List toLinesFullTrim_java(String text) {
return toLinesFullTrim(joinLines(map("javaDropComments", toLinesFullTrim(text))));
}
static A callPostProcessor(Object f, A a) {
return f == null ? a : (A) callF(f, a);
}
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 String parse3_cached_s;
static List parse3_cached_l;
static synchronized List parse3_cached(String s) {
if (neq(s, parse3_cached_s))
parse3_cached_l = parse3(parse3_cached_s = s);
return parse3_cached_l;
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
// works on lists and strings and null
static int indexOfIgnoreCase(Object a, Object b) {
if (a == null) return -1;
if (a instanceof String) {
Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a);
if (m.find()) return m.start(); else return -1;
}
if (a instanceof List) {
for (int i = 0; i < ((List) a).size(); i++) {
Object o = ((List) a).get(i);
if (o != null && ((String) o).equalsIgnoreCase((String) b))
return i;
}
return -1;
}
throw fail("Unknown type: " + a);
}
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 void updateLookAndFeelOnAllWindows() {
for (Window window : Window.getWindows())
SwingUtilities.updateComponentTreeUI(window);
renewConsoleFrame();
}
static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
for (int i = startIndex; i < l(l); i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
static String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static