Warning : session_start(): open(/var/lib/php/sessions/sess_j4ni7a23o6vkrag928hirv5669, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.TitledBorder;
import javax.swing.border.*;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.awt.geom.*;
import org.jnativehook.GlobalScreen;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyAdapter;
import java.text.SimpleDateFormat;
class main {
public static class DiscordFan extends DynPrintLogAndEnabled {
public transient Map protos = syncCIMap();
public IF1> segmenter;
public void cleanMeUp_shooter() {
{
cleanUp(shooter);
shooter = null;
}
}
public transient ScreenShooter shooter = new ScreenShooter();
public transient ReliableSingleThread rstSegment = dm_rst(module(), new Runnable() {
public void run() {
try {
segment();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "segment();";
}
});
public transient ReliableSingleThread rstAOA = dm_rst(module(), new Runnable() {
public void run() {
try {
aoa();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "aoa();";
}
});
public transient ImageInfo info, latestWithAOA;
public transient ImageSurface isThings;
public transient double minScore = 95;
public transient Thinker thinker = new Thinker();
public static boolean _switchableField_waitBeforeClick = true;
public double waitBeforeClick = 1.0;
public static boolean _switchableField_patience = true;
public double patience = 1.0;
public static class Segment extends BWImageAndRect {
public Segment() {
}
public Segment(Rect r) {
super(r);
}
}
public static class ImageInfo extends ImageWithProtos {
}
public JComponent visualize() {
return jvsplit(jCenteredSection("Things found on screen", jscroll_center(isThings = jDoubleBufferedImageSurface())), super.visualize());
}
public void start() {
super.start();
startThread("Start", new Runnable() {
public void run() {
try {
AutoCloseable __7 = enter();
try {
dm_watchFieldAndNow("enabled", new Runnable() {
public void run() {
try {
set(shooter, "enabled", enabled);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "set(shooter, +enabled)";
}
});
if (empty(protos))
putAll(protos, mapValues("loadBWImage", imageSnippetIDsForNames(llQuoted("Open", "Open discord"))));
print("Have " + n2(protos, "proto"));
if (segmenter == null)
setField("segmenter", segmenterFromAGIBlue("Find things on discordapp.com #1"));
print("Have segmenter: " + segmenter);
shooter.onNewImage.add(rstSegment);
shooter.start("enter", new F0() {
public AutoCloseable get() {
try {
return enter();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret enter();";
}
});
doEvery(1.0, new Runnable() {
public void run() {
try {
AutoCloseable __9 = enter();
try {
thinker.think();
} finally {
_close(__9);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); thinker.think()";
}
});
} finally {
_close(__7);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __7 = enter(); try { \r\n dm_watchFieldAndNow enabled(new Runn...";
}
});
}
public void segment() {
BufferedImage img = shooter.latestImage;
if (!enabled || img == null || segmenter == null)
return;
this.info = (ImageInfo) imageWithProtos_segment(segmenter, img, "iwpClass", ImageInfo.class, "segmentClass", Segment.class);
rstAOA.trigger();
}
public void aoa() {
ImageInfo info = this.info;
if (info == null)
return;
imageWithProtos_doAllOnAll(info, protos, "minScore", minScore, "isThings", isThings);
latestWithAOA = info;
}
public class Thinker {
public WaitForStableValue wait = new WaitForStableValue(patience);
public void think() {
if (!enabled)
return;
ImageInfo info = latestWithAOA;
if (info == null)
return;
Segment s = mapGet(info.foundProtos, quote("Open discord"));
Rect r = s == null ? null : s.rect;
print("r", r);
dm_moveMouseAndClick(wait.setAndClear(r), "Discord button");
}
}
}
public static boolean _moduleClass_DiscordFan = false;
public static Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A callF(F0 f) {
return f == null ? null : f.get();
}
public static A callF(IF0 f) {
return f == null ? null : f.get();
}
public static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
public static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
public static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
public static void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
public static Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
public static Object call(Object o) {
return callF(o);
}
public static Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
public static void _onLoad_initUtils() {
utils.__javax = javax();
}
public static void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
});
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent = false;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static volatile Object print_preprocess;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
public static void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable 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);
}
public static void print_autoRotate() {
}
public static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
public static Map syncCIMap() {
return (Map) synchroMap(caseInsensitiveMap());
}
public static boolean cleanUp_interruptThreads = false;
public static void cleanUp(Object c) {
if (c == null)
return;
if (c instanceof AutoCloseable) {
close_pcall(((AutoCloseable) c));
return;
}
if (c instanceof java.util.Timer) {
((java.util.Timer) c).cancel();
return;
}
if (c instanceof Collection) {
cleanUp((Collection) c);
return;
}
if (c instanceof Map) {
for (Object o : keys((Map) c)) cleanUp(o);
for (Object o : values((Map) c)) cleanUp(o);
((Map) c).clear();
return;
}
try {
preCleanUp(c);
setOpt(c, "ping_pauseAll", false);
innerCleanUp(c);
List androids = (List) getOpt(c, "record_list");
for (Object android : unnull(androids)) pcallOpt(android, "dispose");
List classes = (List) (getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) {
try {
cleanUp(cc.get());
} catch (Throwable __e) {
_handleException(__e);
}
}
if (cleanUp_interruptThreads) {
List threads = registeredThreads(c);
if (nempty(threads)) {
print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
interruptThreads(threads);
}
}
} catch (Throwable __e) {
_handleException(__e);
}
setOpt(c, "cleaningUp_flag", false);
if (c instanceof Class && ((Class) c).getName().equals("main"))
retireClassLoader(((Class) c).getClassLoader());
}
public static void cleanUp(Collection l) {
if (l == null)
return;
for (Object c : l) cleanUp(c);
l.clear();
}
public static ReliableSingleThread dm_rst(Runnable r) {
return dm_rst(dm_current_mandatory(), r);
}
public static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
public static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
public static JSplitPane jvsplit(Component n, Component s) {
return jvsplit(n, s, 0.5);
}
public static JSplitPane jvsplit(Component n, Component s, double splitPoint, int delay) {
return jvsplit(n, s, splitPoint);
}
public static JSplitPane jvsplit(Component n, Component s, double splitPoint) {
return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.VERTICAL_SPLIT, wrap(n), wrap(s)), splitPoint);
}
public static JSplitPane jvsplit(double splitPoint, Component n, Component s) {
return jvsplit(n, s, splitPoint);
}
public static JPanel jCenteredSection(Component c) {
return jCenteredSection("", c);
}
public static JPanel jCenteredSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = jSection(title, c);
((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = jSection(title, c);\r\n ((TitledBorder) p.getBorder()).setTitleJu...";
}
});
}
public static JPanel jCenteredSection(String title) {
return jCenteredSection(title, jpanel());
}
public static JScrollPane jscroll_center(Component c) {
return jscroll_centered(c);
}
public static ImageSurface jDoubleBufferedImageSurface() {
return doubleBufferedImageSurface();
}
public static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
public static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
public static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
public static void dm_watchFieldAndNow(String field, Runnable onChange) {
dm_watchField(field, onChange);
dm_q(onChange);
}
public static A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
public static void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_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());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static boolean empty(Collection c) {
return c == null || c.isEmpty();
}
public static boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
public static boolean empty(Map map) {
return map == null || map.isEmpty();
}
public static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
public 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);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
public static boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
public static boolean empty(float[] a) {
return a == null || a.length == 0;
}
public static boolean empty(int[] a) {
return a == null || a.length == 0;
}
public static boolean empty(long[] a) {
return a == null || a.length == 0;
}
public static boolean empty(byte[] a) {
return a == null || a.length == 0;
}
public static boolean empty(short[] a) {
return a == null || a.length == 0;
}
public static boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
public static boolean empty(File f) {
return getFileSize(f) == 0;
}
public static Map putAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
public static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
public static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
public static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
public static BWImage loadBWImage(String snippetIDOrURL) {
return new BWImage(loadBufferedImage(snippetIDOrURL));
}
public static BWImage loadBWImage(File f) {
return new BWImage(loadBufferedImage(f));
}
public static Map imageSnippetIDsForNames(Collection names) {
Map map = new HashMap();
for (Map m : listImageServer_rawData(paramsWithSameKey("name", names))) mapPut_noOverwrite(map, (String) m.get("name"), (String) m.get("id"));
return map;
}
public static List llQuoted(String... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (String x : a) l.add(quote(x));
return l;
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
public static ParameterizedSegmenter segmenterFromAGIBlue(String name) {
return parameterizedSegmenterFromAGIBlue(name);
}
public static FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
public static FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return timer;
}
public static FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
public static FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
public static void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
public static ImageWithProtos imageWithProtos_segment(IF1> segmenter, BufferedImage img, Object... __) {
if (img == null || segmenter == null)
return null;
long time = sysNow();
ImageWithProtos info = nu(optPar("iwpClass", __, ImageWithProtos.class));
info.image = img;
info.segments = map(segmenter.get(img), r -> nuObject(optPar("segmentClass", __, BWImageAndRect.class), r));
done2_always(time, "Make " + nSegments(info.segments));
return info;
}
public static void imageWithProtos_doAllOnAll(ImageWithProtos info, Map protos, Object... __) {
if (info == null)
return;
long time = sysNow();
double minScore = doublePar("minScore", __, 95);
AOA_CompareImagesToProtos aoa = info.aoa;
aoa.addProtos(protos);
for (BWImageAndRect s : info.segments) s.bw = toBWImage(bufferedImageClip(info.image, s.rect));
aoa.addImages(iotaKeys_str(collect("bw", info.segments)));
stepAll(aoa);
Map> bestImageForProto = aoa.bestImageForProto;
Map> foundProtos1 = filterMapByValuePredicate(bestImageForProto, v -> score(v) >= minScore / 100);
Map foundProtos = ciMap();
for (String proto : keys(foundProtos1)) {
Scored scoredImage = foundProtos1.get(proto);
mapPut(foundProtos, proto, getStartingWith1(info.segments, parseInt(scoredImage.get())));
}
info.foundProtos = foundProtos;
ImageSurface isThings = (ImageSurface) (optPar("isThings", __));
if (isThings != null)
isThings.setImage(mergeBWImagesHorizontally(map("bwInverted", collect("bw", values(info.foundProtos)))));
print(mapValues("doubleScoreAsIntPercent", bestImageForProto));
if (boolPar("printTiming", __))
done2_always("AOA", time);
}
public static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
public static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
public static String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public static String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
public 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 if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static boolean dm_moveMouseAndClick(Rect r, String targetName, Object... __) {
if (r == null)
return false;
Object enabled = (Object) (optPar("enabled", __));
double waitBeforeClick = doublePar("waitBeforeClick", __, 1.0);
print("Moving mouse to " + targetName + "!!!!");
Object mover = vmBus_query("mouseMover");
if (mover == null) {
print("No mover");
return false;
}
callWithImportExport(mover, "moveMouse", centerOfRect(r));
print("MOVED");
long startTime = sysNow();
while (licensed() && sysNow() < startTime + toMS(waitBeforeClick)) {
if (isFalse_callF(enabled))
return false;
if (isTrue_rcall("blocked", mover)) {
print("INTERFERENCE, EXITING");
return false;
}
sleepSeconds(0.05);
}
if (!r.contains(mouseLocationPt())) {
print("Mouse outside of target area, exiting");
return false;
}
print("CLICKING!");
rcall("click", mover);
print("CLICKED!");
return true;
}
public static Class mc() {
return main.class;
}
public static Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found in " + c);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Class javax() {
return getJavaX();
}
public static void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
public static HashMap findClass_fullName_cache = new HashMap();
public static Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static String substring(String s, int x) {
return substring(s, x, strL(s));
}
public 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);
}
public static String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
public static Object _defaultClassFinder_value = defaultDefaultClassFinder();
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static String programID;
public static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
public static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
public static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
public static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
public static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
public static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
public static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
public static Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
public static TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
public static void close_pcall(AutoCloseable c) {
if (c != null) {
try {
c.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiSet ms) {
return ms.keySet();
}
public static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
public static void preCleanUp(Object c) {
if (c instanceof Collection) {
for (Object o : ((Collection) c)) preCleanUp(o);
return;
}
callOpt(c, "licensed_off");
setOpt(c, "ping_anyActions", true);
setOpt(c, "cleaningUp_flag", true);
}
public static void innerCleanUp(Object c) {
if (!isFalse(pcallOpt(c, "cleanMeUp")))
for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try {
callOpt(c, name);
} catch (Throwable e) {
print("Error cleaning up: " + programID(c));
_handleException(e);
}
}
public static void innerCleanUp() {
innerCleanUp(mc());
}
public static String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
public static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
public static Object pcallOpt(Object o, String method, Object... args) {
try {
return callOpt(o, method, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static List registeredThreads(Object o) {
Map map = (Map) (getOpt(o, "_registerThread_threads"));
if (map == null)
return ll();
map.size();
synchronized (map) {
return asList(keys(map));
}
}
public static List registeredThreads() {
_registerThread_threads.size();
return asList(keys(_registerThread_threads));
}
public static boolean nempty(Collection c) {
return !empty(c);
}
public static boolean nempty(CharSequence s) {
return !empty(s);
}
public static boolean nempty(Object[] o) {
return !empty(o);
}
public static boolean nempty(byte[] o) {
return !empty(o);
}
public static boolean nempty(int[] o) {
return !empty(o);
}
public static boolean nempty(Map m) {
return !empty(m);
}
public static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
public static boolean nempty(Object o) {
return !empty(o);
}
public static String joinWithComma(Collection c) {
return join(", ", c);
}
public static String joinWithComma(String... c) {
return join(", ", c);
}
public static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
public static List allToString(Iterable c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
public static List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
public static void interruptThreads(Collection threads) {
for (Thread t : unnull(threads)) t.interrupt();
}
public static void interruptThreads(Class mainClass) {
interruptThreads(registeredThreads(mainClass));
}
public static void retireClassLoader(ClassLoader cl) {
if (isJavaXClassLoader(cl))
setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader());
}
public static F0 dm_rEnter(final DynModule mod) {
return mod == null ? null : new F0() {
public AutoCloseable get() {
try {
return mod.enter();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mod.enter();";
}
};
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static JSplitPane setSplitPaneOnFirstShowing(final Component c, final double value) {
final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
if (sp != null)
onFirstResize(sp, new Runnable() {
public void run() {
try {
sp.setDividerLocation(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sp.setDividerLocation(value);";
}
});
return sp;
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static A swing(IF0 f) {
return (A) swingAndWait(f);
}
public static JPanel jSection(Component c) {
return jSection("", c);
}
public static JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
public static JPanel jSection(String title) {
return jSection(title, jpanel());
}
public static JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
public static JPanel jpanel() {
return swingNu(JPanel.class);
}
public static JScrollPane jscroll_centered(Component c) {
return jscroll(jFullCenter(c));
}
public static ImageSurface doubleBufferedImageSurface() {
ImageSurface is = imageSurface();
setDoubleBuffered(is, true);
return is;
}
public static String defaultThreadName_name;
public static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
public static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
public static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
public static Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
public static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
public static Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
public static Map _registerThread_threads;
public static Object _onRegisterThread;
public static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
public static void _registerThread() {
_registerThread(Thread.currentThread());
}
public static void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
public static Q dm_q() {
return dm_current_mandatory().q();
}
public static void dm_q(Runnable r) {
dm_inQ(r);
}
public static void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
public static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
public static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
public static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
public static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
public static String getType(Object o) {
return getClassName(o);
}
public static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
public static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
public static boolean loadBufferedImage_useImageCache = true;
public static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) {
try {
ping();
if (snippetIDOrURLOrFile == null)
return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedImage loadBufferedImage(File file) {
try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static List listImageServer_rawData(Object... __) {
return loadJSONList("https://botcompany.de/images/bot/list" + hquery(__));
}
public static Object[] paramsWithSameKey(Object key, Collection values) {
return paramsWithSameKey(key, asObjectArray(values));
}
public static Object[] paramsWithSameKey(Object key, Object... values) {
int n = l(values);
Object[] o = new Object[n * 2];
for (int i = 0; i < n; i++) {
o[i * 2] = key;
o[i * 2 + 1] = values[i];
}
return o;
}
public static void mapPut_noOverwrite(Map map, A key, B value) {
if (map != null && key != null && value != null && !map.containsKey(key))
map.put(key, value);
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static ParameterizedSegmenter parameterizedSegmenterFromAGIBlue(String name) {
ParameterizedSegmenter segmenter = new ParameterizedSegmenter();
List> values = agiBlue_lookupMultipleKeys(agiBlue_imageSegmentationSlice(), name, nonTransientNonStaticFieldNames(segmenter));
if (empty(values))
return null;
for (Pair __220 : values) {
String key = pairA(__220);
String value = pairB(__220);
set(segmenter, key, safeUnstructureAllowingCertainClasses_plusUtils(value, "Rect", "DoubleRange"));
}
return segmenter;
}
public static int shorten_default = 100;
public static String shorten(String s) {
return shorten(s, shorten_default);
}
public static String shorten(String s, int max) {
return shorten(s, max, "...");
}
public static String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
public static String shorten(int max, String s) {
return shorten(s, max);
}
public static TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
public static class SmartTimerTask extends TimerTask {
public static String _fieldOrder = "r timer delay threadInfo lastRun";
public Object r;
public java.util.Timer timer;
public long delay;
public Object threadInfo;
public SmartTimerTask() {
}
public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;
}
public String toString() {
return "SmartTimerTask(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
}
public long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __225 = tempActivity(r);
try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay * 0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally {
_close(__225);
}
}
}
}
public static int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
public static int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
public static long toMS(double seconds) {
return (long) (seconds * 1000);
}
public static long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
public static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
public static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
public static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
public static Object optPar(String name, Map params) {
return optParam(name, params);
}
public static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public 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;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
public static List map(IF1 f, Iterable l) {
return map(l, f);
}
public static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(IF1 f, A[] l) {
return map(l, f);
}
public static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(Object f, Object[] l) {
return map(f, asList(l));
}
public static List map(Object[] l, Object f) {
return map(f, l);
}
public static List map(Object f, Map map) {
return map(map, f);
}
public 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;
}
public static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
public static Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static long done2_always(long startTime, String desc) {
long time = sysNow() - startTime;
print(desc + " [" + time + " ms]");
return time;
}
public static long done2_always(String desc, long startTime) {
return done2_always(startTime, desc);
}
public static long done2_always(long startTime) {
return done2_always(startTime, "");
}
public static String nSegments(long n) {
return n2(n, "segment");
}
public static String nSegments(Collection l) {
return nSegments(l(l));
}
public static double doublePar(String name, Object[] __, double defaultValue) {
Number n = (Number) (optPar(name, __));
return n == null ? defaultValue : n.doubleValue();
}
public static BWImage toBWImage(RGBImage img) {
return toBW(img);
}
public static BWImage toBWImage(BufferedImage img) {
return img == null ? null : new BWImage(img);
}
public static BufferedImage bufferedImageClip(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, clip);
}
public static BufferedImage bufferedImageClip(BufferedImage src, Rect r) {
return clipBufferedImage(src, r);
}
public static BufferedImage bufferedImageClip(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, x, y, w, h);
}
public static Map iotaKeys_str(Collection l) {
LinkedHashMap map = new LinkedHashMap();
int i = 0;
for (A a : unnull(l)) map.put(str(++i), a);
return map;
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static void stepAll(Steppable s) {
if (s != null)
while (s.step()) {
ping();
}
}
public static Map filterMapByValuePredicate(Map map, IF1 pred) {
return filterMap(map, new F2() {
public Boolean get(A key, B value) {
try {
return pred.get(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pred.get(value)";
}
});
}
public static float score(Scored s) {
return s == null ? 0 : s.score();
}
public static TreeMap ciMap() {
return caseInsensitiveMap();
}
public static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
public static A getStartingWith1(List l, int i) {
return _get(l, i - 1);
}
public static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
public static int parseInt(char c) {
return Integer.parseInt(str(c));
}
public static BWImage mergeBWImagesHorizontally(BWImage... images) {
return mergeBWImagesHorizontally(toList(images));
}
public static BWImage mergeBWImagesHorizontally(List images, Object... params) {
if (empty(images))
return null;
int spacing = imageMergeSpacing();
float spaceColor = toFloat(optPar(params, "spaceColor", 0.9f));
int w = intSum(images, "width") + (l(images) - 1) * spacing, h = intMax(images, "height");
BWImage out = new BWImage(w, h, spaceColor);
int x = 0;
for (int i = 0; i < l(images); i++) {
BWImage img = images.get(i);
int y = (h - img.h()) / 2;
copyBWImage(img, 0, 0, out, x, y);
x += img.w() + spacing;
}
return out;
}
public static BWImage bwInverted(BWImage bw) {
if (bw == null)
return bw;
int w = bw.getWidth(), h = bw.getHeight();
BWImage bw2 = new BWImage(w, h);
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) bw2.setInt(x, y, 255 - bw.getInt(x, y));
return bw2;
}
public static int doubleScoreAsIntPercent(Scored s) {
return toIntPercent(doubleScore(s));
}
public static boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
public static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Map __) {
return boolOptParam(name, __);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __72 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__72 != null)
return __72;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
public static MouseMover mouseMover_instance;
public static MouseMover mouseMover() {
if (mouseMover_instance == null) {
swing(new Runnable() {
public void run() {
try {
if (mouseMover_instance == null) {
mouseMover_instance = new MouseMover();
mouseMover_instance.enable();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (mouseMover_instance == null) {\r\n mouseMover_instance = new MouseMove...";
}
});
}
return mouseMover_instance;
}
public static void cleanMeUp_mouseMover() {
cleanUp(mouseMover_instance);
}
public static Object callWithImportExport(Object o, String method, Object... args) {
return quickImport(call(o, method, (Object[]) quickExport(args, o)));
}
public static Pt centerOfRect(Rect r) {
return r == null ? null : new Pt(r.x + r.w / 2, r.y + r.h / 2);
}
public static volatile boolean licensed_yes = true;
public static boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
public static void licensed_off() {
licensed_yes = false;
}
public static boolean isFalse_callF(Object condition, Object... args) {
return isFalse(callF(condition, args));
}
public static boolean isTrue_rcall(String method, Object o, Object... args) {
return isTrue(rcall(method, o, args));
}
public static void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
public static Pt mouseLocationPt() {
return mousePointer();
}
public static Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
public static void click(Rect r) {
mouseClickAfterMove(r);
}
public static final Map callOpt_cache = newDangerousWeakHashMap();
public static Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
public static Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
public static List classNames(Collection l) {
return getClassNames(l);
}
public static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
public static int strL(String s) {
return s == null ? 0 : s.length();
}
public static int listL(Collection l) {
return l == null ? 0 : l.size();
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "loadableUtils.utils$"))
return findClass_fullName("main" + substring(name, 19));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
};
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
public static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
public static Class getMainClass() {
return mc();
}
public static Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean ping_pauseAll = false;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions = false;
public static Map ping_actions = newWeakHashMap();
public static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
public static boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
public static boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
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);
}
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
public static void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
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);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
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);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
public static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
public static Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List sorted(Collection c, final Object comparator) {
List l = cloneList(c);
sort(l, makeComparator(comparator));
return l;
}
public static List sorted(Collection c) {
List l = cloneList(c);
sort(l);
return l;
}
public static List methodsStartingWith(Object o, final String prefix) {
return filter(allMethodNames(o), new F1() {
public Object get(String s) {
try {
return startsWith(s, prefix);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startsWith(s, prefix)";
}
});
}
public static Map emptyMap() {
return new HashMap();
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) 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(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static boolean isJavaXClassLoader(ClassLoader cl) {
return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader");
}
public static void setOptAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) setOpt(o, field, fields.get(field));
}
public static void setOptAll(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
setOpt(o, field, value);
}
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
public static List childrenOfType(Class theClass, Component c) {
return childrenOfType(c, theClass);
}
public static void onFirstResize(final Component c, final Object r) {
if (c != null && r != null) {
swing(new Runnable() {
public void run() {
try {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
c.removeComponentListener(this);
pcallF(r);
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.addComponentListener(new ComponentAdapter {\r\n public void componentRes...";
}
});
}
}
public static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
public static JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
public static JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static JPanel jFullCenter(final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;";
}
});
}
public static ImageSurface imageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
public static ImageSurface imageSurface() {
return swingNu(ImageSurface.class);
}
public static A setDoubleBuffered(A c, boolean b) {
{
swing(new Runnable() {
public void run() {
try {
if (c != null)
c.setDoubleBuffered(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c?.setDoubleBuffered(b);";
}
});
}
return c;
}
public static Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static void dm_inQ(Runnable r) {
dm_q().add(r);
}
public static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
public static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
public static BufferedImage imageIO_readURL(String url) {
try {
if (startsWith(url, "https:"))
disableCertificateValidation();
return ImageIO.read(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
public static boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
public static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
public static File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
public static String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
public static String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
public static List loadJSONList(String url) {
return (List) loadJSONPage(url);
}
public static String hquery(Map params) {
return htmlQuery(params);
}
public static String hquery(Object... data) {
return htmlQuery(data);
}
public static Object[] asObjectArray(Collection l) {
return toObjectArray(l);
}
public static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
public static String trim(StringBuilder buf) {
return buf.toString().trim();
}
public static String trim(StringBuffer buf) {
return buf.toString().trim();
}
public static List> agiBlue_lookupMultipleKeys(String sliceID, String q, Collection keys) {
return map((List>) agiBlue_loadBotPage("lookupMultipleKeys", paramsPlus_noOverwrite(paramsWithSameKey("key", keys), "slice", sliceID, "q", q)), map -> pair(map.get("key"), map.get("value")));
}
public static String agiBlue_imageSegmentationSlice() {
return "lgobeactljkewwtz";
}
public static Set nonTransientNonStaticFieldNames(Object o) {
return allNonStaticNonTransientFields(o);
}
public static A pairA(Pair p) {
return p == null ? null : p.a;
}
public static B pairB(Pair p) {
return p == null ? null : p.b;
}
public static Object safeUnstructureAllowingCertainClasses_plusUtils(String s, String... allowedClasses) {
Set allowedClassesSet = new HashSet();
for (String name : unnull(allowedClasses)) {
allowedClassesSet.add("main$" + name);
allowedClassesSet.add("loadableUtils.utils$" + name);
}
Object classFinder = new F1() {
public Object get(String name) {
try {
if (!allowedClassesSet.contains(name))
throw fail("Class not allowed to unstructure: " + name);
return classForName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!allowedClassesSet.contains(name)) fail(\"Class not allowed to unstructure...";
}
};
return unstructure(s, false, classFinder);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static float min(float a, float b) {
return Math.min(a, b);
}
public static float min(float a, float b, float c) {
return min(min(a, b), c);
}
public static double min(double a, double b) {
return Math.min(a, b);
}
public static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
public static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
public static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
public static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
public static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
public static AutoCloseable tempActivity(Object r) {
return null;
}
public static long fixTimestamp(long timestamp) {
return timestamp > now() ? 0 : timestamp;
}
public static long now_virtualTime;
public static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
public static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
public static A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
public static B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static A setAll(A o, Map fields) {
if (fields == null)
return o;
for (String field : keys(fields)) set(o, field, fields.get(field));
return o;
}
public static A setAll(A o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
return o;
}
public static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
public static A optParam(ThreadLocal tl) {
return optPar(tl);
}
public static Object optParam(String name, Map params) {
return mapGet(params, name);
}
public static A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
public static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
public static Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
public static Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
public static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
public static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
public static BWImage toBW(RGBImage img) {
return img == null ? null : new BWImage(img);
}
public static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, new Rect(clip));
}
public static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
if (src == null || r == null)
return null;
r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
if (rectEmpty(r))
return null;
return src.getSubimage(r.x, r.y, r.w, r.h);
}
public static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, new Rect(x, y, w, h));
}
public static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
public static Map filterMap(Map map, Object f) {
Map m2 = similarEmptyMap(map);
for (A a : keys(map)) {
B b = map.get(a);
if (isTrue(callF(f, a, b)))
m2.put(a, b);
}
return m2;
}
public static Map filterMap(Object f, Map map) {
return filterMap(map, f);
}
public static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static Object _get(Object o, String field) {
return get(o, field);
}
public static Object _get(String field, Object o) {
return get(o, field);
}
public static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static ArrayList toList(A[] a) {
return asList(a);
}
public static ArrayList toList(int[] a) {
return asList(a);
}
public static ArrayList toList(Set s) {
return asList(s);
}
public static ArrayList toList(Iterable s) {
return asList(s);
}
public static int imageMergeSpacing = 5;
public static int imageMergeSpacing() {
return imageMergeSpacing;
}
public static void imageMergeSpacing(int pixels) {
imageMergeSpacing = pixels;
}
public static float toFloat(Object o) {
if (o == null)
return 0f;
if (o instanceof Number)
return ((Number) o).floatValue();
if (o instanceof Boolean)
return ((Boolean) o).booleanValue() ? 1f : 0f;
throw fail("Not convertible to float: " + _getClass(o));
}
public static int intSum(Collection c, String field) {
int sum = 0;
for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
return sum;
}
public static int intSum(Iterable l) {
int sum = 0;
for (Integer i : unnull(l)) if (i != null)
sum += i;
return sum;
}
public static int intMax(Collection c, String field) {
int max = Integer.MIN_VALUE;
for (Object o : c) max = Math.max(max, toInt(getOpt(o, field)));
return max;
}
public static int intMax(Iterable l) {
int max = Integer.MIN_VALUE;
for (int i : unnull(l)) max = Math.max(max, i);
return max;
}
public static void copyBWImage(BWImage src, int srcX, int srcY, BWImage dst, int dstX, int dstY) {
copyBWImage(src, srcX, srcY, dst, dstX, dstY, src.getWidth() - srcX, src.getHeight() - srcY);
}
public static void copyBWImage(BWImage src, int srcX, int srcY, BWImage dst, int dstX, int dstY, int w, int h) {
w = min(w, dst.getWidth() - dstX);
h = min(h, dst.getHeight() - dstY);
w = min(w, src.getWidth() - srcX);
h = min(h, src.getHeight() - srcY);
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) dst.setByte(dstX + x, dstY + y, src.getByte(srcX + x, srcY + y));
}
public static int toIntPercent(double ratio) {
return roundToInt(ratio * 100);
}
public static int toIntPercent(float ratio) {
return toIntPercent((double) ratio);
}
public static double doubleScore(Scored s) {
return s == null ? 0 : (double) s.score();
}
public static boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
public static boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
public static boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
public static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __274 = pcallF(f, args);
if (__274 != null)
return __274;
}
return null;
}
public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __276 = pcallF(it.next(), args);
if (__276 != null)
return __276;
}
return null;
}
public static Set vm_busListeners_live_cache;
public static Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
public static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
public static Map vm_busListenersByMessage_live_cache;
public static Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
public static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
public static Object quickImport(Object o) {
return quickExport(o, mc());
}
public static Object quickExport(Object o, Object dest) {
return quickExport_impl(o, dest, new IdentityHashMap(), new HashMap());
}
public static Object quickExport(Object o, Object dest, int expectedNumberOfObjects) {
return quickExport_impl(o, dest, new IdentityHashMap(expectedNumberOfObjects), new HashMap());
}
public static Object quickExport_impl(Object o, Object dest, IdentityHashMap seen, HashMap classMap) {
try {
if (o == null || o instanceof String || o instanceof Number)
return o;
Object oo = seen.get(o);
if (oo != null)
return oo;
if (o instanceof Object[]) {
Object[] l = (Object[]) o;
Object[] destO = newObjectArrayOfSameType(l, l.length);
seen.put(o, destO);
for (int i = 0; i < l.length; i++) destO[i] = quickExport_impl(l[i], dest, seen, classMap);
return destO;
}
if (o instanceof List) {
List l = (List) o;
List destO = new ArrayList(l.size());
seen.put(o, destO);
for (int i = 0; i < l.size(); i++) destO.add(quickExport_impl(l.get(i), dest, seen, classMap));
return destO;
}
if (o instanceof Map) {
Map m = (Map) o;
Map destO = new HashMap();
seen.put(o, destO);
for (Object e : ((Map) o).entrySet()) destO.put(quickExport_impl(((Map.Entry) e).getKey(), dest, seen, classMap), quickExport_impl(((Map.Entry) e).getValue(), dest, seen, classMap));
return destO;
}
Class c = o.getClass();
String className = c.getName();
className = loadableUtilsClassNameToMain(className);
if (className.startsWith("main$")) {
Class destClass = classMap.get(c);
if (destClass == null) {
if (!classMap.containsKey(c)) {
if (!isAnonymousClassName(className))
destClass = getClass_vmName_withLoadableUtils(dest, className);
classMap.put(c, destClass);
}
if (destClass == null)
return o;
}
if (c == destClass)
return o;
Object destO = nuObjectWithoutArguments(destClass);
seen.put(o, destO);
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
Object value = field.get(o);
setOpt(destO, field.getName(), quickExport_impl(value, dest, seen, classMap));
}
c = c.getSuperclass();
}
return destO;
}
return o;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean sleep_noSleep = false;
public static void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static long round(double d) {
return Math.round(d);
}
public static Pt mousePointer() {
return new Pt(getMouseLocation());
}
public static void mouseClickAfterMove(Rect r) {
if (r == null)
throw fail("Nothing to click on");
moveMouseTo(r);
mouseClick();
}
public static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
public static String joinWithSpace(Collection c) {
return join(" ", c);
}
public static String joinWithSpace(String... c) {
return join(" ", c);
}
public static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
public static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
public static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
public static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
public static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
public static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
public static betterCIComparator_C betterCIComparator_instance;
public static betterCIComparator_C betterCIComparator() {
if (betterCIComparator_instance == null)
betterCIComparator_instance = new betterCIComparator_C();
return betterCIComparator_instance;
}
public static class betterCIComparator_C implements Comparator {
public int compare(String s1, String s2) {
if (s1 == null)
return s2 == null ? 0 : -1;
if (s2 == null)
return 1;
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
return c1 - c2;
}
}
}
}
return n1 - n2;
}
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
public static void sort(T[] a) {
Arrays.sort(a);
}
public static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
public static void sort(List a) {
Collections.sort(a);
}
public static Comparator makeComparator(final Object f) {
if (f instanceof Comparator)
return (Comparator) f;
return new Comparator() {
public int compare(Object a, Object b) {
return (Integer) callF(f, a, b);
}
};
}
public static List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
public static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
public static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
public static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
public static List allMethodNames(Object o) {
Class c = _getClass(o);
TreeSet names = new TreeSet();
while (c != null) {
for (Method m : c.getDeclaredMethods()) names.add(m.getName());
c = c.getSuperclass();
}
return asList(names);
}
public static Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
public static Object collectionMutex(List l) {
return l;
}
public static Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
public static String className(Object o) {
return getClassName(o);
}
public static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
public static void scanForComponents(final Component c, final Class theClass, final List l) {
if (theClass.isInstance(c))
l.add((A) c);
if (c instanceof Container) {
swing(new Runnable() {
public void run() {
try {
for (Component comp : ((Container) c).getComponents()) scanForComponents(comp, theClass, l);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (Component comp : ((Container) c).getComponents())\r\n scanForComponen...";
}
});
}
}
public static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
public static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
public static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
public static volatile boolean disableCertificateValidation_attempted = false;
public static void disableCertificateValidation() {
try {
if (disableCertificateValidation_attempted)
return;
disableCertificateValidation_attempted = true;
try {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
public static A proxy(Class intrface, final Object target) {
if (target == null)
return null;
if (isInstance(intrface, target))
return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return call(target, method.getName(), unnull(args));
}
});
}
public static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
public static File javaxCachesDir_dir;
public static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
public static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
public static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
public static String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
public static String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
public static String snippetImageURL(String snippetID, String contentType) {
if (isURL(snippetID))
return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (id == 1000010 || id == 1000012)
url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id;
else if (isImageServerSnippet(id))
url = imageServerLink(id);
else
url = "https://www.botcompany.de:8443/img/" + id;
return url;
}
public static Object loadJSONPage(String url) {
return jsonDecode(loadPage(url));
}
public static String htmlQuery(Map params) {
return empty(params) ? "" : "?" + makePostData(params);
}
public static String htmlQuery(Object... data) {
return empty(data) ? "" : "?" + makePostData(data);
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static Object agiBlue_loadBotPage(String cmd, Object... params) {
return loadJSONPage(agiBlueURL() + "/bot" + addSlashPrefix(cmd) + hquery(params));
}
public static Object[] paramsPlus_noOverwrite(Object[] a1, Object... a2) {
if (a2 == null || l(a2) == 2 && a2[0] == null)
return a1;
if (a1 == null)
return a2;
return concatArrays(assertEvenLength(a1), assertEvenLength(a2));
}
public static Pair pair(A a, B b) {
return new Pair(a, b);
}
public static Pair pair(A a) {
return new Pair(a, a);
}
public static Set allNonStaticNonTransientFields(Object o) {
TreeSet fields = new TreeSet();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)
fields.add(f.getName());
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
public static Object unstructure(String text) {
return unstructure(text, false);
}
public static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
public static int structure_internStringsLongerThan = 50;
public static int unstructure_unquoteBufSize = 100;
public static int unstructure_tokrefs;
public abstract static class unstructure_Receiver {
public abstract void set(Object o);
}
public static Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
public static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
throw fail("unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
throw fail("unsatisfied token reference " + ref + " at " + tokIndex);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("ll")) {
consume();
{
parseList(new LinkedList(), out);
return;
}
}
if (t.equals("syncLL")) {
consume();
{
parseList(synchroLinkedList(), out);
return;
}
}
if (t.equals("sync")) {
consume();
{
parse(new unstructure_Receiver() {
public void set(Object value) {
if (value instanceof Map) {
if (value instanceof NavigableMap) {
out.set(Collections.synchronizedNavigableMap((NavigableMap) value));
return;
}
if (value instanceof SortedMap) {
out.set(Collections.synchronizedSortedMap((SortedMap) value));
return;
}
{
out.set(Collections.synchronizedMap((Map) value));
return;
}
} else {
out.set(Collections.synchronizedList((List) value));
return;
}
}
});
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
this.parseList(new ArrayList(), out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray")) {
parseArray(out);
return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume();
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
if (eq(t, "cu")) {
consume();
t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = "main$" + t;
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c == null)
throw fail("Class not found: " + fullClassName);
final Object o = nuEmptyObject(c);
out.set(o);
parse(new unstructure_Receiver() {
public void set(Object value) {
call(o, "_deserialize", value);
}
});
return;
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava());
return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + t);
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = "main$" + t;
}
if (c == null) {
if (allDynamic)
c = null;
else
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c != null)
classesMap.put(className, c);
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
final LinkedHashMap fields = new LinkedHashMap();
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ","))
consume();
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
String t = tpp();
if (!eq(t, "="))
throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t())...";
}
});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
setOptAllDyn(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
else
for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume();
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r...";
}
});
}
public void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix("main$", name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v = false;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_initial(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
Boolean b = DynamicObject_loading.get();
DynamicObject_loading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_initial(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
DynamicObject_loading.set(b);
}
}
public static boolean unstructure_debug = false;
public static Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
public static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
public static Rect intersectRects(Rect a, Rect b) {
int x = max(a.x, b.x), y = max(a.y, b.y);
int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h);
return new Rect(x, y, x2 - x, y2 - y);
}
public static boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
public static int roundToInt(double d) {
return (int) Math.round(d);
}
public static A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
public static String loadableUtilsClassNameToMain(String className) {
String c = dropPrefixOrNull("loadableUtils.utils$", className);
if (c != null)
return "main$" + c;
return className;
}
public static boolean isAnonymousClassName(String s) {
for (int i = 0; i < l(s); i++) if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i + 1)))
return true;
return false;
}
public static Class getClass_vmName_withLoadableUtils(Object realm, String name) {
try {
ClassLoader cl = getClassLoader(realm);
Class c = loadClassFromClassLoader_orNull(cl, name);
if (c == null && name.startsWith("main$"))
return loadClassFromClassLoader_orNull(cl, "loadableUtils.utils" + substring(name, 4));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object sleepQuietly_monitor = new Object();
public static void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Point getMouseLocation() {
return MouseInfo.getPointerInfo().getLocation();
}
public static void moveMouseTo(int newx, int newy) {
moveMouse(newx, newy);
}
public static void moveMouseTo(Pt pt) {
moveMouse(pt.x, pt.y);
}
public static void moveMouseTo(Rect r) {
moveMouseTo(centerOfRect(r));
}
public static int mouseClick_delay = 100;
public static void mouseClick(Rect r) {
mouseClick(centerOfRect(r));
}
public static void mouseClick(Pt p) {
mouseClick(p.x, p.y);
}
public static void mouseClick(int x, int y) {
try {
final Robot robot = new Robot();
robot.mouseMove(x, y);
mouseClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void mouseClick() {
try {
final Robot robot = new Robot();
final int button = InputEvent.BUTTON1_DOWN_MASK;
robot.mousePress(button);
sleep(mouseClick_delay);
robot.mouseRelease(button);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
public static Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static boolean odd(int i) {
return (i & 1) != 0;
}
public static boolean odd(long i) {
return (i & 1) != 0;
}
public static boolean odd(BigInteger i) {
return odd(toInt(i));
}
public static A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
public static Map vm_generalMap_map;
public static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
public static long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
public static long parseLong(Object s) {
return Long.parseLong((String) s);
}
public static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
public static String _userHome;
public static String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
public static File userHome(String path) {
return new File(userDir(), path);
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
public static File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
public static String fsI(String id) {
return formatSnippetID(id);
}
public static String fsI(long id) {
return formatSnippetID(id);
}
public static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
public static String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
public static String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
public static boolean jsonDecode_useOrderedMaps = true;
public static Object jsonDecode(final String text) {
final List tok = jsonTok(text);
if (l(tok) == 1)
return null;
class Y {
public int i = 1;
public 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 this.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);
}
public 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;
}
public Object parseMap() {
consume("{");
Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : 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;
}
public 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();
}
public static String makePostData(Map map) {
StringBuilder buf = new StringBuilder();
for (Map.Entry e : map.entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
public static String makePostData(Object... params) {
StringBuilder buf = new StringBuilder();
int n = l(params);
for (int i = 0; i + 1 < n; i += 2) {
String key = (String) (params[i]);
Object val = params[i + 1];
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
public static boolean agiBlueURL_noHTTPS = false;
public static String agiBlueURL_url = "https://agi.blue";
public static String agiBlueURL() {
return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url;
}
public static String addSlashPrefix(String s) {
return addPrefix("/", s);
}
public static Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
public static Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
public static Producer javaTokC_noMLS_iterator(final String s) {
return javaTokC_noMLS_iterator(s, 0);
}
public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) {
return new Producer() {
public final int l = s.length();
public int i = startIndex;
public String next() {
if (i >= l)
return null;
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l)
return null;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
public static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
public StringBuilder buf = new StringBuilder();
public char c, d, e = 'x';
public X() {
nc();
nc();
nc();
}
public void nc() {
try {
c = d;
d = e;
if (e == '\0')
return;
int i = r.read();
e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc();
nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0')
return null;
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') {
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L')
ncSave();
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
public static String unquoteUsingCharArray(String s, char[] buf) {
if (s == null)
return null;
if (startsWith(s, '[')) {
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.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
if (l > buf.length)
return unquote(s);
int n = 0;
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
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++;
}
}
buf[n++] = (char) Integer.parseInt(code, 8);
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
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 '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);
char[] x = Character.toChars(code);
int lx = x.length;
for (int j = 0; j < lx; j++) buf[n++] = x[j];
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
buf[n++] = ch;
}
return new String(buf, 0, n);
}
}
return s;
}
public static boolean structure_isMarker(String s, int i, int j) {
if (i >= j)
return false;
if (s.charAt(i) != 'm')
return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
public static String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? intern(s) : s;
}
public static String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
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.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? 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);
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 '\\':
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 '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;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
public static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0);
}
public static double parseDouble(String s) {
return Double.parseDouble(s);
}
public static float parseFloat(String s) {
return Float.parseFloat(s);
}
public static boolean isLongConstant(String s) {
if (!s.endsWith("L"))
return false;
s = s.substring(0, l(s) - 1);
return isInteger(s);
}
public static boolean isInteger(String s) {
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;
}
public static List parseList(String s) {
return (List) safeUnstructure(s);
}
public static List synchroLinkedList() {
return Collections.synchronizedList(new LinkedList ());
}
public static byte[] hexToBytes(String s) {
if (odd(l(s)))
throw fail("Hex string has odd length: " + quote(shorten(10, s)));
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
int a = parseHexChar(s.charAt(i * 2));
int b = parseHexChar(s.charAt(i * 2 + 1));
if (a < 0 || b < 0)
throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
bytes[i] = (byte) ((a << 4) | b);
}
return bytes;
}
public static boolean[] boolArrayFromBytes(byte[] a, int n) {
boolean[] b = new boolean[n];
int m = min(n, l(a) * 8);
for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0;
return b;
}
public 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;
}
public static Map nuEmptyObject_cache = newDangerousWeakHashMap();
public static A nuEmptyObject(Class c) {
try {
Constructor ctr;
synchronized (nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
makeAccessible(ctr);
}
}
try {
return (A) ctr.newInstance();
} catch (InstantiationException e) {
if (empty(e.getMessage()))
if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
throw fail("Can't instantiate abstract class " + className(c), e);
else
throw fail("Can't instantiate " + className(c), e);
else
throw rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
public static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
public static String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
public static A nuStubInnerObject(Class c) {
return nuStubInnerObject(c, null);
}
public static A nuStubInnerObject(Class c, Object classFinder) {
try {
Class outerType = getOuterClass(c, classFinder);
Constructor m = c.getDeclaredConstructor(outerType);
makeAccessible(m);
return (A) m.newInstance(new Object[] { null });
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static HashMap findClass_cache = new HashMap();
public static Class findClass(String name) {
synchronized (findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name))
return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
public static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null)
return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) {
String field = e.getKey();
Object val = e.getValue();
boolean has = fieldMap.containsKey(field);
if (has)
setOpt(o, field, val);
else {
o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, intern(field), val);
}
}
}
public static void setOptAll_pcall(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) try {
setOpt(o, field, fields.get(field));
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public static void setOptAll_pcall(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
try {
setOpt(o, field, value);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
}
public static void setDynObjectValue(DynamicObject o, String field, Object value) {
o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, field, value);
}
public static String intern(String s) {
return fastIntern(s);
}
public static void pcallOpt_noArgs(Object o, String method) {
try {
callOpt_noArgs(o, method);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
public static List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
public static int[] toIntArray(List l) {
int[] a = new int[l(l)];
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
return a;
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static TreeSet ciSet() {
return caseInsensitiveSet();
}
public static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
public static boolean jmatch(String pat, String s, Matches matches) {
if (s == null)
return false;
return jmatch(pat, javaTok(s), matches);
}
public static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
public static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
if (m == null)
return false;
else {
if (matches != null)
matches.m = m;
return true;
}
}
public static boolean warn_on = true;
public static ThreadLocal> warn_warnings = new ThreadLocal();
public static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
public static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
addToCollection(warn_warnings.get(), s);
}
public static A popLast(List l) {
return liftLast(l);
}
public static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
public static Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
public static Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String classNameToVM(String name) {
return name.replace(".", "$");
}
public static String dropPrefixOrNull(String prefix, String s) {
return s != null && s.startsWith(prefix) ? s.substring(l(prefix)) : null;
}
public static ClassLoader getClassLoader(Object o) {
return o == null ? null : _getClass(o).getClassLoader();
}
public static Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
try {
return cl == null ? null : cl.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static void assertFalse(Object o) {
if (!(eq(o, false)))
throw fail(str(o));
}
public static boolean assertFalse(boolean b) {
if (b)
throw fail("oops");
return b;
}
public static boolean assertFalse(String msg, boolean b) {
if (b)
throw fail(msg);
return b;
}
public static void moveMouse(int newx, int newy) {
try {
mouseMover().moveMouse(pt(newx, newy));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void moveMouse(Pt p) {
if (p != null)
moveMouse(p.x, p.y);
}
public static void moveMouse(Rect r) {
moveMouse(centerOfRect(r));
}
public static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
public static String hostNameFromURL(String url) {
try {
return new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
public static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static String actualUserHome_value;
public static String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
public static File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
public static File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
public static boolean possibleMD5(String s) {
return isMD5(s);
}
public static List jsonTok(String s) {
List tok = new ArrayList();
int l = l(s);
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
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);
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;
}
public static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
public static String quickSubstring(String s, int i, int j) {
if (i == j)
return "";
return s.substring(i, j);
}
public static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
public static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
public static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
public static Object safeUnstructure(String s) {
return unstructure(s, true);
}
public static int parseHexChar(char c) {
if (c >= '0' && c <= '9')
return charDiff(c, '0');
if (c >= 'a' && c <= 'f')
return charDiff(c, 'a') + 10;
if (c >= 'A' && c <= 'F')
return charDiff(c, 'A') + 10;
return -1;
}
public static String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
public static String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
public static Class getOuterClass(Class c) {
return getOuterClass(c, null);
}
public static Class getOuterClass(Class c, Object classFinder) {
try {
String s = c.getName();
int i = s.lastIndexOf('$');
String name = substring(s, 0, i);
if (classFinder != null)
return (Class) callF(classFinder, name);
return Class.forName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static HashMap instanceFieldsMap(Object o) {
Class c = o.getClass();
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map;
}
public static LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) {
if (map != null && key != null)
if (value != null) {
if (map == null)
map = new LinkedHashMap();
synchronized (collectionMutex(map)) {
map.put(key, value);
}
} else
synchronized (collectionMutex(map)) {
map.remove(key);
}
return map;
}
public static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
public static Method fastIntern_method;
public static String fastIntern(String s) {
try {
if (s == null)
return null;
if (fastIntern_method == null) {
fastIntern_method = findMethodNamed(javax(), "internPerProgram");
if (fastIntern_method == null)
upgradeJavaXAndRestart();
}
return (String) fastIntern_method.invoke(null, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap();
public static Object callOpt_noArgs(Object o, String method) {
try {
if (o == null)
return null;
if (o instanceof Class)
return callOpt(o, method);
Class c = o.getClass();
HashMap map;
synchronized (callOpt_noArgs_cache) {
map = callOpt_noArgs_cache.get(c);
if (map == null)
map = callOpt_noArgs_makeCache(c);
}
Method m = map.get(method);
return m != null ? m.invoke(o) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static HashMap callOpt_noArgs_makeCache(Class c) {
HashMap map = new HashMap();
Class _c = c;
do {
for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) {
makeAccessible(m);
String name = m.getName();
if (!map.containsKey(name))
map.put(name, m);
}
_c = _c.getSuperclass();
} while (_c != null);
callOpt_noArgs_cache.put(c, map);
return map;
}
public static TreeSet caseInsensitiveSet() {
return caseInsensitiveSet_treeSet();
}
public static TreeSet caseInsensitiveSet(Collection c) {
return caseInsensitiveSet_treeSet(c);
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt = false;
public static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
public static String[] match2(List pat, List tok) {
int i = pat.indexOf("...");
if (i < 0)
return match2_match(pat, tok);
pat = new ArrayList(pat);
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i + 1, "");
}
return match2_match(pat, tok);
}
public static String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t)))
return null;
}
return result.toArray(new String[result.size()]);
}
public static boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
public static A liftLast(List l) {
if (l.isEmpty())
return null;
int i = l(l) - 1;
A a = l.get(i);
l.remove(i);
return a;
}
public static Pt pt(int x, int y) {
return new Pt(x, y);
}
public static class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
public static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
public static HashMap getOpt_special;
public 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 Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null)
return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null)
getOpt_cache.put(c, map);
return map;
}
public static boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
public static String theAGIBlueDomain() {
return "agi.blue";
}
public static boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
public static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
public 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;
}
public static List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
public static List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
public static List dropLast(Iterable l) {
return dropLast(asList(l));
}
public static String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
public static String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
public static String dropLast(int n, String s) {
return dropLast(s, n);
}
public static int charDiff(char a, char b) {
return (int) a - (int) b;
}
public static int charDiff(String a, char b) {
return charDiff(stringToChar(a), b);
}
public static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
public static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
public static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
public static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
public static Method findMethodNamed(Object obj, String method) {
if (obj == null)
return null;
if (obj instanceof Class)
return findMethodNamed((Class) obj, method);
return findMethodNamed(obj.getClass(), method);
}
public static Method findMethodNamed(Class c, String method) {
while (c != null) {
for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) {
makeAccessible(m);
return m;
}
c = c.getSuperclass();
}
return null;
}
public static void upgradeJavaXAndRestart() {
run("#1001639");
restart();
sleep();
}
public static boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
public static TreeSet caseInsensitiveSet_treeSet() {
return new TreeSet(caseInsensitiveComparator());
}
public static TreeSet caseInsensitiveSet_treeSet(Collection c) {
return toCaseInsensitiveSet_treeSet(c);
}
public static String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
public static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
public static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
public static boolean equalsIgnoreCase(String a, String b) {
return eqic(a, b);
}
public static boolean equalsIgnoreCase(char a, char b) {
return eqic(a, b);
}
public static void clear(Collection c) {
if (c != null)
c.clear();
}
public static void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
public static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
public static List _registerDangerousWeakMap_preList;
public static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
public static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1() {
public void get(Map map) {
try {
callMC(f, map);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callMC(f, map)";
}
};
}
if (javax() == null) {
if (_registerDangerousWeakMap_preList == null)
_registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
public static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null)
return;
for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
public static B mapGet2(Map map, A a) {
return map == null ? null : map.get(a);
}
public static B mapGet2(A a, Map map) {
return map == null ? null : map.get(a);
}
public static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a);
}
public static Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath");
public static Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
public static boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
public static boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
public static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
public static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
public static boolean isLowerHexString(String s) {
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
} else
return false;
}
return true;
}
public static char stringToChar(String s) {
if (l(s) != 1)
throw fail("bad stringToChar: " + s);
return firstChar(s);
}
public static Class run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
public static void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
public static TreeSet toCaseInsensitiveSet_treeSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, c);
return set;
}
public static TreeSet toCaseInsensitiveSet_treeSet(String... x) {
TreeSet set = caseInsensitiveSet_treeSet();
addAll(set, x);
return set;
}
public static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
public static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static HashSet litset(A... items) {
return lithashset(items);
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
public static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
public static char firstChar(String s) {
return s.charAt(0);
}
public static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized (j) {
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) (call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
public static A callMain(A c, String... args) {
callOpt(c, "main", new Object[] { args });
return c;
}
public static void callMain() {
callMain(mc());
}
public static boolean isCISet(Iterable l) {
return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}
public static void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
public static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
public static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
public static Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null)
a.putAll(b);
return a;
}
public static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
public static boolean _inCore() {
return false;
}
public static List hotwire_copyOver_after = synchroList();
public static void hotwire_copyOver(Class c) {
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot", getMainBot());
setOpt(c, "creator_class", new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
public static void setOptIfNotNull(Object o, String field, Object value) {
if (value != null)
setOpt(o, field, value);
}
public static Object mainBot;
public static Object getMainBot() {
return mainBot;
}
public static final class _MethodCache {
public final Class c;
public final HashMap