Warning : session_start(): open(/var/lib/php/sessions/sess_g3tud429b57nnetd84lebp6rno, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.*;
import java.awt.geom.*;
import java.awt.font.GlyphVector;
import java.awt.geom.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.swing.Timer;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
class main {
public static void main(final String[] args) throws Exception {
Web web = new Web();
WebNode a = web.node("abcd");
WebNode b = web.node("efgh");
web.getRelation(a, b).addLabel("leads to");
CirclesAndLines cal = webToCAL(web);
cal.show();
}
static boolean traits_multiLine = true;
static class WebToCAL {
BufferedImage img = newBufferedImage(20, 20, Color.white);
CirclesAndLines cal = new CirclesAndLines();
Map map = new HashMap();
//new Map, Line> lines;
String makeLabel(Lisp lisp) {
return conceptLanguageToEnglish(clUnparse(lisp));
}
void convert(Web web) {
List nodes = web.nodes;
nodes = listMinusSet(nodes, values(web.relations));
for (WebNode node : nodes) {
Circle c = cal.circle(img, cal_randomCircleCoord(), cal_randomCircleCoord(), makeLabel(first(node.labels)));
map.put(node, c);
for (Lisp l : dropFirst(node.labels))
c.addTrait(makeLabel(l));
}
for (Pair p : keys(web.relations)) {
WebNode rel = web.relations.get(p);
Circle a = map.get(p.a), b = map.get(p.b);
if (a == null || b == null) {
warn("webToCAL: Circle not found");
continue;
}
if (a == b) continue; // TODO
/*Line line = lines.get(p);
if (line == null)
lines.put(p,*/
Line line = cal.arrow(a, makeLabel(first(rel.labels)), b);
for (Lisp l : dropFirst(rel.labels))
line.addTrait(makeLabel(l));
}
}
}
static CirclesAndLines webToCAL(Web web) {
WebToCAL wtc = new WebToCAL();
wtc.convert(web);
return wtc.cal;
}
static Map _registerThread_threads = Collections.synchronizedMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static String conceptLanguageToEnglish(String s) {
if (s == null) return null;
try {
return conceptLanguageToEnglish_xyz(s);
} catch (Throwable __e) { printStackTrace2(__e); }
return s;
}
static String conceptLanguageToEnglish(Lisp l) {
return conceptLanguageToEnglish(clUnparse(l));
}
static boolean warn_on = true;
static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
static List listMinusSet(List l, Collection stuff) {
if (empty(stuff)) return l;
Set set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a)) l2.add(a);
return l2;
}
// undefined color, seems to be all black in practice
static BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
static BufferedImage newBufferedImage(int w, int h, Color color) {
BufferedImage img = newBufferedImage(w, h);
Graphics2D g = img.createGraphics();
g.setColor(color);
g.fillRect(0, 0, w, h);
return img;
}
static BufferedImage newBufferedImage(Pt p, Color color) {
return newBufferedImage(p.x, p.y, color);
}
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 Set keys(Map map) {
return map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static double cal_randomCircleCoord() {
return random(0.2, 0.8);
}
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 A first(Pair p) {
return p == null ? null : p.a;
}
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 dropFirst(String s) { return substring(s, 1); }
static List ll(A... a) {
return litlist(a);
}
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 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 String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(String s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static 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 List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static String conceptLanguageToEnglish_xyz_noCrazy(String s) {
List tok = javaTokC(s);
if (empty(tok)) return s;
String pattern = conceptToNameOpt(first(tok));
if (empty(pattern)) return s;
return formatXYZ_appendRest(pattern, map(new Object() { Object get(String s) { try { return conceptQuote(conceptToName(s)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "conceptQuote(conceptToName(s))"; }}, dropFirst(tok)));
}
static String conceptLanguageToEnglish_xyz(String s) {
return crazyEnglishFixing(conceptLanguageToEnglish_xyz_noCrazy(s));
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array)
if (o != null)
set.add(o);
return set;
}
static Set asSet(Collection l) {
if (l instanceof Set) return (Set) l;
HashSet set = new HashSet();
for (A o : l)
if (o != null)
set.add(o);
return set;
}
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 String conceptQuote(String s) {
if (isIdentifier(s) || isInteger(s) || isProperlyQuoted(s)) return s;
return quote(s);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal> print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
max /= 2;
if (buf.length() > max) try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection> lists) {
List l = new ArrayList();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(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 volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(ping_actions) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static 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 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 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 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 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 ArrayList litlist(A... a) {
return new ArrayList (Arrays.asList(a));
}
static Class mc() {
return main.class;
}
static String conceptToName(String s) {
AIConcept c = aiConceptsMap_cached().get(s);
return c == null || empty(c.name) ? s : c.name;
}
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 List javaTokC(String s) {
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(quickSubstring(s, i, j));
i = j;
}
return tok;
}
static boolean isFalse(Object o) {
return eq(false, o);
}
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 boolean isProperlyQuoted(String s) {
return s.length() >= 2
&& s.startsWith("\"")
&& s.endsWith("\"")
&& (!s.endsWith("\\\"") || s.endsWith("\\\\\""));
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(unnull(msg)); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getType(Object o) {
return getClassName(o);
}
static String crazyEnglishFixing(String s) {
s = jreplace(s, "A", "a");
s = jreplace(s, "a a", "a");
return firstToUpper(s);
}
static List reverseSorted(Collection c, final Object comparator) {
return sortedDesc(c, comparator);
}
static List reverseSorted(Collection c) {
return sortedDesc(c);
}
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 RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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);
}
// 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 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 boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
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 String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !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 Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static void remove(Collection l, A a) {
if (l != null) l.remove(a);
}
static 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 String firstToUpper(String s) {
if (empty(s)) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
static String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
jreplace(tok, in, out, condition);
return join(tok);
}
// leaves tok properly tokenized
// returns true iff anything was replaced
static boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
static boolean jreplace(List tok, String in, String out, Object condition) {
return jreplace(tok, in, out, false, true, condition);
}
static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
String[] toks = toStringArray(codeTokensOnly(tokin));
boolean anyChange = false;
for (int n = 0; n < 10000; n++) {
int i = findCodeTokens(tok, 1, ignoreCase, toks, condition);
if (i < 0)
return anyChange;
List subList = tok.subList(i-1, i+l(tokin)-1); // N to N
String expansion = jreplaceExpandRefs(out, subList);
int end = i+l(tokin)-2;
clearAllTokens(tok, i, end); // C to C
tok.set(i, expansion);
if (reTok) // would this ever be false??
reTok(tok, i, end);
anyChange = true;
}
throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
}
static boolean jreplace_debug;
static 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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
// supports the usual quotings (', ", variable length double brackets)
static boolean isQuoted(String s) {
if (startsWith(s, "'") || startsWith(s, "\"")) return true;
return isMultilineQuoted(s);
}
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 int findCodeTokens(List tok, String... tokens) {
return findCodeTokens(tok, 1, false, tokens);
}
static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, 1, ignoreCase, tokens);
}
static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}
static List findCodeTokens_specials = litlist("*", "", "", "", "\\*");
static boolean findCodeTokens_debug;
static int findCodeTokens_indexed, findCodeTokens_unindexed;
static int findCodeTokens_bails, findCodeTokens_nonbails;
static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
if (findCodeTokens_debug) {
if (eq(getClassName(tok), "main$IndexedList2"))
findCodeTokens_indexed++;
else
findCodeTokens_unindexed++;
}
// bail out early if first token not found (works great with IndexedList)
if (!findCodeTokens_specials.contains(tokens[0])
&& !tok.contains(tokens[0] /*, startIdx << no signature in List for this, unfortunately */)) {
++findCodeTokens_bails;
return -1;
}
++findCodeTokens_nonbails;
outer: for (int i = startIdx | 1; i+tokens.length*2-2 < tok.size(); i += 2) {
for (int j = 0; j < tokens.length; j++) {
String p = tokens[j], t = tok.get(i+j*2);
boolean match;
if (eq(p, "*")) match = true;
else if (eq(p, "")) match = isQuoted(t);
else if (eq(p, "")) match = isIdentifier(t);
else if (eq(p, "")) match = isInteger(t);
else if (eq(p, "\\*")) match = eq("*", t);
else match = ignoreCase ? eqic(p, t) : eq(p, t);
if (!match)
continue outer;
}
if (condition == null || checkCondition(condition, tok, i-1)) // pass N index
return i;
}
return -1;
}
// "$1" is first code token, "$2" second code token etc.
static String jreplaceExpandRefs(String s, List tokref) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) {
String x = tokref.get(-1+parseInt(tok.get(i).substring(1))*2);
tok.set(i, x);
}
}
return join(tok);
}
static 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;
}
// 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 codeTokensOnly(List tok) {
List l = new ArrayList();
for (int i = 1; i < tok.size(); i += 2)
l.add(tok.get(i));
return l;
}
// replacement for class JavaTok
// maybe incomplete, might want to add floating point numbers
// todo also: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;
static List javaTok(String s) {
return javaTok(s, null);
}
static List javaTok(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(quickSubstring(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTok(join(tok), tok);
}
static boolean javaTok_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, int startIdx, String in, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
return jfind(tok, startIdx, tokin, condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static int jfind(List tok, int startIdx, List tokin, Object condition) {
return findCodeTokens(tok, startIdx, false, toStringArray(codeTokensOnly(tokin)), condition);
}
static void jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int"))
replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
}
static List sortedDesc(Collection c, final Object comparator) {
List l = cloneList(c);
sort(l, makeReversedComparator(comparator));
return l;
}
static List sortedDesc(Collection c) {
List l = cloneList(c);
sort(l);
Collections.reverse(l);
return l;
}
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 List reTok(List tok) {
replaceCollection(tok, javaTok(tok));
return tok;
}
static List reTok(List tok, int i) {
return reTok(tok, i, i+1);
}
static List reTok(List tok, int i, int j) {
// extend i to an "N" token
// and j to "C" (so j-1 is an "N" token)
i = i & ~1;
j = j | 1;
List t = javaTok(join(subList(tok, i, j)));
replaceListPart(tok, i, j, t);
// fallback to safety
// reTok(tok);
return tok;
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static void clearAllTokens(List tok) {
for (int i = 0; i < tok.size(); i++)
tok.set(i, "");
}
static void clearAllTokens(List tok, int i, int j) {
for (; i < j; i++)
tok.set(i, "");
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 void replaceListPart(List l, int i, int j, List l2) {
l.subList(i, j).clear();
l.addAll(i, l2);
}
static Comparator makeReversedComparator(final Object f) {
return new Comparator() {
public int compare(Object a, Object b) {
return (int) callF(f, b, a);
}
};
}
static List replaceSublist(List l, List x, List y) {
if (x == null) return l;
int i = 0;
while (true) {
i = indexOfSubList(l, x, i);
if (i < 0) break;
// It's inefficient :D
for (int j = 0; j < l(x); j++) l.remove(i);
l.addAll(i, y);
i += l(y);
}
return l;
}
static List replaceSublist(List l, int fromIndex, int toIndex, List y) {
// inefficient
while (toIndex > fromIndex) l.remove(--toIndex);
l.addAll(fromIndex, y);
return l;
}
static void replaceCollection(Collection dest, Collection src) {
dest.clear();
dest.addAll(src);
}
static boolean isMultilineQuoted(String s) {
if (!startsWith(s, "[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
}
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 boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static boolean checkCondition(Object condition, Object... args) {
return isTrue(call(condition, "get", args));
}
static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static void sort(T[] a) {
Arrays.sort(a);
}
static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
static void sort(List a) {
Collections.sort(a);
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static int charDiff(char a, char b) {
return (int) a-(int) b;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static 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 boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static int indexOfSubList(List x, List y) {
return indexOfSubList(x, y, 0);
}
static int indexOfSubList(List x, List y, int i) {
outer: for (; i+l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++)
if (neq(x.get(i+j), y.get(j)))
continue outer;
return i;
}
return -1;
}
static int indexOfSubList(List x, A[] y, int i) {
outer: for (; i+l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++)
if (neq(x.get(i+j), y[j]))
continue outer;
return i;
}
return -1;
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static abstract class F1 {
abstract B get(A a);
}
static class WebNode {
Web web;
List labels = new ArrayList();
WebNode() {}
WebNode(Web web) {
this.web = web;}
void addLabel(String label) {
addLabel(clParse(label));
}
void addLabel(Lisp label) {
if (setAdd(labels, label) && web != null) {
web.index(label, this);
++web.size;
}
}
boolean hasLabel(Lisp label) { return labels.contains(label); }
public String toString() { return str(labels); }
int count() { return 1 + l(labels); }
}
static class Web {
List nodes = new ArrayList();
Map, WebNode> relations = new HashMap();
MultiMap index = new MultiMap();
Map> pots = new HashMap();
transient Lock lock = reentrantLock(true);
int size;
boolean potNotEmpty(String pot) { return nempty(getPot(pot)); }
List clearPot(String pot) {
List l = getPot(pot);
List l2 = cloneList(l);
l.clear();
return l2;
}
List getPot(String pot) {
List l = pots.get(pot);
if (l == null)
pots.put(pot, l = cloneList(nodes));
return l;
}
void relation(Lisp l) {
if (l(l) == 1) {
findNode(l.get(0)).addLabel(lisp("wvuyakuvuelmxpwp", l.head));
} else if (l(l) == 2) {
String a = lisp2label(l.get(0)), b = lisp2label(l.get(1));
if (l.is("fgvvrzypbkqomktd")) { // X is Y.
findNode(a).addLabel(b);
findNode(b).addLabel(a);
}
getRelation(a, b).addLabel(l.head);
}
}
void relations(List l) {
for (Lisp li : l) relation(li);
}
WebNode getRelation(String a, String b) {
return getRelation(findNode(a), findNode(b));
}
WebNode getRelation(WebNode a, WebNode b) {
Pair p = pair(a, b);
WebNode r = relations.get(p);
if (r == null) relations.put(p, r = newNode());
return r;
}
WebNode newNode() {
WebNode node = new WebNode(this);
nodes.add(node); ++size;
for (List l : values(pots)) l.add(node);
return node;
}
WebNode node(String s) { return findNode(s); }
WebNode node(Lisp l) { return findNode(l); }
WebNode findNode(String s) {
return findNode(clParse(s));
}
WebNode findNode(Lisp l) {
WebNode n = findNodeOpt(l);
return n != null ? n : newNode(l);
}
WebNode findNodeOpt(Lisp l) {
return first(index.get(l));
/*for (WebNode n : nodes)
if (n.labels.contains(l))
ret n;
null;*/
}
WebNode newNode(String... labels) {
WebNode n = newNode();
for (String label : labels) n.addLabel(label);
return n;
}
WebNode newNode(Lisp... labels) {
WebNode n = newNode();
for (Lisp label : labels) n.addLabel(label);
return n;
}
public String toString() { return webToString(this); }
int count() {
return size;
/*int count = 0;
for (WebNode n : nodes) count += n.count();
for (WebNode n : values(relations)) count += n.count();
ret count;*/
}
void index(Lisp label, WebNode n) {
index.put(label, n);
}
}
static class Cache {
Object maker; // func -> A
A value;
long loaded;
static boolean debug;
Cache() {}
Cache(Object maker) {
this.maker = maker;}
synchronized A get() {
if (loaded == 0) {
value = (A) callF(maker);
loaded = sysNow();
}
return value;
}
synchronized void clear() {
if (debug && loaded != 0)
print("Clearing cache");
value = null;
loaded = 0;
}
// clear if older than x seconds
// 0 does not do anything
synchronized void clear(double seconds) {
if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000)
clear();
}
// override
synchronized void set(A a) {
value = a;
loaded = sysNow();
}
}
static class BaseBase {
String text;
String textForRender() { return text; }
}
static class Base extends BaseBase {
List traits = new ArrayList();
boolean hasTrait(String t) { return containsIC(traits(), t); }
List traits() { if (nempty(text) && neq(first(traits), text)) traits.add(0, text); return traits; }
void addTraits(List l) { setAddAll(traits(), l); }
void addTrait(String t) { if (nempty(t)) setAdd(traits(), t); }
String textForRender() {
List traits = traits();
if (traits_multiLine) return lines(traits);
if (l(traits) <= 1) return first(traits);
return first(traits) + " [" + join(", ", dropFirst(traits)) + "]";
}
}
static class CirclesAndLines {
List circles = new ArrayList();
List lines = new ArrayList();
Class extends Arrow> arrowClass = Arrow.class;
Class extends Circle> circleClass = Circle.class;
transient Lock lock = fairLock();
transient String defaultImageID = "#1007372";
double imgZoom = 1;
// auto-visualize
Circle circle_autoVis(String text, String visualizationText, double x, double y) {
return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(quickVisualizeOr(visualizationText, defaultImageID))));
}
String makeVisualizationText(String text) {
return possibleGlobalID(text) ? "" : text;
}
Circle circle_autoVis(String text, double x, double y) {
return circle_autoVis(text, makeVisualizationText(text), x, y);
}
Circle circle(BufferedImage img, double x, double y, String text) {
return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(img)));
}
Circle circle(String text, double x, double y) {
return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(loadImage2("#1007452")))); // white
}
Circle addCircle(String imageID, double x, double y) {
return addCircle(imageID, x, y, "");
}
Circle addCircle(String imageID, double x, double y, String text) {
return addAndReturn(circles, nu(circleClass, "x", x, "y", y, "text", text, "img" , processImage(loadImage2(imageID))));
}
Arrow findArrow(Circle a, Circle b) {
for (Line l : getWhere(lines, "a", a, "b", b))
if (l instanceof Arrow)
return (Arrow) l;
return null;
}
Line addLine(Circle a, Circle b) {
Line line = findWhere(lines, "a", a, "b", b);
if (line == null)
lines.add(line = nu(Line.class, "a", a, "b", b));
return line;
}
Arrow arrow(Circle a, String text, Circle b) {
return addArrow(a, b, text);
}
Arrow addArrow(Circle a, Circle b) {
return addArrow(a, b, "");
}
Arrow addArrow(Circle a, Circle b, String text) {
return addAndReturn(lines, nu(arrowClass, "a", a, "b", b, "text", text));
}
BufferedImage makeImage(int w, int h) {
BufferedImage bg = renderTiledBackground("#1007195", w, h);
if (!lock.tryLock()) return null;
try {
for (Line l : lines) {
Pt a = l.a.pt(w, h), b = l.b.pt(w, h);
if (l instanceof Arrow)
drawThoughtArrow(bg, l.a.img(), a.x, a.y, l.b.img(), b.x, b.y, l.color);
else
drawThoughtLine(bg, l.a.img(), a.x, a.y, l.b.img(), b.x, b.y, l.color);
String text = l.textForRender();
if (nempty(text))
drawThoughtLineText(bg, l.a.img(), a.x, a.y, l.b.img(), b.x, b.y, text, l.color);
}
for (Circle c : circles) {
Pt p = c.pt(w, h);
drawThoughtCircle(bg, c.img(), p.x, p.y);
String text = c.textForRender();
if (nempty(text))
drawThoughtCircleText(bg, c.img(), p, text);
}
} finally {
lock.unlock();
}
return bg;
}
Canvas showAsFrame(int w, int h) {
Canvas canvas = showAsFrame();
frameInnerSize(canvas, w, h);
centerFrame(getFrame(canvas));
return canvas;
}
Canvas showAsFrame() {
return (Canvas) swing(new Object() { Object get() { try {
Canvas canvas = makeCanvas();
showCenterFrame(canvas);
return canvas;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Canvas canvas = makeCanvas();\r\n showCenterFrame(canvas);\r\n return canv..."; }});
}
Canvas makeCanvas() {
final Object makeImg = new Object() { Object get(int w, int h) { try { return makeImage(w, h) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "makeImage(w, h)"; }};
final Canvas canvas = jcanvas(makeImg);
disableImageSurfaceSelector(canvas);
new CircleDragger(canvas, new Runnable() { public void run() { try { updateCanvas(canvas, makeImg) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "updateCanvas(canvas, makeImg)"; }}, circles);
componentPopupMenu(canvas, new Object() { void get(JPopupMenu menu) { try {
Pt p = canvas.pointFromEvent(componentPopupMenu_mouseEvent.get());
final Circle c = findCircle(canvas, p);
if (c != null)
addMenuItem(menu, "Delete Circle", new Runnable() { public void run() { try { deleteCircle(c); canvas.update() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "deleteCircle(c); canvas.update()"; }});
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Pt p = canvas.pointFromEvent(componentPopupMenu_mouseEvent.get());\r\n final ..."; }});
return canvas;
}
Canvas show() { return showAsFrame(); }
Canvas show(int w, int h) { return showAsFrame(w, h); }
Circle findCircle(String text) {
for (Circle c : circles)
if (eqic(c.text, text))
return c;
return null;
}
void clear() {
lines.clear();
circles.clear();
}
Circle findCircle(Canvas canvas, Pt p) {
Lowest best = new Lowest();
for (Circle c : circles)
if (c.contains(canvas, p))
best.put(c, pointDistance(p, c.pt(canvas)));
return best.get();
}
BufferedImage processImage(BufferedImage img) {
return scaleImage(img, imgZoom);
}
void deleteCircle(Circle c) {
for (Line l : cloneList(lines))
if (l.a == c || l.b == c) lines.remove(l);
circles.remove(c);
}
} // end class CirclesAndLines
static class Circle extends Base {
transient BufferedImage img;
double x, y;
static BufferedImage defaultImage;
BufferedImage img() {
if (img != null) return img;
if (defaultImage == null) defaultImage = loadImage2("#1007372");
return defaultImage;
}
Pt pt(ImageSurface is) {
return pt(is.getWidth(), is.getHeight());
}
Pt pt(int w, int h) {
return new Pt(iround(x*w), iround(y*h));
}
boolean contains(ImageSurface is, Pt p) {
return pointDistance(p, pt(is)) <= thoughtCircleSize(img())/2+1;
}
}
static class Line extends Base {
Circle a, b;
Color color = Color.white;
Line setColor(Color color) {
this.color = color;
return this;
}
}
static class Arrow extends Line {}
static class CircleDragger extends MouseAdapter {
ImageSurface is;
List circles;
Object update;
int dx, dy;
Circle circle;
CircleDragger(ImageSurface is, Object update, List circles) {
this.circles = circles;
this.update = update;
this.is = is;
if (containsInstance(is.tools, CircleDragger.class)) return;
is.tools.add(this);
is.addMouseListener(this);
is.addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
Pt p = is.pointFromEvent(e);
circle = findCircle(p);
if (circle != null) {
dx = p.x-iround(circle.x*is.getWidth());
dy = p.y-iround(circle.y*is.getHeight());
}
}
}
public void mouseDragged(MouseEvent e) {
if (circle != null) {
Pt p = is.pointFromEvent(e);
circle.x = (p.x-dx)/(double) is.getWidth();
circle.y = (p.y-dy)/(double) is.getHeight();
callF(update);
}
}
public void mouseReleased(MouseEvent e) {
mouseDragged(e);
circle = null;
}
Circle findCircle(Pt p) {
Lowest best = new Lowest();
for (Circle c : circles)
if (c.contains(is, p))
best.put(c, pointDistance(p, c.pt(is)));
return best.get();
}
}
static class Node extends Concept {
String globalID = isTrue(DynamicObject_loading.get()) ? null : aGlobalID();
String importedFrom; // computer or snippet ID
String originatingUniverse; // global ID of "universe" concept was created in
boolean exportable = true;
Ref pngFile = new Ref();
String imageMD5, suggestedImageMD5;
Ref suggestedImage = new Ref();
boolean searchedForSuggestedImage;
long imported, touched; // timestamps
long dataLength; // length of optional byte data (wherever it is stored)
boolean dataIsText; // can optional data be shown as text
}
static class AIConcept extends Node {
String name;
String comment;
}
static class Pair {
A a;
B b;
Pair() {}
Pair(A a, B b) {
this.b = b;
this.a = a;}
public int hashCode() {
return hashCodeFor(a) + 2*hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
}
// a Lisp-like form
static class Lisp implements Iterable {
String head;
List args = new ArrayList();
Object more; // additional info, user-defined
Lisp() {}
Lisp(String head) {
this.head = head;}
Lisp(String head, Lisp... args) {
this.head = head;
this.args.addAll(asList(args));
}
Lisp(String head, Collection args) {
this.head = head;
for (Object arg : args) add(arg);
}
// INEFFICIENT
public String toString() {
if (args.isEmpty())
return quoteIfNotIdentifierOrInteger(head);
List bla = new ArrayList();
for (Lisp a : args)
bla.add(a.toString());
String inner = join(", ", bla);
if (head.equals(""))
return "{" + inner + "}"; // list
else
return quoteIfNotIdentifier(head) + "(" + inner + ")";
}
String raw() {
if (!isEmpty ()) throw fail("not raw: " + this);
return head;
}
Lisp add(Lisp l) {
args.add(l);
return this;
}
Lisp add(String s) {
args.add(new Lisp(s));
return this;
}
Lisp add(Object o) {
if (o instanceof Lisp) add((Lisp) o);
else if (o instanceof String) add((String) o);
else throw fail("Bad argument type: " + structure(o));
return this;
}
int size() {
return args.size();
}
boolean empty() { return args.isEmpty(); }
boolean isEmpty() { return args.isEmpty(); }
boolean isLeaf() { return args.isEmpty(); }
Lisp get(int i) {
return main.get(args, i);
}
String getString(int i) { Lisp a = get(i); return a == null ? null : a.head; }
String s(int i) { return getString(i); }
String rawOrNull(int i) {
Lisp a = get(i); return a != null && a.isLeaf() ? a.head : null;
}
String raw(int i) { return assertNotNull(rawOrNull(i)); }
boolean isLeaf(int i) { return rawOrNull(i) != null; }
boolean isA(String head) {
return eq(head, this.head);
}
boolean is(String head, int size) {
return isA(head) && size() == size;
}
boolean is(String head) { return isA(head); }
boolean headIs(String head) { return isA(head); }
boolean is(String... heads) {
return asList(heads).contains(head);
}
// check head for one of these (ignore case)
boolean isic(String... heads) {
return containsIgnoreCase(heads, head);
}
public Iterator iterator() {
return args.iterator();
}
Lisp subList(int fromIndex, int toIndex) {
Lisp l = new Lisp(head);
l.args.addAll(args.subList(fromIndex, toIndex)); // better to copy here I guess - safe
return l;
}
public boolean equals(Object o) {
if (o == null || o.getClass() != Lisp.class) return false;
Lisp l = (Lisp) ( o);
return eq(head, l.head) && eq(args, l.args);
}
public int hashCode() {
return head.hashCode() + args.hashCode();
}
Lisp addAll(List args) {
for (Object arg : args) add(arg);
return this;
}
String unquoted() { return unquote(raw()); }
String unq() { return unquoted(); }
String unq(int i) { return get(i).unq(); }
// heads of arguments
List heads() { return collect(args, "head"); }
}
// A concept should be an object, not just a string.
static int concepts_internStringsLongerThan = 10;
static ThreadLocal concepts_unlisted = new ThreadLocal();
static interface Derefable {
Concept get();
}
static interface IConceptIndex {
void update(Concept c); // also for adding
void remove(Concept c);
}
static interface IFieldIndex {
List getAll(Val val);
}
static class Concepts {
Map concepts = synchroTreeMap();
HashMap perClassData = new HashMap();
String programID; // set to "-" for non-persistent (possibly not implemented)
long idCounter;
volatile long changes = 1, changesWritten;
volatile java.util.Timer autoSaver;
volatile boolean savingConcepts;
int autoSaveInterval = -1000; // 1 second + wait logic
boolean useGZIP = true, quietSave;
ReentrantLock lock = new ReentrantLock(true);
ReentrantLock saverLock = new ReentrantLock(true);
long lastSaveTook, lastSaveWas;
float maxAutoSavePercentage = 10;
List conceptIndices;
Map, Map> fieldIndices;
Concepts() {}
Concepts(String programID) {
this.programID = programID;}
synchronized long internalID() {
do {
++idCounter;
} while (hasConcept(idCounter));
return idCounter;
}
void initProgramID() {
if (programID == null)
programID = getDBProgramID();
}
// Now tries to load from bot first, then go to disk.
Concepts load() {
return load(false);
}
Concepts safeLoad() {
return load(true);
}
Concepts load(boolean allDynamic) {
initProgramID();
if (tryToGrab(allDynamic)) return this;
return loadFromDisk(allDynamic);
}
Concepts loadFromDisk() { return loadFromDisk(false); }
Concepts loadFromDisk(boolean allDynamic) {
clearConcepts();
DynamicObject_loading.set(true);
try {
long time = now();
Map _concepts = concepts; // empty map
readLocally2_allDynamic.set(allDynamic);
readLocally2(this, programID, "concepts");
Map __concepts = concepts;
concepts = _concepts;
concepts.putAll(__concepts);
int l = readLocally_stringLength;
int tokrefs = unstructure_tokrefs;
assignConceptsToUs();
done("Loaded " + n(l(concepts), "concepts"), time);
if (fileSize(getProgramFile(programID, "idCounter.structure")) != 0)
readLocally2(this, programID, "idCounter");
else
calcIdCounter();
} finally {
DynamicObject_loading.set(null);
}
allChanged();
return this;
}
Concepts loadConcepts() { return load(); }
boolean tryToGrab(boolean allDynamic) {
if (sameSnippetID(programID, getDBProgramID())) return false;
RemoteDB db = connectToDBOpt(programID);
try {
if (db != null) {
loadGrab(db.fullgrab(), allDynamic);
return true;
}
} finally {
if (db != null) db.close();
}
return false;
}
Concepts load(String grab) {
return loadGrab(grab, false);
}
Concepts safeLoad(String grab) {
return loadGrab(grab, true);
}
Concepts loadGrab(String grab, boolean allDynamic) {
clearConcepts();
DynamicObject_loading.set(true);
try {
Map map = (Map)
(allDynamic ? safeUnstructure(grab) : unstructure(grab));
concepts.putAll(map);
assignConceptsToUs();
for (long l : map.keySet())
idCounter = max(idCounter, l);
} finally {
DynamicObject_loading.set(null);
}
allChanged();
return this;
}
void assignConceptsToUs() {
for (Concept c : values(concepts)) {
c._concepts = this;
callOpt_noArgs(c, "_doneLoading2");
}
}
String progID() {
return programID == null ? getDBProgramID() : programID;
}
Concept getConcept(String id) {
return empty(id) ? null : getConcept(parseLong(id));
}
Concept getConcept(long id) {
return (Concept) concepts.get((long) id);
}
Concept getConcept(RC ref) {
return ref == null ? null : getConcept(ref.longID());
}
boolean hasConcept(long id) {
return concepts.containsKey((long) id);
}
void deleteConcept(long id) {
Concept c = getConcept(id);
if (c == null)
print("Concept " + id + " not found");
else
c.delete();
}
void calcIdCounter() {
long id_ = 0;
for (long id : keys(concepts))
id_ = max(id_, id);
idCounter = id_+1;
saveLocally2(this, programID, "idCounter");
}
void saveConceptsIfDirty() { saveConcepts(); }
void save() { saveConcepts(); }
void saveConcepts() {
initProgramID();
saverLock.lock();
savingConcepts = true;
long start = now(), time;
try {
String s = null;
//synchronized(main.class) {
long _changes = changes;
if (_changes == changesWritten) return;
File f = getProgramFile(programID, useGZIP ? "concepts.structure.gz" : "concepts.structure");
lock.lock();
long fullTime = now();
try {
saveLocally2(this, programID, "idCounter");
if (useGZIP) {
saveGZStructureToFile(f, cloneMap(concepts));
getProgramFile(programID, "concepts.structure").delete();
} else
s = structure(cloneMap(concepts));
} finally {
lock.unlock();
}
changesWritten = _changes; // only update when structure didn't fail
if (!useGZIP) {
time = now()-start;
if (!quietSave)
print("Saving " + toM(l(s)) + "M chars (" /*+ changesWritten + ", "*/ + time + " ms)");
start = now();
saveTextFile(f, javaTokWordWrap(s));
getProgramFile(programID, "concepts.structure.gz").delete();
}
copyFile(f, getProgramFile(programID, "concepts.structure" + (useGZIP ? ".gz" : "") + ".backup" + ymd() + "-" + formatInt(hours(), 2)));
time = now()-start;
if (!quietSave)
print(programID + ": Saved " + toK(f.length()) + " K, " + n(concepts, "concepts") + " (" + time + " ms)");
lastSaveWas = fullTime;
lastSaveTook = now()-fullTime;
} finally {
savingConcepts = false;
saverLock.unlock();
}
}
void _autoSaveConcepts() {
if (autoSaveInterval < 0 && maxAutoSavePercentage != 0) {
long pivotTime = Math.round(lastSaveWas+lastSaveTook*100.0/maxAutoSavePercentage);
if (now() < pivotTime) {
//print("Skipping auto-save (last save took " + lastSaveTook + ")");
return;
}
}
saveConcepts();
}
void clearConcepts() {
concepts.clear();
allChanged();
}
synchronized void allChanged() {
++changes;
}
// auto-save every second if dirty
synchronized void autoSaveConcepts() {
if (autoSaver == null) {
if (isTransient()) throw fail("Can't persist transient database");
autoSaver = doEvery_daemon(abs(autoSaveInterval), new Runnable() { public void run() { try { _autoSaveConcepts() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_autoSaveConcepts()"; }});
// print("Installed auto-saver (" + autoSaveInterval + " ms, " + progID() + ")");
}
}
void cleanMeUp() {
if (autoSaver != null) {
autoSaver.cancel();
autoSaver = null;
}
while (savingConcepts) sleepInCleanUp(10);
saveConceptsIfDirty();
}
Map getIDsAndNames() {
Map map = new HashMap();
Map cloned = cloneMap(concepts);
for (long id : keys(cloned))
map.put(id, cloned.get(id).className);
return map;
}
void deleteConcepts(List l) {
for (Object o : l)
if (o instanceof Long)
concepts.remove((Long) o);
else if (o instanceof Concept)
((Concept) o).delete();
else
warn("Can't delete " + getClassName(o));
}
A conceptOfType(Class type) {
return firstOfType(allConcepts(), type);
}
List conceptsOfType(Class type) {
return filterByType(allConcepts(), type);
}
List listConcepts(Class type) {
return conceptsOfType(type);
}
List list(Class type) {
return conceptsOfType(type);
}
List list(String type) {
return conceptsOfType(type);
}
List conceptsOfType(String type) {
return filterByDynamicType(allConcepts(), "main$" + type);
}
boolean hasConceptOfType(Class extends Concept> type) {
return hasType(allConcepts(), type);
}
void persistConcepts() {
loadConcepts();
autoSaveConcepts();
}
// We love synonyms
void conceptPersistence() {
persistConcepts();
}
void persist() { persistConcepts(); }
void persist(int interval) { autoSaveInterval = interval; persist(); }
// Runs r if there is no concept of that type
A ensureHas(Class c, Runnable r) {
A a = conceptOfType(c);
if (a == null) {
r.run();
a = conceptOfType(c);
if (a == null)
throw fail("Concept not made by " + r + ": " + shortClassName(c));
}
return a;
}
// Ensures that every concept of type c1 is ref'd by a concept of
// type c2.
// Type of func: voidfunc(concept)
void ensureHas(Class extends Concept> c1, Class extends Concept> c2, Object func) {
for (Concept a : conceptsOfType(c1)) {
Concept b = findBackRef(a, c2);
if (b == null) {
callF(func, a);
b = findBackRef(a, c2);
if (b == null)
throw fail("Concept not made by " + func + ": " + shortClassName(c2));
}
}
}
// Type of func: voidfunc(concept)
void forEvery(Class extends Concept> type, Object func) {
for (Concept c : conceptsOfType(type))
callF(func, c);
}
int deleteAll(Class extends Concept> type) {
List l = (List) conceptsOfType(type);
for (Concept c : l) c.delete();
return l(l);
}
Collection allConcepts() {
synchronized(concepts) {
return new ArrayList(values(concepts));
}
}
int countConcepts(Class c, Object... params) {
int n = 0;
for (A x : list(c)) if (checkConceptFields(x, params)) ++n;
return n;
}
int countConcepts(String c, Object... params) {
int n = 0;
for (Concept x : list(c)) if (checkConceptFields(x, params)) ++n;
return n;
}
int countConcepts() {
return l(concepts);
}
synchronized void addConceptIndex(IConceptIndex index) {
if (conceptIndices == null)
conceptIndices = new ArrayList();
conceptIndices.add(index);
}
synchronized void addFieldIndex(Class extends Concept> c, String field, IFieldIndex index) {
if (fieldIndices == null)
fieldIndices = new HashMap();
Map map = fieldIndices.get(c);
if (map == null)
fieldIndices.put(c, map = new HashMap());
map.put(field, index);
}
synchronized IFieldIndex getFieldIndex(Class extends Concept> c, String field) {
if (fieldIndices == null) return null;
Map map = fieldIndices.get(c);
return map == null ? null : map.get(field);
}
// inter-process methods
RC xnew(String name, Object... values) {
return new RC(cnew(name, values));
}
void xset(long id, String field, Object value) {
xset(new RC(id), field, value);
}
void xset(RC c, String field, Object value) {
if (value instanceof RC)
value = getConcept((RC) value);
cset(getConcept(c), field, value);
}
Object xget(long id, String field) {
return xget(new RC(id), field);
}
Object xget(RC c, String field) {
return xgetPost(cget(getConcept(c), field));
}
Object xgetPost(Object o) {
o = deref(o);
if (o instanceof Concept)
return new RC((Concept) o);
return o;
}
void xdelete(long id) {
xdelete(new RC(id));
}
void xdelete(RC c) {
getConcept(c).delete();
}
void xdelete(List l) {
for (RC c : l)
xdelete(c);
}
List xlist() {
return map("toPassRef", allConcepts());
}
List xlist(String className) {
return map("toPassRef", conceptsOfType(className));
}
boolean isTransient() { return eq(programID, "-"); }
String xfullgrab() {
lock.lock();
try {
if (changes == changesWritten && !isTransient())
return loadConceptsStructure(programID);
return structure(cloneMap(concepts));
} finally {
lock.unlock();
}
}
void xshutdown() {
// Killing whole VM if someone wants this DB to shut down
cleanKillVM();
}
long xchangeCount() { return changes; }
int xcount() { return countConcepts(); }
void register(Concept c) {
if (c._concepts == this) return;
if (c._concepts != null) throw fail("Can't re-register");
c._concepts = this;
c.id = internalID();
c.created = now();
concepts.put((long) c.id, c);
c.change();
}
} // class Concepts
static volatile Concepts mainConcepts = new Concepts(); // Where we create new concepts
static class Concept extends DynamicObject {
transient Concepts _concepts; // Where we belong
long id;
//O madeBy;
//double energy;
//bool defunct;
long created;
// used only internally (cnew)
Concept(String className) {
super(className);
_created();
}
Concept() {
if (!_loading()) {
//className = shortClassName(this); // XXX - necessary?
//print("New concept of type " + className);
_created();
}
}
List[ refs;
List][ backRefs;
static boolean loading() { return _loading(); }
static boolean _loading() { return isTrue(DynamicObject_loading.get()); }
void _created() {
if (!isTrue(concepts_unlisted.get()))
mainConcepts.register(this);
}
/*void put(S field, O value) {
fieldValues.put(field, value);
change();
}
O get(S field) {
ret fieldValues.get(field);
}*/
class Ref] {
A value;
Ref() {
if (!isTrue(DynamicObject_loading.get())) refs = addDyn(refs, this);
}
Ref(A value) {
this.value = value;
refs = addDyn(refs, this);
index();
}
// get owning concept (source)
Concept concept() {
return Concept.this;
}
// get target
A get() { return value; }
boolean has() { return value != null; }
void set(A a) {
if (a == value) return;
unindex();
value = a;
index();
}
void set(Ref ref) { set(ref.get()); }
void clear() { set((A) null); }
void index() {
if (value != null)
value.backRefs = addDyn(value.backRefs, this);
change();
}
void unindex() {
if (value != null)
value.backRefs = removeDyn(value.backRefs, this);
}
void change() {
Concept.this.change();
}
}
class RefL extends AbstractList {
List < Ref < A > > l = new ArrayList();
public A set(int i, A o) {
A prev = l.get(i).get();
l.get(i).set(o);
return prev;
}
public void add(int i, A o) {
l.add(i, new Ref(o));
}
public A get(int i) {
return l.get(i).get();
}
public A remove(int i) {
return l.remove(i).get();
}
public int size() {
return l.size();
}
public boolean contains(Object o) {
if (o instanceof Concept)
for (Ref r : l) if (eq(r.get(), o)) return true;
return super.contains(o);
}
}
void delete() {
//name = "[defunct " + name + "]";
//defunct = true;
//energy = 0;
for (Ref r : unnull(refs))
r.unindex();
refs = null;
for (Ref r : cloneList(backRefs))
r.set((Concept) null);
backRefs = null;
if (_concepts != null) {
_concepts.concepts.remove((long) id);
_concepts.allChanged();
if (_concepts.conceptIndices != null)
for (IConceptIndex index : _concepts.conceptIndices)
index.remove(this);
_concepts = null;
}
id = 0;
}
BaseXRef export() {
return new BaseXRef(_concepts.progID(), id);
}
// notice system of a change in this object
void change() {
if (_concepts != null) {
_concepts.allChanged();
if (_concepts.conceptIndices != null)
for (IConceptIndex index : _concepts.conceptIndices)
index.update(this);
}
}
String _programID() {
return _concepts == null ? getDBProgramID() : _concepts.progID();
}
} // class Concept
// remote reference (for inter-process communication or
// external databases). Formerly "PassRef".
// prepared for string ids if we do them later
static class RC {
transient Object owner;
String id;
RC() {} // make serialisation happy
RC(long id) { this.id = str(id); }
RC(Object owner, long id) { this.id = str(id); this.owner = owner; }
RC(Concept c) { this(c.id); }
long longID() { return parseLong(id); }
public String toString() {
return id;
}
transient RemoteDB db;
String getString(String field) { return db.xS(this, field); }
Object get(String field) { return db.xget(this, field); }
void set(String field, Object value) { db.xset(this, field, value); }
}
// Reference to a concept in another program
static class BaseXRef {
String programID;
long id;
BaseXRef() {}
BaseXRef(String programID, long id) {
this.id = id;
this.programID = programID;}
public boolean equals(Object o) {
if (!(o instanceof BaseXRef)) return false;
BaseXRef r = (BaseXRef) ( o);
return eq(programID, r.programID) && eq(id, r.id);
}
public int hashCode() {
return programID.hashCode() + (int) id;
}
}
// BaseXRef as a concept
static class XRef extends Concept {
BaseXRef ref;
XRef() {}
XRef(BaseXRef ref) {
this.ref = ref; _doneLoading2(); }
// after we have been added to concepts
void _doneLoading2() {
getIndex().put(ref, this);
}
HashMap getIndex() {
return getXRefIndex(_concepts);
}
}
static synchronized HashMap getXRefIndex(Concepts concepts) {
HashMap cache = (HashMap) concepts.perClassData.get(XRef.class);
if (cache == null)
concepts.perClassData.put(XRef.class, cache = new HashMap());
return cache;
}
// uses mainConcepts
static XRef lookupOrCreateXRef(BaseXRef ref) {
XRef xref = getXRefIndex(mainConcepts).get(ref);
if (xref == null)
xref = new XRef(ref);
return xref;
}
// define standard concept functions to use main concepts
static List list(Class type) {
return mainConcepts.list(type);
}
static List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static List list(String type) {
return mainConcepts.list(type);
}
static List list(Concepts concepts, String type) {
return concepts.list(type);
}
static int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static void cleanMeUp_concepts() {
mainConcepts.cleanMeUp();
}
static void loadAndAutoSaveConcepts() {
mainConcepts.persist();
}
static void loadAndAutoSaveConcepts(int interval) {
mainConcepts.persist(interval);
}
static void loadConceptsFrom(String progID) {
mainConcepts.programID = progID;
mainConcepts.load();
}
static List conceptsOfType(String type) {
return mainConcepts.conceptsOfType(type);
}
static long changeCount() {
return mainConcepts.changes;
}
static List exposedDBMethods = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount");
static RC toPassRef(Concept c) {
return new RC(c);
}
// so we can instantiate the program to run as a bare DB bot
static int drawThoughtLine_width = 10;
static void drawThoughtLine(BufferedImage bg,
BufferedImage img1, int x1, int y1,
BufferedImage img2, int x2, int y2, Color color) {
Graphics2D g = imageGraphics(bg);
g.setColor(color);
g.setStroke(new BasicStroke(drawThoughtLine_width));
g.drawLine(x1, y1, x2, y2);
g.dispose();
}
static String aGlobalID() {
return randomID(16);
}
static Pt pt(int x, int y) {
return new Pt(x, y);
}
static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static int drawThoughtArrow_size = 15;
static void drawThoughtArrow(BufferedImage bg,
BufferedImage img1, int x1, int y1,
BufferedImage img2, int x2, int y2, Color color) {
double cs = thoughtCircleSize(img2)/2-1;
double dist = pointDistance(x1, y1, x2, y2);
double arrowLen = drawThoughtArrow_size*drawArrowHead_length-1;
Pt v = blendPoints(new Pt(x2, y2), new Pt(x1, y1), (cs+arrowLen)/dist);
Pt p = blendPoints(new Pt(x2, y2), new Pt(x1, y1), cs/dist);
Graphics2D g = imageGraphics(bg);
g.setColor(color);
g.setStroke(new BasicStroke(drawThoughtLine_width));
g.drawLine(x1, y1, v.x, v.y);
drawArrowHead(g, x1, y1, p.x, p.y, drawThoughtArrow_size);
g.dispose();
}
static JFrame showCenterFrame(String title, int w, int h) {
return showCenterFrame(title, w, h, null);
}
static JFrame showCenterFrame(String title, int w, int h, Component content) {
JFrame frame = makeFrame(title, content);
frame.setSize(w, h);
return centerFrame(frame);
}
static JFrame showCenterFrame(String title, Component content) {
return centerFrame(makeFrame(title, content));
}
static JFrame showCenterFrame(Component content) {
return centerFrame(makeFrame(content));
}
static int updateCanvas_retryInterval = 50;
// if makeImg returns null, it is recalled after a delay
static void updateCanvas(final Canvas canvas, final Object makeImg) {
swingNowOrLater(new Runnable() { public void run() { try {
if (canvas.updating || canvas.getWidth() == 0) return;
canvas.updating = true;
try {
BufferedImage img = asBufferedImage(callF(makeImg, canvas.getWidth(), canvas.getHeight()));
if (img != null) {
canvas.setImage(img);
canvas.updating = false;
} else
awtLater(updateCanvas_retryInterval, new Runnable() { public void run() { try {
canvas.updating = false;
updateCanvas(canvas, makeImg);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "canvas.updating = false;\r\n updateCanvas(canvas, makeImg);"; }});
} catch (Throwable e) {
canvas.updating = false;
throw rethrow(e);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (canvas.updating || canvas.getWidth() == 0) return;\n canvas.updating = tru..."; }});
}
static ReentrantLock reentrantLock(boolean fair) {
return new ReentrantLock(fair);
}
static Lisp clParse(String s) {
List tok = tok_groupRoundBrackets(s);
if (l(tok) == 1) return null;
Lisp l = lisp(unquote(tok.get(1)));
for (int i = 3; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("(") && t.endsWith(")"))
l.add(assertNotNull(clParse(dropFirstAndLast(t))));
else
l.add(lisp(aiUsing(unquote(t))));
}
return l;
}
static List clParse(List l) {
return map("clParse", l);
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static int thoughtCircleSize(BufferedImage img) {
return min(img.getWidth(), img.getHeight()) + 20;
}
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 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 containsInstance(Iterable i, Class c) {
if (i != null) for (Object o : i)
if (isInstanceX(c, o))
return true;
return false;
}
// uses bilinear interpolation
static BufferedImage scaleImage(BufferedImage before, double scale) {
if (scale == 1) return before;
int w = before.getWidth();
int h = before.getHeight();
int neww = max(1, iround(w*scale)), newh = max(1, iround(h*scale));
BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
return scaleOp.filter(before, after);
}
static JFrame centerFrame(Component c) {
JFrame frame = getFrame(c);
if (frame != null)
frame.setLocationRelativeTo(null); // magic trick
return frame;
}
static String quoteIfNotIdentifier(String s) {
if (s == null) return null;
return isJavaIdentifier(s) ? s : quote(s);
}
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());
}
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static BufferedImage quickVisualizeOr(String query, String defaultImageID) {
BufferedImage img = quickVisualize(query);
return img != null ? img : loadImage2(defaultImageID);
}
static A addAndReturn(Collection c, A a) {
if (c != null) c.add(a);
return a;
}
static int iround(double d) {
return (int) Math.round(d);
}
static double pointDistance(Pt a, Pt b) {
return sqrt(sqr(a.x-b.x) + sqr(a.y-b.y));
}
static double pointDistance(int x1, int y1, int x2, int y2) {
return sqrt(sqr(x1-x2) + sqr(y1-y2));
}
static String quoteIfNotIdentifierOrInteger(String s) {
if (s == null) return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static List getWhere(Collection c, Object... data) {
List l = new ArrayList();
for (A x : c)
if (checkFields(x, data))
l.add(x);
return l;
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static void drawThoughtCircle(BufferedImage bg, BufferedImage img, int x, int y) {
// TODO: crop to certain size
BufferedImage circle = cutImageToCircle(img_addBorder(cutImageToCircle(img), Color.white, 10));
x -= circle.getWidth()/2;
y -= circle.getHeight()/2;
drawImageOnImage(circle, bg, x, y);
}
static void addAll(Collection c, Collection b) {
if (c != null && b != null) c.addAll(b);
}
static void addAll(Collection c, A... b) {
if (c != null) c.addAll(Arrays.asList(b));
}
static boolean equals(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
static String lisp2label(Lisp l) {
return l.isLeaf() ? l.head : clUnparse(l);
}
static A findWhere(Collection c, Object... data) {
for (A x : c)
if (checkFields(x, data))
return x;
return null;
}
static String webToString(Web web) {
List out = new ArrayList();
Map index = new HashMap();
for (int i = 0; i < l(web.nodes); i++) {
out.add("Node " + (i+1) + ": " + web.nodes.get(i));
index.put(web.nodes.get(i), i+1);
}
for (Pair p : keys(web.relations))
out.add(index.get(p.a) + " -> " + index.get(p.b) + " = " + web.relations.get(p));
return fromLines(out);
}
static class Canvas extends ImageSurface {
Object makeImg;
boolean updating;
Canvas() {}
Canvas(Object makeImg) {
this.makeImg = makeImg;}
void update() { updateCanvas(this, makeImg); }
}
// f: (int w, int h) -> BufferedImage
static Canvas jcanvas(Object f) {
return jcanvas(f, 0); // 100
}
static Canvas jcanvas(final Object f, final int updateDelay) {
return (Canvas) swing(new Object() { Object get() { try {
final Canvas is = new Canvas(f);
final Runnable update = new Runnable() {
boolean first = true;
public void run() {
BufferedImage img = is.getImage();
int w = is.getWidth(), h = is.getHeight();
if (first || img.getWidth() != w || img.getHeight() != h) {
updateCanvas(is, f);
first = false;
}
}
};
onResize(is, new Runnable() { public void run() { try { awtLater(is, updateDelay, update) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "awtLater(is, updateDelay, update)"; }});
bindToComponent(is, update); // first update
return is;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "final Canvas is = new Canvas(f);\r\n final Runnable update = new Runnable {\r\n ..."; }});
}
static void disableImageSurfaceSelector(ImageSurface is) {
ImageSurfaceSelector s = firstInstance(is.tools, ImageSurfaceSelector.class);
if (s == null) return;
is.removeMouseListener(s);
is.removeMouseMotionListener(s);
is.tools.add(s);
}
// 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 int formatXYZ_varToIndex_maybeQuoted(String t) {
if (formatXYZ_quotedVars && isQuoted(t))
return formatXYZ_varToIndex(unquote(t));
return formatXYZ_varToIndex(t);
}
static List collect(Collection c, String field) {
return collectField(c, field);
}
static List collect(String field, Collection c) {
return collectField(c, field);
}
static List collect(Class c, String field) {
return collect(list(c), field);
}
static void setAddAll(List a, Collection b) {
for (A x : b)
setAdd(a, x);
}
static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static JFrame getFrame(final Object _o) {
return swing(new F0() { JFrame get() { try {
Object o = _o;
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGro..."; }});
}
static int drawThoughtLineText_shift = 5;
static void drawThoughtLineText(BufferedImage bg,
BufferedImage img1, int x1, int y1,
BufferedImage img2, int x2, int y2,
String text, Color color) {
Graphics2D g = imageGraphics(bg);
g.setColor(color);
g.setFont(sansSerif(20));
drawOutlineTextAlongLine(g, text, x1, y1, x2, y2, drawThoughtLine_width/2+drawThoughtLineText_shift, color, Color.black);
g.dispose();
}
static JFrame frameInnerSize(final Component c, final double w, final double h) {
final JFrame frame = getFrame(c);
if (frame != null) { swingAndWait(new Runnable() { public void run() { try {
Container cp = frame.getContentPane();
Dimension oldSize = cp.getPreferredSize();
cp.setPreferredSize(new Dimension(iround(w), iround(h)));
frame.pack();
cp.setPreferredSize(oldSize);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Container cp = frame.getContentPane();\r\n Dimension oldSize = cp.getPreferredS..."; }}); }
return frame;
}
static void frameInnerSize(JFrame frame, Dimension d) {
frameInnerSize(frame, d.width, d.height);
}
static JFrame frameInnerSize(Pt p, JFrame frame) {
frameInnerSize(frame, p.x, p.y);
return frame;
}
static boolean containsIC(List l, String s) {
return containsIgnoreCase(l, s);
}
static boolean containsIC(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static boolean containsIC(String s, char c) {
return containsIgnoreCase(s, c);
}
static boolean containsIC(String a, String b) {
return containsIgnoreCase(a, b);
}
static long sysNow() {
return System.nanoTime()/1000000;
}
static OccTree2 findNode(OccTree2 tree, E e) {
if (eq(tree.e, e)) return tree;
for (OccTree2 n : tree.next) {
OccTree2 t = findNode(n, e);
if (t != null) return t;
}
return null;
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static boolean setAdd(Collection c, A a) {
if (c.contains(a)) return false;
c.add(a);
return true;
}
static RuntimeException rethrow(Throwable e) {
throw asRuntimeException(e);
}
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean possibleGlobalID(String s) {
return l(s) == 16 && allLowerCaseCharacters(s);
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static String getString(List l, int idx) {
return (String) get(l, idx);
}
static String getString(Object o, Object key) {
if (o instanceof Map) return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
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 Pair pair(A a, B b) {
return new Pair(a, b);
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
boolean noStringSharing;
IdentityHashMap seen = new IdentityHashMap();
//new BitSet refd;
HashMap strings = new HashMap();
HashSet concepts = new HashSet();
HashMap> fieldsByClass = new HashMap();
int n; // token count
List stack = new ArrayList();
// append single token
structure_Data append(String token) { out.print(token); ++n; return this; }
structure_Data append(int i) { out.print(i); ++n; return this; }
// append multiple tokens
structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; }
// extend last token
structure_Data app(String token) { out.print(token); return this; }
structure_Data app(int i) { out.print(i); return this; }
}
static void structure_1(final Object o, final structure_Data d) {
if (o == null) { d.append("null"); return; }
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
// these are never back-referenced (for readability)
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; }
if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; }
if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; }
if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; }
if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; }
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f"); return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o)); return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath())); return;
}
// referencable objects follow
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null) ref = d.strings.get((String) o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
if (!(o instanceof String))
d.seen.put(o, d.n); // record token number
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out); d.n++; return;
}
if (o instanceof HashSet) {
d.append("hashset ");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset ");
structure_1(new ArrayList((Set) o), d);
return;
}
String name = c.getName();
if (o instanceof Collection
&& !startsWith(name, "main$")
/* && neq(name, "main$Concept$RefL") */) {
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.stack...."; }});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap) d.append("lhm");
else if (o instanceof HashMap) d.append("hm");
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
boolean v;
Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l) d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o))); return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i-1) == '0' && hex.charAt(i-2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
//ret "intarray " + quote(intArrayToHex((int[]) o));
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0) d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (d.n != l) d.append(", ");
d.append(i);
}
d.append("}"); return;
}
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o))); return; // Hm. this is not unstructure-able
}
if (o instanceof Lisp) {
d.append("l(", 2);
final Lisp lisp = (Lisp) ( o);
structure_1(lisp.head, d);
final Iterator it = lisp.args.iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext())
d.append(")");
else {
d.stack.add(this);
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\")\");\r\n else {\r\n d...."; }});
return;
}
/*if (name.equals("main$Lisp")) {
fail("lisp not supported right now");
}*/
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
// serialize an object with fields.
// first, collect all fields and values in fv.
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
String fieldName = field.getName();
fields.add(field);
// put special cases here...
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
// Render this$1 first because unstructure needs it for constructor call.
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
} // << if (lFields == null)
else { // ref handling for lFields != null
Integer ref = d.seen.get(o);
if (ref != null) { /*d.refd.set(ref);*/ d.append("t").app(ref); return; }
d.seen.put(o, d.n); // record token number
}
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null)
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
// Now we have fields & values. Process fieldValues if it's a DynamicObject.
// omit field "className" if equal to class's name
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() { public void run() { try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else {\r..."; }});
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
/*static void printStackTrace2(S indent, Throwable e) {
if (endsWithLetter(indent)) indent += " ";
printIndent(indent, getStackTrace2(e));
}*/
static BufferedImage renderTiledBackground(String tileImageID, int w, int h) {
BufferedImage tileImage = loadImage2(tileImageID);
BufferedImage img = newBufferedImage(w, h, Color.black);
Graphics2D g = img.createGraphics();
for (int x = 0; x < w; x += tileImage.getWidth())
for (int y = 0; y < h; y += tileImage.getHeight())
g.drawImage(tileImage, x, y, null);
g.dispose();
return img;
}
static int drawThoughtCircleText_margin = 5;
static Color drawThoughtCircleText_color = Color.yellow;
static void drawThoughtCircleText(BufferedImage bg, BufferedImage img, Pt p, String text) {
Graphics2D g = imageGraphics(bg);
g.setFont(sansSerifBold(20));
FontMetrics fm = g.getFontMetrics();
int h = fm.getHeight();
int y = p.y+thoughtCircleSize(img)/2+drawThoughtCircleText_margin;
for (String s : lines(text)) {
drawTextWithOutline(g, s, p.x-fm.stringWidth(s)/2, y+fm.getLeading()+fm.getMaxAscent(), drawThoughtCircleText_color, Color.black);
y += h;
}
g.dispose();
}
static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static WeakHashMap makeFrame_myFrames = new WeakHashMap();
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return (JFrame) swing(new Object() { Object get() { try {
if (getFrame(content) != null)
return setFrameTitle((Component) content, title);
final JFrame frame = new JFrame(title);
makeFrame_myFrames.put(frame, Boolean.TRUE);
JComponent wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
standardTitlePopupMenu(frame);
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret setFrameTitle((Component) content, tit..."; }});
}
static String quickVisualize_progID = "#1007145";
static BufferedImage quickVisualize_fromCache(String query) {
File f = quickVisualize_imageFile(query);
if (f.length() != 0) try { return loadPNG(f); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static String quickVisualize_preprocess(String query) {
return toUpper(trim(query));
}
static BufferedImage quickVisualize(String query) {
query = quickVisualize_preprocess(query);
if (empty(query)) return null;
BufferedImage img = quickVisualize_fromCache(query);
if (img != null) return img;
File f = quickVisualize_imageFile(query);
/*L urls = googleImageSearch_multi(query);
saveTextFile(quickVisualize_urlsFile(query), joinLines(urls));
if (empty(urls)) null;
img = loadBufferedImage(first(urls));*/
img = googleImageSearchFirst(query);
if (img == null) return null;
savePNG(f, img);
return img;
}
static String quickVisualize_imagePath(String query) {
query = quickVisualize_preprocess(query);
return fsI(quickVisualize_progID) + "/" + urlencode(query) + ".png";
}
static File quickVisualize_imageFile(String query) {
query = quickVisualize_preprocess(query);
return prepareProgramFile(quickVisualize_progID, urlencode(query) + ".png");
}
static File quickVisualize_urlsFile(String query) {
query = quickVisualize_preprocess(query);
return prepareProgramFile(quickVisualize_progID, "urls-" + urlencode(query) + ".txt");
}
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 void onResize(Component c, final Object r) {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
pcallF(r);
}
});
}
static List fastLoadAIConcepts() {
print("fast-loading ai concepts");
Class main = getBotMainClass(dbBotName(aiConceptsProgram()));
Object concepts = get(main, "mainConcepts");
return map("fastLoadAIConcept", (List) call(concepts, "list", "AIConcept"));
}
static List buttonsInGroup(ButtonGroup g) {
if (g == null) return ll();
return asList(g.getElements());
}
static Font sansSerif(int fontSize) {
return new Font(Font.SANS_SERIF, Font.PLAIN, fontSize);
}
static List collectField(Collection c, String field) {
List l = new ArrayList();
for (Object a : c)
l.add(getOpt(a, field));
return l;
}
static void drawOutlineTextAlongLine(Graphics2D g, String text, int x1, int y1, int x2, int y2, int shift, Color fillColor, Color outlineColor) {
if (y2 == y1 && x2 == x1) ++x2;
AffineTransform tx = new AffineTransform();
double angle = Math.atan2(y2-y1, x2-x1);
boolean flip = abs(angle) > pi()/2;
if (flip) angle -= pi();
tx.translate((x1+x2)/2.0, (y1+y2)/2.0);
tx.rotate(angle);
AffineTransform old = g.getTransform();
g.setTransform(tx);
FontMetrics fm = g.getFontMetrics();
// int y = shift+fm.getLeading()+fm.getMaxAscent(); // below
int y = -shift-fm.getMaxDescent(); // above
drawTextWithOutline(g, text, -fm.stringWidth(text)/2.0f, y, fillColor, outlineColor);
g.setTransform(old);
}
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 ThreadLocal imageGraphics_antiAlias = new ThreadLocal();
static Graphics2D imageGraphics(BufferedImage img) {
return !isFalse(imageGraphics_antiAlias.get()) ? antiAliasGraphics(img) : img.createGraphics();
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURL) { try {
if (snippetIDOrURL == null) return null;
if (isURL(snippetIDOrURL))
return ImageIO.read(new URL(snippetIDOrURL));
if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
try {
File dir = getCacheProgramDir("Image-Snippets");
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL(snippetID);
System.err.println("Loading image: " + imageURL);
BufferedImage image = ImageIO.read(new URL(imageURL));
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
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 ArrayList list(A[] a) {
return asList(a);
}
static ArrayList list(int[] a) {
return asList(a);
}
static ArrayList list(Set s) {
return asList(s);
}
static List tok_groupRoundBrackets(String s) {
List tok = javaTok(s);
while (true) {
int i = tok.lastIndexOf("(");
if (i < 0) return tok;
int j = indexOf(tok, ")", i);
if (j < 0) return tok;
tok.set(i, join(subList(tok, i, j+1)));
tok.subList(i+1, j+1).clear();
assertTrue(odd(l(tok)));
}
}
static BufferedImage asBufferedImage(Object o) {
BufferedImage bi = toBufferedImageOpt(o);
if (bi == null) throw fail(getClassName(o));
return bi;
}
// usually L
static String fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines)
buf.append(str(line)).append('\n');
return buf.toString();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static A bindToComponent(A component, final Runnable onShow, final Runnable onUnShow) {
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
pcallF(onUnShow);
}
public void ancestorMoved(AncestorEvent event) {
}
});
return component;
}
static A bindToComponent(A component, Runnable onShow) {
return bindToComponent(component, onShow, null);
}
static BufferedImage img_addBorder(BufferedImage img, Color color, int border) {
int top = border, bottom = border, left = border, right = border;
int w = img.getWidth(), h = img.getHeight();
BufferedImage img2 = createBufferedImage(left+w+right, top+h+bottom, color);
Graphics2D g = img2.createGraphics();
g.drawImage(img, left, top, null);
g.dispose();
return img2;
}
static boolean checkFields(Object x, Object... data) {
for (int i = 0; i < l(data); i += 2)
if (neq(getOpt(x, (String) data[i]), data[i+1]))
return false;
return true;
}
static BufferedImage cutImageToCircle(String imageID) {
return cutImageToCircle(loadImage2(imageID));
}
static BufferedImage cutImageToCircle(BufferedImage image) {
int w = min(image.getWidth(), image.getHeight());
return cutImageToCircle(image, w);
}
static BufferedImage cutImageToCircle(BufferedImage image, int w) {
int h = w;
image = img_getCenterPortion(image, w, w);
BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = output.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new Ellipse2D.Float(0, 0, w, h));
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(image, 0, 0, null);
g2.dispose();
return output;
}
// 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 boolean allLowerCaseCharacters(String s) {
for (int i = 0; i < l(s); i++)
if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false;
return true;
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object getOpt(Class c, String field) {
try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static A popLast(List l) {
return liftLast(l);
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
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 double sqrt(double x) {
return Math.sqrt(x);
}
static String getStackTrace2(Throwable throwable) {
return getStackTrace(throwable) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
str(getInnerException(throwable))) + "\n";
}
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 String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static JMenuItem jmenuItem(String text, final Object r) {
JMenuItem mi = new JMenuItem(text);
mi.addActionListener(actionListener(r));
return mi;
}
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 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 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 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;
}
// 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 Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
// independent timer
static void awtLater(int delay, final Object r) {
swingLater(delay, r);
}
static void awtLater(Object r) {
swingLater(r);
}
// dependent timer (runs only when component is visible)
static void awtLater(JComponent component, int delay, Object r) {
installTimer(component, r, delay, delay, false);
}
static void awtLater(JFrame frame, int delay, Object r) {
awtLater(frame.getRootPane(), delay, r);
}
// changes & returns canvas
static BufferedImage drawImageOnImage(BufferedImage img, BufferedImage canvas, int x, int y) {
Graphics2D g = canvas.createGraphics();
g.drawImage(img, x, y, null);
g.dispose();
return canvas;
}
static Point blendPoints(Point x, Point y, double yish) {
double xish = 1-yish;
return new Point((int) (x.x*xish+y.x*yish), (int) (x.y*xish+y.y*yish));
}
static Pt blendPoints(Pt x, Pt y, double yish) {
double xish = 1-yish;
return new Pt((int) (x.x*xish+y.x*yish), (int) (x.y*xish+y.y*yish));
}
static Pt blendPoints(Pt x, double xf, Pt y, double yf) {
return new Pt((int) (x.x*xf+y.x*yf), (int) (x.y*xf+y.y*yf));
}
static Pt blendPoints(int x1, int y1, int x2, int y2, double yish) {
return blendPoints(new Pt(x1, y1), new Pt(x2, y2), yish);
}
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 Font sansSerifBold(int fontSize) {
return new Font(Font.SANS_SERIF, Font.BOLD, fontSize);
}
static long sysDone(String desc, long startTime, int minPrint) {
return done2(startTime, desc, minPrint);
}
static long sysDone(long startTime, String desc, int minPrint) {
return done2(startTime, desc, minPrint);
}
static long sysDone(long startTime, String desc) {
return done2(startTime, desc);
}
static long sysDone(String desc, long startTime) {
return done2(desc, startTime);
}
static long sysDone(long startTime) {
return done2(startTime);
}
static Object nuObject(String className, Object... args) { try {
return nuObject(Class.forName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw new RuntimeException("Constructor " + c.getName() + getClasses(args) + " not found");
}
static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static A firstInstance(Collection c, Class type) {
return firstOfType(c, type);
}
static long sqr(long l) {
return l*l;
}
static void setAll(Object o, Map fields) {
if (fields == null) return;
for (String field : keys(fields))
set(o, field, fields.get(field));
}
static void setAll(Object o, Object... values) {
//values = expandParams(c.getClass(), values);
failIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
set(o, field, value);
}
}
static boolean loadAIConcepts_alwaysFromDisk;
static List loadAIConcepts() {
Concepts c = new Concepts("#1006463");
if (loadAIConcepts_alwaysFromDisk) c.loadFromDisk(); else c.load();
return list(c, AIConcept.class);
}
static int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static void drawTextWithOutline(Graphics2D g2, String text, float x, float y, Color fillColor, Color outlineColor) {
BasicStroke outlineStroke = new BasicStroke(2.0f);
g2.translate(x, y);
// remember original settings
Stroke originalStroke = g2.getStroke();
RenderingHints originalHints = g2.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = g2.getFont().createGlyphVector(g2.getFontRenderContext(), text);
// get the shape object
Shape textShape = glyphVector.getOutline();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(outlineColor);
g2.setStroke(outlineStroke);
g2.draw(textShape); // draw outline
g2.setColor(fillColor);
g2.fill(textShape); // fill the shape
// reset to original settings after painting
g2.setStroke(originalStroke);
g2.setRenderingHints(originalHints);
g2.translate(-x, -y);
}
static float drawArrowHead_length = 2f;
static void drawArrowHead(Graphics2D g, int x1, int y1, int x2, int y2, int size) {
if (y2 == y1 && x2 == x1) return;
Polygon arrowHead = new Polygon();
arrowHead.addPoint(0, 0);
int l = iround(drawArrowHead_length*size);
arrowHead.addPoint(-size, -l);
arrowHead.addPoint(size, -l);
AffineTransform tx = new AffineTransform();
double angle = Math.atan2(y2-y1, x2-x1);
tx.translate(x2, y2);
tx.rotate(angle-Math.PI/2d);
AffineTransform old = g.getTransform();
g.setTransform(tx);
g.fill(arrowHead);
g.setTransform(old);
}
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 String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static boolean isURL(String s) {
return s.startsWith("http://") || s.startsWith("https://");
}
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
static BufferedImage createBufferedImage(int w, int h, Color color) {
return newBufferedImage(w, h, color);
}
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 A firstOfType(Collection c, Class type) {
for (Object x : c)
if (isInstanceX(type, x))
return (A) x;
return null;
}
static ActionListener actionListener(final Object runnable) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
static void set(Object o, String field, Object value) {
if (o instanceof Class) set((Class) o, field, value);
else try {
Field f = set_findField(o.getClass(), field);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Graphics2D antiAliasGraphics(BufferedImage img) {
Graphics2D g = (Graphics2D) ( img.getGraphics());
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
return g;
}
static Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static float abs(float f) { return Math.abs(f); }
static int abs(int i) { return Math.abs(i); }
static double abs(double d) { return Math.abs(d); }
static String toUpper(String s) {
return s == null ? null : s.toUpperCase();
}
// 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 || c instanceof JTree)
return new JScrollPane(c);
return c;
}
static File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static String getStackTrace(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
static void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
static String aiConceptsProgram() {
return "#1006463";
}
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 snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static String snippetImageURL(String snippetID, String contentType) {
long id = parseSnippetID(snippetID);
String url;
if (id == 1000010 || id == 1000012)
url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id;
else if (isImageServerSnippet(id))
url = "http://ai1.lol/images/raw/" + id;
else
url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id
+ "&contentType=image/" + contentType;
return url;
}
static String dbBotName(String progID) {
return fsI(progID) + " Concepts";
}
static BufferedImage googleImageSearchFirst(String q) {
String html = str(googleImageSearch_loadPage(q));
String id = regexpFirstGroup("\"id\":\"(..............):\"", html);
if (id == null) return null;
print("Image search: ID=" + id);
String s = regexpFirstGroup("\\[\"" + id + ":\",\"data:image/(?:png|jpeg|gif);base64,([^\"]+)", html);
if (s == null) {
print("Image search: ID not found. Saving debug");
saveTextFile(prepareProgramFile("#1007145", "debug.html"), html);
return null;
}
try {
return decodeImage(base64decode(unquote("\"" + s + "\"")));
} catch (Throwable _e) {
print("Tried to decode: " + quote(s));
throw rethrow(_e); }
}
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 standardTitlePopupMenu(final JFrame frame) {
// standard right-click behavior on titles
if (isSubstanceLAF())
titlePopupMenu(frame,
new Object() { void get(JPopupMenu menu) { try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() { public void run() { try {
toggleAlwaysOnTop(frame) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "toggleAlwaysOnTop(frame)"; }}));
menu.add(jMenuItem("Shoot Window", new Runnable() { public void run() { try { shootWindowGUI_external(frame, 500) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "shootWindowGUI_external(frame, 500)"; }}));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restart P..."; }});
}
static void savePNG(BufferedImage img, File file) { try {
File tempFile = new File(file.getPath() + "_temp");
CriticalAction ca = beginCriticalAction("Save " + f2s(file));
try {
ImageIO.write(img, "png", mkdirsFor(tempFile));
file.delete();
tempFile.renameTo(file);
} finally {
ca.done();
}
} catch (Exception __e) { throw rethrow(__e); } }
// gotta love convenience & program-smartness
static void savePNG(File file, BufferedImage img) {
savePNG(img, file);
}
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);
}
// first delay = delay
static Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
// first delay = delay
static Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
// first delay = delay
static Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static void installTimer(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
return (Timer) swingAndWait(new Object() { Object get() { try {
Timer timer = new Timer(toInt(delay), new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
if (!allPaused())
callF(r);
} catch (Throwable __e) { printStackTrace2(__e); }
}});
timer.setInitialDelay(toInt(firstDelay));
timer.setRepeats(repeats);
bindTimerToComponent(timer, component);
return timer;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Timer timer = new Timer(toInt(delay), actionListener {\r\n pcall {\r\n i..."; }});
}
static Timer installTimer(JFrame frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), r, delay, firstDelay);
}
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 String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(r));
timer.setRepeats(false);
timer.start();
}
static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static String fsI(String id) {
return formatSnippetID(id);
}
static String fsI(long id) {
return formatSnippetID(id);
}
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 odd(int i) {
return (i & 1) != 0;
}
static int done2_minPrint = 10;
static long done2(long startTime, String desc) {
return done2(startTime, desc, done2_minPrint);
}
static long done2(long startTime, String desc, int minPrint) {
long time = sysNow()-startTime;
if (time >= minPrint)
print(desc + " [" + time + " ms]");
return time;
}
static long done2(String desc, long startTime) {
return done2(startTime, desc);
}
static long done2(long startTime) {
return done2(startTime, "");
}
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 A setFrameTitle(A c, String title) {
JFrame f = getFrame(c);
if (f == null)
showFrame(title, c);
else
f.setTitle(title);
return c;
}
static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
// magically find a field called "frame" in main class :-)
static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static File getCacheProgramDir() {
return getCacheProgramDir(getProgramID());
}
static File getCacheProgramDir(String snippetID) {
return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID));
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
static BufferedImage img_getCenterPortion(BufferedImage img, int w, int h) {
int iw = img.getWidth(), ih = img.getHeight();
if (iw < w || ih < h) throw fail("Too small");
int x = (iw-w)/2, y = (ih-h)/2;
return clipBufferedImage(img, x, y, w, h);
}
static String programTitle() {
return getProgramName();
}
static BufferedImage loadPNG(File file) {
return loadBufferedImage(file);
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
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 BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage) return (BufferedImage) o;
String c = getClassName(o);
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
if (eq(c, "main$PNGFile"))
return (BufferedImage) call(o, "getImage");
return null;
}
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) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
static final WeakHashMap> getOpt_cache = new WeakHashMap();
static final HashMap getOpt_special = new HashMap(); // just a marker
static {
getOpt_cache.put(Class.class, getOpt_special);
getOpt_cache.put(String.class, getOpt_special);
}
static Object getOpt_cached(Object o, String field) { try {
if (o == null) return null;
Class c = o.getClass();
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
/*if (o instanceof S)
ret getOpt(getBot((S) o), field);*/
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null) return f.get(o);
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
return null;
} catch (Exception __e) { throw rethrow(__e); } }
// used internally - we are in synchronized block
static HashMap getOpt_makeCache(Class c) {
HashMap