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.dnd.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.DataFlavor;
import javax.swing.event.AncestorEvent;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.geom.AffineTransform;
import java.awt.geom.*;
import javax.swing.event.AncestorListener;
import javax.swing.Timer;
import java.awt.geom.*;
import java.awt.font.GlyphVector;
import java.awt.geom.*;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
class main {
public static void main(final String[] args) throws Exception {
WebThoughtSpace ts = new WebThoughtSpace();
ts.addWeb(webFromTriple("a sentence", "is", "a string of words"));
printStruct(ts);
//ai_applyWebFunctionToThoughtSpace(f web_reverseIs_ask);
for (WebRelation r : thoughtSpace_search_dollarXY(ts, "$X", "is", "$Y")) {
thoughtSpace_addQuestionTriple(ts, web_text(r.b), "is?", web_text(r.a));
}
printWebs(ts.webs);
}
static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static A printStruct(A a) {
printStructure(a);
return a;
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static String web_text(WebNode node) {
return node == null ? null : node.text();
}
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 List thoughtSpace_search_dollarXY(WebThoughtSpace ts, String a, String b, String c) {
return webs_search_dollarXY_rel(webFromTriples(a, b, c), thoughtSpace_indexedWebs(ts, a, b, c));
}
static void printWebs(Collection webs) {
for (Web web : webs) printWeb(web);
}
static boolean thoughtSpace_addQuestionTriple(WebThoughtSpace ts, String a, String b, String c) {
if (thoughtSpace_hasTriple(ts, a, b, c)) return false;
Web web = webFromTriple(a, b, c);
ts.addWeb(web);
ts.openQuestions.add(web);
return true;
}
static Web webFromTriple(String a, String b, String c) {
return webFromTriple(triple(a, b, c));
}
static Web webFromTriple(T3 t) {
return webFromTriple(t, 0.2, 0.2, 0.8, 0.7);
}
static Web webFromTriple(T3 t, double x1, double y1, double x2, double y2) {
Web web = webFromTriples(t.a, t.b, t.c);
web_setPosition(first(web.nodes), x1, y1);
web_setPosition(second(web.nodes), x2, y2);
return web;
}
static List thoughtSpace_indexedWebs(WebThoughtSpace ts, String... queries) {
List < List < WebNode > > lists = new ArrayList();
for (String q : queries)
if (!isDollarVar(q))
lists.add(ts.indexedNodes(q));
if (empty(lists)) return ts.webs;
return nodesToWebs(shortestList(lists));
}
static boolean thoughtSpace_hasTriple(WebThoughtSpace ts, String a, String b, String c) {
return webs_search_noVar_bool(
webFromTriples(a, b, c), thoughtSpace_indexedWebs(ts, a, b, c));
}
static A second(List l) {
return get(l, 1);
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static B second(T3 t) {
return t == null ? null : t.b;
}
static Web webFromTriples(String... l) {
Web web = simpleWeb();
for (int i = 0; i < l(l); i += 3) {
String a = unnull(get(l, i)), b = unnull(get(l, i+1)), c = unnull(get(l, i+2));
web_addRelation(web, a, c, b);
}
return web;
}
static Web webFromTriples(List l) {
return webFromTriples(toStringArray(l));
}
static List webs_search_dollarXY_rel(final Web searchWeb, Collection webs) {
List < Map > mappings = new ArrayList();
for (Web web : webs)
addIfNotNull(mappings, web_matchAllPerms_x(searchWeb, web, "nodeMatch_dollarVars"));
return map(mappings, new Object() { Object get(Map map) { try {
map = web_addRelationsToMapping(map);
return web_getRelation(map.get(web_findNodeOrRelation(searchWeb, "$X")),
map.get(web_findNodeOrRelation(searchWeb, "$Y")));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "map = web_addRelationsToMapping(map);\r\n ret web_getRelation(map.get(web_findN..."; }});
}
static T3 triple(A a, B b, C c) {
return new T3(a, b, c);
}
static WebNode web_setPosition(WebNode node, double x, double y) {
node.x = x;
node.y = y;
return node;
}
static void printWeb(Web web) {
if (web == null) { print("-"); return; }
List> relations = web_nonEmptyRelations(web);
print("Web " + web.globalID + " from " + web.source + ": " + n(web.nodes, "node") + ", " + n(relations, "relation"));
print();
pnlIndent(collectMethod(web_nonRelationNodes(web), "text"));
print();
web_printRelations(web);
}
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 void printStructure(String prefix, Object o) {
if (endsWithLetter(prefix)) prefix += ": ";
print(prefix + structureForUser(o));
}
static void printStructure(Object o) {
print(structureForUser(o));
}
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 A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static void web_printRelations(Web web) {
List> relations = web_nonEmptyRelations(web);
if (nempty(relations)) {
for (Pair p : relations) {
WebNode rel = web.relations.get(p);
String lbl = rel.text();
if (l(rel.labels) > 1) lbl += "+";
printIndent(p.a.text() + " -> " + lbl + " -> " + p.b.text());
}
print();
}
}
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 List collectMethod(Collection c, String methodName) {
return mapMethod(c, methodName);
}
static List Collection(String methodName, Collection c) {
return mapMethod(c, methodName);
}
static WebNode web_findNodeOrRelation(Web web, String name) {
WebNode n = web.findNode(name);
if (n != null) return n;
return web_findRelationWithLabel(web, name);
}
static boolean isDollarVar(String s) {
return startsWith(s, "$") && isIdentifier(substring(s, 1));
}
static boolean webs_search_noVar_bool(Web searchWeb, Collection webs) {
for (Web web : webs)
if (web_matchAllPerms(searchWeb, web) != null)
return true;
return false;
}
static void addIfNotNull(Collection l, A a) {
if (a != null) l.add(a);
}
// 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() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static void pnlIndent(Collection l) {
print_noNewLine(indentx(numberedLines(l)));
}
static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List> web_nonEmptyRelations(Web web) {
List> l = new ArrayList();
for (Pair r : keys(web.relations))
if (nempty(web.relations.get(r).labels))
l.add(r);
return l;
}
static boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
static RuntimeException rethrow(Throwable e) {
throw asRuntimeException(e);
}
static List shortestList(List> lists) {
Lowest < List < A > > best = new Lowest();
for (List l : lists)
best.put(l, l(l));
return best.get();
}
static Web simpleWeb() {
Web web = new Web();
web.useCLParse = false;
return web;
}
static Map web_addRelationsToMapping(Map map) {
Web web = firstKey(map).web;
Map map2 = cloneMap(map);
for (WebRelation rel : web_relationObjects(web)) {
WebNode a2 = map.get(rel.a), b2 = map.get(rel.b);
if (a2 != null && b2 != null)
mapPut(map2, rel, web_findRelationObject(a2, b2));
}
return map2;
}
static WebRelation web_getRelation(WebNode a, WebNode b) {
return a.web.getRelation(a, b);
}
static List web_nonRelationNodes(Web web) {
return listMinusSet(web.nodes, values(web.relations));
}
static void web_addRelation(WebNode a, WebNode b, String rel) {
if (a != null && b != null && rel != null)
a.web.getRelation(a, b).addLabel(rel);
}
static void web_addRelation(Web web, String a, String b, String rel) {
web_addRelation(web.node(a), web.node(b), rel);
}
static void web_addRelation(WebNode a, String rel, WebNode b) {
web_addRelation(a, b, rel);
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static int l(Lisp l) { return l == null ? 0 : l.size(); }
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static String n(Collection l, String name) {
return n(l(l), name);
}
static String n(Map m, String name) {
return n(l(m), name);
}
static String n(Object[] a, String name) {
return n(l(a), name);
}
static double nodeMatch_dollarVars(WebNode a, WebNode b) {
if (a.text().startsWith("$")) return b.text().startsWith("$") ? -1 : 0;
return containsAll(web_ucTexts(a), web_ucTexts(b)) ? 0 : -1;
}
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);
}
}
}
// nodeMatcher: func(WebNode, WebNode) -> double
static Map web_matchAllPerms_x(Web patternWeb, Web inputWeb, Object nodeMatcher) {
List patternNodes = web_nodes(patternWeb);
List inputNodes = web_nodes(inputWeb);
if (l(patternNodes) != l(inputNodes))
return null;
//fail("Can't match, differing number of nodes: " + l(patternNodes) + "/" + l(inputNodes));
List> perms = allPermutations(inputNodes);
Best < List < WebNode > > best = new Best();
for (List perm : perms)
best.put(perm, web_matchNodeLists_x(patternNodes, perm, nodeMatcher));
List l = best.getIfScoreAbove(0);
return l == null ? null : twoListsToOrderedMap(patternNodes, l);
}
static List nodesToWebs(Collection nodes) {
Set webs = litorderedset();
for (WebNode node : nodes)
webs.add(node.web);
return asList(webs);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
static List mapMethod(Collection c, final String methodName) {
return map(c, new Object() { Object get(Object o) { try { return callOpt(o, methodName) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callOpt(o, methodName)"; }});
}
static List mapMethod(String methodName, Collection c) {
return mapMethod(c, methodName);
}
static WeakHashMap> callF_cache = new WeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
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 LinkedHashSet litorderedset(A... items) {
LinkedHashSet set = new LinkedHashSet();
for (A a : items) set.add(a);
return set;
}
static void printIndent(Object o) {
print(indentx(str(o)));
}
static void printIndent(String indent, Object o) {
print(indentx(indent, str(o)));
}
static void printIndent(int indent, Object o) {
print(indentx(indent, str(o)));
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList() : 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 List web_ucTexts(WebNode node) {
return allToUpper(web_texts(node));
}
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 String indentx(String s) {
return indentx(indent_default, s);
}
static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static List web_nodes(Web web) {
return web_nonRelationNodes(web);
}
static A last(List l) {
return empty(l) ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static List getPlural_specials = ll("sheep", "fish");
static String getPlural(String s) {
if (containsIgnoreCase(getPlural_specials, s)) return s;
if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies";
if (ewic(s, "ss")) return s + "es";
if (ewic(s, "s")) return s;
return s + "s";
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static String numberedLines(Collection l) {
int i = 0;
List lines = new ArrayList();
if (l != null) for (A a : l) lines.add(((++i) + ". " + str(a)));
return lines(lines);
}
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(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getType(Object o) {
return getClassName(o);
}
static WebRelation web_findRelationWithLabel(Web web, String s) {
for (WebRelation r : web_relationObjects(web))
if (web_matchNodeName(r, s))
return r;
return null;
}
static A firstKey(Map map) {
return first(keys(map));
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine");
static String singular(String s) {
if (s == null) return null;
{ String _a_288 = singular_specials.get(s); if (!empty(_a_288)) return _a_288; }
{ String _a_289 = hippoSingulars().get(lower(s)); if (!empty(_a_289)) return _a_289; }
if (singular_specials2.contains(dropSuffix("s", s)))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
if (endsWith(s, "bases")) return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static WebRelation web_findRelationObject(WebNode a, WebNode b) {
return a.web.relations.get(pair(a, b));
}
static Collection web_relationObjects(Web web) {
return values(web.relations);
}
static String beautifyStructure(String s) {
return structure_addTokenMarkers(s);
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiMap mm) {
return mm.keySet();
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = (Map) synchroMap(newWeakHashMap());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(ping_actions) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static List> allPermutations(List l) {
List < List < A > > out = new ArrayList();
allPermutations_impl(cloneList(l), l(l), out);
return out;
}
static void allPermutations_impl(List l, int n, List> out) {
if (n <= 1) {
ping();
out.add(cloneList(l));
} else for(int i = 0; i < n; i++) {
allPermutations_impl(l, n-1, out);
swapElements(l, n % 2 == 0 ? i : 0, n-1);
}
}
static LinkedHashMap twoListsToOrderedMap(List l1, List l2) {
if (l(l1) != l(l2)) throw fail("Differing list size: " + l(l1) + "/" + l(l2));
LinkedHashMap map = new LinkedHashMap();
int n = l(l1);
for (int i = 0; i < n; i++)
map.put(l1.get(i), l2.get(i));
return map;
}
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 isLetter(char c) {
return Character.isLetter(c);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static List emptyList(int capacity) {
return new ArrayList(capacity);
}
// Try to match capacity
static List emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static List listMinusSet(Collection l, Collection stuff) {
if (empty(stuff)) return asList(l);
Set set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a)) l2.add(a);
return l2;
}
static boolean web_matchNodeLists_x_debug;
// nodeMatcher: func(WebNode, WebNode) -> double
static int web_matchNodeLists_x(List l1, List l2, Object nodeMatcher) {
if (l(l1) != l(l2)) return -1000;
int score = 0;
if (empty(l1)) return score;
HashMap map = twoListsToHashMap(l1, l2);
Web web = first(l1).web, web2 = first(l2).web;
// Score nodes
for (int i = 0; i < l(l1); i++) {
WebNode a = l1.get(i), b = l2.get(i);
score += toDouble(callF(nodeMatcher, a, b));
}
// Score relations
for (WebRelation rel : web_relationObjects(web)) {
WebNode aa = map.get(rel.a), bb = map.get(rel.b);
if (aa == null || bb == null) continue;
WebRelation rel2 = web2.getRelationOpt(aa, bb);
if (web_matchNodeLists_x_debug)
print("a=" + rel.a + ", b=" + rel.b + ", aa=" + aa + ", bb=" + bb + ", rel2 labels=" + (rel2 == null ? "-" : str(rel2.labels)) + ", labels=" + rel.labels);
//if (rel2 == null || !containsAll(rel2.labels, rel.labels))
// --score;
if (rel2 == null) --score;
else score += toDouble(callF(nodeMatcher, rel, rel2));
}
return score;
}
static Map cloneMap(Map map) {
if (map == null) return litmap();
// assume mutex is equal to collection
synchronized(map) {
return map instanceof TreeMap ? new TreeMap(map)
: map instanceof LinkedHashMap ? new LinkedHashMap(map)
: new HashMap(map);
}
}
static boolean containsAll(Collection extends A> a, Collection b) {
for (A o : b)
if (!a.contains(o))
return false;
return true;
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) {
return !isEmpty(o);
}
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static Map web_matchAllPerms(Web patternWeb, Web inputWeb) {
List patternNodes = web_nodes(patternWeb);
List inputNodes = web_nodes(inputWeb);
if (l(patternNodes) != l(inputNodes))
return null;
//fail("Can't match, differing number of nodes: " + l(patternNodes) + "/" + l(inputNodes));
List> perms = allPermutations(inputNodes);
Best < List < WebNode > > best = new Best();
for (List perm : perms)
best.put(perm, web_matchNodeLists(patternNodes, perm));
List l = best.getIfScoreAbove(0);
return l == null ? null : twoListsToOrderedMap(patternNodes, l);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
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 HashMap twoListsToHashMap(List l1, List l2) {
if (l(l1) != l(l2)) throw fail("Differing list size: " + l(l1) + "/" + l(l2));
HashMap map = new HashMap();
int n = l(l1);
for (int i = 0; i < n; i++)
map.put(l1.get(i), l2.get(i));
return map;
}
static HashMap twoListsToHashMap(A[] l1, A[] l2) {
return twoListsToHashMap(Arrays.asList(l1), Arrays.asList(l2));
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
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() & java.lang.reflect.Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
static String dropLast(String s, int n) {
return substring(s, 0, l(s)-n);
}
static String dropLast(int n, String s) {
return dropLast(s, n);
}
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
throw fail(o);
}
// 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 HashSet litset(A... items) {
return lithashset(items);
}
static Thread currentThread() {
return Thread.currentThread();
}
static String lower(String s) {
return s == null ? null : s.toLowerCase();
}
static char lower(char c) {
return Character.toLowerCase(c);
}
static List cloneList(Collection l) {
if (l == null) return new ArrayList();
// assume collection's mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does.
synchronized(l) {
return new ArrayList(l);
}
}
static Map litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length-1; i += 2)
if (x[i+1] != null)
map.put(x[i], x[i+1]);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
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 String dropSuffixIgnoreCase(String suffix, String s) {
return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static List web_texts(WebNode node) {
return node == null ? new ArrayList() : node.texts();
}
static Map hippoSingulars() {
return pairsToMap((List>) scanStructureLog("#1011041", "singulars"));
}
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 boolean web_matchNodeName(WebNode node, String pat) {
return eq(pat, "*") || eqic(pat, web_text(node));
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static List ll(A... a) {
return litlist(a);
}
static List allToUpper(Collection l) {
return map("upper", l);
}
static void swapElements(List l, int i, int j) {
if (i == j) return;
Object o = l.get(i);
l.set(i, l.get(j));
l.set(j, o);
}
static String structure_addTokenMarkers(String s) {
List tok = javaTok(s);
// find references
TreeSet refs = new TreeSet();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("t") && isInteger(t.substring(1)))
refs.add(parseInt(t.substring(1)));
}
if (empty(refs)) return s;
// add markers
for (int i : refs) {
int idx = i*2+1;
String t = "";
if (endsWithLetterOrDigit(tok.get(idx-1))) t = " ";
tok.set(idx, t + "m" + i + " " + tok.get(idx));
}
return join(tok);
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static boolean web_matchNodeLists_debug;
static int web_matchNodeLists(List l1, List l2) {
if (l(l1) != l(l2)) return -1000;
int score = 0;
if (empty(l1)) return score;
HashMap map = twoListsToHashMap(l1, l2);
Web web = first(l1).web, web2 = first(l2).web;
// Score nodes
for (int i = 0; i < l(l1); i++) {
WebNode a = l1.get(i), b = l2.get(i);
if (web_isAnythingVariable(a)) continue;
//if (neq(web_labels(a), web_labels(b))) --score;
if (!containsAll(web_labels(b), web_labels(a))) --score;
}
// Score relations
for (WebRelation rel : web_relationObjects(web)) {
WebNode aa = map.get(rel.a), bb = map.get(rel.b);
if (aa == null || bb == null) continue;
WebRelation rel2 = web2.getRelationOpt(aa, bb);
if (web_matchNodeLists_debug)
print("a=" + rel.a + ", b=" + rel.b + ", aa=" + aa + ", bb=" + bb + ", rel2 labels=" + (rel2 == null ? "-" : str(rel2.labels)) + ", labels=" + rel.labels);
if (rel2 == null || !containsAll(rel2.labels, rel.labels))
--score;
}
return score;
}
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() & java.lang.reflect.Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
}
static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && call_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
}
private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static List concatLists(Collection... lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection> lists) {
List l = new ArrayList();
for (List list : lists)
if (list != null)
l.addAll(list);
return l;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static int indent_default = 2;
static String indent(int indent) {
return repeat(' ', indent);
}
static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
static String indent(String s) {
return indent(indent_default, s);
}
static List indent(String indent, List lines) {
List l = new ArrayList();
for (String s : lines)
l.add(indent + s);
return l;
}
static Object callOpt(Object o) {
if (o == null) return null;
return callF(o);
}
static Object callOpt(Object o, String method, Object... args) {
try {
if (o == null) return null;
if (o instanceof Class) {
Method m = callOpt_findStaticMethod((Class) o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = callOpt_findMethod(o, method, args, false);
if (m == null) return null;
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
//fail(e.getMessage() + " | Method: " + method + ", receiver: " + className(o) + ", args: (" + join(", ", map(f className, args) + ")");
throw new RuntimeException(e);
}
}
static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++)
chars[i] = c;
return new String(chars);
}
static List repeat(A a, int n) {
List l = new ArrayList(n);
for (int i = 0; i < n; i++)
l.add(a);
return l;
}
static List repeat(int n, A a) {
return repeat(a, n);
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
static boolean containsIgnoreCase(Collection 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 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