import java.math.*;
import javax.imageio.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.*;
import java.security.spec.*;
import java.security.*;
import java.lang.management.*;
import java.lang.ref.*;
import java.lang.reflect.*;
import java.net.*;
import java.io.*;
import javax.swing.table.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.List;
import java.util.zip.*;
import java.util.*;
public class main {
// a persistent map using a clever combination of persisting and logging
// (well, only logging as of now)
// Note: don't put in static initializer (programID not set yet)
static class PersistentMap extends AbstractMap {
Map m = new TreeMap();
File file;
PersistentMap(String fileName) {
this(getProgramFile(fileName));
}
PersistentMap(String progID, String fileName) {
this(getProgramFile(progID, fileName));
}
PersistentMap(File file) {
this.file = file;
for (String s : scanLog(file)) try {
List l = (List) ( unstructure(s));
if (eq(l.get(0), "add"))
m.put((A) l.get(1), (B) l.get(2));
else if (eq(l.get(0), "remove"))
m.remove((A) l.get(1));
else
print("Unknown command in log: " + l.get(0));
} catch (Throwable __e) { printStackTrace(__e); }
}
// just delegates
public int size() {
return m.size();
}
public B get(Object a) {
return m.get(a);
}
// TODO: calling remove() in the iterator will have unpersisted
// effects.
public Set> entrySet() {
return m.entrySet();
}
// delegates with logging
public B put(A a, B b) {
B result = m.put(a, b);
logQuoted(file, structure(litlist("add", a, b)));
return result;
}
public B remove(Object a) {
B result = m.remove(a);
logQuoted(file, structure(litlist("remove", a)));
return result;
}
}
static class Matches {
String[] m;
String get(int i) { return m[i]; }
String unq(int i) { return unquote(m[i]); }
String fsi(int i) { return formatSnippetID(unq(i)); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
}
static String url = "http://bots.tinybrain.de/1002076/raw";
static String param = "q";
static List> qlist = new ArrayList>(); // questions and answers
static List protocol = new ArrayList();
static class TuringScore {
String url;
long score, n;
long date;
}
static PersistentMap scores; // key = url
public static void main(String[] args) throws Exception {
scores = new PersistentMap("turing-scores.map");
tests();
prot("It is unix day " + unixDay() + ", and we are doing some Turing testing!");
prot("Test ID: " + formatSnippetID(getProgramID()));
prot();
prot("Made " + l(qlist) + " questions.");
prot();
prot("Checking " + url + "...");
int score = 0;
{ long __time_startTime = now(); try {
for (List qa : qlist) try {
String q = qa.get(0), a = qa.get(1);
String result = loadPage(url + hquery(param, q));
result = htmldecode(result);
prot(quote(q) + " => " + quote(result));
boolean ok = matchStart(a, result) || matchStart(quote(a), result);
if (ok) { ++score; prot("OK!"); }
} catch (Throwable __e) { printStackTrace(__e); }
} finally { __time_startTime = now()-__time_startTime; saveTiming(__time_startTime); } }
prot("");
prot(format("Score for *: * / *", url, score, l(qlist)));
TuringScore ts = new TuringScore();
ts.date = now();
ts.url = url;
ts.score = score;
ts.n = l(qlist);
logStructure(getProgramFile("turing-tests.log"), ts);
scores.put(url, ts);
saveTextFile(getProgramFile("protocol-" + urlencode(url)), fromLines(protocol));
}
static void add(String q, boolean yes) {
qlist.add(litlist(q, yes ? "yes" : "no"));
}
static void add(String q, long number) {
qlist.add(litlist(q, str(number)));
}
static void add(String q, String s) {
qlist.add(litlist(q, s));
}
static void prot(String s) {
print(s);
protocol.add(s);
}
static void prot() { prot(""); } // Turing
static void tests() {
questions();
}
static void questions() {
// example question just to test that the standard dialog module seems to be there.
add("are you a program", "yes");
}
static File getProgramFile(String progID, String fileName) {
return new File(getProgramDir(progID), fileName);
}
static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static String htmldecode(final String input) {
if (input == null) return null;
final int MIN_ESCAPE = 2;
final int MAX_ESCAPE = 6;
StringWriter writer = null;
int len = input.length();
int i = 1;
int st = 0;
while (true) {
// look for '&'
while (i < len && input.charAt(i-1) != '&')
i++;
if (i >= len)
break;
// found '&', look for ';'
int j = i;
while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
j++;
if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
i++;
continue;
}
// found escape
if (input.charAt(i) == '#') {
// numeric escape
int k = i + 1;
int radix = 10;
final char firstChar = input.charAt(k);
if (firstChar == 'x' || firstChar == 'X') {
k++;
radix = 16;
}
try {
int entityValue = Integer.parseInt(input.substring(k, j), radix);
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
if (entityValue > 0xFFFF) {
final char[] chrs = Character.toChars(entityValue);
writer.write(chrs[0]);
writer.write(chrs[1]);
} else {
writer.write(entityValue);
}
} catch (NumberFormatException ex) {
i++;
continue;
}
}
else {
// named escape
CharSequence value = htmldecode_lookupMap.get(input.substring(i, j));
if (value == null) {
i++;
continue;
}
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
writer.append(value);
}
// skip escape
st = j + 1;
i = st;
}
if (writer != null) {
writer.append(input.substring(st, len));
return writer.toString();
}
return input;
}
private static final String[][] htmldecode_ESCAPES = {
{"\"", "quot"}, // " - double-quote
{"&", "amp"}, // & - ampersand
{"<", "lt"}, // < - less-than
{">", "gt"}, // > - greater-than
// Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents.
{"\u00A0", "nbsp"}, // non-breaking space
{"\u00A1", "iexcl"}, // inverted exclamation mark
{"\u00A2", "cent"}, // cent sign
{"\u00A3", "pound"}, // pound sign
{"\u00A4", "curren"}, // currency sign
{"\u00A5", "yen"}, // yen sign = yuan sign
{"\u00A6", "brvbar"}, // broken bar = broken vertical bar
{"\u00A7", "sect"}, // section sign
{"\u00A8", "uml"}, // diaeresis = spacing diaeresis
{"\u00A9", "copy"}, // copyright sign
{"\u00AA", "ordf"}, // feminine ordinal indicator
{"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
{"\u00AC", "not"}, // not sign
{"\u00AD", "shy"}, // soft hyphen = discretionary hyphen
{"\u00AE", "reg"}, // registered trademark sign
{"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar
{"\u00B0", "deg"}, // degree sign
{"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign
{"\u00B2", "sup2"}, // superscript two = superscript digit two = squared
{"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed
{"\u00B4", "acute"}, // acute accent = spacing acute
{"\u00B5", "micro"}, // micro sign
{"\u00B6", "para"}, // pilcrow sign = paragraph sign
{"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot
{"\u00B8", "cedil"}, // cedilla = spacing cedilla
{"\u00B9", "sup1"}, // superscript one = superscript digit one
{"\u00BA", "ordm"}, // masculine ordinal indicator
{"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
{"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter
{"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half
{"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters
{"\u00BF", "iquest"}, // inverted question mark = turned question mark
{"\u00C0", "Agrave"}, // ? - uppercase A, grave accent
{"\u00C1", "Aacute"}, // ? - uppercase A, acute accent
{"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent
{"\u00C3", "Atilde"}, // ? - uppercase A, tilde
{"\u00C4", "Auml"}, // ? - uppercase A, umlaut
{"\u00C5", "Aring"}, // ? - uppercase A, ring
{"\u00C6", "AElig"}, // ? - uppercase AE
{"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla
{"\u00C8", "Egrave"}, // ? - uppercase E, grave accent
{"\u00C9", "Eacute"}, // ? - uppercase E, acute accent
{"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent
{"\u00CB", "Euml"}, // ? - uppercase E, umlaut
{"\u00CC", "Igrave"}, // ? - uppercase I, grave accent
{"\u00CD", "Iacute"}, // ? - uppercase I, acute accent
{"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent
{"\u00CF", "Iuml"}, // ? - uppercase I, umlaut
{"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic
{"\u00D1", "Ntilde"}, // ? - uppercase N, tilde
{"\u00D2", "Ograve"}, // ? - uppercase O, grave accent
{"\u00D3", "Oacute"}, // ? - uppercase O, acute accent
{"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent
{"\u00D5", "Otilde"}, // ? - uppercase O, tilde
{"\u00D6", "Ouml"}, // ? - uppercase O, umlaut
{"\u00D7", "times"}, // multiplication sign
{"\u00D8", "Oslash"}, // ? - uppercase O, slash
{"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent
{"\u00DA", "Uacute"}, // ? - uppercase U, acute accent
{"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent
{"\u00DC", "Uuml"}, // ? - uppercase U, umlaut
{"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent
{"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic
{"\u00DF", "szlig"}, // ? - lowercase sharps, German
{"\u00E0", "agrave"}, // ? - lowercase a, grave accent
{"\u00E1", "aacute"}, // ? - lowercase a, acute accent
{"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent
{"\u00E3", "atilde"}, // ? - lowercase a, tilde
{"\u00E4", "auml"}, // ? - lowercase a, umlaut
{"\u00E5", "aring"}, // ? - lowercase a, ring
{"\u00E6", "aelig"}, // ? - lowercase ae
{"\u00E7", "ccedil"}, // ? - lowercase c, cedilla
{"\u00E8", "egrave"}, // ? - lowercase e, grave accent
{"\u00E9", "eacute"}, // ? - lowercase e, acute accent
{"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent
{"\u00EB", "euml"}, // ? - lowercase e, umlaut
{"\u00EC", "igrave"}, // ? - lowercase i, grave accent
{"\u00ED", "iacute"}, // ? - lowercase i, acute accent
{"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent
{"\u00EF", "iuml"}, // ? - lowercase i, umlaut
{"\u00F0", "eth"}, // ? - lowercase eth, Icelandic
{"\u00F1", "ntilde"}, // ? - lowercase n, tilde
{"\u00F2", "ograve"}, // ? - lowercase o, grave accent
{"\u00F3", "oacute"}, // ? - lowercase o, acute accent
{"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent
{"\u00F5", "otilde"}, // ? - lowercase o, tilde
{"\u00F6", "ouml"}, // ? - lowercase o, umlaut
{"\u00F7", "divide"}, // division sign
{"\u00F8", "oslash"}, // ? - lowercase o, slash
{"\u00F9", "ugrave"}, // ? - lowercase u, grave accent
{"\u00FA", "uacute"}, // ? - lowercase u, acute accent
{"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent
{"\u00FC", "uuml"}, // ? - lowercase u, umlaut
{"\u00FD", "yacute"}, // ? - lowercase y, acute accent
{"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic
{"\u00FF", "yuml"}, // ? - lowercase y, umlaut
{"'", "apos"}, // the controversial (but who cares!) '
// stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes
};
private static final HashMap htmldecode_lookupMap;
static {
htmldecode_lookupMap = new HashMap();
for (final CharSequence[] seq : htmldecode_ESCAPES)
htmldecode_lookupMap.put(seq[1].toString(), seq[0]);
}
static String programID;
static String getProgramID() {
return programID;
}
// TODO: ask JavaX instead
static String getProgramID(Class c) {
return or((String) getOpt(c, "programID"), "?");
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static String hquery(Map params) {
return htmlQuery(params);
}
static String hquery(Object... data) {
return htmlQuery(data);
}
static String format(String pat, Object... args) {
return format3(pat, args);
}
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPageSilently(URL url) {
try {
IOException e = null;
for (int tries = 0; tries < 60; tries++)
try {
URLConnection con = url.openConnection();
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
print("Retrying because of: " + e);
sleepSeconds(1);
}
throw e;
} catch (IOException e) { throw new RuntimeException(e); }
}
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = "tinybrain.de:8080/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
return loadPage(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + url.toExternalForm());
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//Log.info("Content-Type: " + contentType);
String charset = loadPage_guessCharset(contentType);
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
//Log.info("Chars read: " + buf.length());
buf.append((char) ch);
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return m.matches() ? m.group(1) : "ISO-8859-1";
}
public static String fromLines(List lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (String line : lines)
buf.append(line).append('\n');
return buf.toString();
}
static int l(Object[] array) {
return array == null ? 0 : array.length;
}
static int l(byte[] array) {
return array == null ? 0 : array.length;
}
static int l(int[] array) {
return array == null ? 0 : array.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(String s) {
return s == null ? 0 : s.length();
}
static String str(Object o) {
return String.valueOf(o);
}
static StringBuffer print_log;
static void print() {
print("");
}
static void print(Object o) {
String s = String.valueOf(o) + "\n";
synchronized(StringBuffer.class) {
if (print_log == null) print_log = new StringBuffer();
}
print_log.append(s);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static String quote(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
}
static String quote(long l) {
return quote("" + l);
}
/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static void logStructure(File logFile, Object o) {
logQuoted(logFile, structure(o));
}
static long unixDay() {
return unixHour()/24;
}
static boolean matchStart(String pat, String s) {
return matchStart(pat, s, null);
}
// matches are as you expect, plus an extra item for the rest string
static boolean matchStart(String pat, String s, Matches matches) {
if (s == null) return false;
List tokpat = parse3(pat), toks = parse3(s);
if (toks.size() < tokpat.size()) return false;
String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) {
matches.m = new String[m.length+1];
arraycopy(m, matches.m);
matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size())); // for Matches.rest()
}
return true;
}
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
static String[] match2(List pat, List tok) {
// standard case (no ...)
int i = pat.indexOf("...");
if (i < 0) return match2_match(pat, tok);
pat = new ArrayList(pat); // We're modifying it, so copy first
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i+1, ""); // doesn't matter
}
return match2_match(pat, tok);
}
static String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
/*if (debug)
print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
/*if (debug)
print("Checking " + p + " against " + t);*/
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now
return null;
}
return result.toArray(new String[result.size()]);
}
static String format3(String pat, Object... args) {
if (args.length == 0) return pat;
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2)
if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static String format3_formatArg(Object arg) {
if (arg == null) return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg);
return quote(structure(arg));
}
static void sleepSeconds(long s) {
if (s > 0) sleep(s*1000);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static String htmlQuery(Map params) {
return params.isEmpty() ? "" : "?" + makePostData(params);
}
static String htmlQuery(Object... data) {
return htmlQuery(litmap(data));
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static void logQuoted(File logFile, String line) {
appendToFile(logFile, quote(line) + "\n");
}
static long unixHour() {
return unixTime()/(60*60);
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) fail("0 is not a snippet ID");
return id;
}
static void arraycopy(Object[] a, Object[] b) {
int n = min(a.length, b.length);
for (int i = 0; i < n; i++)
b[i] = a[i];
}
public static String join(String glue, Iterable strings) {
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 A or(A a, A b) {
return a != null ? a : b;
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static String structure(Object o) {
return structure(o, 0);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static String structure(Object o, int stringSizeLimit) {
if (o == null) return "null";
String name = o.getClass().getName();
StringBuilder buf = new StringBuilder();
if (o instanceof Collection) { // TODO: store the type (e.g. HashSet/TreeSet)
for (Object x : (Collection) o) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure(x, stringSizeLimit));
}
return "[" + buf + "]";
}
if (o instanceof Map) {
for (Object e : ((Map) o).entrySet()) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure(((Map.Entry) e).getKey(), stringSizeLimit));
buf.append("=");
buf.append(structure(((Map.Entry) e).getValue(), stringSizeLimit));
}
return (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}";
}
if (o.getClass().isArray()) {
int n = Array.getLength(o);
for (int i = 0; i < n; i++) {
if (buf.length() != 0) buf.append(", ");
buf.append(structure(Array.get(o, i), stringSizeLimit));
}
return "array{" + buf + "}";
}
if (o instanceof String)
return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
if (o instanceof Class)
return "class(" + quote(((Class) o).getName()) + ")";
if (o instanceof Throwable)
return "exception(" + quote(((Throwable) o).getMessage()) + ")";
if (o instanceof BigInteger)
return "bigint(" + o + ")";
// Need more cases? This should cover all library classes...
if (name.startsWith("java.") || name.startsWith("javax."))
return String.valueOf(o);
String shortName = o.getClass().getName().replaceAll("^main\\$", "");
int numFields = 0;
String fieldName = "";
if (shortName.equals("DynamicObject")) {
shortName = (String) get(o, "className");
Map fieldValues = (Map) get(o, "fieldValues");
for (String _fieldName : fieldValues.keySet()) {
fieldName = _fieldName;
Object value = fieldValues.get(fieldName);
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure(value, stringSizeLimit));
}
++numFields;
}
} else {
// regular class
// TODO: go to superclasses too
Field[] fields = o.getClass().getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
Object value;
try {
field.setAccessible(true);
value = field.get(o);
} catch (Exception e) {
value = "?";
}
fieldName = field.getName();
// put special cases here...
if (value != null) {
if (buf.length() != 0) buf.append(", ");
buf.append(fieldName + "=" + structure(value, stringSizeLimit));
}
++numFields;
}
}
String b = buf.toString();
if (numFields == 1 && structure_allowShortening)
b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
String s = shortName;
if (buf.length() != 0)
s += "(" + b + ")";
return s;
}
static Object getOpt(Object o, String field) {
if (o == null) return null;
if (o instanceof Class) return getOpt((Class) o, field);
if (o.getClass().getName().equals("main$DynamicObject"))
return call(getOpt_raw(o, "fieldValues"), "get", field);
return getOpt_raw(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 {
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) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
return null;
}
static Field getOpt_findField(Class> c, String field) {
for (Field f : c.getDeclaredFields())
if (f.getName().equals(field))
return f;
return null;
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static String shorten(String s, int max) {
if (s == null) return "";
return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
}
// Let's just generally synchronize this to be safe.
static synchronized void appendToFile(String path, String s) { try {
new File(path).getParentFile().mkdirs();
//print("[Logging to " + path + "]");
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path, true), "UTF-8"));
writer.write(s);
writer.close();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void appendToFile(File path, String s) {
appendToFile(path.getPath(), s);
}
static String makePostData(Map