import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
public class main {
public static void main(final String[] args) throws Exception {
String s;
printIndent(openStreetMap_localCountryName(print("Hamburg")));
printIndent(openStreetMap_localCountryName(print("New York")));
printIndent(s = openStreetMap_localCountryName(print("Israel")));
printIndent(openStreetMap_localCountryName(print("Nizza")));
printStruct(getOpt(openStreetMap_json("Israel"), "address"));
print(toHex(charsToDoubleBytes(s)));
}
static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static A printStruct(A a) {
printStructure(a);
return a;
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static volatile ThreadLocal> print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
max /= 2;
if (buf.length() > max) try {
int newLength = max/2;
int ofs = buf.length()-newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
}
static String openStreetMap_localCountryName(String place) {
return (String) getOpt((Map) getOpt(openStreetMap_json(place), "address"), "country");
}
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 String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static byte[] charsToDoubleBytes(String s) {
byte[] b = new byte[l(s)*2];
for (int i = 0; i < l(s); i++) {
int x = (int) s.charAt(i);
b[i*2] = (byte) (x >> 8);
b[i*2+1] = (byte) x;
}
return b;
}
static Map _registerThread_threads = synchroMap(new WeakHashMap());
static Thread _registerThread(Thread t) {
_registerThread_threads.put(t, true);
return t;
}
static Map openStreetMap_json(String query) {
return (Map) first(jsonDecodeList(loadPage("http://nominatim.openstreetmap.org/search/" + urlencode(query).replace("+", "%20") + "?format=json&addressdetails=1&limit=1")));
}
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 String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(mc()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static List jsonDecodeList(String s) {
Object o = jsonDecode(s);
if (o instanceof List)
return (List) o;
if (o instanceof Map && empty((Map) o))
return ll();
else
throw fail("Not a JSON list: " + s);
}
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
static boolean loadPage_anonymous; // don't send computer ID
static int loadPage_verboseness = 100000;
static int loadPage_retries = 60; // seconds
static ThreadLocal loadPage_silent = new ThreadLocal();
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 < loadPage_retries; tries++)
try {
URLConnection con = openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
}
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 {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
print("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + hideCredentials(url.toExternalForm()));
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
InputStream in = con.getInputStream();
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read");
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\s*charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return or(match, "ISO-8859-1");
}
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 String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
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 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 map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
f.setAccessible(true);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
getOpt_cache.put(c, map);
return map;
}
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 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 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 void printStructure(String prefix, Object o) {
if (endsWithLetter(prefix)) prefix += ": ";
print(prefix + structureForUser(o));
}
static void printStructure(Object o) {
print(structureForUser(o));
}
static List ll(A... a) {
return litlist(a);
}
static Object jsonDecode(final String text) {
final List tok = jsonTok(text);
class Y {
int i = 1;
Object parse() {
String t = tok.get(i);
if (t.startsWith("\"")) {
String s = unquote(tok.get(i));
i += 2;
return s;
}
if (t.equals("{"))
return parseMap();
if (t.equals("["))
return parseList();
if (t.equals("null")) {
i += 2; return null;
}
if (t.equals("false")) {
i += 2; return false;
}
if (t.equals("true")) {
i += 2; return true;
}
boolean minus = false;
if (t.equals("-")) {
minus = true;
i += 2;
t = get(tok, i);
}
if (isInteger(t)) {
i += 2;
if (eq(get(tok, i), ".")) {
String x = t + "." + get(tok, i+2);
i += 4;
double d = parseDouble(x);
if (minus) d = -d;
return d;
} else {
long l = parseLong(t);
if (minus) l = -l;
return l != (int) l ? new Long(l) : new Integer((int) l);
}
}
throw new RuntimeException("Unknown token " + (i+1) + ": " + t + ": " + text);
}
Object parseList() {
consume("[");
List list = new ArrayList();
while (!tok.get(i).equals("]")) {
list.add(parse());
if (tok.get(i).equals(",")) i += 2;
}
consume("]");
return list;
}
Object parseMap() {
consume("{");
Map map = new TreeMap();
while (!tok.get(i).equals("}")) {
String key = unquote(tok.get(i));
i += 2;
consume(":");
Object value = parse();
map.put(key, value);
if (tok.get(i).equals(",")) i += 2;
}
consume("}");
return map;
}
void consume(String s) {
if (!tok.get(i).equals(s)) {
String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
}
i += 2;
}
}
return new Y().parse();
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
static boolean empty(Map map) {
return map == null || map.isEmpty();
}
static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static Object mc() {
return getMainClass();
}
// 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 URLConnection openConnection(URL url) { try {
ping();
return url.openConnection();
} catch (Exception __e) { throw rethrow(__e); } }
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
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 void sleepSeconds(double s) {
if (s > 0) sleep(round(s*1000));
}
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 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 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();
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 hideCredentials(String url) {
return url.replaceAll("&_pass=[^&]*", "&_pass=");
}
static String structureForUser(Object o) {
structure_Data data = new structure_Data();
data.shareStringsLongerThan = Integer.MAX_VALUE;
return structure(o, data);
}
static boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
static void setHeaders(URLConnection con) throws IOException {
String computerID = getComputerID_quick();
if (computerID != null) try {
con.setRequestProperty("X-ComputerID", computerID);
con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
} catch (Throwable e) {
//printShortException(e);
}
}
static A or(A a, A b) {
return a != null ? a : b;
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static String exceptionToStringShort(Throwable e) {
e = getInnerException(e);
String msg = unnull(e.getMessage());
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + ": " + msg;
else
return msg;
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
throw fail(getClassName(o));
}
static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static final boolean loadPageThroughProxy_enabled = false;
static String loadPageThroughProxy(String url) {
return null;
}
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 String getComputerID_quick() {
File file = new File(userHome(), ".tinybrain/computer-id");
return assertNempty(loadTextFile(file.getPath(), null));
}
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();
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 RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 A last(List l) {
return l.isEmpty() ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static List jsonTok(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i); // cc is not needed in rest of loop body
// scan for non-whitespace (json strings, "null" identifier, numbers. everything else automatically becomes a one character token.)
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isLetter(c))
do ++j; while (j < l && Character.isLetter(s.charAt(j)));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static String getType(Object o) {
return getClassName(o);
}
static String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static boolean isLetter(char c) {
return Character.isLetter(c);
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static void sleep(long ms) {
ping();
if (ms < 0) return;
// allow spin locks
if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) { throw new RuntimeException(e); }
}
static void sleep() { try {
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) { throw rethrow(__e); } }
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
// get purpose 1: access a list/array (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.')+1);
}
static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
public static String unquote(String s) {
if (s == null) return null;
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
return s; // not quoted - return original
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static 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 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 Throwable getInnerException(Throwable e) {
while (e.getCause() != null)
e = e.getCause();
return e;
}
static boolean structure_showTiming, structure_checkTokenCount;
static String structure(Object o) {
return structure(o, new structure_Data());
}
static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack))
popLast(d.stack).run();
}
static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
// leave to false, unless unstructure() breaks
static boolean structure_allowShortening = false;
static class structure_Data {
PrintWriter out;
int stringSizeLimit;
int shareStringsLongerThan = 20;
IdentityHashMap