Warning : session_start(): open(/var/lib/php/sessions/sess_o14n8ph31tp1aokr7fiq9db96h, 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_getEvent;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
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.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.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 java.awt.geom.AffineTransform;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.text.SimpleDateFormat;
import javax.swing.border.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
class main {
public static class LearnDogsVsCats extends DynSingleFunctionWithPrintLog {
public transient File dir = userDir("dev/dogs-vs-cats/train");
public transient int eyeWidth = 10;
public transient double eyeSurround = 0.5;
public transient List allImageFiles;
public transient List allEyeImages;
public transient Map eyeImageSources;
public transient ImageSurface is, isFound;
public void start() {
super.start();
if (!dm_osBooting())
startThread(new Runnable() {
public void run() {
try {
doIt();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "doIt();";
}
});
}
public JComponent makeButtons() {
return hstackWithSpacing(super.makeButtons(), jbutton("Random Image", runnableThread(new Runnable() {
public void run() {
try {
randomImage();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "randomImage();";
}
})));
}
public void randomImage() {
recognizeImage(random(allImageFiles));
}
public void doIt() {
allImageFiles = listImageFiles(dir);
Map>> markingsMap = new HashMap();
for (File f : allImageFiles) mapPutIfNemptyValue(markingsMap, f, loadImageFileMarkings(f));
pnlStruct(markingsMap);
if (empty(markingsMap)) {
print("No marked images found in " + dir);
return;
}
Map iImages = new HashMap();
for (File f : keys(markingsMap)) iImages.put(f, new BWIntegralImage(f));
print("Have " + n2(iImages, "integral image") + ", total size: " + str_toM(deepObjectSize(iImages)));
allEyeImages = new ArrayList();
eyeImageSources = new HashMap();
for (File f : keys(markingsMap)) if (fileNameContains(f, "cat"))
for (Pair mark : markingsMap.get(f)) if (eqic(mark.b, "eye")) {
BWImage img = bwResizeSmooth(iBWImageToBWImage(safeClipIBWImage(virtualScaledIntegralImageBW(iImages.get(f)), growRectProportionally(eyeSurround, mark.a))), eyeWidth);
allEyeImages.add(img);
eyeImageSources.put(img, f);
}
File f = firstFileWithName(allImageFiles, "cat.2516.jpg");
recognizeImage(f);
}
public void recognizeImage(File f) {
print(f);
BWII_MultiPatternFinder finder = new BWII_MultiPatternFinder(allEyeImages, new BWIntegralImage(f));
disposePIFrame(is);
is = null;
for (FoundImg found : finder) {
if (is == null || is.getImage().getWidth() != finder.currentScaleWidth)
is = showImage(is, iBWImageToBWImage(finder.scaled));
print(found + " / " + eyeImageSources.get(finder.pattern));
overlaySelectionsOnImageSurface(is, ll(foundImgRect(found)));
isFound = showZoomedImage(isFound, "Found", finder.pattern);
}
}
}
public static boolean _moduleClass_LearnDogsVsCats;
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 B callF(F1 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;
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 File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
public static boolean dm_osBooting() {
return dm_osLoading();
}
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 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 int hstackWithSpacing_spacing = 10;
public static JPanel hstackWithSpacing(Object... parts) {
parts = flattenArray2(parts);
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
public static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
public static JButton jbutton(String text) {
return newButton(text, null);
}
public static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
public static Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
public static Random random_random = new Random();
public static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
public static double random(double max) {
return random() * max;
}
public static double random() {
return random_random.nextInt(100001) / 100000.0;
}
public static double random(double min, double max) {
return min + random() * (max - min);
}
public static int random(int min, int max) {
return min + random(max - min);
}
public static A random(List l) {
return oneOf(l);
}
public static A random(Collection c) {
if (c instanceof List)
return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
public static List listImageFiles(File dir) {
return filter("isImageFile", listFiles_noDirs(dir));
}
public static void mapPutIfNemptyValue(Map map, A key, String value) {
if (map != null && key != null && nempty(value))
map.put(key, value);
}
public static void mapPutIfNemptyValue(Map map, A key, B value) {
if (map != null && key != null && nempty(value))
map.put(key, value);
}
public static List> loadImageFileMarkings(File f) {
return unnull((List>) unstructFileOpt(associatedImageMarkingsFile(f)));
}
public static void pnlStruct(Object o) {
if (o instanceof Collection)
pnlStruct(((Collection) o));
else if (o instanceof Map)
pnlStruct(((Map) o));
else if (o != null)
pnlStruct(ll(o));
}
public static Collection pnlStruct(Collection l) {
pnlStruct((Iterable ) l);
return l;
}
public static Iterable pnlStruct(Iterable l) {
int i = 0;
if (l != null)
for (A a : l) print((++i) + ". " + struct_noStringSharing(a));
return l;
}
public static A[] pnlStruct(A[] l) {
pnlStruct(asList(l));
return l;
}
public static Map pnlStruct(Map map) {
pnl(map(map, new F2 () {
public Object get(A a, B b) {
try {
return sfu(a) + " = " + sfu(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sfu(a) + \" = \" + sfu(b)";
}
}));
return map;
}
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(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(File f) {
return getFileSize(f) == 0;
}
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 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 str_toM(long l) {
return toM(l) + " MB";
}
public static long deepObjectSize(Object o) {
return guessDeepObjectSize_recursive(o);
}
public static long deepObjectSize(guessDeepObjectSize_recursive_Data data, Object o) {
return guessDeepObjectSize_recursive(data, o);
}
public static boolean fileNameContains(File f, String s) {
return contains(fileName(f), s);
}
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 BWImage bwResizeSmooth(BWImage img, int w) {
return new BWImage(scaleImage(img.getBufferedImage(), ((double) w) / img.getWidth()));
}
public static BWImage bwResizeSmooth(BWImage img, int w, int h) {
return new BWImage(scaleImage(img.getBufferedImage(), ((double) w) / img.getWidth(), ((double) h) / img.getHeight()));
}
public static BWImage iBWImageToBWImage(IBWImage img) {
int w = img.getWidth(), h = img.getHeight();
BWImage out = new BWImage(w, h);
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) out.setPixel(x, y, img.getFloatPixel(x, y));
return out;
}
public static IBWImage safeClipIBWImage(IBWImage img, Rect r) {
return clipIBWImage(img, intersectRects(r, rect(0, 0, img.getWidth(), img.getHeight())));
}
public static IBWImage virtualScaledIntegralImageBW(BWIntegralImage img) {
return virtualScaledIntegralImageBW(img, img.getWidth(), img.getHeight());
}
public static IBWImage virtualScaledIntegralImageBW(BWIntegralImage img, int w) {
return virtualScaledIntegralImageBW(img, w, iround(w * img.h / (double) img.w));
}
public static IBWImage virtualScaledIntegralImageBW(BWIntegralImage img, int w, int h) {
return new IBWImage() {
public int w1 = img.w, h1 = img.h;
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public float getFloatPixel(int x, int y) {
int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w);
int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h);
int area = (x2 - x1) * (y2 - y1);
int pixel = bwIntegralImage_sumRect(img, x1, y1, x2, y2) / area;
return pixel / 255f;
}
};
}
public static Rect growRectProportionally(double p, Rect r) {
int growX = iround(p * r.w), growY = iround(p * r.h);
return growRect(r, growX, growY);
}
public static File firstFileWithName(Iterable l, String name) {
return firstThat(l, f -> eq(fileName(f), name));
}
public static void disposePIFrame(Component c) {
disposePossiblyInternalFrame(c);
}
public static String showImage_defaultIcon = "#1004230";
public static ImageSurface showImage(String snippetIDOrURL, String title) {
return showImage(loadImage(snippetIDOrURL), title);
}
public static ImageSurface showImage(String title, BufferedImage img) {
return showImage(img, title);
}
public static ImageSurface showImage(final BufferedImage img, final String title) {
return (ImageSurface) swing(new F0() {
public Object get() {
try {
ImageSurface is = showImage(img);
getFrame(is).setTitle(title);
return is;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ImageSurface is = showImage(img);\r\n getFrame(is).setTitle(title);\r\n ret...";
}
});
}
public static ImageSurface showImage(final BufferedImage img) {
return (ImageSurface) swing(new F0() {
public Object get() {
try {
ImageSurface is = new ImageSurface(img);
JFrame frame = showPackedFrame(new JScrollPane(is));
moveToTopRightCorner(frame);
frameIcon(frame, showImage_defaultIcon);
return is;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ImageSurface is = new ImageSurface(img);\r\n JFrame frame = showPackedFrame(...";
}
});
}
public static ImageSurface showImage(String imageID) {
return showImage(loadImage2(imageID));
}
public static ImageSurface showImage(ImageSurface surface, BufferedImage img) {
return showImage(img, surface);
}
public static ImageSurface showImage(ImageSurface surface, String title, BufferedImage img) {
return showImage(surface, img, title);
}
public static ImageSurface showImage(ImageSurface surface, BufferedImage img, String title) {
return setFrameTitle(showImage(img, surface), title);
}
public static ImageSurface showImage(BufferedImage img, ImageSurface surface) {
if (surface == null)
return showImage(img);
else {
surface.setImage(img);
return surface;
}
}
public static ImageSurface showImage(String title, MakesBufferedImage img) {
return showImage(title, img.getBufferedImage());
}
public static ImageSurface showImage(ImageSurface is, MakesBufferedImage img) {
return showImage(is, img.getBufferedImage());
}
public static ImageSurface showImage(RGBImage img) {
return showImage(img.getBufferedImage());
}
public static ImageSurface showImage(RGBImage img, String title) {
ImageSurface is = showImage(img.getBufferedImage());
getFrame(is).setTitle(title);
return is;
}
public static ImageSurface showImage(ImageSurface surface, RGBImage img) {
return showImage(img, surface);
}
public static ImageSurface showImage(RGBImage img, ImageSurface surface) {
if (surface == null)
return showImage(img);
else {
surface.setImage(img);
return surface;
}
}
public static ImageSurface showImage(ImageSurface surface, String title, RGBImage img) {
return showImage(surface, img, title);
}
public static ImageSurface showImage(ImageSurface surface, RGBImage img, String title) {
return setFrameTitle(showImage(img, surface), title);
}
public static ImageSurface showImage(BWImage img) {
return showImage(img.getBufferedImage());
}
public static ImageSurface showImage() {
return showImage(currentImage());
}
public static ImageSurface showImage(File f) {
return showImage(f2s(f), loadImage2(f));
}
public static void overlaySelectionsOnImageSurface(final ImageSurface is, final List rects) {
if (is == null)
return;
is.overlay = new VF1() {
public void get(Graphics2D g) {
try {
for (Rect r : rects) is.drawSelectionRect(g, r.getRectangle(), Color.blue, Color.white);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (Rect r : rects)\r\n is.drawSelectionRect(g, r.getRectangle(), Color.b...";
}
};
is.repaint();
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static Rect foundImgRect(FoundImg fi) {
return foundImgToRect(fi);
}
public static ImageSurface showZoomedImage(final RGBImage image) {
return showZoomedImage(image, 2);
}
public static ImageSurface showZoomedImage(String title, RGBImage image) {
return showZoomedImage(title, image, 2);
}
public static ImageSurface showZoomedImage(String title, BufferedImage image) {
return showZoomedImage(title, image, 2);
}
public static ImageSurface showZoomedImage(String title, RGBImage image, double zoom) {
return setFrameTitle(showZoomedImage(image, zoom), title);
}
public static ImageSurface showZoomedImage(String title, BufferedImage image, double zoom) {
return setFrameTitle(showZoomedImage(image, zoom), title);
}
public static ImageSurface showZoomedImage(RGBImage image, double zoom) {
return showZoomedImage(image.getBufferedImage(), zoom);
}
public static ImageSurface showZoomedImage(BufferedImage image) {
return showZoomedImage(image, 2);
}
public static ImageSurface showZoomedImage(final BufferedImage image, final double zoom) {
return (ImageSurface) swingAndWait(new F0() {
public Object get() {
try {
ImageSurface is = showImage(image);
is.setZoom(zoom);
packFrame(is);
return is;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ImageSurface is = showImage(image);\r\n is.setZoom(zoom);\r\n packFrame(is)...";
}
});
}
public static ImageSurface showZoomedImage(BWImage image) {
return showZoomedImage(image.getBufferedImage());
}
public static ImageSurface showZoomedImage(BWImage image, double zoom) {
return showZoomedImage(image.getBufferedImage(), zoom);
}
public static ImageSurface showZoomedImage(RGBImage img, ImageSurface surface) {
if (surface == null)
return showZoomedImage(img);
else {
surface.setImage(img);
return surface;
}
}
public static ImageSurface showZoomedImage(ImageSurface surface, BufferedImage img, String title) {
return setFrameTitle(showZoomedImage(img, surface), title);
}
public static ImageSurface showZoomedImage(ImageSurface surface, RGBImage img, String title) {
return setFrameTitle(showZoomedImage(img, surface), title);
}
public static ImageSurface showZoomedImage(ImageSurface surface, String title, RGBImage img) {
return showZoomedImage(surface, img, title);
}
public static ImageSurface showZoomedImage(ImageSurface surface, String title, MakesBufferedImage img) {
return showZoomedImage(surface, img.getBufferedImage(), title);
}
public static ImageSurface showZoomedImage(BufferedImage img, ImageSurface surface) {
if (surface == null)
return showZoomedImage(img);
else {
surface.setImage(img);
return surface;
}
}
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");
}
} 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 Object _defaultClassFinder_value;
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 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 StringBuilder))
return;
StringBuilder buf = (StringBuilder) _buf;
max /= 2;
if (buf.length() > max)
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 boolean dm_osLoading() {
return isTrue(dm_callOS("isLoading"));
}
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 _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
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 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 Component wrapForSmartAdd(Object o) {
if (o == null)
return jpanel();
if (o instanceof String)
return jlabel((String) o);
return wrap(o);
}
public static Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
public static boolean newButton_autoToolTip = true;
public static JButton newButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
}
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt...";
}
});
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
public static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
public static String oneOf(String... l) {
return oneOf(asList(l));
}
public static A collectionGet(Collection c, int idx) {
if (c == null || idx < 0 || idx >= l(c))
return null;
if (c instanceof List)
return listGet((List ) c, idx);
Iterator it = c.iterator();
for (int i = 0; i < idx; i++) if (it.hasNext())
it.next();
else
return null;
return it.hasNext() ? it.next() : null;
}
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).booleanValue())
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).booleanValue())
x.add(o);
return x;
}
public static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
public static boolean isImageFile(File f) {
return isImageFileName(fileName(f));
}
public static List listFiles_noDirs(String dir) {
return listFilesOnly(dir);
}
public static List listFiles_noDirs(File... dirs) {
return listFilesOnly(dirs);
}
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 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 A unstructFileOpt(File f) {
return !isFile(f) ? null : (A) unstructFile(f);
}
public static File associatedImageMarkingsFile(File f) {
return replaceExtension(f, ".markings");
}
public static String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
public static A pnl(A l) {
printNumberedLines(l);
return l;
}
public static void pnl(Map map) {
printNumberedLines(map);
}
public static void pnl(Object[] a) {
printNumberedLines(a);
}
public static void pnl(String s) {
printNumberedLines(lines(s));
}
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(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(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 String sfu(Object o) {
return structureForUser(o);
}
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 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 long toM(long l) {
return (l + 1024 * 1024 - 1) / (1024 * 1024);
}
public static String toM(long l, int digits) {
return formatDouble(toM_double(l), digits);
}
public static class guessDeepObjectSize_recursive_Data {
public long size;
public List stack = new ArrayList();
public Set seen = identityHashSet();
public Set fieldsToIgnore;
public Set realmsToIgnore;
}
public static long guessDeepObjectSize_recursive(Object o) {
if (o == null)
return 0;
return guessDeepObjectSize_recursive(new guessDeepObjectSize_recursive_Data(), o);
}
public static long guessDeepObjectSize_recursive(guessDeepObjectSize_recursive_Data data, Object o) {
if (o == null)
return 0;
data.stack.add(o);
while (nempty(data.stack)) {
ping();
guessDeepObjectSize_recursive_step(data, popLast(data.stack));
}
return data.size;
}
public static void guessDeepObjectSize_recursive_step(guessDeepObjectSize_recursive_Data data, Object o) {
if (!data.seen.add(o))
return;
if (o instanceof Component)
return;
if (o instanceof Thread)
return;
if (data.realmsToIgnore != null && contains(data.realmsToIgnore, getRealm(o)))
return;
if (o instanceof Class)
return;
if (isArray(o)) {
int len;
if (o instanceof Object[]) {
len = unsafe_sizeOf(o);
for (Object x : (Object[]) o) if (x != null && !data.seen.contains(x))
data.stack.add(x);
} else
len = inMemorySizeOfPrimitiveArray(o);
data.size += len;
return;
}
data.size += unsafe_sizeOf(o);
if (sizeCalculation_shouldSkipObject(o))
return;
for (Field f : nonStaticNonPrimitiveFieldObjects(o)) {
if (contains(data.fieldsToIgnore, f))
continue;
Object x;
try {
x = f.get(o);
} catch (Throwable e) {
print("Error trying to access " + f + ": " + e);
continue;
}
if (x != null && !data.seen.contains(x)) {
data.stack.add(x);
}
}
}
public static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
public static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
public static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
public static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
public static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
public static String fileName(File f) {
return f == null ? null : f.getName();
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static BufferedImage scaleImage(BufferedImage before, double scale) {
return scaleImage(before, scale, scale);
}
public static BufferedImage scaleImage(BufferedImage before, double scaleX, double scaleY) {
if (scaleX == 1 && scaleY == 1)
return before;
int w = before.getWidth();
int h = before.getHeight();
int neww = max(1, iround(w * scaleX)), newh = max(1, iround(h * scaleY));
BufferedImage after = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
return scaleOp.filter(before, after);
}
public static BufferedImage scaleImage(double scale, BufferedImage before) {
return scaleImage(before, scale);
}
public static IBWImage clipIBWImage(IBWImage img, int x1, int y1, int w, int h) {
if (x1 == 0 && y1 == 0 && w == img.getWidth() && h == img.getHeight())
return img;
return new IBWImage() {
public int getWidth() {
return w;
}
public int getHeight() {
return h;
}
public float getFloatPixel(int x, int y) {
return img.getFloatPixel(x + x1, y + y1);
}
};
}
public static IBWImage clipIBWImage(IBWImage img, Rect r) {
return clipIBWImage(img, r.x, r.y, r.w, r.h);
}
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 Rect rect(int x, int y, int w, int h) {
return new Rect(x, y, w, h);
}
public static int iround(double d) {
return (int) Math.round(d);
}
public static int iround(Number n) {
return iround(toDouble(n));
}
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 int bwIntegralImage_sumRect(BWIntegralImage img, int x1, int y1, int x2, int y2) {
int bottomLeft = img.get(x1 - 1, y2 - 1);
int bottomRight = img.get(x2 - 1, y2 - 1);
int topLeft = img.get(x1 - 1, y1 - 1);
int topRight = img.get(x2 - 1, y1 - 1);
return bottomRight + topLeft - topRight - bottomLeft;
}
public static Rect growRect(int pixels, Rect r) {
return growRect(r, pixels);
}
public static Rect growRect(Rect r, int pixels) {
return new Rect(r.x - pixels, r.y - pixels, r.w + pixels * 2, r.h + pixels * 2);
}
public static Rect growRect(Rect r, int x, int y) {
return new Rect(r.x - x, r.y - y, r.w + x * 2, r.h + y * 2);
}
public static A firstThat(Iterable l, Object pred) {
if (l != null)
for (A a : l) if (checkCondition(pred, a))
return a;
return null;
}
public static A firstThat(Iterable l, IF1 pred) {
return firstThat(l, (Object) pred);
}
public static A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
public static void disposePossiblyInternalFrame(Component c) {
Container f = (Container) (getPossiblyInternalFrame(c));
if (f instanceof JInternalFrame)
disposeInternalFrame((JInternalFrame) f);
else if (f instanceof Window)
disposeWindow(f);
}
public static RGBImage loadImage(String snippetIDOrURL) {
return new RGBImage(loadBufferedImage(snippetIDOrURL));
}
public static RGBImage loadImage(File f) {
return new RGBImage(loadBufferedImage(f));
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static JFrame getFrame(final Object _o) {
return swing(new F0() {
public JFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame)
return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
public static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
public static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
public static int moveToTopRightCorner_inset = 20;
public static A moveToTopRightCorner(A a) {
return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
}
public static A moveToTopRightCorner(int insetX, int insetY, A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width - w.getWidth() - insetX, insetY);
return a;
}
public static Component frameIcon(Component c, String imageID) {
setFrameIconLater(c, imageID);
return c;
}
public static Component frameIcon(String imageID, Component c) {
setFrameIconLater(c, imageID);
return c;
}
public static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
public static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
public static A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) {
swing(new Runnable() {
public void run() {
try {
f.setTitle(title);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.setTitle(title);";
}
});
}
return c;
}
public static A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
public static JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
public static ThreadLocal currentImage_var = new ThreadLocal();
public static BufferedImage currentImage() {
return currentImage_var.get();
}
public static void currentImage(BufferedImage img) {
currentImage_var.set(img);
}
public static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
public static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
public static Rect foundImgToRect(FoundImg fi) {
return fi == null ? null : fi.r;
}
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 int packFrame_minw = 150, packFrame_minh = 50;
public static A packFrame(final A c) {
{
swing(new Runnable() {
public void run() {
try {
Window w = getWindow(c);
if (w != null) {
w.pack();
int maxW = getScreenWidth() - 50, maxH = getScreenHeight() - 50;
w.setSize(min(maxW, max(w.getWidth(), packFrame_minw)), min(maxH, max(w.getHeight(), packFrame_minh)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Window w = getWindow(c);\r\n if (w != null) {\r\n w.pack();\r\n int ma...";
}
});
}
return c;
}
public static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
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 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 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 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;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions;
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 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 Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
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 Object[] asObjectArray(List l) {
return toObjectArray(l);
}
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 String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
public static JPanel jpanel() {
return swingNu(JPanel.class);
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static Component wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static Component wrap_2(Object swingable) {
if (swingable == null)
return null;
Component c;
if (swingable instanceof Component)
c = (Component) swingable;
else
c = (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 String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
public static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __371 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__371);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
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 listGet(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static boolean isImageFileName(String s) {
return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
}
public static List listFilesOnly(String dir) {
return listFilesOnly(new File(dir));
}
public static List listFilesOnly(File... dirs) {
return concatMap(rcurry("listFilesWithSuffix", ""), dirs);
}
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 Map emptyMap() {
return new HashMap();
}
public static boolean isFile(File f) {
return f != null && f.isFile();
}
public static boolean isFile(String path) {
return isFile(newFile(path));
}
public static A unstructFile(File f) {
return unstructureFromFile(f);
}
public static File replaceExtension(File f, String extOld, String extNew) {
return newFile(replaceExtension(f2s(f), extOld, extNew));
}
public static File replaceExtension(File f, String extNew) {
return replaceExtension(f, fileExtension(f), extNew);
}
public static String replaceExtension(String s, String extOld, String extNew) {
s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
return s + addPrefixOptIfNempty(".", extNew);
}
public static String replaceExtension(String name, String extNew) {
return replaceExtension(name, fileExtension(name), extNew);
}
public static List printNumberedLines(List l) {
printNumberedLines((Collection ) l);
return l;
}
public static void printNumberedLines(Map map) {
printNumberedLines(mapToLines(map));
}
public static A printNumberedLines(A l) {
int i = 0;
if (l != null)
for (Object a : l) print((++i) + ". " + str(a));
return l;
}
public static void printNumberedLines(Object[] l) {
printNumberedLines(asList(l));
}
public static void printNumberedLines(Object o) {
printNumberedLines(lines(str(o)));
}
public static String lines(Iterable lines) {
return fromLines(lines);
}
public static String lines(Object[] lines) {
return fromLines(asList(lines));
}
public static List lines(String s) {
return toLines(s);
}
public static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
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 String formatDouble(double d, int digits) {
String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
}
public static double toM_double(long l) {
return l / (1024 * 1024.0);
}
public static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
public static A popLast(List l) {
return liftLast(l);
}
public static String getRealm(Object o) {
if (o == null)
return null;
Object classLoader = getClass(o).getClassLoader();
return (String) getOpt(classLoader, "progID");
}
public static boolean isArray(Object o) {
return o != null && o.getClass().isArray();
}
public static Map unsafe_sizeOf_cache = weakHashMap();
public static int unsafe_sizeOf(Object o) {
Class c = _getClass(o);
if (o instanceof Object[])
return unsafe_sizeOf_uncached(o, c);
Integer l = unsafe_sizeOf_cache.get(c);
if (l == null)
unsafe_sizeOf_cache.put(c, l = unsafe_sizeOf_uncached(o, c));
return l;
}
public static int unsafe_sizeOf_uncached(Object o, Class src) {
int WORD = javaDataModelWordSize();
int MIN_SIZE = 16;
List instanceFields = new ArrayList();
while (src != null && src != Object.class && empty(instanceFields)) {
for (Field f : src.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) == 0)
instanceFields.add(f);
src = src.getSuperclass();
}
long maxOffset = MIN_SIZE;
if (o instanceof Object[]) {
int n = l((Object[]) o);
maxOffset = lowestValue(unsafe_allFieldOffsets(Pair.class)) + 4 + java_pointerSize() * (n - 1);
} else
for (Field f : instanceFields) {
long offset = (long) (call(theUnsafe_gen(), "objectFieldOffset", f));
if (offset > maxOffset)
maxOffset = offset;
}
return (((int) maxOffset / WORD) + 1) * WORD;
}
public static int inMemorySizeOfPrimitiveArray(Object o) {
return roundUpTo(javaDataModelWordSize(), unsafe_sizeOf(_SimulatedArrayStub.class) + primitiveTypeSize(arrayElementType(o)) * l(o));
}
public static TreeSet sizeCalculation_shouldSkipObject_set = asTreeSet(tlft("\r\n java.io.\r\n java.lang.reflect.\r\n java.awt.\r\n javax.swing.\r\n"));
public static boolean sizeCalculation_shouldSkipObject(Object o) {
if (o instanceof Reference)
return true;
return startsWithOneOf_treeSet(className(o), sizeCalculation_shouldSkipObject_set);
}
public static final Map> nonStaticNonPrimitiveFieldObjects_cache = dangerousWeakMap();
public static List nonStaticNonPrimitiveFieldObjects(Object o) {
Class c = o.getClass();
List fields;
synchronized (nonStaticNonPrimitiveFieldObjects_cache) {
fields = nonStaticNonPrimitiveFieldObjects_cache.get(c);
if (fields == null)
nonStaticNonPrimitiveFieldObjects_cache.put(c, fields = nonStaticNonPrimitiveFieldObjects_uncached(c));
}
return fields;
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
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 double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o == null)
return 0.0;
throw fail(o);
}
public static boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
public static RootPaneContainer getPossiblyInternalFrame(Component c) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
return f;
return optCast(RootPaneContainer.class, getWindow(c));
}
public static void disposeInternalFrame(Component c) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) {
swing(new Runnable() {
public void run() {
try {
f.dispose();
setOpt(f, "lastFocusOwner", null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.dispose();\r\n setOpt(f, \"lastFocusOwner\" , null); // Help GC";
}
});
}
}
public static void disposeWindow(final Window window) {
if (window != null) {
swing(new Runnable() {
public void run() {
try {
window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));
myFrames_list.remove(window);
window.dispose();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); //...";
}
});
}
}
public static void disposeWindow(final Component c) {
disposeWindow(getWindow(c));
}
public static void disposeWindow(Object o) {
if (o != null)
disposeWindow(((Component) o));
}
public static void disposeWindow() {
disposeWindow(heldInstance(Component.class));
}
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 buttonsInGroup(ButtonGroup g) {
if (g == null)
return ll();
return asList(g.getElements());
}
public static JFrame showFrame() {
return makeFrame();
}
public static JFrame showFrame(Object content) {
return makeFrame(content);
}
public static JFrame showFrame(String title) {
return makeFrame(title);
}
public static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
public static JFrame showFrame(final JFrame f) {
if (f != null) {
swing(new Runnable() {
public void run() {
try {
if (frameTooSmall(f))
frameStandardSize(f);
if (!f.isVisible())
f.setVisible(true);
if (f.getState() == Frame.ICONIFIED)
f.setState(Frame.NORMAL);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (frameTooSmall(f)) frameStandardSize(f);\r\n if (!f.isVisible()) f.setVis...";
}
});
}
return f;
}
public static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
public static Window getWindow(Object o) {
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Window)
return (Window) c;
c = c.getParent();
}
return null;
}
public static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
public static JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() {
public void run() {
try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() {
public void run() {
try {
frame.setIconImage(i);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setIconImage(i);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL...";
}
});
return frame;
}
public static Frame getAWTFrame(final Object _o) {
return swing(new F0 () {
public Frame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof Frame)
return (Frame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n /*\r\n ifdef HaveProcessing\r\n if (o instanceof PApplet) ...";
}
});
}
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 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 int getScreenWidth() {
return getScreenSize().width;
}
public static int getScreenHeight() {
return getScreenSize().height;
}
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) {
int n = min(a.length, b.length);
for (int i = 0; i < n; i++) b[i] = a[i];
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
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 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 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 List listFilesWithSuffix(File dir, String suffix) {
List l = new ArrayList();
for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix)))
l.add(f);
return l;
}
public static Map myFrames_list = weakHashMap();
public static List myFrames() {
return swing(new F0>() {
public List get() {
try {
return keysList(myFrames_list);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret keysList(myFrames_list);";
}
});
}
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 void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
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 Object dm_os() {
{
Object __237 = vm_generalMap_get("stefansOS");
if (__237 != null)
return __237;
}
return creator();
}
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 WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return 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 ThreadLocal> holdInstance_l = new ThreadLocal();
public static AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
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 void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
public static void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
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);
m.setAccessible(true);
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 boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
public static String fileExtension(File f) {
if (f == null)
return null;
return fileExtension(f.getName());
}
public static String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
public static List concatMap(Object f, Iterable l) {
return concatLists(map(f, l));
}
public static List concatMap(Iterable l, Object f) {
return concatMap(f, l);
}
public static List concatMap(Object f, Object[] l) {
return concatLists(map(f, l));
}
public static List concatMap(Object[] l, Object f) {
return concatMap(f, l);
}
public static Object rcurry(final Object f, final Object arg) {
int n = numberOfFunctionArguments(f);
if (n == 0)
throw fail("function takes no arguments");
if (n == 1)
return new F0() {
public Object get() {
return callF(f, arg);
}
};
if (n == 2)
return new F1() {
public Object get(Object a) {
return callF(f, a, arg);
}
};
throw todo("currying a function with " + n + "arguments");
}
public static A unstructureFromFile(File f) {
try {
InputStream fis = new FileInputStream(f);
try {
InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
return (A) unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), false, null);
} finally {
_close(fis);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String dropSuffixIC(String suffix, String s) {
return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static String addPrefixOptIfNempty(String prefix, String s) {
return addPrefixIfNotEmpty2(prefix, s);
}
public static List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
public static String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
public static String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
public static String fromLines(String... lines) {
return fromLines(asList(lines));
}
public static IterableIterator toLines(File f) {
return linesFromFile(f);
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
public static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static String beautifyStructure(String s) {
List tok = javaTok(s);
structure_addTokenMarkers(tok);
jreplace(tok, "lhm", "");
return join(tok);
}
public static String rep(int n, char c) {
return repeat(c, n);
}
public static String rep(char c, int n) {
return repeat(c, n);
}
public static List rep(A a, int n) {
return repeat(a, n);
}
public static List rep(int n, A a) {
return repeat(n, 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 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 Map weakHashMap() {
return newWeakHashMap();
}
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 int javaDataModelWordSize_value;
public static int javaDataModelWordSize() {
if (javaDataModelWordSize_value == 0)
javaDataModelWordSize_value = Integer.valueOf(System.getProperty("sun.arch.data.model")) / 8;
return javaDataModelWordSize_value;
}
public static B lowestValue(Map map) {
B best = null;
for (B b : values(map)) if (best == null || cmp(b, best) < 0)
best = b;
return best;
}
public static Map unsafe_allFieldOffsets(Object o) {
Class src = _getClass(o);
Map map = new HashMap();
while (src != null && src != Object.class) {
for (Field f : src.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) == 0) {
long offset = (long) (call(theUnsafe_gen(), "objectFieldOffset", f));
map.put(f.getName(), offset);
}
}
src = src.getSuperclass();
}
return orderMapByValue(map);
}
public static int java_pointerSize() {
boolean c = compressedOOPSEnabled();
return compressedOOPSEnabled_is64bitHotSpot && !c ? 8 : 4;
}
public static Object theUnsafe_gen_theUnsafe;
public static Object theUnsafe_gen() {
if (theUnsafe_gen_theUnsafe == null)
theUnsafe_gen_theUnsafe = get(classForName("sun.misc.Unsafe"), "theUnsafe");
return theUnsafe_gen_theUnsafe;
}
public static int roundUpTo(int n, int x) {
return (x + n - 1) / n * n;
}
public static long roundUpTo(long n, long x) {
return (x + n - 1) / n * n;
}
public static int primitiveTypeSize(Class c) {
if (c == byte.class || c == boolean.class)
return 1;
if (c == short.class || c == char.class)
return 2;
if (c == int.class || c == float.class)
return 4;
return 8;
}
public static Class arrayElementType(Object o) {
return _getClass(o).getComponentType();
}
public static TreeSet asTreeSet(List l) {
TreeSet set = new TreeSet();
for (Object o : l) if (o != null)
set.add(o);
return set;
}
public static TreeSet asTreeSet(Set set) {
return set instanceof TreeSet ? (TreeSet) set : new TreeSet(set);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static boolean startsWithOneOf_treeSet(String s, TreeSet set) {
if (set == null || s == null)
return false;
while (licensed()) {
String key = set.floor(s);
if (key == null)
return false;
int n = lCommonPrefix(key, s);
if (n == l(key))
return true;
s = takeFirst(s, n);
}
return false;
}
public static String className(Object o) {
return getClassName(o);
}
public static Map dangerousWeakMap() {
return newDangerousWeakHashMap();
}
public static Map dangerousWeakMap(Object initFunction) {
return newDangerousWeakHashMap(initFunction);
}
public static List nonStaticNonPrimitiveFieldObjects_uncached(Object o) {
List fields = new ArrayList();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields()) if ((f.getModifiers() & Modifier.STATIC) == 0 && !isPrimitiveType(f.getType()))
fields.add(makeAccessible(f));
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
public static JInternalFrame getInternalFrame(final Object _o) {
return _o == null ? null : swing(new F0() {
public JInternalFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JInternalFrame)
return (JInternalFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
public static A optCast(Class c, Object o) {
return isInstance(c, o) ? (A) o : null;
}
public static A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l) - 1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
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 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 String makeFrame_defaultIcon;
public static boolean makeFrame_hideConsole;
public static ThreadLocal> makeFrame_post = new ThreadLocal();
public static JFrame makeFrame() {
return makeFrame((Component) null);
}
public static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
public static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
public static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
public static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
final VF1 post = optParam(makeFrame_post);
return swing(new F0() {
public JFrame get() {
try {
if (getFrame(content) != null)
return getFrame(setFrameTitle((Component) content, title));
final JFrame frame = new JFrame(title);
if (makeFrame_defaultIcon != null)
setFrameIconLater(frame, makeFrame_defaultIcon);
_initFrame(frame);
Component wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(defaultNewFrameBounds());
callF(post, frame);
if (showIt)
frame.setVisible(true);
if (showIt && makeFrame_hideConsole) {
hideConsole();
makeFrame_hideConsole = false;
}
return frame;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (getFrame(content) != null)\r\n ret getFrame(setFrameTitle((Component) ...";
}
});
}
public static boolean frameTooSmall(JFrame frame) {
return frame.getWidth() < 100 || frame.getHeight() < 50;
}
public static void frameStandardSize(JFrame frame) {
frame.setBounds(300, 100, 500, 400);
}
public static void setFrameContents(final Component c, final Object contents) {
{
swing(new Runnable() {
public void run() {
try {
JFrame frame = getFrame(c);
frame.getContentPane().removeAll();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrap(contents));
revalidate(frame);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JFrame frame = getFrame(c);\r\n frame.getContentPane().removeAll();\r\n fra...";
}
});
}
}
public static int imageIcon_cacheSize = 10;
public static boolean imageIcon_verbose;
public static Map imageIcon_cache;
public static Lock imageIcon_lock = lock();
public static ThreadLocal imageIcon_fixGIF = new ThreadLocal();
public static ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __84 = imageIcon_lock;
lock(__84);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__84);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ImageIcon imageIcon(File f) {
try {
return new ImageIcon(f.toURI().toURL());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
public static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
public static String or2(String a, String b) {
return nempty(a) ? a : b;
}
public static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
public static void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
public static void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
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 A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
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 File[] listFiles(File dir) {
File[] files = dir.listFiles();
return files == null ? new File[0] : files;
}
public static File[] listFiles(String dir) {
return listFiles(new File(dir));
}
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 List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
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 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 Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
public static WeakReference creator_class;
public static Object creator() {
return creator_class == null ? null : creator_class.get();
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(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 void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
public static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null)
return null;
A a = popLast(l);
if (empty(l))
tl.set(null);
return a;
}
public static boolean headless() {
return isHeadless();
}
public static Throwable printStackTrace(Throwable 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 String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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 Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
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())) {
m.setAccessible(true);
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 int smartLastIndexOf(String s, char c) {
if (s == null)
return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
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 int numberOfFunctionArguments(Object f) {
if (f instanceof F0)
return 0;
if (f instanceof F1)
return 1;
if (f instanceof F2)
return 2;
if (f instanceof VF1)
return 1;
if (f instanceof String)
return numberOfMethodArguments(mc(), (String) f);
return numberOfMethodArguments(f, "get");
}
public static RuntimeException todo() {
throw new RuntimeException("TODO");
}
public static RuntimeException todo(String msg) {
throw new RuntimeException("TODO: " + msg);
}
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)
print("Warning: 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)
print("Warning: unsatisfied token reference " + ref);
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("sync")) {
consume();
if (t().equals("tm")) {
consume();
{
parseMap(synchronizedTreeMap(), out);
return;
}
}
if (t().equals("[")) {
parseList(synchroList(), out);
return;
}
{
parseMap(synchronizedMap(), out);
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("c");
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
}
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(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
if (!eq(tpp(), "="))
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);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ...";
}
});
} 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 (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field));
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 out.set(list);\r\n ...";
}
});
}
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;
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_x(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_x(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;
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 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 String addPrefixIfNotEmpty2(String prefix, String s) {
return empty(s) ? "" : addPrefix(prefix, s);
}
public static CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt;
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)) || "'".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;
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 structure_addTokenMarkers(String s) {
return join(structure_addTokenMarkers(javaTok(s)));
}
public static List structure_addTokenMarkers(List tok) {
TreeSet refs = new TreeSet();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("t") && isInteger(t.substring(1)))
refs.add(parseInt(t.substring(1)));
}
if (empty(refs))
return tok;
for (int i : refs) {
int idx = i * 2 + 1;
String t = "";
if (endsWithLetterOrDigit(tok.get(idx - 1)))
t = " ";
tok.set(idx, t + "m" + i + " " + tok.get(idx));
}
return tok;
}
public static String jreplace(String s, String in, String out) {
return jreplace(s, in, out, null);
}
public static String jreplace(String s, String in, String out, Object condition) {
List tok = javaTok(s);
return jreplace(tok, in, out, condition) ? join(tok) : s;
}
public static boolean jreplace(List tok, String in, String out) {
return jreplace(tok, in, out, false, true, null);
}
public static boolean jreplace(List tok, String in, String out, Object condition) {
return jreplace(tok, in, out, false, true, condition);
}
public static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
String[] toks = javaTokForJFind_array(in);
int lTokin = toks.length * 2 + 1;
boolean anyChange = false;
int i = -1;
for (int n = 0; n < 10000; n++) {
i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
if (i < 0)
return anyChange;
List subList = tok.subList(i - 1, i + lTokin - 1);
String expansion = jreplaceExpandRefs(out, subList);
int end = i + lTokin - 2;
clearAllTokens(tok, i, end);
tok.set(i, expansion);
if (reTok)
reTok(tok, i, end);
i = end;
anyChange = true;
}
throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
}
public static boolean jreplace_debug;
public static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++) chars[i] = c;
return new String(chars);
}
public static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++) l.add(a);
return l;
}
public static List repeat(int n, A a) {
return repeat(a, n);
}
public static String classNameToVM(String name) {
return name.replace(".", "$");
}
public static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
public static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
public static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
public static int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
public static LinkedHashMap orderMapByValue(final Map map) {
List l = new ArrayList(map.keySet());
sort(l, mapComparator(map));
LinkedHashMap map2 = litorderedmap();
for (A a : l) map2.put(a, map.get(a));
return map2;
}
public static boolean compressedOOPSEnabled_is64bitHotSpot;
public static boolean compressedOOPSEnabled_compressedOOPS;
public static boolean compressedOOPSEnabled_checked;
public static boolean compressedOOPSEnabled() {
if (compressedOOPSEnabled_checked)
return compressedOOPSEnabled_compressedOOPS;
String OS_ARCH = System.getProperty("os.arch");
String MANAGEMENT_FACTORY_CLASS = "java.lang.management.ManagementFactory";
String HOTSPOT_BEAN_CLASS = "com.sun.management.HotSpotDiagnosticMXBean";
String x = System.getProperty("sun.arch.data.model");
boolean is64Bit = contains(or(x, OS_ARCH), "64");
if (is64Bit) {
try {
final Class> beanClazz = Class.forName(HOTSPOT_BEAN_CLASS);
final Object hotSpotBean = Class.forName(MANAGEMENT_FACTORY_CLASS).getMethod("getPlatformMXBean", Class.class).invoke(null, beanClazz);
if (hotSpotBean != null) {
compressedOOPSEnabled_is64bitHotSpot = true;
final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
try {
final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "UseCompressedOops");
compressedOOPSEnabled_compressedOOPS = Boolean.parseBoolean(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
} catch (ReflectiveOperationException | RuntimeException e) {
compressedOOPSEnabled_is64bitHotSpot = false;
}
}
} catch (ReflectiveOperationException | RuntimeException e) {
compressedOOPSEnabled_is64bitHotSpot = false;
}
}
compressedOOPSEnabled_checked = true;
return compressedOOPSEnabled_compressedOOPS;
}
public static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static int lCommonPrefix(String a, String b) {
int i = 0, n = min(l(a), l(b));
while (i < n && a.charAt(i) == b.charAt(i)) ++i;
return i;
}
public static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
public static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
public static String takeFirst(int n, String s) {
return substring(s, 0, n);
}
public static String takeFirst(String s, int n) {
return substring(s, 0, n);
}
public static List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_1141 = 0; _repeat_1141 < n; _repeat_1141++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
public static boolean isPrimitiveType(Class c) {
return c != null && c.isPrimitive();
}
public static Field makeAccessible(Field f) {
f.setAccessible(true);
return f;
}
public static Method makeAccessible(Method m) {
m.setAccessible(true);
return m;
}
public static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
public static boolean isInstanceOf(Object o, Class type) {
return type.isInstance(o);
}
public static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
public static volatile boolean disableCertificateValidation_attempted;
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 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(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 String programTitle() {
return getProgramName();
}
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 void _initFrame(JFrame f) {
myFrames_list.put(f, Boolean.TRUE);
standardTitlePopupMenu(f);
}
public static Rectangle defaultNewFrameBounds_r = new Rectangle(300, 100, 500, 400);
public static Rectangle defaultNewFrameBounds() {
return swing(new F0() {
public Rectangle get() {
try {
defaultNewFrameBounds_r.translate(60, 20);
if (!screenRectangle().contains(defaultNewFrameBounds_r))
defaultNewFrameBounds_r.setLocation(30 + random(30), 20 + random(20));
return new Rectangle(defaultNewFrameBounds_r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "defaultNewFrameBounds_r.translate(60, 20);\r\n if (!screenRectangle().contai...";
}
});
}
public static void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() {
public void run() {
try {
frame.setVisible(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setVisible(false);";
}
});
}
}
public static A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(new Runnable() {
public void run() {
try {
c.revalidate();
c.repaint();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r...";
}
});
}
return c;
}
public static void revalidate(JFrame f) {
revalidate((Component) f);
}
public static void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
public static void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
public static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
public static ReentrantLock lock() {
return fairLock();
}
public static String fsI(String id) {
return formatSnippetID(id);
}
public static String fsI(long id) {
return formatSnippetID(id);
}
public static File loadBinarySnippet(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean loadBufferedImageFixingGIFs_debug;
public static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
public static Image loadBufferedImageFixingGIFs(File file) {
try {
if (!file.exists())
return null;
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": checking gif");
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
try {
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
BufferedImage frameIn = reader.read(i);
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
((IIOMetadataNode) node).setAttribute("delayTime", "10");
}
break;
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally {
_close(ios);
}
}
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug)
print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
public static void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null)
return new ArrayList();
synchronized (mutex) {
return new ArrayList (l);
}
}
public static long parseLong(String s) {
if (s == null)
return 0;
return Long.parseLong(dropSuffix("L", s));
}
public static long parseLong(Object s) {
return Long.parseLong((String) s);
}
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 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(Object 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 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 Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
public static int numberOfMethodArguments(Object o, String method) {
Class c;
boolean mustBeStatic = false;
if (o instanceof Class) {
c = (Class) o;
mustBeStatic = true;
} else
c = o.getClass();
Class _c = c;
int n = -1;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if (mustBeStatic && !methodIsStatic(m))
continue;
int nn = l(m.getParameterTypes());
if (n == -1)
n = nn;
else if (n != nn)
throw fail("Variable number of method arguments: " + _c + "." + method);
}
c = c.getSuperclass();
}
if (n == -1)
throw fail("Method not found: " + _c + "." + method);
return n;
}
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 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 boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static TreeMap ciMap() {
return caseInsensitiveMap();
}
public static SortedMap synchronizedTreeMap() {
return synchroTreeMap();
}
public static List parseList(String s) {
return (List) safeUnstructure(s);
}
public static Map synchronizedMap() {
return synchroMap();
}
public static Map synchronizedMap(Map map) {
return synchroMap(map);
}
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 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);
m.setAccessible(true);
return (A) m.newInstance(new Object[] { null });
} catch (Exception __e) {
throw rethrow(__e);
}
}
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));
ctr.setAccessible(true);
}
}
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 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 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 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.put(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 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(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 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 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 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);
}
public static String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
public static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
public static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
public static BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
public static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
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 Map javaTokForJFind_array_cache = synchronizedMRUCache(1000);
public static String[] javaTokForJFind_array(String s) {
String[] tok = javaTokForJFind_array_cache.get(s);
if (tok == null)
javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
return tok;
}
public static int findCodeTokens(List tok, String... tokens) {
return findCodeTokens(tok, 1, false, tokens);
}
public static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, 1, ignoreCase, tokens);
}
public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}
public static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*");
public static boolean findCodeTokens_debug;
public static int findCodeTokens_indexed, findCodeTokens_unindexed;
public static int findCodeTokens_bails, findCodeTokens_nonbails;
public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
if (findCodeTokens_debug) {
if (eq(getClassName(tok), "main$IndexedList2"))
findCodeTokens_indexed++;
else
findCodeTokens_unindexed++;
}
int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
int i = startIdx | 1;
String firstToken = tokens[0];
if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
while (i < end && !firstToken.equals(tok.get(i))) i += 2;
}
outer: for (; i < end; i += 2) {
for (int j = 0; j < nTokens; j++) {
String p = tokens[j], t = tok.get(i + j * 2);
boolean match;
if (eq(p, "*"))
match = true;
else if (eq(p, ""))
match = isQuoted(t);
else if (eq(p, ""))
match = isIdentifier(t);
else if (eq(p, ""))
match = isInteger(t);
else if (eq(p, "\\*"))
match = eq("*", t);
else
match = ignoreCase ? eqic(p, t) : eq(p, t);
if (!match)
continue outer;
}
if (condition == null || checkTokCondition(condition, tok, i - 1))
return i;
}
return -1;
}
public static String jreplaceExpandRefs(String s, List tokref) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) {
String x = tokref.get(-1 + parseInt(tok.get(i).substring(1)) * 2);
tok.set(i, x);
}
}
return join(tok);
}
public static void clearAllTokens(List tok) {
for (int i = 0; i < tok.size(); i++) tok.set(i, "");
}
public static void clearAllTokens(List tok, int i, int j) {
for (; i < j; i++) tok.set(i, "");
}
public static List reTok(List tok) {
replaceCollection(tok, javaTok(tok));
return tok;
}
public static List reTok(List tok, int i) {
return reTok(tok, i, i + 1);
}
public static List reTok(List tok, int i, int j) {
i = i & ~1;
j = j | 1;
List t = javaTok(join(subList(tok, i, j)));
replaceListPart(tok, i, j, t);
return tok;
}
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 mapComparator(final Map map) {
return new Comparator () {
public int compare(A a, A b) {
return cmp(map.get(a), map.get(b));
}
};
}
public static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
public static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
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 String getProgramName_cache;
public static String getProgramName() {
Lock __271 = downloadLock();
lock(__271);
try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally {
unlock(__271);
}
}
public static void _onLoad_getProgramName() {
startThread(new Runnable() {
public void run() {
try {
getProgramName();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getProgramName();";
}
});
}
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 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 boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static void standardTitlePopupMenu(final JFrame frame) {
if (isSubstanceLAF())
titlePopupMenu(frame, new VF1() {
public void get(JPopupMenu menu) {
try {
boolean alwaysOnTop = frame.isAlwaysOnTop();
menu.add(jmenuItem("Restart Program", "restart"));
menu.add(jmenuItem("Duplicate Program", "duplicateThisProgram"));
menu.add(jmenuItem("Show Console", "showConsole"));
menu.add(jCheckBoxMenuItem("Always On Top", alwaysOnTop, new Runnable() {
public void run() {
try {
toggleAlwaysOnTop(frame);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "toggleAlwaysOnTop(frame)";
}
}));
menu.add(jMenuItem("Shoot Window", new Runnable() {
public void run() {
try {
shootWindowGUI_external(frame, 500);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "shootWindowGUI_external(frame, 500)";
}
}));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "bool alwaysOnTop = frame.isAlwaysOnTop();\r\n menu.add(jmenuItem(\"Restar...";
}
});
}
public static Rectangle screenRectangle() {
return new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
}
public static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
public static void autoVMExit() {
call(getJavaX(), "autoVMExit");
}
public static void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static File loadImageAsFile(String snippetIDOrURL) {
try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL))
throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
return file;
}
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
File file = new File(dir, snippetID + ".png");
saveBinaryFile(file, data);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
public static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
public static long fileSize(String path) {
return getFileSize(path);
}
public static long fileSize(File f) {
return getFileSize(f);
}
public static File loadDataSnippetToFile(String snippetID) {
try {
snippetID = fsI(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/" + psI(snippetID)));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] isGIF_magic = bytesFromHex("47494638");
public static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
public static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
public static void setVar(IVar v, A value) {
if (v != null)
v.set(value);
}
public static void restart() {
Object j = getJavaX();
call(j, "cleanRestart", get(j, "fullArgs"));
}
public static void duplicateThisProgram() {
nohupJavax(trim(programID() + " " + smartJoin((String[]) get(getJavaX(), "fullArgs"))));
}
public static void showConsole() {
callOpt(get(javax(), "console"), "showConsole");
}
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 String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return 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 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 TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
public static NavigableMap synchroTreeMap() {
return Collections.synchronizedNavigableMap(new TreeMap());
}
public static Object safeUnstructure(String s) {
return unstructure(s, true);
}
public static Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
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 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 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 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 void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
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)) {
m.setAccessible(true);
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 new TreeSet(caseInsensitiveComparator());
}
public static TreeSet caseInsensitiveSet(Collection c) {
return toCaseInsensitiveSet(c);
}
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 BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
public static String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
public static A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
public static FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
public static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
public static int gzInputStream_defaultBufferSize = 65536;
public static GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
public static String[] codeTokensAsStringArray(List tok) {
int n = max(0, (l(tok) - 1) / 2);
String[] out = new String[n];
for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
return out;
}
public static int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
public static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
public static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
public static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
public static int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
public static int jfind(List tok, List