Warning : session_start(): open(/var/lib/php/sessions/sess_kgraiu5ihu3kqttrcp944kn9kl, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.TitledBorder;
import javax.swing.border.*;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
class main {
public static class ChessBoardRecognizer extends DynModule {
public String segmenterPreset;
public ParameterizedSegmenter segmenter;
public List segments;
public Rect boardLocation;
public double recognitionScore;
public String status;
public String selectedSquare;
public String piece;
public List> recognized;
public String fen;
public static boolean _switchableField_squareHeightAtBottom = true;
public boolean squareHeightAtBottom = true;
public transient int recreatedSquareSize = 32;
public transient ReliableSingleThread rst = dm_rst(module(), new Runnable() {
public void run() {
try {
recognize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "recognize();";
}
});
public transient BufferedImage img, board, square, recreated;
public transient List> squareImages;
public transient ImageSurface isInput, isBoard, isSquare, isRecreated;
public transient List pieces = ai_chessPieces();
public transient Map> recreateStock;
public JComponent visualize() {
isBoard = jImageSurface();
imageSurfaceOnHover(isBoard, new VF1() {
public void get(Pt p) {
try {
if (board == null || p == null) {
noToolTip(isBoard);
return;
}
setToolTip(isBoard, toolTipForSquare(boardPointToSquare(p)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (board == null || p == null) ret with noToolTip(isBoard);\r\n setToolTi...";
}
});
imageSurfaceOnLeftClick(isBoard, new VF1() {
public void get(Pt p) {
try {
selectSquare(boardPointToSquare(p));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectSquare(boardPointToSquare(p))";
}
});
isRecreated = jImageSurface(recreated);
imageSurfaceOnHover(isRecreated, new VF1() {
public void get(Pt p) {
try {
if (recreated == null || p == null) {
noToolTip(isRecreated);
return;
}
setToolTip(isRecreated, toolTipForSquare(recreatedPointToSquare(p)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (recreated == null || p == null) ret with noToolTip(isRecreated);\r\n s...";
}
});
imageSurfaceOnLeftClick(isRecreated, new VF1() {
public void get(Pt p) {
try {
selectSquare(recreatedPointToSquare(p));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectSquare(recreatedPointToSquare(p))";
}
});
return withCalc(rst, jvsplit(jCenteredSection("Input image", jscroll_center(isInput = jImageSurface(or_func(img, () -> whiteImage(100))))), northCenterAndSouthWithMargins(centerAndEastWithMargin(withLabel("Segmenter preset: ", main.onChange(rst, dm_comboBox("segmenterPreset", agiBlue_chessBoardSegmenterPresetNames()))), hstackWithSpacing(jbutton("Recognize", rst), jPopDownButton_noText("Show possible chess boards found", runnableThread(new Runnable() {
public void run() {
try {
showSegments();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "showSegments();";
}
}), "Publish training image...", runnableThread(new Runnable() {
public void run() {
try {
publishImage();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "publishImage();";
}
}), "---", null, "Screenshot (hiding OS)", runnableThread(new Runnable() {
public void run() {
try {
isInput.setImageAndZoomToDisplay(dm_shootScreenHidingOS());
rst.trigger();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "isInput.setImageAndZoomToDisplay(dm_shootScreenHidingOS());\r\n ...";
}
})))), hgridWithSpacing(jCenteredSection("Recreated", jscroll_center(isRecreated)), jCenteredSection("Chess board in image", centerAndSouthWithMargin(jscroll_center(isBoard), dm_centeredCalculatedLabel(() -> "Recognition score: " + formatDouble(recognitionScore, 2)))), jCenteredLiveValueSection(dm_calculatedLiveValue(String.class, () -> "Selected square" + (empty(selectedSquare) ? "" : " (" + selectedSquare + ")")), centerAndSouthWithMargin(jscroll_center(isSquare = jImageSurface(square)), rightAlignedLine(withLabel("Piece: ", dm_comboBox("piece", pieces)), jbutton("Save & upload", runnableThread(new Runnable() {
public void run() {
try {
saveAndUploadPiece();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveAndUploadPiece();";
}
})))))), vstackWithSpacing(dm_label("status"), withLabel("FEN:", dm_label("fen"))))));
}
public void recognize() {
status("Recognizing...");
segmenter = parameterizedSegmenterFromAGIBlue(segmenterPreset);
if (segmenter == null) {
infoBox(status("No segmenter"));
return;
}
if (isInput != null)
img = isInput.getImage();
List rects = segmenter.get(img);
setField("segments", rects);
if (empty(rects)) {
clearImageSurfaces(isBoard, isRecreated);
setField("fen", "");
{
status("No chess board found");
return;
}
}
Rect r = first(rects);
boolean corrected = squareHeightAtBottom && abs(r.w - r.h) > 3;
if (corrected)
r.h = r.w;
List comments = new ArrayList();
if (l(rects) > 1)
comments.add("randomly choosing one from " + nBoards(rects));
if (corrected)
comments.add("height-corrected");
status("Chess board found at: " + r + appendRoundBracketed(joinWithComma(comments)));
setField("boardLocation", r);
board = clipBufferedImage(img, r);
squareImages = bufferedImageMNGrid(board, 8, 8);
if (isBoard != null)
isBoard.setImageAndZoomToDisplay(mergeBufferedImagesVertically(map(bufferedImageNVerticalSlices(8, board), i -> mergeBufferedImagesHorizontally(bufferedImageNHorizontalSlices(8, i)))));
ChessPieceRecognizer pieceRecognizer = new ChessPieceRecognizer();
pieceRecognizer.load();
recognized = new ArrayList();
for (BufferedImage img : concatLists(squareImages)) recognized.add(pieceRecognizer.recognize(img));
setField("recognitionScore", doubleAvg(pairsB(recognized)));
setField("fen", makeFEN());
print(recognized);
recreate();
}
public String status(String status) {
setField("status", status);
return status;
}
public Object _getReloadData() {
return img;
}
public void _setReloadData(BufferedImage img) {
this.img = img;
}
public void setImage(BufferedImage img) {
this.img = img;
if (isInput != null)
isInput.setImageAndZoomToDisplay(img);
rst.trigger();
}
public String boardPointToSquare(Pt p) {
double space = imageMergeSpacing();
double squareW = board.getWidth() / 8.0 + space;
double squareH = board.getHeight() / 8.0 + space;
int x = clamp(iratio_floor(p.x + space / 2, squareW), 0, 7);
int y = clamp(iratio_floor(p.y + space / 2, squareH), 0, 7);
return strCharPlus('A', x) + (8 - y);
}
public String recreatedPointToSquare(Pt p) {
int x = clamp(iratio_floor(p.x, recreatedSquareSize), 0, 7);
int y = clamp(iratio_floor(p.y, recreatedSquareSize), 0, 7);
return strCharPlus('A', x) + (8 - y);
}
public void saveAndUploadPiece() {
AutoCloseable __7 = enter();
try {
if (square == null || empty(piece))
return;
chessOCR_uploadPieceImage(selectedSquare, piece, square);
if (mapGet(mapGet(recreateStock, chess_isLightSquare(selectedSquare)), piece) == null)
recreateStock = null;
rst.trigger();
} finally {
_close(__7);
}
}
public void recreate() {
if (recognized == null)
return;
if (recreateStock == null)
recreateStock = mapToValues(ll(false, true), light -> mapValues(pairsToMap(reversePairs(chessPieceImagesFromAGIBlue(light))), imageID -> resizeImage(loadImage2(imageID), recreatedSquareSize, recreatedSquareSize)));
List out = new ArrayList();
int i = 0;
for (String piece : pairsA(recognized)) {
boolean light = even(i / 8 + i % 8);
out.add(or_func(mapGet(mapGet(recreateStock, light), piece), () -> whiteImage(recreatedSquareSize, recreatedSquareSize)));
++i;
}
List rows = new ArrayList();
for (List row : listToChunks(out, 8)) rows.add(mergeBufferedImagesHorizontally(row, "spacing", 0));
recreated = mergeBufferedImagesVertically(rows, "spacing", 0);
if (isRecreated != null)
isRecreated.setImageAndZoomToDisplay(recreated);
}
public Pair recognitionForSquare(String square) {
int x;
int y;
Pair __11 = chess_squareToPos(square);
x = __11.a;
y = __11.b;
return _get(recognized, y * 8 + x);
}
public String toolTipForSquare(String square) {
Pair rec = recognitionForSquare(square);
return square + " - " + (rec == null ? "?" : rec.a + " [" + iround(clamp(rec.b, 0, 100)) + "%]");
}
public void selectSquare(String _square) {
setField("selectedSquare", _square);
String rec = pairA(recognitionForSquare(selectedSquare));
if (rec != null)
setField("piece", rec);
int x;
int y;
Pair __12 = chess_squareToPos(selectedSquare);
x = __12.a;
y = __12.b;
square = _get(_get(squareImages, y), x);
ChessPieceProfile1 profile = chessOCR_pieceProfileFromRawImage_1(square, "withPreprocessedImages", true);
isSquare.setImage(mergeBufferedImagesHorizontally(itemPlusList(square, map("toBufferedImage", profile.preprocessedImages))));
}
public void showSegments() {
List segments = this.segments;
showImage_centered(n2(segments, "segment") + " found", mergeBufferedImagesVertically(map(segments, r -> clipBufferedImage(img, r))));
}
public void publishImage() {
AutoCloseable __8 = enter();
try {
BufferedImage img = this.img;
String segmenterPreset = this.segmenterPreset;
JCheckBox cbFound = jcheckbox(true), cbHasBoard = jcheckbox(true);
JTextField tfFEN = jtextfield(fen), tfComments = jtextfield(), tfImageCredits = jtextfield();
showFormTitled("Publish training image", "Image", jImageSurface(scaleImageToWidth(img, 500)), "Segmenter used", jlabel(segmenterPreset), "Is there a chess board in the image?", cbHasBoard, "FEN (empty if no board in image)", tfFEN, "Was the chess board found?", cbFound, "Image credits (optional)", tfImageCredits, "Random comments", tfComments, "NOTE:", jMultiLineLabel("By clicking 'publish', you PUBLISH this image (fair use/public domain)."), "", jThreadedButton("Publish", new Runnable() {
public void run() {
try {
AutoCloseable __9 = tempInfoBox_noHide("Uploading training image...");
try {
String imageURL = uploadToImageServer("Chess board recognition training image", img);
String desc = "Chess board recognition training image " + assertNempty("Parseable image URL", parseSnippetImageURL(imageURL));
LinkedHashMap map = new LinkedHashMap();
map.put("Input image", imageURL);
mapPutIfNemptyValue(map, "Image credits", gtt(tfImageCredits));
String fen = gtt(tfFEN);
map.put("Image has chess board", yesNo_short_firstUpper(isChecked(cbHasBoard) || nempty(fen)));
mapPutIfNemptyValue(map, "FEN", fen);
map.put("Segmenter used", segmenterPreset);
map.put("Chess board found", yesNo_short_firstUpper(isChecked(cbFound)));
if (isChecked(cbFound))
map.put("Board location", struct(boardLocation));
String sliceID = agiBlue_chessBoardRecognitionTrainingImagesSliceID();
List toPost = new ArrayList();
String name = agiBlue_createUnusedNumberedPage(sliceID, desc + " #");
for (String key : keys(map)) {
String value = map.get(key);
toPost.add(litmap("q", name, "key", key, "value", value));
}
agiBot_postMulti(keyPairForProgram(), toPost, "slice", sliceID);
infoBox("Training image uploaded!");
openURLInBrowser(agiBlue_linkForPhrase(name, "slice", sliceID));
disposeWindow(heldButton());
} finally {
_close(__9);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __9 = tempInfoBox_noHide(\"Uploading training image...\"); try {\r...";
}
}));
} finally {
_close(__8);
}
}
public String makeFEN() {
return chess_makeFEN(listToChunks(pairsA(recognized), 8));
}
}
public static boolean _moduleClass_ChessBoardRecognizer = false;
public static Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A callF(F0 f) {
return f == null ? null : f.get();
}
public static A callF(IF0 f) {
return f == null ? null : f.get();
}
public static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
public static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
public static void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
public static Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
public static Object call(Object o) {
return callF(o);
}
public static Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
public static void _onLoad_initUtils() {
utils.__javax = javax();
}
public static void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
});
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent = false;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static volatile Object print_preprocess;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
public static void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
public static void print_autoRotate() {
}
public static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
public static BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
public static ReliableSingleThread dm_rst(Runnable r) {
return dm_rst(dm_current_mandatory(), r);
}
public static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
public static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
public static List ai_chessPieces_cache;
public static List ai_chessPieces() {
if (ai_chessPieces_cache == null)
ai_chessPieces_cache = ai_chessPieces_load();
return ai_chessPieces_cache;
}
public static List ai_chessPieces_load() {
return tlft("\r\n empty\r\n white king\r\n black king\r\n white queen\r\n black queen\r\n white rook\r\n black rook\r\n white bishop\r\n black bishop\r\n white knight\r\n black knight\r\n white pawn\r\n black pawn\r\n ");
}
public static ImageSurface jImageSurface() {
return swingNu(ImageSurface.class);
}
public static ImageSurface jImageSurface(MakesBufferedImage img) {
return swingNu(ImageSurface.class, img.getBufferedImage());
}
public static ImageSurface jImageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
public static void imageSurfaceOnHover(ImageSurface is, VF1 onHover) {
if (is == null || onHover == null)
return;
{
swing(new Runnable() {
public void run() {
try {
MouseAdapter ma = new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
pick(e);
}
public void mouseEntered(MouseEvent e) {
pick(e);
}
public void mouseExited(MouseEvent e) {
pick(null);
}
public void pick(MouseEvent e) {
callF(onHover, e == null ? (Pt) null : is.pointFromEvent(e));
}
};
is.addMouseMotionListener(ma);
is.addMouseListener(ma);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "MouseAdapter ma = new MouseAdapter {\r\n public void mouseMoved(MouseEvent...";
}
});
}
}
public static A noToolTip(A c) {
return setToolTip(c, (String) null);
}
public static A setToolTip(A c, Object toolTip) {
return setToolTipText(c, toolTip);
}
public static A setToolTip(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
public static void imageSurfaceOnLeftClick(ImageSurface is, VF1 onClick) {
if (is == null || onClick == null)
return;
{
swing(new Runnable() {
public void run() {
try {
MouseAdapter ma = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1)
callF(onClick, is.pointFromEvent(e));
}
};
is.addMouseListener(ma);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "MouseAdapter ma = new MouseAdapter {\r\n public void mouseClicked(MouseEve...";
}
});
}
}
public static A withCalc(Runnable r, A a) {
return withComputing(r, a);
}
public static JSplitPane jvsplit(Component n, Component s) {
return jvsplit(n, s, 0.5);
}
public static JSplitPane jvsplit(Component n, Component s, double splitPoint, int delay) {
return jvsplit(n, s, splitPoint);
}
public static JSplitPane jvsplit(Component n, Component s, double splitPoint) {
return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.VERTICAL_SPLIT, wrap(n), wrap(s)), splitPoint);
}
public static JSplitPane jvsplit(double splitPoint, Component n, Component s) {
return jvsplit(n, s, splitPoint);
}
public static JPanel jCenteredSection(Component c) {
return jCenteredSection("", c);
}
public static JPanel jCenteredSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = jSection(title, c);
((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = jSection(title, c);\r\n ((TitledBorder) p.getBorder()).setTitleJu...";
}
});
}
public static JPanel jCenteredSection(String title) {
return jCenteredSection(title, jpanel());
}
public static JScrollPane jscroll_center(Component c) {
return jscroll_centered(c);
}
public static A or_func(A a, IF0 b) {
return a != null ? a : callF(b);
}
public static BufferedImage whiteImage(int w, int h) {
return newBufferedImage(w, h, Color.white);
}
public static BufferedImage whiteImage(int size) {
return whiteImage(size, size);
}
public static JPanel northCenterAndSouthWithMargins(Component n, Component c, Component s) {
return applyDefaultMargin(northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s)));
}
public static JPanel centerAndEastWithMargin(Component c, Component e) {
return centerAndEastWithMarginInbetween(c, e);
}
public static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
public static A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
public static A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
public static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
public static A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
public static JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
public static JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
public static JComboBox dm_comboBox(String field, Collection values) {
return jLiveValueComboBox(values, dm_fieldLiveValue(field));
}
public static Collection agiBlue_chessBoardSegmenterPresetNames() {
return allContainingIC("chess board", agiBlue_segmenterPresetNames());
}
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 JButton jPopDownButton_noText(final Object... menuParams) {
return jPopDownButton("", menuParams);
}
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 BufferedImage dm_shootScreenHidingOS() {
AutoCloseable __50 = dm_tempMinimizeOS();
try {
sleepSeconds(3);
return shootScreen2();
} finally {
_close(__50);
}
}
public static JPanel hgridWithSpacing(final Object... parts) {
final JPanel panel = hgrid(parts);
{
swing(new Runnable() {
public void run() {
try {
GridLayout gl = (GridLayout) (panel.getLayout());
gl.setHgap(6);
gl.setVgap(6);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "GridLayout gl = (GridLayout) (panel.getLayout());\r\n gl.setHgap(6);\r\n g...";
}
});
}
return panel;
}
public static JPanel centerAndSouthWithMargin(Component c, Component s) {
return centerAndSouth(c, withTopMargin(s));
}
public static JLabel dm_centeredCalculatedLabel(IF0 calc) {
return centerLabel(dm_calculatedLabel(calc));
}
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 class jCenteredLiveValueSection_class extends SingleComponentPanel {
public LiveValue liveValue;
public String getTitle() {
return liveValue.get();
}
public jCenteredLiveValueSection_class(LiveValue lv, Component c) {
super(c);
bindLiveValueListenerToComponent(this, liveValue = lv, new Runnable() {
public void run() {
try {
swingLater(new Runnable() {
public void run() {
try {
setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), liveValue.get()));
centerSection(jCenteredLiveValueSection_class.this);
revalidate();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setBorder(BorderFactory.createTitledBorder(\r\n BorderFactory.createBeve...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "swingLater(r {\r\n setBorder(BorderFactory.createTitledBorder(\r\n Bo...";
}
});
}
}
public static JPanel jCenteredLiveValueSection(final LiveValue lv, final Component c) {
return swingNu(jCenteredLiveValueSection_class.class, lv, c);
}
public static LiveValue dm_calculatedLiveValue(final DynModule module, final Class type, final F0 calc) {
Lock __58 = module.lock;
lock(__58);
try {
final SimpleLiveValue value = new SimpleLiveValue(type, callF(calc));
module.onChange(new Runnable() {
public void run() {
try {
value.set(callF(calc));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "value.set(callF(calc))";
}
});
return value;
} finally {
unlock(__58);
}
}
public static LiveValue dm_calculatedLiveValue(Class type, F0 calc) {
return dm_calculatedLiveValue(dm_current_mandatory(), type, calc);
}
public static LiveValue dm_calculatedLiveValue(Class type, IF0 calc) {
return dm_calculatedLiveValue(type, if0ToF0(calc));
}
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(short[] a) {
return a == null || a.length == 0;
}
public static boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
public static boolean empty(File f) {
return getFileSize(f) == 0;
}
public static JPanel rightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
public static JPanel rightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
public static int vstackWithSpacing_default = 10;
public static JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
public static JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing / 2, 0, spacing / 2, 0);
smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
public static JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
public static JLabel dm_label(String fieldName) {
return dm_fieldLabel(fieldName);
}
public static Map status_map;
public abstract static class Status {
public abstract String answer(String s);
}
public static synchronized Status status() {
status_load();
return status_map.get(getDialogID());
}
public static void status_load() {
if (status_map == null) {
status_map = new TreeMap();
load("status_map");
}
}
public static synchronized void status(Status s) {
status_load();
if (s == null)
status_map.remove(getDialogID());
else
status_map.put(getDialogID(), s);
save("status_map");
}
public static String status_answer(String s) {
Status status = status();
if (status != null)
return status.answer(s);
return null;
}
public static ParameterizedSegmenter parameterizedSegmenterFromAGIBlue(String name) {
ParameterizedSegmenter segmenter = new ParameterizedSegmenter();
List> values = agiBlue_lookupMultipleKeys(agiBlue_imageSegmentationSlice(), name, nonTransientNonStaticFieldNames(segmenter));
if (empty(values))
return null;
for (Pair __486 : values) {
String key = pairA(__486);
String value = pairB(__486);
set(segmenter, key, safeUnstructureAllowingCertainClasses_plusUtils(value, "Rect", "DoubleRange"));
}
return segmenter;
}
public static JWindow infoBox(String text) {
return infoMessage(text);
}
public static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
public static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
public static void clearImageSurfaces(ImageSurface... l) {
for (ImageSurface is : unnull(l)) if (is != null)
is.noImage();
}
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 float abs(float f) {
return Math.abs(f);
}
public static int abs(int i) {
return Math.abs(i);
}
public static double abs(double d) {
return Math.abs(d);
}
public static String nBoards(long n) {
return n2(n, "board");
}
public static String nBoards(Collection l) {
return nBoards(l(l));
}
public static String appendRoundBracketed(String b) {
return empty(b) ? "" : "" + " (" + b + ")";
}
public static String appendRoundBracketed(String a, String b) {
return empty(b) ? a : a + appendRoundBracketed(b);
}
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 BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, new Rect(clip));
}
public static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
if (src == null || r == null)
return null;
r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
if (rectEmpty(r))
return null;
return src.getSubimage(r.x, r.y, r.w, r.h);
}
public static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, new Rect(x, y, w, h));
}
public static List> bufferedImageMNGrid(int cols, int rows, BufferedImage img) {
List> out = new ArrayList();
for (List l : gridOfRects3(img.getWidth(), img.getHeight(), cols, rows)) out.add(map(r -> clipBufferedImage(img, r), l));
return out;
}
public static List> bufferedImageMNGrid(BufferedImage img, int cols, int rows) {
return bufferedImageMNGrid(cols, rows, img);
}
public static BufferedImage mergeBufferedImagesVertically(BufferedImage... images) {
return mergeBufferedImagesVertically(asList(images));
}
public static BufferedImage mergeBufferedImagesVertically(List images, Object... __) {
return mergeImagesVertically(map("toRGBImage", images), __).getBufferedImage();
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
public static List map(IF1 f, Iterable l) {
return map(l, f);
}
public static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(IF1 f, A[] l) {
return map(l, f);
}
public static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(Object f, Object[] l) {
return map(f, asList(l));
}
public static List map(Object[] l, Object f) {
return map(f, l);
}
public static List map(Object f, Map map) {
return map(map, f);
}
public static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
public static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
public static List bufferedImageNVerticalSlices(int n, BufferedImage img) {
return bufferedImageVerticalSlices(doubleRatio(img.getHeight(), n), img);
}
public static BufferedImage mergeBufferedImagesHorizontally(BufferedImage... images) {
return mergeBufferedImagesHorizontally(toList(images));
}
public static BufferedImage mergeBufferedImagesHorizontally(List images, Object... __) {
int spacing = optPar("spacing", __, imageMergeSpacing());
RGB spaceColor = new RGB(0.9f);
int w = intSum(mapMethod("getWidth", images)) + (l(images) - 1) * spacing, h = intMax(mapMethod("getHeight", images));
BufferedImage out = newBufferedImage(w, h, spaceColor);
int x = 0;
for (int i = 0; i < l(images); i++) {
BufferedImage img = images.get(i);
int y = (h - img.getHeight()) / 2;
copyBufferedImage(img, out, x, y);
x += img.getWidth() + spacing;
}
return out;
}
public static List bufferedImageNHorizontalSlices(int n, BufferedImage img) {
return bufferedImageHorizontalSlices(doubleRatio(img.getWidth(), n), img);
}
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 double doubleAvg(int... a) {
return doubleAverage(a);
}
public static double doubleAvg(double... l) {
return doubleAverage(l);
}
public static double doubleAvg(Collection l) {
return doubleAverage(l);
}
public static List pairsB(Collection> l) {
return secondOfPairs(l);
}
public static int imageMergeSpacing = 5;
public static int imageMergeSpacing() {
return imageMergeSpacing;
}
public static void imageMergeSpacing(int pixels) {
imageMergeSpacing = pixels;
}
public static float clamp(float x, float a, float b) {
return x < a ? a : x > b ? b : x;
}
public static double clamp(double x, double a, double b) {
return x < a ? a : x > b ? b : x;
}
public static int clamp(int x, int a, int b) {
return x < a ? a : x > b ? b : x;
}
public static int iratio_floor(double a, double b) {
return ifloor(ratio(a, b));
}
public static String strCharPlus(char a, int b) {
return str(charPlus(a, b));
}
public static void chessOCR_uploadPieceImage(String square, String piece, BufferedImage img) {
AutoCloseable __96 = tempInfoBox_noHide("Uploading...");
try {
String imageURL = uploadToImageServer("Chess square: " + piece, img);
agiBlue_postInSlice(agiBlue_chessPieceImagesSlice(), imageURL, "is", piece);
agiBlue_postInSlice(agiBlue_chessPieceImagesSlice(), imageURL, "was on square", square);
infoBox("Uploaded!");
} finally {
_close(__96);
}
}
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 chess_isLightSquare(String square) {
int x;
int y;
Pair __932 = chess_squareToPos(square);
x = __932.a;
y = __932.b;
return even(x + y);
}
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 Map mapToValues(Iterable l, Object f) {
return mapKeyAndFunction(l, f);
}
public static Map mapToValues(Object f, Iterable l) {
return mapKeyAndFunction(f, l);
}
public static Map mapToValues(Iterable l, IF1 f) {
return mapKeyAndFunction(f, l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
public static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
public static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
public static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
public static HashMap pairsToMap(Collection extends Pair > l) {
HashMap map = new HashMap();
if (l != null)
for (Pair p : l) map.put(p.a, p.b);
return map;
}
public static List> reversePairs(Iterable> l) {
return map("reversedPair", l);
}
public static List> chessPieceImagesFromAGIBlue() {
return mapPairsA("parseImageSnippetURL", filter(p -> isURL(p.a) && ai_chessPiecesSet().contains(p.b), agiBlue_pagesAndValuesForKey(agiBlue_chessPieceImagesSlice(), "is")));
}
public static List> chessPieceImagesFromAGIBlue(boolean lightSquares) {
List> raw = agiBlue_pagesAndValuesForKey(agiBlue_chessPieceImagesSlice(), "is");
List> squares = agiBlue_pagesAndValuesForKey(agiBlue_chessPieceImagesSlice(), "was on square");
Set set = asSet(pairsA(filter(squares, p -> lightSquares == chess_isLightSquare(p.b))));
List> filtered = filter(raw, p -> set.contains(p.a));
return mapPairsA("parseImageSnippetURL", filtered);
}
public static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
}
public static BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
if (newW == img.getWidth() && newH == img.getHeight())
return img;
Image tmp = img.getScaledInstance(newW, newH, scaleType);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
public static BufferedImage resizeImage(BufferedImage img, int newW) {
int newH = iround(img.getHeight() * (double) newW / img.getWidth());
return resizeImage(img, newW, newH);
}
public static BufferedImage resizeImage(int newW, BufferedImage img) {
return resizeImage(img, newW);
}
public static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
public static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
public static List pairsA(Collection> l) {
return firstOfPairs(l);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static List> listToChunks(List l, int chunkSize) {
int rows = intRatio_ceil(l(l), chunkSize);
List> out = emptyList(rows);
for (int y = 0; y < rows; y++) out.add(subList(l, y * chunkSize, (y + 1) * chunkSize));
return out;
}
public static Pair chess_squareToPos(String square) {
if (square == null)
return null;
assertLength(2, square);
return pair(charDiff(upper(first(square)), 'A'), 8 - charDiff(second(square), '0'));
}
public static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static Object _get(Object o, String field) {
return get(o, field);
}
public static Object _get(String field, Object o) {
return get(o, field);
}
public static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static int iround(double d) {
return (int) Math.round(d);
}
public static int iround(Number n) {
return iround(toDouble(n));
}
public static A pairA(Pair p) {
return p == null ? null : p.a;
}
public static ChessPieceProfile1 chessOCR_pieceProfileFromRawImage_1(BufferedImage img, Object... __) {
boolean withPreprocessedImages = boolPar("withPreprocessedImages", __);
BWImage bw = chessOCR_piecePreprocessing_1(img);
BWImage bw2 = chessOCR_piecePreprocessingForFillGrade_1(img);
ChessPieceProfile1 profile = new ChessPieceProfile1(ocr_sideProfile_scaledTo127(20, 0.5, bw), 1f - bwAverageBrightness(bw2));
if (withPreprocessedImages)
profile.preprocessedImages = ll(bw, bw2);
return profile;
}
public static List itemPlusList(A a, Collection l) {
return concatLists(ll(a), l);
}
public static ImageSurface showImage_centered(final BufferedImage img) {
return (ImageSurface) swing(new F0() {
public Object get() {
try {
ImageSurface is = new ImageSurface(img);
JPanel panel = new JPanel(new GridBagLayout());
panel.add(is);
JFrame frame = showPackedFrame(new JScrollPane(panel));
frameIcon(frame, showImage_defaultIcon);
return is;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ImageSurface is = new ImageSurface(img);\r\n JPanel panel = new JPanel(new G...";
}
});
}
public static ImageSurface showImage_centered(final BufferedImage img, final String title) {
return setFrameTitle(showImage_centered(img), title);
}
public static ImageSurface showImage_centered(String title, BufferedImage img) {
return showImage_centered(img, title);
}
public static ImageSurface showImage_centered(String title, RGBImage img) {
return showImage_centered(title, img.getBufferedImage());
}
public static ImageSurface showImage_centered(ImageSurface is, BufferedImage img) {
if (is == null)
return showImage_centered(img);
is.setImage(img);
return is;
}
public static ImageSurface showImage_centered(ImageSurface is, String title, BufferedImage img) {
if (is == null)
return showImage_centered(title, img);
is.setImage(img);
setFrameTitle(is, title);
return is;
}
public static ImageSurface showImage_centered(ImageSurface surface, RGBImage img, String title) {
return setFrameTitle(showImage_centered(img, surface), title);
}
public static ImageSurface showImage_centered(RGBImage img, ImageSurface surface) {
if (surface == null)
return showImage_centered(img);
else {
surface.setImage(img);
return surface;
}
}
public static ImageSurface showImage_centered(RGBImage img) {
return showImage_centered(img.getBufferedImage());
}
public static ImageSurface showImage_centered(ImageSurface surface, String title, RGBImage img) {
return showImage_centered(surface, img, title);
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
public static JCheckBox jcheckbox() {
return jCheckBox();
}
public static JCheckBox jcheckbox(boolean checked) {
return jCheckBox(checked);
}
public static JCheckBox jcheckbox(String text, boolean checked) {
return jCheckBox(text, checked);
}
public static JCheckBox jcheckbox(String text) {
return jCheckBox(text);
}
public static JCheckBox jcheckbox(JCheckBox cb, String text) {
return jcheckbox(text, isChecked(cb));
}
public static JTextField jtextfield() {
return jTextField();
}
public static JTextField jtextfield(String text) {
return jTextField(text);
}
public static JTextField jtextfield(Object o) {
return jTextField(o);
}
public static int showForm_defaultGap = 4;
public static int showForm_gapBetweenColumns = 10;
public static JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null)
return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() {
public JPanel get() {
try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p...";
}
});
}
public static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
public static BufferedImage scaleImageToWidth(BufferedImage img, int newW) {
return resizeImage(img, newW);
}
public static BufferedImage scaleImageToWidth(int newW, BufferedImage img) {
return scaleImageToWidth(img, newW);
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static JLabel jMultiLineLabel(String text) {
return setVerticalAlignment(JLabel.TOP, jlabel(jlabel_textAsHTML(text)));
}
public static JButton jThreadedButton(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);
btn.setToolTipText(btn.getText());
if (action != null)
btn.addActionListener(actionListenerInNewThread(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 AutoCloseable tempInfoBox_noHide(String msg) {
return tempDisposeWindow(infoBox_noHide(msg));
}
public static String uploadToImageServer(BufferedImage img, String name) {
return uploadToImageServerIfNotThere(img, name);
}
public static String uploadToImageServer(String name, BufferedImage img) {
return uploadToImageServerIfNotThere(img, name);
}
public static String uploadToImageServer(File f) {
return uploadFileToImageServer(f);
}
public static A assertNempty(A a) {
return assertNempty("empty", a);
}
public static A assertNempty(String msg, A a) {
if (empty(a))
throw fail(msg + ": " + a);
return a;
}
public static String parseSnippetImageURL(String url) {
return parseImageSnippetURL(url);
}
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 String gtt(JTextComponent c) {
return getTextTrim(c);
}
public static String gtt(JComboBox cb) {
return getTextTrim(cb);
}
public static String yesNo_short_firstUpper(boolean b) {
return b ? "Yes" : "No";
}
public static boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return checkBox.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret checkBox.isSelected();";
}
});
}
public static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() {
public Boolean get() {
try {
return mi.isSelected();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mi.isSelected();";
}
});
}
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 agiBlue_chessBoardRecognitionTrainingImagesSliceID() {
return "jxoivvjqucrsrque";
}
public static String agiBlue_createUnusedNumberedPage(String sliceID, String q) {
return getString("q", agiBlue_loadBotPage("createUnusedNumberedPage", "q", q, "slice", sliceID));
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiSet ms) {
return ms.keySet();
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
public static void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
public static Object agiBot_postMulti(PKIKeyPair keys, List posts, Object... __) {
return print(postJSONPage("http://agi.blue/bot/postSigned", paramsPlus(__, "text", pki_signTextIncludingKey(jsonEncodeLines(posts), keys))));
}
public static PKIKeyPair keyPairForProgram() {
Lock __147 = programLock();
lock(__147);
try {
File f = secretProgramFile("key-pair.txt");
try {
PKIKeyPair pair = pkiKeyPairFromTwoLineFile(f);
if (pair != null)
return pair;
} catch (Throwable __e) {
_handleException(__e);
}
PKIKeyPair pair = pki_newKeyPair();
saveTextFile(f, linesLL(pair.publicKey, pair.privateKey));
return pair;
} finally {
unlock(__147);
}
}
public static void openURLInBrowser(String url) {
openPlatformBrowser(url);
}
public static String agiBlue_linkForPhrase(String phrase, Object... additionalParams) {
return agiBlueURL() + hquery(arrayPlus(additionalParams, "q", phrase));
}
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 JButton heldButton() {
return heldInstance(JButton.class);
}
public static String chess_makeFEN(List> recognized) {
if (empty(recognized))
return null;
List out = new ArrayList();
for (List row : recognized) {
int i = 0;
StringBuilder buf = new StringBuilder();
while (i < 8) {
int j = smartIndexOfNot(row, "empty", i);
if (j > i) {
buf.append(j - i);
i = j;
} else {
String p = row.get(i++);
String piece = secondWord(p);
char c = eq(piece, "knight") ? 'n' : first(piece);
if (startsWith(p, "white"))
c = upper(c);
buf.append(c);
}
}
out.add(str(buf));
}
return join("/", out);
}
public static Class mc() {
return main.class;
}
public static Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found in " + c);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Class javax() {
return getJavaX();
}
public static void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
public static HashMap findClass_fullName_cache = new HashMap();
public static Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static String substring(String s, int x) {
return substring(s, x, strL(s));
}
public static String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
public static String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
public static 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 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 Object _defaultClassFinder_value = defaultDefaultClassFinder();
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static String programID;
public static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
public static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
public static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
public static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
public static A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
public static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
public static AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
public static BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage)
return (BufferedImage) o;
if (o instanceof MakesBufferedImage)
return ((MakesBufferedImage) o).getBufferedImage();
if (o instanceof File)
if (isImageFile(((File) o)))
return loadImage2(((File) o));
String c = getClassName(o);
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
if (eq(c, "main$PNGFile"))
return (BufferedImage) call(o, "getImage");
return null;
}
public static F0 dm_rEnter(final DynModule mod) {
return mod == null ? null : new F0() {
public AutoCloseable get() {
try {
return mod.enter();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mod.enter();";
}
};
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static A swing(IF0 f) {
return (A) swingAndWait(f);
}
public static A setToolTipText(final A c, final Object toolTip) {
if (c == null)
return null;
{
swing(new Runnable() {
public void run() {
try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ...";
}
});
}
return c;
}
public static A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
public static A withComputing(Runnable r, A a) {
callF(r);
return a;
}
public static JSplitPane setSplitPaneOnFirstShowing(final Component c, final double value) {
final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
if (sp != null)
onFirstResize(sp, new Runnable() {
public void run() {
try {
sp.setDividerLocation(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sp.setDividerLocation(value);";
}
});
return sp;
}
public static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static JPanel jSection(Component c) {
return jSection("", c);
}
public static JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
public static JPanel jSection(String title) {
return jSection(title, jpanel());
}
public static JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
public static JPanel jpanel() {
return swingNu(JPanel.class);
}
public static JScrollPane jscroll_centered(Component c) {
return jscroll(jFullCenter(c));
}
public static BufferedImage newBufferedImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
public static BufferedImage newBufferedImage(int w, int h, RGB rgb) {
return newBufferedImage(w, h, toColor(rgb));
}
public static BufferedImage newBufferedImage(int w, int h, Color color) {
BufferedImage img = newBufferedImage(w, h);
Graphics2D g = img.createGraphics();
g.setColor(color);
g.fillRect(0, 0, w, h);
return img;
}
public static BufferedImage newBufferedImage(Pt p, Color color) {
return newBufferedImage(p.x, p.y, color);
}
public static A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
public static JPanel northCenterAndSouth(Component n, Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.NORTH, wrap(n));
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
public static int withBottomMargin_defaultWidth = 6;
public static JPanel withBottomMargin(Component c) {
return withBottomMargin(withBottomMargin_defaultWidth, c);
}
public static JPanel withBottomMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static int withTopMargin_defaultWidth = 6;
public static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
public static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
return centerAndEast(c, withLeftMargin(e));
}
public static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST...";
}
});
}
public static ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
public static ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
public static void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
public static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
public static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
public static JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
public static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() {
public void run() {
try {
pcallF(f, selectedItem(cb));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, selectedItem(cb))";
}
});
return cb;
}
public static JComboBox jLiveValueComboBox(Collection values, final SimpleLiveValue lv) {
final JComboBox cb = jComboBox(values);
bindComboBoxToLiveValue(cb, lv);
return cb;
}
public static SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
public static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __190 = module.lock;
lock(__190);
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
module.onChange(new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
unlock(__190);
}
}
public static List allContainingIC(Collection l, final String x) {
return containingIC(l, x);
}
public static List allContainingIC(String x, Collection l) {
return containingIC(x, l);
}
public static Collection agiBlue_segmenterPresetNames() {
return agiBlue_pagesWithKey(agiBlue_imageSegmentationSlice(), "Input image");
}
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 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 JButton jPopDownButton(String text, final Object... menuParams) {
return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() {
public void run() {
try {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
String position = (String) (optPar(menuParams, "position"));
fillJPopupMenu(menu, paramsWithout(menuParams, "position"));
if (menu.getComponentCount() != emptyCount) {
JButton btn = heldInstance(JButton.class);
int x = 0;
if (eq(position, "center"))
x = (btn.getWidth() - getPreferredWidth(menu)) / 2;
else if (eq(position, "right"))
x = btn.getWidth() - getPreferredWidth(menu);
menu.show(btn, x, btn.getHeight());
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JPopupMenu menu;\r\n int emptyCount = menu.getComponentCount();\r\n Str...";
}
});
}
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 AutoCloseable dm_tempMinimizeOS() {
dm_minimizeOS();
return new AutoCloseable() {
public String toString() {
return "dm_activateOS();";
}
public void close() throws Exception {
dm_activateOS();
}
};
}
public static void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
public static boolean shootScreen_useScrot = false;
public static BufferedImage shootScreen2() {
return shootScreen2(screenRectangle());
}
public static BufferedImage shootScreen2(Rectangle area) {
try {
ping();
if (shootScreen_useScrot && eq(area, screenRectangle())) {
if (!isOnPATH("scrot"))
shootScreen2_fallback();
if (shootScreen_useScrot) {
String filename = "screenshot-" + randomID(12) + ".png";
File f = linux_fileInRamDisk(filename);
if (f == null)
f = prepareProgramFile(filename);
try {
String cmd = "scrot " + bashQuote(f);
String out = backtick(cmd);
if (f.exists())
return loadPNG(f);
shootScreen2_fallback();
} catch (Throwable e) {
print(e);
shootScreen2_fallback();
} finally {
f.delete();
}
}
}
return new Robot().createScreenCapture(area);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedImage shootScreen2(Rect area) {
return shootScreen2(area.getRectangle());
}
public static BufferedImage shootScreen2(int x, int y, int w, int h) {
return shootScreen2(new Rectangle(x, y, w, h));
}
public static void shootScreen2_fallback() {
if (shootScreen_useScrot) {
if (isLinux())
print("Scrot failed. Reverting to internal screenshots.");
shootScreen_useScrot = false;
}
}
public static JPanel hgrid(final Object... parts) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel();
Object[] _parts = flattenArray2(parts);
panel.setLayout(new GridLayout(1, _parts.length));
smartAdd(panel, _parts);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JPanel panel;\r\n O[] _parts = flattenArray2(parts);\r\n panel.setLayou...";
}
});
}
public static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
public static A centerLabel(A l) {
if (l != null)
l.setHorizontalAlignment(SwingConstants.CENTER);
return l;
}
public static JLabel dm_calculatedLabel(IF0 calc) {
return jLiveValueLabel(dm_calculatedLiveValue(Object.class, calc));
}
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 bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component, new Runnable() {
public void run() {
try {
lv.onChangeAndNow(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL...";
}
}, new Runnable() {
public void run() {
try {
lv.removeOnChangeListener(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.removeOnChangeListener(listener)";
}
});
return component;
}
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 JPanel centerSection(JPanel section) {
if (section != null) {
swing(new Runnable() {
public void run() {
try {
Border border = section.getBorder();
if (border instanceof TitledBorder)
((TitledBorder) border).setTitleJustification(TitledBorder.CENTER);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = section.getBorder();\r\n if (border instanceof TitledBorder)...";
}
});
}
return section;
}
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 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 F0 if0ToF0(IF0 f) {
return f == null ? null : new F0 () {
public A get() {
try {
return f.get();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.get();";
}
};
}
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 JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() {
public RightAlignedLine get() {
try {
return new RightAlignedLine(components);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret RightAlignedLine(components);";
}
});
}
public static JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
public static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
return panel;
}
public static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static List nonNulls(List l) {
return withoutNulls(l);
}
public static List nonNulls(A[] l) {
return withoutNulls(l);
}
public static Map nonNulls(Map map) {
return withoutNulls(map);
}
public static JLabel dm_fieldLabel(String fieldName) {
return jLiveValueLabel(dm_fieldLiveValue(fieldName));
}
public static String getDialogID() {
return (String) callOpt(getMainBot(), "getDialogID");
}
public static Object load(String varName) {
readLocally(varName);
return get(mc(), varName);
}
public static Object load(String progID, String varName) {
readLocally(progID, varName);
return get(mc(), varName);
}
public static void save(String varName) {
saveLocally(varName);
}
public static void save(String progID, String varName) {
saveLocally(progID, varName);
}
public static List> agiBlue_lookupMultipleKeys(String sliceID, String q, Collection keys) {
return map((List>) agiBlue_loadBotPage("lookupMultipleKeys", paramsPlus_noOverwrite(paramsWithSameKey("key", keys), "slice", sliceID, "q", q)), map -> pair(map.get("key"), map.get("value")));
}
public static String agiBlue_imageSegmentationSlice() {
return "lgobeactljkewwtz";
}
public static Set nonTransientNonStaticFieldNames(Object o) {
return allNonStaticNonTransientFields(o);
}
public static B pairB(Pair p) {
return p == null ? null : p.b;
}
public static A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
public static void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static Object safeUnstructureAllowingCertainClasses_plusUtils(String s, String... allowedClasses) {
Set allowedClassesSet = new HashSet();
for (String name : unnull(allowedClasses)) {
allowedClassesSet.add("main$" + name);
allowedClassesSet.add("loadableUtils.utils$" + name);
}
Object classFinder = new F1() {
public Object get(String name) {
try {
if (!allowedClassesSet.contains(name))
throw fail("Class not allowed to unstructure: " + name);
return classForName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!allowedClassesSet.contains(name)) fail(\"Class not allowed to unstructure...";
}
};
return unstructure(s, false, classFinder);
}
public static boolean infoMessage_alwaysOnTop = true;
public static double infoMessage_defaultTime = 5.0;
public static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
public static JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
public static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
public static JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text))
return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless())
return null;
return (JWindow) swingAndWait(new F0() {
public Object get() {
try {
final JWindow window = showWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s...";
}
});
}
public static JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
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 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 String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static Rect intersectRects(Rect a, Rect b) {
int x = max(a.x, b.x), y = max(a.y, b.y);
int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h);
return new Rect(x, y, x2 - x, y2 - y);
}
public static boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
public static List> gridOfRects3(int w, int h, int cols, int rows) {
return gridOfRects3(new Rect(0, 0, w, h), cols, rows);
}
public static List> gridOfRects3(Rect r, int cols, int rows) {
List> l = new ArrayList();
for (int row = 0; row < rows; row++) {
List line = new ArrayList();
int y1 = r.y + iround(r.h * (double) row / rows);
int y2 = r.y + iround(r.h * (double) (row + 1) / rows);
for (int col = 0; col < cols; col++) {
int x1 = r.x + iround(r.w * (double) col / cols);
int x2 = r.x + iround(r.w * (double) (col + 1) / cols);
line.add(new Rect(x1, y1, x2 - x1, y2 - y1));
}
l.add(line);
}
return l;
}
public static RGBImage mergeImagesVertically(RGBImage... images) {
return mergeImagesVertically(toList(images));
}
public static RGBImage mergeImagesVertically(List images, Object... __) {
int spacing = optPar("spacing", __, imageMergeSpacing());
RGB spaceColor = optPar("spaceColor", __, new RGB(0.9f));
int h = intSum(images, "height") + (l(images) - 1) * spacing, w = intMax(images, "width");
RGBImage out = new RGBImage(w, h, spaceColor);
int y = 0;
for (int i = 0; i < l(images); i++) {
RGBImage img = images.get(i);
int x = (w - img.w()) / 2;
copyRGBImage(img, 0, 0, out, x, y);
y += img.h() + spacing;
}
return out;
}
public static RGBImage toRGBImage(BWImage img) {
return img == null ? null : img.toRGB();
}
public static RGBImage toRGBImage(BufferedImage img) {
return img == null ? null : new RGBImage(img);
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static List bufferedImageVerticalSlices(double sliceHeight, BufferedImage img) {
List out = new ArrayList();
int w = img.getWidth(), h = img.getHeight();
for (double y = 0; iround(y) < h; y += sliceHeight) {
int actualY = iround(y), nextY = min(h, iround(y + sliceHeight));
if (nextY > actualY)
out.add(clipBufferedImage(img, rectFromPoints(0, actualY, w, nextY)));
}
return out;
}
public static double doubleRatio(double x, double y) {
return y == 0 ? 0 : x / y;
}
public static ArrayList toList(A[] a) {
return asList(a);
}
public static ArrayList toList(int[] a) {
return asList(a);
}
public static ArrayList toList(Set s) {
return asList(s);
}
public static ArrayList toList(Iterable s) {
return asList(s);
}
public static 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 int intSum(Collection c, String field) {
int sum = 0;
for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
return sum;
}
public static int intSum(Iterable l) {
int sum = 0;
for (Integer i : unnull(l)) if (i != null)
sum += i;
return sum;
}
public static List mapMethod(Object[] l, final String methodName) {
return map(l, new F1() {
public Object get(Object o) {
try {
return callOpt(o, methodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(o, methodName)";
}
});
}
public static List mapMethod(Iterable c, final String methodName) {
return map(c, new F1() {
public Object get(Object o) {
try {
return callOpt(o, methodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(o, methodName)";
}
});
}
public static List mapMethod(String methodName, Iterable c) {
return mapMethod(c, methodName);
}
public static List mapMethod(String methodName, Enumeration c) {
return mapMethod(methodName, enumerationToIterator(c));
}
public static int getWidth(Component c) {
return c == null ? 0 : (int) swingCall(c, "getWidth");
}
public static int intMax(Collection c, String field) {
int max = Integer.MIN_VALUE;
for (Object o : c) max = Math.max(max, toInt(getOpt(o, field)));
return max;
}
public static int intMax(Iterable l) {
int max = Integer.MIN_VALUE;
for (int i : unnull(l)) max = Math.max(max, i);
return max;
}
public static int getHeight(Component c) {
return c == null ? 0 : (int) swingCall(c, "getHeight");
}
public static void copyBufferedImage(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) {
copyImagePart(src, srcx, srcy, dest, destx, desty, w, h);
}
public static void copyBufferedImage(BufferedImage src, BufferedImage dest, int destx, int desty) {
if (src != null)
copyBufferedImage(src, 0, 0, dest, destx, desty, src.getWidth(), src.getHeight());
}
public static List bufferedImageHorizontalSlices(double sliceWidth, BufferedImage img) {
List out = new ArrayList();
int w = img.getWidth(), h = img.getHeight();
for (double x = 0; iround(x) < w; x += sliceWidth) {
int actualX = iround(x), nextX = min(w, iround(x + sliceWidth));
if (nextX > actualX)
out.add(clipBufferedImage(img, rectFromPoints(actualX, 0, nextX, h)));
}
return out;
}
public static double doubleAverage(int... a) {
double sum = 0;
for (int i = 0; i < l(a); i++) sum += a[i];
return doubleRatio(sum, l(a));
}
public static double doubleAverage(double... l) {
return doubleRatio(doubleSum(l), l(l));
}
public static double doubleAverage(Collection l) {
return doubleRatio(doubleSum(l), l(l));
}
public static List secondOfPairs(Collection> l) {
return map("secondOfPair", l);
}
public static int ifloor(double d) {
return (int) Math.floor(d);
}
public static long ratio(long x, long y) {
return y == 0 ? 0 : x / y;
}
public static double ratio(double x, double y) {
return y == 0 ? 0 : x / y;
}
public static char charPlus(char a, int b) {
return (char) (((int) a) + b);
}
public static ThreadLocal>> agiBlue_postInSlice_queue = new ThreadLocal();
public static String agiBlue_postInSlice(String slice, String a, String b, String c) {
List> queue = agiBlue_postInSlice_queue.get();
if (queue != null) {
queue.add(ll(slice, a, b, c));
return "Queued";
} else
return loadPage(agiBlueURL() + "/bot/post" + hquery("slice", slice, "q", a, "key", b, "value", c));
}
public static String agiBlue_chessPieceImagesSlice() {
return "rowmdrceiqdnlfso";
}
public static Map mapKeyAndFunction(Iterable l, Object f) {
return mapKeyAndFunction(f, l);
}
public static Map mapKeyAndFunction(Object f, Iterable l) {
HashMap map = new HashMap();
if (l != null)
for (Object o : l) map.put(o, callF(f, o));
return map;
}
public static Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
public static Pair reversedPair(Pair p) {
return p == null ? null : pair(p.b, p.a);
}
public static List> mapPairsA(final Object f, Iterable> l) {
return mapPairA(f, l);
}
public static List> mapPairsA(F1 f, Iterable> l) {
return mapPairA(f, l);
}
public static List> mapPairsA(IF1 f, Iterable> l) {
return mapPairA(f, l);
}
public static String parseImageSnippetURL(String url) {
String id = regexpExtract("\\d+$", url);
return id == null ? null : "#" + id;
}
public static List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
public static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
public static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
public static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
public static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
public static Set ai_chessPiecesSet_cache;
public static Set ai_chessPiecesSet() {
if (ai_chessPiecesSet_cache == null)
ai_chessPiecesSet_cache = ai_chessPiecesSet_load();
return ai_chessPiecesSet_cache;
}
public static Set ai_chessPiecesSet_load() {
return asCISet(ai_chessPieces());
}
public static List> agiBlue_pagesAndValuesForKey(String slice, String key) {
List> l = new ArrayList();
for (Map map : (List) loadJSONPage(agiBlueURL() + "/bot/entriesForKey" + hquery("slice", slice, "key", key))) l.add(pair((String) map.get("q"), (String) map.get("value")));
return l;
}
public static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
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 firstOfPairs(Collection> l) {
List out = new ArrayList();
for (Pair p : unnull(l)) out.add(firstOfPair(p));
return out;
}
public static int intRatio_ceil(int a, int b) {
return idiv_ceil(a, b);
}
public static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
public static List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
public static List assertLength(int length, List l) {
assertEquals(length, l(l));
return l;
}
public static String assertLength(int length, String s) {
assertEquals(s, length, l(s));
return s;
}
public static String assertLength(String s, int length) {
return assertLength(length, s);
}
public static Pair pair(A a, B b) {
return new Pair(a, b);
}
public static Pair pair(A a) {
return new Pair(a, a);
}
public static int charDiff(char a, char b) {
return (int) a - (int) b;
}
public static int charDiff(String a, char b) {
return charDiff(stringToChar(a), b);
}
public static String upper(String s) {
return s == null ? null : s.toUpperCase();
}
public static char upper(char c) {
return Character.toUpperCase(c);
}
public static A second(List l) {
return get(l, 1);
}
public static A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
public static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
public static B second(Pair p) {
return p == null ? null : p.b;
}
public static A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
public static char second(String s) {
return charAt(s, 1);
}
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 boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
public static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Map __) {
return boolOptParam(name, __);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static BWImage chessOCR_piecePreprocessing_1(BufferedImage img, Object... __) {
int version = optPar("version", __, 1);
BWImage bw = bwImageTo2Bit(0.75f, img_cubedDistanceFromColor_withGain(rgbBlack(), 3.0, blurFilterBufferedImage(minFilterBufferedImage(3, img))));
if (version == 1)
bw = bwAutoCrop(bw);
return bw;
}
public static BWImage chessOCR_piecePreprocessingForFillGrade_1(BufferedImage img) {
return img_cubedDistanceFromColor_withGain(rgbBlack(), 2.5, img);
}
public static byte[] ocr_sideProfile_scaledTo127(int n, double stopAtRatio, BWImage img) {
return concatByteArrays_reverseSecond(ocr_leftProfile_scaledTo127(n, stopAtRatio, img), ocr_rightProfile_scaledTo127(n, stopAtRatio, img));
}
public static float bwAverageBrightness(BWImage img) {
return img == null ? 0 : (float) img.averageBrightness();
}
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 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 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 String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
public static JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
public static JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
public static JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
public static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
public static JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
public static JTextField jTextField() {
return jTextField("");
}
public static JTextField jTextField(final String text) {
return swing(new F0() {
public JTextField get() {
try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu...";
}
});
}
public static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
public static JDesktopPane mainDesktopPane_value;
public static JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
public static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
JPanel panel = showForm_makePanel(true, _parts);
showForm_makeInternalFrame(desktop, title, panel);
return panel;
}
public static JFrame showForm_makeFrame(String title, JPanel panel) {
return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
}
public static List showForm_arrange1(List> l) {
int minW = showForm_leftWidth(l);
List out = new ArrayList();
for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidth(minW, first(row))), second(row)));
return out;
}
public static List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
List> l = new ArrayList();
List parts = asList(_parts);
JButton submitButton = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i + 1);
if (o instanceof String && next instanceof Component)
setComponentID((Component) next, (String) o);
if (o instanceof Component || o instanceof String || next instanceof Component) {
l.add(mapLL("wrapForSmartAdd", o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next));
if (next instanceof JButton && submitButton == null)
submitButton = (JButton) next;
i++;
} else if (isRunnable(o))
l.add(mapLL("wrapForSmartAdd", null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() {
public void run() {
try {
Object result = call(o);
if (neq(Boolean.FALSE, result)) {
if (isTrue(internalFrame))
disposeInternalFrame(heldInstance(JButton.class));
else if (isFalse(internalFrame))
disposeFrame(heldInstance(JButton.class));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result)) {\r\n ...";
}
})));
else
print("showForm: Unknown element type: " + getClassName(o));
}
if (submitButton != null) {
final JButton _submitButton = submitButton;
onEnterInAllTextFields(concatLists(l), new Runnable() {
public void run() {
try {
clickButton(_submitButton);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clickButton(_submitButton)";
}
});
}
for (List row : l) {
JComponent left = first(row);
if (left instanceof JLabel)
makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
}
return l;
}
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 setVerticalAlignment(final int pos, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setVerticalAlignment(pos);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setVerticalAlignment(pos);";
}
});
}
return a;
}
public static A setVerticalAlignment(final int pos, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setVerticalAlignment(pos);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setVerticalAlignment(pos);";
}
});
}
return a;
}
public static String jlabel_textAsHTML(String text) {
return hhtml(replace(htmlencode(text), "\n", " "));
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
public static ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __1246 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1246);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1246 = holdInstance(instanceToHold); try {\r\n callF(runna...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
public static AutoCloseable tempDisposeWindow(final Window w) {
return new AutoCloseable() {
public void close() {
disposeWindow(w);
}
};
}
public static JWindow infoBox_noHide(String message) {
return infoBoxForever(message);
}
public static int uploadToImageServerIfNotThere_tries = 3;
public static String uploadToImageServerIfNotThere(BufferedImage img, String name) {
return uploadToImageServerIfNotThere(null, img, name);
}
public static String uploadToImageServerIfNotThere(File f, BufferedImage img, String name) {
String md5 = md5OfRGBImage(new RGBImage(img));
Throwable lastException = null;
for (int tries = 0; tries < uploadToImageServerIfNotThere_tries; tries++) try {
long id = imageServerCheckMD5(md5);
if (id == 0)
return uploadToImageServer_new(f, img, name);
else
return snippetImgLink(fsI(id));
} catch (Throwable e) {
lastException = printException(e);
}
throw fail(lastException);
}
public static String uploadFileToImageServer(File f) {
return uploadToImageServerIfNotThere(f, loadImage2(f), f.getName());
}
public static String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
public static String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
public static String getTextTrim(JComponent c) {
if (c instanceof JLabel)
return trim(((JLabel) c).getText());
if (c instanceof JComboBox)
return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
public static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
public static String getString(List l, int idx) {
return (String) get(l, idx);
}
public static String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static String getString(String key, Object o) {
return getString(o, (Object) key);
}
public static Object agiBlue_loadBotPage(String cmd, Object... params) {
return loadJSONPage(agiBlueURL() + "/bot" + addSlashPrefix(cmd) + hquery(params));
}
public static Object postJSONPage(String url, Object... params) {
return jsonDecode(postPage(url, params));
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], a2) };
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
public static String pki_signTextIncludingKey(String s, PKIKeyPair keyPair) {
s = fromLines(toLines(s));
return s + "sig: " + pki_signatureForText(s, keyPair) + "\n" + "signer: " + keyPair.publicKey + "\n";
}
public static String jsonEncodeLines(List l) {
return mapToLines("jsonEncode", l);
}
public static Lock programLock() {
return mainLock();
}
public static File secretProgramFile(String progID, String fileName) {
return new File(getSecretProgramDir(progID), fileName);
}
public static File secretProgramFile(String fileName) {
return secretProgramFile(getProgramID(), fileName);
}
public static PKIKeyPair pkiKeyPairFromTwoLineFile(File f) {
List l = tlft(loadTextFile(f));
if (l(l) == 2)
return new PKIKeyPair(second(l), first(l));
return null;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static PKIKeyPair pki_newKeyPair() {
try {
KeyPair keyPair = PKI.makeKeyPair();
return new PKIKeyPair(PKI.privateKeyToString(keyPair.getPrivate().getEncoded()), PKI.publicKeyToString(keyPair.getPublic()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
public static File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String linesLL(String... x) {
return lines(ll(x));
}
public static void openPlatformBrowser(String url) {
try {
if (isHeadless())
return;
Desktop.getDesktop().browse(uri(url));
print("Opening platform-specific browser on: " + url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean agiBlueURL_noHTTPS = false;
public static String agiBlueURL_url = "https://agi.blue";
public static String agiBlueURL() {
return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url;
}
public static String hquery(Map params) {
return htmlQuery(params);
}
public static String hquery(Object... data) {
return htmlQuery(data);
}
public static Object[] arrayPlus(Object[] a1, Object... a2) {
return concatArrays(a1, a2);
}
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 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 int smartIndexOfNot(List l, A sub) {
return smartIndexOfNot(l, sub, 0);
}
public static int smartIndexOfNot(List l, A sub, int start) {
int i = start, n = l(l);
while (i < n && eq(l.get(i), sub)) ++i;
return i;
}
public static String secondWord(String s) {
return secondJavaToken(s);
}
public static boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
public static final Map callOpt_cache = newDangerousWeakHashMap();
public static Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
public static Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
public static List classNames(Collection l) {
return getClassNames(l);
}
public static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
public static int strL(String s) {
return s == null ? 0 : s.length();
}
public static int listL(Collection l) {
return l == null ? 0 : l.size();
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static B secondOfPair(Pair p) {
return p == null ? null : p.b;
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static 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 RGBImage loadImage(String snippetIDOrURL) {
return new RGBImage(loadBufferedImage(snippetIDOrURL));
}
public static RGBImage loadImage(File f) {
return new RGBImage(loadBufferedImage(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 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 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 Map weakHashMap() {
return newWeakHashMap();
}
public static List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
public static List keysList(MultiSet ms) {
return ms == null ? null : keysList(ms.map);
}
public static Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "loadableUtils.utils$"))
return findClass_fullName("main" + substring(name, 19));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
};
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
public static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
public static Class getMainClass() {
return mc();
}
public static Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean ping_pauseAll = false;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions = false;
public static Map ping_actions = newWeakHashMap();
public static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
public static boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
public static boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
public static boolean isImageFile(File f) {
return isImageFileName(fileName(f));
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 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 String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
public static