Warning : session_start(): open(/var/lib/php/sessions/sess_bcb79akk00c6ok58phlf0q0m5b, 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
1004015
1004016
1013692
1400546
1400547
1400548
1400552
1400553
1400555
1400556
1400563
1400577
1400579
1400580
1400583
1400584
//FILENAME: loadableUtils/utils.java
package loadableUtils;
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 java.util.function.*;
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 java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import java.time.Duration;
import java.lang.invoke.VarHandle;
import java.lang.invoke.MethodHandles;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.Const;
import org.apache.bcel.generic.*;
import java.lang.reflect.Type;
import org.ejml.data.*;
import org.ejml.dense.row.*;
import org.ejml.dense.row.decomposition.eig.*;
import me.saharnooby.qoi.plugin.*;
import javax.swing.border.TitledBorder;
import java.text.*;
import javax.swing.border.*;
import javax.swing.Timer;
import java.util.TimeZone;
import java.util.jar.*;
import java.awt.image.DataBufferByte;
import java.awt.geom.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.nio.file.Path;
import javax.swing.undo.UndoManager;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.*;
import java.awt.geom.Line2D;
import com.github.sarxos.webcam.*;
import org.fife.ui.rsyntaxtextarea.*;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.awt.dnd.*;
import javax.swing.border.Border;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import com.jogamp.graph.curve.OutlineShape;
import com.jogamp.graph.curve.Region;
import com.jogamp.graph.curve.opengl.GLRegion;
import com.jogamp.graph.curve.opengl.RegionRenderer;
import com.jogamp.graph.curve.opengl.RenderState;
import com.jogamp.graph.geom.SVertex;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.*;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.util.Animator;
import com.jogamp.opengl.util.PMVMatrix;
import javax.swing.plaf.basic.BasicSliderUI;
import java.awt.geom.Ellipse2D;
import java.awt.datatransfer.UnsupportedFlavorException;
import org.fife.ui.rsyntaxtextarea.TokenMakerBase;
import org.fife.ui.autocomplete.*;
import org.fife.rsta.ui.CollapsibleSectionPanel;
import org.fife.rsta.ui.GoToDialog;
import org.fife.rsta.ui.SizeGripIcon;
import org.fife.rsta.ui.search.FindDialog;
import org.fife.rsta.ui.search.ReplaceDialog;
import org.fife.rsta.ui.search.ReplaceToolBar;
import org.fife.rsta.ui.search.SearchEvent;
import org.fife.rsta.ui.search.SearchListener;
import org.fife.rsta.ui.search.FindToolBar;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.fife.ui.rtextarea.SearchResult;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.SyntaxScheme;
import net.lingala.zip4j.model.*;
import net.lingala.zip4j.io.outputstream.*;
import net.lingala.zip4j.model.enums.*;
import net.lingala.zip4j.headers.*;
import net.lingala.zip4j.util.*;
import java.util.zip.ZipOutputStream;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import java.awt.geom.Path2D;
import javax.swing.Icon;
import java.util.*;
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.*;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import org.bytedeco.javacpp.*;
import static org.bytedeco.javacpp.avcodec.*;
import static org.bytedeco.javacpp.avformat.*;
import static org.bytedeco.javacpp.avutil.*;
import org.bytedeco.javacpp.presets.avutil;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.nio.charset.*;
import java.nio.*;
public class utils {
static public String utilsSnippetID() {
return "#1033861";
}
static public interface Derefable {
public Concept get();
}
static public class DynamicObject {
public String className;
public LinkedHashMap fieldValues;
public DynamicObject() {
}
public DynamicObject(String className) {
this.className = className;
}
public Map _map() {
return fieldValues;
}
public String toString() {
return getClass() == DynamicObject.class ? "dyn " + className : super.toString();
}
}
static public File nohupJavax(String javaxargs) {
return directNohupJavax(javaxargs);
}
static public File nohupJavax(String javaxargs, String vmArgs) {
return directNohupJavax(javaxargs, vmArgs);
}
static public interface DynamicMethods {
abstract public Object _dynCall(String methodName, Object[] args);
}
static public class BetterLabel extends JLabel {
public boolean autoToolTip = true;
public BetterLabel() {
final WeakReference me = new WeakReference<>(this);
componentPopupMenu(this, BetterLabel_menuItems(me));
}
public BetterLabel(String text) {
this();
this.setText(text);
}
public void setText(String text) {
super.setText(text);
if (autoToolTip)
if (!swic(text, ""))
setToolTipText(nullIfEmpty(text));
}
}
static public VF1 BetterLabel_menuItems(final WeakReference me) {
return new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(me.get().getText());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(me.get().getText());";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, \"Copy text to clipboard\", r {\r\n copyTextToClipboard(me...";
}
};
}
static public class SingleComponentPanel extends JPanel {
public SingleComponentPanel() {
super(new BorderLayout());
}
public SingleComponentPanel(Component component) {
this();
if (component != null)
setComponent(component);
}
public void set(Swingable component) {
set(wrap(component));
}
final public void set(Component component) {
setComponent(component);
}
public void setComponent(Component component) {
{
swing(() -> {
if (getComponent() == component)
return;
removeAll();
if (component != null)
add(BorderLayout.CENTER, wrap(component));
_revalidate(SingleComponentPanel.this);
});
}
}
public void setComponentAndRevalidateParent(Component component) {
setComponent(component);
_revalidate(_getParent(this));
}
final public void clear() {
noComponent();
}
public void noComponent() {
setComponent(null);
}
final public Component get() {
return getComponent();
}
public Component getComponent() {
return swing(() -> getComponentCount() == 0 ? null : getComponent(0));
}
public boolean isEmpty() {
return getComponent() == null;
}
public boolean hasComponent() {
return getComponent() != null;
}
}
static public class Snippet {
public String id, title, md5, type, text;
public boolean isPublic = false;
public Snippet() {
}
public Snippet(String id, String title) {
this.title = title;
this.id = id;
}
public Snippet(String id, String title, String md5) {
this.md5 = md5;
this.title = title;
this.id = id;
}
public String toString() {
return id + " - " + title;
}
public boolean equals(Object o) {
return stdEq2(this, o);
}
public int hashCode() {
return stdHash2(this);
}
}
static final public class BWImage extends Meta implements MakesBufferedImage, IBWImage {
public int width, height;
public byte[] pixels;
public float borderColor = 0.0f;
public BWImage() {
}
public BWImage(int width, int height) {
this.height = height;
this.width = width;
pixels = new byte[width * height];
}
public BWImage(int width, int height, float brightness) {
this.height = height;
this.width = width;
pixels = new byte[width * height];
fillArrayUnlessZero(pixels, _toByte(brightness));
}
public BWImage(int width, int height, float[] pixels) {
this.pixels = new byte[pixels.length];
this.height = height;
this.width = width;
for (int i = 0; i < pixels.length; i++) this.pixels[i] = _toByte(pixels[i]);
}
public BWImage(int width, int height, byte[] pixels) {
this.height = height;
this.width = width;
this.pixels = pixels;
}
public BWImage(BWImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) pixels[y * width + x] = image.getByte(x, y);
}
public BWImage(RGBImage image) {
width = image.getWidth();
height = image.getHeight();
byte[] pixels = this.pixels = new byte[height * width];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
RGB rgb = image.getRGB(x, y);
pixels[y * width + x] = BWImage._toByte(rgb.getBrightness());
}
}
public BWImage(BufferedImage image) {
try {
width = image.getWidth();
height = image.getHeight();
int[] pixels = new int[width * height];
byte[] bytePixels = this.pixels = new byte[width * height];
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
if (!pixelGrabber.grabPixels())
throw fail("Could not grab pixels");
int n = width * height;
for (int i = 0; i < n; i++) {
int packed = pixels[i];
int r = ((packed >> 16) & 0xFF);
int g = ((packed >> 8) & 0xFF);
int b = (packed & 0xFF);
bytePixels[i] = (byte) ((r + g + b + 1) / 3);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte pixelToByte(int packed) {
float r = ((packed >> 16) & 0xFF) / 255f;
float g = ((packed >> 8) & 0xFF) / 255f;
float b = (packed & 0xFF) / 255f;
return (byte) ((r + g + b) / 3.0f * 255f);
}
public byte getByte(int x, int y) {
return inRange(x, y) ? getByte_noRangeCheck(x, y) : _toByte(borderColor);
}
public int getInt(int x, int y) {
return ubyteToInt(getByte(x, y));
}
public int getInt_noRangeCheck(int idx) {
return ubyteToInt(pixels[idx]);
}
public int getInt(int x, int y, int defaultValue) {
return inRange(x, y) ? getInt(x, y) : defaultValue;
}
public double averageBrightness() {
double sum = 0;
int n = width * height;
for (int i = 0; i < n; i++) sum += getInt_noRangeCheck(i);
return sum / n;
}
public float minimumBrightness() {
float min = 1;
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) min = Math.min(min, getPixel(x, y));
return min;
}
public float maximumBrightness() {
float max = 0;
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) max = Math.max(max, getPixel(x, y));
return max;
}
public float getPixel(int x, int y) {
return inRange(x, y) ? _toFloat(getByte(x, y)) : borderColor;
}
public float getFloatPixel(int x, int y) {
return getPixel(x, y);
}
public float getPixel(Pt p) {
return getPixel(p.x, p.y);
}
static public byte _toByte(float pixel) {
return (byte) (pixel * 255f);
}
static public float _toFloat(byte pixel) {
return (((int) pixel) & 255) / 255f;
}
private boolean inRange(int x, int y) {
return x >= 0 && x < width && y >= 0 && y < height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public RGBImage toRGB() {
int[] rgbs = new int[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
int b = getByte(x, y) & 0xFF;
rgbs[y * width + x] = 0xFF000000 | b * 0x010101;
}
return new RGBImage(width, height, rgbs);
}
public RGBImage toRGB_slow() {
RGB[] rgbs = new RGB[width * height];
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) {
float p = getPixel(x, y);
rgbs[y * width + x] = new RGB(p, p, p);
}
return new RGBImage(width, height, rgbs);
}
public BWImage clip(int x, int y, int w, int h) {
return clip(new Rectangle(x, y, w, h));
}
private Rectangle fixClipRect(Rectangle r) {
return r.intersection(new Rectangle(0, 0, width, height));
}
public BWImage clip(Rect r) {
return clip(r.getRectangle());
}
public BWImage clip(Rectangle r) {
r = fixClipRect(r);
byte[] newPixels = new byte[r.height * r.width];
for (int y = 0; y < r.height; y++) for (int x = 0; x < r.width; x++) newPixels[y * r.width + x] = getByte(r.x + x, r.y + y);
return new BWImage(r.width, r.height, newPixels);
}
public void setPixel(int x, int y, float brightness) {
setByte(x, y, _toByte(fixPixel(brightness)));
}
public void setInt(int x, int y, int i) {
setByte(x, y, (byte) limitToUByte(i));
}
public void setInt(Pt p, int i) {
setInt(p.x, p.y, i);
}
public void setByte(int x, int y, byte b) {
if (x >= 0 && x < width && y >= 0 && y < height)
pixels[y * width + x] = b;
}
public byte getByte_noRangeCheck(int x, int y) {
return pixels[y * width + x];
}
public void setByte(int x, int y, int brightness) {
setByte(x, y, (byte) brightness);
}
private float fixPixel(float pixel) {
return Math.max(0, Math.min(1, pixel));
}
public float getBorderColor() {
return borderColor;
}
public void setBorderColor(float borderColor) {
this.borderColor = borderColor;
}
public boolean anyPixelBrighterThan(double threshold) {
for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) if (getPixel(x, y) > threshold)
return true;
return false;
}
public int[] getRGBPixels() {
int n = width * height;
int[] out = new int[n];
for (int i = 0; i < n; i++) {
var b = ubyteToInt(pixels[i]);
b |= (b << 8) | (b << 16);
out[i] = b | 0xFF000000;
}
return out;
}
public BufferedImage getBufferedImage() {
return bufferedImage(getRGBPixels(), width, height);
}
public byte[] getBytes() {
return pixels;
}
}
static public class Cache {
public Object maker;
public A value;
public long loaded;
static public boolean debug = false;
public long changeCount;
public Lock lock = lock();
public Cache() {
}
public Cache(Object maker) {
this.maker = maker;
}
public Cache(IF0 maker) {
this.maker = maker;
}
public A get() {
if (hasLock(lock))
return value;
Lock __20 = lock;
lock(__20);
try {
if (loaded == 0) {
value = make();
changeCount++;
loaded = sysNow();
}
return value;
} finally {
unlock(__20);
}
}
public void clear() {
Lock __21 = lock;
lock(__21);
try {
if (debug && loaded != 0)
print("Clearing cache");
value = null;
changeCount++;
loaded = 0;
} finally {
unlock(__21);
}
}
public void clear(double seconds) {
Lock __22 = lock;
lock(__22);
try {
if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
clear();
} finally {
unlock(__22);
}
}
public void set(A a) {
Lock __23 = lock;
lock(__23);
try {
value = a;
++changeCount;
loaded = sysNow();
} finally {
unlock(__23);
}
}
public A make() {
return (A) callF(maker);
}
}
static abstract public class DynModule extends DynamicObject implements Enterable, ChangeTriggerable, IHasChangeListeners {
public String name, toolTip;
public PersistableThrowable _error;
public Map> mechLists;
public Map _persistenceInfo;
transient public Object _host;
transient public Map timers = newWeakHashMap();
transient public Set _resources = synchroHashSet();
transient public Lock lock;
transient public boolean persistOnChangedField = true;
transient public int changeCount;
transient public Object changeCountSync = new Object();
transient public List onChange;
transient public List onTransientChange;
transient public boolean verboseTimers = false;
transient public ReliableSingleThread rstUpdate;
transient public Set componentFieldsToKeep;
transient public Map transientGeneralMap = synchroHashMap();
transient public Q q;
transient public List onFieldChange;
transient public boolean _hasPreviousBounds = false;
transient public StringBuffer _printLog = new StringBuffer();
transient public boolean deleted = false;
public DynModule() {
if (useErrorHandling())
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
public boolean useErrorHandling() {
return true;
}
public boolean isVisible() {
return isTrue(getOpt(_host, "visible"));
}
public String moduleName() {
return name;
}
public void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
setField("name", name);
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
public void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
public JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
public A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
public A ownTimer(A timer) {
if (timer instanceof AutoCloseable)
ownResource((AutoCloseable) timer);
else
ownTimer(timer, __36 -> cancelTimerOrInterruptThread(__36));
return timer;
}
public void ownTimer(Object timer, IVF1 closerHelper) {
timers.put(timer, closerHelper);
}
public void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
public void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try {
resource.close();
} catch (Throwable __e) {
pcallFail(__e);
}
}
for (Map.Entry extends Object, ? extends IVF1> __26 : _entrySet(getAndClearMap(timers))) {
Object timer = __26.getKey();
IVF1 closerHelper = __26.getValue();
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallF(closerHelper, timer);
}
}
public boolean isDeleted() {
return deleted;
}
public boolean deleted() {
return deleted;
}
public void cleanMeUp_dynModule() {
deleted = true;
{
cleanUp(q);
q = null;
}
stopAllTimers();
}
public void persistMe() {
synchronized (changeCountSync) {
++changeCount;
}
pcallFAll(onChange);
callOpt(_host, "_change");
updateMe();
}
public void fireChangeWithoutPersisting() {
pcallFAll(onChange);
}
public void fireTransientChange() {
pcallFAll(onTransientChange);
}
final public void _change() {
persistMe();
}
final public void change() {
persistMe();
}
public void updateMe() {
rstUpdate().trigger();
}
public void changeAndUpdate() {
_change();
updateMe();
}
public boolean setField_noPersist(String name, Object value) {
return setField(name, value, true);
}
public boolean _setField(String name, Object value) {
return setField(name, value);
}
public boolean setField(String name, Object value) {
return setField(name, value, false);
}
public boolean setField(String name, Object value, boolean noPersist) {
AutoCloseable __32 = enter();
try {
try {
if (eq(get(this, name), value))
return false;
} catch (Throwable __e) {
pcallFail(__e);
}
return setField_noCheck(name, value, noPersist);
} finally {
_close(__32);
}
}
public boolean setField_noCheck(String name, Object value) {
return setField_noCheck(name, value, false);
}
public boolean setField_noCheck(String name, Object value, boolean noPersist) {
AutoCloseable __33 = enter();
try {
setOpt(this, name, value);
pcallFAll(onFieldChange, name);
if (!noPersist && dm_isPersistentField(me(), name))
_change();
return true;
} finally {
_close(__33);
}
}
public A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
public boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i + 1]))
change = true;
return change;
}
public void start() {
_hasPreviousBounds = dm_getBounds() != null;
if (hasMethod_onTypes(this, "onTopInput", String.class))
dm_onTopInput_q(new VF1() {
public void get(String s) {
try {
call(module(), "onTopInput", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(module(), 'onTopInput, s)";
}
});
}
public void revisualize() {
call(dm_os(), "revisualizeModule", _host);
}
public boolean useEnterShortcut() {
return false;
}
public AutoCloseable enter() {
AutoCloseable c = tempSetBetterThreadLocalIfNecessary_weakRef(dm_current_generic_tl(), this);
if (c == null && useEnterShortcut())
return null;
Object realMC = getMainClass(this);
if (printToModule())
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor()));
if (realMC != mc()) {
if (printToModule())
c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor()));
else
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() {
public Boolean get(String s) {
try {
{
call(realMC, "print", s);
return false;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret false with call(realMC, 'print, s);";
}
}));
c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC));
}
return c;
}
public F1 _printToModuleInterceptor() {
return new F1() {
public Boolean get(String s) {
try {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = _printLog;
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);
if (printAlsoToSystemOut)
System.out.print(s);
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ...";
}
};
}
public boolean printToModule() {
return true;
}
public AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
public boolean setError(Throwable e) {
setField("_error", persistableThrowable(e));
return true;
}
public void clearError() {
setField("_error", null);
}
public DynModule onChange(Runnable r) {
Lock __27 = lock;
lock(__27);
try {
if (onChange == null)
onChange = synchroList();
addIfNotThere(onChange, r);
return this;
} finally {
unlock(__27);
}
}
public DynModule removeChangeListener(Runnable r) {
remove(onChange, r);
return this;
}
public void onFieldChange(VF1 r) {
Lock __29 = lock;
lock(__29);
try {
if (onFieldChange == null)
onFieldChange = synchroList();
addIfNotThere(onFieldChange, r);
} finally {
unlock(__29);
}
}
public void removeFieldChangeListener(VF1 r) {
remove(onFieldChange, r);
}
public void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
public void onChangeAndNow(List extends JComponent> l, Object r) {
utils.onChangeAndNow(l, r);
}
public void onChangeAndNow(JTextComponent c, IVF1 r) {
onUpdateAndNow(c, r);
}
public A onChange(A tc, Object r) {
onUpdate(tc, r);
return tc;
}
public void update() {
}
public void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
public Object menuItems() {
return null;
}
public void enhanceFrame(Container f) {
Object items = menuItems();
if (items instanceof Object[])
items = paramsToAbstractActions((Object[]) items);
internalFramePopupMenuFromActions_threaded(f, (List) items);
String switchableFields = (String) (callOpt(this, "switchableFields"));
Set set = asLinkedHashSet(splitAtSpace(switchableFields));
Matches m = new Matches();
for (String field : allFields(getClass())) if (startsWith(field, "_switchableField_", m))
set.add(m.rest());
for (String field : set) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(long.class, type))
dm_longFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
else if (eq(float.class, type))
dm_floatFieldMenuItem(f, field);
else if (eq(String.class, type))
dm_stringFieldMenuItem(f, field);
else if (eq(File.class, type))
dm_fileFieldMenuItem(f, field);
}
}
public ReliableSingleThread rstUpdate() {
if (rstUpdate == null)
rstUpdate = dm_rst(this, new Runnable() {
public void run() {
try {
AutoCloseable __34 = enter();
try {
update();
} finally {
_close(__34);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); update();";
}
});
return rstUpdate;
}
public Q q() {
AutoCloseable __35 = enter();
try {
if (q == null) {
Lock __30 = lock;
lock(__30);
try {
if (q == null)
q = dm_startQ();
} finally {
unlock(__30);
}
}
return q;
} finally {
_close(__35);
}
}
public A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
public DynModule module() {
return this;
}
public DynModule me() {
return this;
}
public JComponent visualize() {
return dm_noVisualisation();
}
public String programTitle_cache;
public String programTitle() {
if (programTitle_cache == null)
programTitle_cache = snippetTitle(programID(mainClass(this)));
return programTitle_cache;
}
public void doPersist(String field) {
_persistenceInfo = mapMinus(_persistenceInfo, field);
}
public void dontPersist(String field) {
_persistenceInfo = mapPlus(_persistenceInfo, "field", false);
}
public Appendable _actualPrintLog() {
return printToModule() ? _printLog : print_log;
}
public Object getHost() {
return _host;
}
public boolean addAndChange(Collection cl, A a) {
if (cl == null || !cl.add(a))
return false;
change();
return true;
}
public void clearAndChange(Collection cl) {
if (cl == null)
return;
cl.clear();
change();
}
public void addAndChange(LongBuffer buf, long a) {
if (buf == null)
return;
buf.add(a);
change();
}
public void clearAndChange(LongBuffer buf) {
if (buf == null)
return;
buf.clear();
change();
}
}
static public void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
var mod = dm_currentModule();
{
if (mod != null)
mod.ownTimer(timer);
}
}
abstract static public class DynPrintLog extends DynModule {
transient public JFastLogView_noWrap printLogView;
transient public Lock updatePrintLog_lock = lock();
transient public StringBuffer actualPrintLog;
transient public int printLogUpdateInterval = 500;
transient public JComponent printLogPanel;
public JComponent visualize() {
return makePrintLogPanel();
}
public JComponent makePrintLogPanel() {
JComponent section = printLogPanel = jSection("Log", jscroll_copyBackground(printLogView = jFastLogView_noWrap(getPrintLog())));
componentPopupMenuItem(section, "Clear", new Runnable() {
public void run() {
try {
AutoCloseable __43 = enter();
try {
dm_clearModulePrintLog();
} finally {
_close(__43);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); dm_clearModulePrintLog();";
}
});
return awtEvery(section, printLogUpdateInterval, new Runnable() {
public void run() {
try {
updatePrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updatePrintLog();";
}
});
}
public void updatePrintLog() {
swing(() -> {
Lock __40 = updatePrintLog_lock;
lock(__40);
try {
JFastLogView_noWrap _view = printLogView;
if (_view == null)
return;
if (_view.setText(getPrintLog())) {
scrollAllTheWayDown(_view);
awtLater(100, new Runnable() {
public void run() {
try {
scrollAllTheWayDown(_view);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "scrollAllTheWayDown(_view)";
}
});
}
} finally {
unlock(__40);
}
});
}
public JFastLogView_noWrap myPrintLogComponent() {
return printLogView;
}
public void enableWordWrap() {
}
public String getPrintLog() {
if (actualPrintLog == null) {
if (printToModule())
actualPrintLog = _printLog;
else
actualPrintLog = liveLocalPrintLog_realMC(this);
}
return str(actualPrintLog);
}
}
abstract static public class DynObjectTable extends DynModule {
public List data = new ArrayList();
transient public JTable table;
transient public F1 itemToMap;
transient public VF1 defaultAction;
transient public boolean debug, fieldsInOrder = true, withSearcher;
transient public TableSearcher searcher;
transient public List onListChanged;
transient public Set hideFields;
transient public boolean useStruct = false;
public void start() {
try {
super.start();
itemToMap = new F1() {
public Map get(A a) {
try {
if (a instanceof String)
return litorderedmap("", (String) a);
Map map = humanizeKeys(fieldsInOrder ? objectToMap_inOrder_withoutFields(a, hideFields) : objectToMap(a));
if (!useStruct)
map = mapValues(__87 -> strOrEmpty(__87), map);
return map;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (a instanceof S) ret litorderedmap(\"\" := (S) a);\r\n Map map = humanize...";
}
};
onChange(new Runnable() {
public void run() {
try {
updateTable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateTable();";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void onListChanged(Runnable r) {
if (r == null)
return;
onListChanged = addDyn_sync(onListChanged, r);
}
public void onListChangedAndNow(Runnable r) {
if (r == null)
return;
onListChanged(r);
r.run();
}
public void addCountToName() {
onListChangedAndNow(new Runnable() {
public void run() {
try {
addCountToNameNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addCountToNameNow();";
}
});
}
public void addCountToNameNow() {
AutoCloseable __47 = enter();
try {
setModuleName(programTitle() + " (" + count() + ")");
} finally {
_close(__47);
}
}
public JComponent visualize() {
List l = map(itemToMap, data);
table = dataToTable_uneditable(sexyTable(), l);
onDoubleClickOrEnter(table, new VF1() {
public void get(Integer row) {
try {
AutoCloseable __48 = enter();
try {
A a = _get(data, row);
if (a != null)
onDoubleClick(a);
} finally {
_close(__48);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter();\r\n A a = _get(data, row);\r\n if (a != null) onDoubleCli...";
}
});
if (withSearcher)
return (searcher = tableWithSearcher2(table)).panel;
return table;
}
public void unvisualize() {
super.unvisualize();
searcher = null;
}
public void onDoubleClick(A line) {
callF(defaultAction, line);
}
public void updateTable() {
AutoCloseable __49 = enter();
try {
if (table != null) {
swing(() -> {
Point scrollPosition = enclosingViewPosition(table);
if (debug)
print("Scroll position: " + scrollPosition);
dataToTable_uneditable(table, map(itemToMap, data));
setEnclosingViewPosition(table, scrollPosition);
if (searcher != null)
searcher.rowIndices = null;
if (debug)
print("dataToTable done, alerting " + n2(onListChanged, "listener"));
});
}
pcallFAll(onListChanged);
} finally {
_close(__49);
}
}
public void dontPersist() {
_persistenceInfo = mapPlus(_persistenceInfo, "data", false);
}
public void clear() {
syncClear(data);
fireDataChanged();
}
public void add(A a) {
syncAdd(data, a);
fireDataChanged();
}
public A addAndReturn(A a) {
add(a);
return a;
}
public void add(int idx, A a) {
syncAdd(data, idx, a);
fireDataChanged();
}
public void addAll(Collection l) {
if (empty(l))
return;
syncAddAll(data, l);
fireDataChanged();
}
public void addAndScrollDown(A a) {
add(a);
scrollDown();
}
public void remove(A a) {
syncRemove(data, a);
fireDataChanged();
}
public void removeAll(List a) {
syncRemoveAll(data, a);
fireDataChanged();
}
public void setList(Iterable data) {
setData(data);
}
public void removeSelected() {
removeAll(allSelected());
}
public void setData(Collection data) {
setData((Iterable) data);
}
public void setData(Iterable data) {
setData(data, false);
}
public void setData(Iterable data, boolean force) {
{
swing(() -> {
int[] selection = selectedTableRows_array(table);
List cloned = cloneList(data);
if (setField("data", cloned) || force) {
updateTable();
dm_vmBus_send("listChanged", module(), cloned);
}
if (force)
change();
selectTableRows(table, selection);
});
}
}
public int count() {
return syncL(data);
}
public void setData_force(Collection data) {
setData(data, true);
}
public void fireDataChanged() {
setData_force(data);
}
public int rowFromSearcher(int i) {
return searcher == null || searcher.rowIndices == null ? i : or(get(searcher.rowIndices, i), -1);
}
public A selected() {
return syncGet(data, rowFromSearcher(selectedTableRowInModel(table)));
}
public List allSelected() {
return syncListGetMulti(data, selectedIndices());
}
public int selectedIndex() {
return selectedTableRow(table);
}
public List selectedIndices() {
return map(i -> rowFromSearcher(i), selectedTableRowsInModel(table));
}
public boolean selectItem(A a) {
int i = indexOf(data, a);
selectRow(table, i);
return i >= 0;
}
public void doubleClickItem(A a) {
if (selectItem(a))
onDoubleClick(a);
}
public void popupMenuItem(String text, Object r) {
tablePopupMenuItemsThreaded(table, text, _convertRunnable(r));
}
public void popupMenuItem_top(String text, Object r) {
tablePopupMenuItemsThreaded_top(table, text, _convertRunnable(r));
}
public Object _convertRunnable(final Object r) {
if (r == null || r instanceof Runnable)
return r;
return new VF1() {
public void get(Integer idx) {
try {
callF(r, syncGet(data, idx));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, syncGet(data, idx))";
}
};
}
public JTable table() {
return table;
}
public void hideFields(String... fields) {
if (hideFields == null)
hideFields = new HashSet();
_addAll(hideFields, fields);
}
public A getRow(int row) {
return get(data, row);
}
public void scrollDown() {
scrollTableDownNow(table);
}
public List getData() {
return data;
}
public List data() {
return getData();
}
public List list() {
return getData();
}
public List getList() {
return getData();
}
public List clonedList() {
return cloneList(data);
}
public File quickBackup() {
File f = programFile("backup-" + ymd_minus_hms_minus_millis() + ".gz");
saveGZStructToFile(f, module());
printFileInfo(f);
return f;
}
}
abstract static public class DynImageSurface extends DynModule {
transient public ImageSurface imageSurface;
transient public BufferedImage image;
transient public String imageID;
transient public boolean useUpdateHack, zoomToWindowOnSetImage;
transient public Object onNewImage;
static public boolean _switchableField_autoSaveToDisk = true;
public boolean autoSaveToDisk = autoSaveToDiskDefault();
static public boolean _switchableField_pixelate = true;
public boolean pixelate = false;
public JComponent visualize() {
return _visualize();
}
final private JComponent _visualize() {
imageSurface = imageSurface(image);
imageSurface.onNewImage = new Runnable() {
public void run() {
try {
newImageFromSurface();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "newImageFromSurface();";
}
};
imageSurface_pixelated(imageSurface, pixelate);
return jscroll_center(imageSurface);
}
public void enableDoubleBuffering() {
if (imageSurface != null)
imageSurface.setDoubleBuffered(true);
}
public JComponent visualizeWithDoubleBuffering() {
JComponent c = _visualize();
enableDoubleBuffering();
return c;
}
public Object _getReloadData() {
return image;
}
public void _setReloadData(BufferedImage image) {
this.image = image;
}
public void start() {
try {
super.start();
dm_watchField("pixelate", () -> imageSurface_pixelated(imageSurface, pixelate));
if (autoSaveToDisk)
autoLoadNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void autoLoadNow() {
AutoCloseable __54 = enter();
try {
try {
File f = autoSaveImageFile();
if (fileExists(f)) {
print("Auto-loading " + f);
setImage(loadImage2(f), true);
}
} catch (Throwable __e) {
pcallFail(__e);
}
} finally {
_close(__54);
}
}
public void autoSaveNow() {
AutoCloseable __55 = enter();
try {
try {
File f = autoSaveImageFile();
savePNG(f, image);
infoBox("Auto-saved " + renderFileInfo(f));
} catch (Throwable __e) {
pcallFail(__e);
}
} finally {
_close(__55);
}
}
public boolean autoSaveToDiskDefault() {
return false;
}
public void enhanceFrame(Container f) {
super.enhanceFrame(f);
internalFramePopupMenuItem(f, "Auto-save now", runnableThread(new Runnable() {
public void run() {
try {
autoSaveNow();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "autoSaveNow();";
}
}));
}
public void setImage(MakesBufferedImage image) {
imageID = null;
setImage(image == null ? null : image.getBufferedImage());
}
public void newImageFromSurface() {
setImage(imageSurface.getImage());
}
public void setImage(BufferedImage image) {
setImage(image, false);
}
public void setImage(BufferedImage image, boolean loadingFromAutoSave) {
this.image = image;
imageID = null;
if (imageSurface != null) {
AutoCloseable __56 = tempSetField(imageSurface, "onNewImage", null);
try {
imageSurface.setImage(image);
if (zoomToWindowOnSetImage)
imageSurface.zoomToWindow();
if (autoSaveToDisk && !loadingFromAutoSave)
autoSaveNow();
} finally {
_close(__56);
}
}
vmBus_send("newImage", this);
pcallF(onNewImage, image);
}
public void setImage(String imageID) {
if (sameSnippetID(this.imageID, imageID))
return;
setImage(loadImage2(imageID));
this.imageID = imageID;
}
public File autoSaveImageFile() {
String id = dm_moduleID(me());
return javaxDataDir("Image Autosaves/" + id + "-autosave.png");
}
public BufferedImage getImage() {
if (useUpdateHack) {
ImageSurface is = imageSurface;
if (is != null && is.getImage() != image)
setImage(is.getImage());
}
return image;
}
public boolean hasImage() {
return image != null;
}
public void setZoom(double zoom) {
if (imageSurface != null)
imageSurface.setZoom(zoom);
}
public Rect getSelection() {
return imageSurface == null ? null : toRect(imageSurface.getSelection());
}
public void setSelection(Rect r) {
if (imageSurface != null)
imageSurface.setSelection(toRectangle(r));
}
public int imageWidth() {
return imageSurface.getImage().getWidth();
}
public int imageHeight() {
return imageSurface.getImage().getHeight();
}
public void pixelate() {
setField("pixelate", true);
}
}
abstract static public class DynCalculatedList extends DynModule {
transient public JList list;
transient public List results;
transient public boolean calculateWhenHidden = false;
public JComponent visualize() {
return list = jlist(calc());
}
public void unvisualize() {
list = null;
}
public void update() {
AutoCloseable __61 = enter();
try {
if (list != null || calculateWhenHidden)
fillListWithStrings(list, results = calc());
} finally {
_close(__61);
}
}
abstract public List calc();
public void scrollDown() {
scrollAllTheWayDown(list);
}
public String selected() {
return selectedItem(list);
}
}
static public Object creator() {
return callOpt(assertNotNull("No real MC", realMC_tl()).get(), "creator");
}
static public String programID;
static public String getProgramID() {
Object mc = realMC_tl().get();
if (mc != null)
return getProgramID(mc);
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public Concepts db_mainConcepts() {
throw fail("No db_mainConcepts");
}
static public JButton basicJButton(String text) {
return swing(() -> {
JButton btn = new JButton(text);
setHorizontalMargin(btn, 4);
return btn;
});
}
static public String fastIntern(String s) {
return s == null ? null : s.intern();
}
static public List myInnerClasses_list = litlist(null, "IVarWithNotify", "NotifyingCollection", "Hi15Image", "DummyPosterizer", "StructureStringIndenter", "IImageRegion", "SnPSettings", "ImageSurface", "JOnScreenKeyboard", "ScreenShotMeta", "ArrayMatrix", "talkToThisVM_IO", "IFieldIndex", "AnimatedLine", "SimpleLiveValue", "GazellePresenceListener", "WebRequest", "WeakIdentityHashMap", "JForm", "SingleComponentPanel", "PosterizeBWImage", "IWebRequest", "RenamedLongIterator", "NumberPt", "HashBufferedImage", "AbstractLayoutManager", "TrayIconLastPosition", "IterableIterator", "betterCIComparator_C", "SynchronizedArrayList", "MakesBufferedImage", "DeleteFilesDialog", "IProbabilisticScheduler", "TextImageAction", "CloseableIterableIterator", "AbstractSSIList", "HuffmanTreeMaker", "PixelPreservingImageOpResult", "ShortBuffer", "HasBounds", "Enterable", "Matches", "WithTimestamp", "SynchronizedLongBuffer", "TableWithTooltips", "Dyn_FieldWatcher", "DoubleRect", "Surface", "WeakVar", "NotifyingList", "Q", "VectorSSIList", "ILongBuffer", "TailFile", "RenderRecognizedBox", "RestartableCountdown", "VStack", "TransientObject", "DynamicVStack", "FixedVarContext", "Htmlable", "DynObjectTable", "mapI_if1_It", "ConceptsComboBox", "HuffmanByteArray", "VarContext", "Average", "IConceptCounter", "IToolTipMaker", "OpenGL_DemoObjects", "RangeSliderUI", "BetterLabel", "componentPopupMenu_Adapter", "BWIntegralImage", "CompressToInterpolatedDoubleArray", "IVStack", "IF0_Pair", "FailedRule", "IHasTokenRangeWithSrc", "IF0_Bool", "IBinaryImage", "IImageRegions", "transpileOnServerWithErrorWindow_DaClass", "StefansOS_ConnectToServer", "LineThroughPoint", "JSection", "RecognizedRegion", "CollapsibleLeftPanel", "IF0WithChangeListeners", "FullChange", "GeneralSSIList", "JECompressionRegime", "WithSideValue", "IntegerIterator", "IStringifier", "CombinedStringifier", "MultiSleeper", "JFilePathLabel", "UTF8Processor", "ReliableSingleThread", "ListAndIndex", "WebSocketFactory", "JVideoLibDownloader", "WindowResizeDragger", "TranspileWithErrorWindow", "NESWDirection", "DoubleBuffer", "ProgramScan", "RegExp", "PersistableOKOrError", "JustCountingOutputStream", "DefaultButtonBorder", "F0", "Snippet", "F1", "DynImageSurface", "RandomAccessAbstractList", "F2", "RGB", "IntPair", "HasChangeListeners", "F3", "BoolVar", "WidthAndHeightFinal", "IHasGlobalID", "ConceptFieldIndexCI", "FormLayout1", "IRecognizedBox", "StringHead", "MakesBWImage", "CenteredComboBoxRenderer", "tablePopupMenu_Maker", "VirtualVar", "Cache", "SynchronizedList", "_MethodCache", "PingSourceCancelledException", "JForwardingLibDownloader", "LiveValue", "Eq", "AbstractHasHi15Color", "IDoubleBuffer", "proxy_InvocationHandler", "MethodMaker", "RunnableWithExceptions", "EphemeralObjectIDs", "JavaXClassLoader", "Probabilistic", "Flattener", "FlexibleRateTimer", "RuleWithParams", "CachedPosterizer", "ByteBuffer", "RangeSlider", "WebSocket", "TransferableImage", "Sleeping", "IConceptIndex", "Updateable", "WithProbability", "BitIO", "SubList", "SecretValue", "GenericArrayTypeImpl", "JSelectableDirLabel", "AppendableChain", "CompactLinkedHashSet", "LoggingBitHead", "FixedRateTimer", "WholeImageFilter", "CompactLongSet", "GridCodec1", "IndexIterator", "GrabbableRGBBytePixels", "MethodOnObject", "MinimumFilter", "XRef", "JGallery", "IUnstructured", "IntegralImage", "ShortIterator", "IntBuffer", "DoublePt", "IIntPred", "SynchronizedNavigableSet", "SynchronizedCircularFifoBuffer", "AbstractMatrix", "Chain", "RegionToBWImage", "ThreadPool", "ComputerCountListener", "JS", "WidthAndHeightImpl", "RunnablesReferenceQueue", "JPopDownButton", "AbstractJavaXExpr", "SSIListFrame", "IDialogHandler", "AWTOnConceptChanges", "VariableSizeUIntForBitHead", "IHasChangeListeners", "JavaCodec", "ImageSurface_PositionToolTip", "TranslucentWindowTest", "FlexWebSocket", "IIntegralImage", "BitHead", "AbstractCompressor_AnyType", "DialogIO", "RegionToImage2B", "Stages", "SynchronizedArrayList_Base", "Scribble", "IAutoCloseableF0", "IPartialStringifier", "BitIOWrapper", "ISleeper_v2", "AlphanumComparator", "JExtendedTabbedPane", "PersistableThrowable", "Animation", "BlockDiff", "talkToSubBot_IO", "IDoublePt", "NumPadFixingInputMap", "PixelUtils", "HasIndex", "WidthAndHeight", "ISubList", "Responder", "TableSearcher", "IMultiSet", "WithToolTip", "VectorSSI", "mapI_It", "ConceptsChange", "JFilePathButton", "TokCondition", "HashRefTokenMaker", "JSyntaxTextFileEditor", "listPopupMenu_Maker", "WAndHImpl", "ConceptWithChangeListeners", "SynchronizedCollection", "OnePathWithOrigin", "TargetAndActual", "CleanExit", "IIntIntPred", "IntMinMax", "ImageSurfaceSelector", "Sentence", "ScreenCamStream", "Concept", "HashedBWImage", "RectAsRecognizedBox", "IRGBImage", "WeightlessShuffledIterator", "MyHTTPD", "RegisteredReference", "TreeMultiMap", "Range", "FreeOfLocalBlockedKeyword", "ContentsIndexedList", "FileTransferable", "AbstractSteppable", "ClassMaker", "IPixelSet", "IContentsIndexedList2", "And", "Value", "ChromeBookmark", "OKOrError", "ImageChooser", "FileBasedLock", "Symbol", "IMeta", "ListToMatrix", "BetterThread", "JFileDropTarget", "BetterThreadLocal", "JTargetAndActualSlider", "Lowest", "CollapsibleNorthPanel", "RegionBorder_innerPoints", "ChangeTrigger", "AnimatedImageSurface", "ScoredSearcher_stable", "DynPrintLog", "JMiniJavaIDE", "AutoVMExit", "BoundsFinder", "MinimalChain", "NamedConcept", "Image2B", "AbstractFastRegions", "SynchronizedSortedSet", "SSI", "IBest", "jLiveValueSection_class", "JE_CompressEachElementIndividually", "DoubleRange", "DynamicObject", "IntegrityCheckable", "DoubleFPSCounter", "Exp", "RenderText", "DynamicMethods", "EGDiff", "Meta", "BStack", "Derefable", "JVMStackCellType", "FastRegions_BWImage", "SingleThread", "JSelfSwingable", "InMemoryClassLoader", "DefunctClassLoader", "CutListToBudget", "IntVar", "BWImage", "PingSource", "Renderable", "jCenteredLiveValueSection_class", "ConceptFieldIndexDesc", "HasTokenRangeWithSrc", "VarMatches", "Best", "DynModule", "ConceptL", "BackgroundProcessesUI", "Rect", "Pt", "TimeoutException_Inner", "BufferedImageWithMeta", "LeftAlignedLine", "RemoteDB", "AverageAndMinMax", "SynchronizedNavigableMap", "Concepts", "RC", "PCallPolicy", "IVF1WithToString", "IBWIntegralImage", "Hasher", "PNGFile", "getOpt_Map", "IFieldsToList", "JTextFileEditor", "IResponder", "WeakValueMap", "structure_Data", "VarWithNotify", "jsonDecode_Y", "Zip4j_MergeZipFilesWithFilter", "JColorBar", "IVar", "DynPrintLogAndEnabled", "Gazelle22_GradientImage", "TokenRangeWithSrc", "ConceptWithGlobalID", "LiteralJavaXExpr", "DynCalculatedList", "SimpleOutlineWalker", "ParameterizedTypeImpl", "Timestamp", "DoLater", "ImageInfiller", "ConceptFieldIndexBase", "ManyCirclePainter", "LongRange", "SSIList", "RawBufferedImageDistance_sameSize", "JECompressionSearch", "OnEnclosingScrollPaneResize", "JComponentWithChangeListeners", "MultiSet", "RuntimeExceptionWithCustomStackTrace", "ListFromFunction", "T3", "IResourceHolder", "CloseablesHolder", "EvalJavaPrep", "SizeInInts", "DynamicStack", "OHLCEntry", "RegionHoleBounds", "IPersistenceInfo", "BoxBlurFilter", "IntRange", "ExtendedCSVParser", "HuffmanTree", "PleaseIncludeFunctionsStatement", "UnsynchronizedCompactHashSet", "ProbabilisticListListener", "TimestampRange", "CopyBlock", "NanoWebSocketServer", "JPaintTool", "Stringifier_ToString", "JavaXClassLoaderWithParent2", "AWTOnConceptChangesByClass", "PtBuffer", "SynchronizedDoubleBuffer", "Frequency", "CompressionRegime_AnyType", "RGBImage", "FileWatchService", "SmartTimerTask", "ComponentResizeDragger", "RegionBorder_innerPoints_v2", "ImageSurfaceScribbleTool", "SimpleCRUD_v2", "ConceptDelete", "SinglePixelPosterizer", "ScanlineBitMatrix", "GoodThingsToTrack", "Literal", "WindowDragger", "unstructure_Handler", "IF2_IntInt_Double", "IMultiMap", "RegionBorder_innerPoints_withDiagonals", "IF1_IntToInt", "ThrowableWithCustomStackTrace", "BoolVarWithNotify", "IBWImage", "PtInComponent", "JConceptsTable", "AutoComboBox", "WebSocketException", "Sentence2", "ConceptFieldIndex", "GrabbableGrayPixels", "IHasBackRefs", "StepperWithStats", "MapI", "VectorOptimizedSSIList", "IfThen", "unstructure_Receiver", "JDraggableBoxDemo", "IF0", "BaseXRef", "IF2", "IF1", "IPosterizer", "IVF3", "IVF1", "IVF2", "NewBlock", "IWithSideValue", "MultiPointGradient", "Options", "IConcept", "structure_ClassInfo", "Func", "ScoredStringSearcher", "TreeSetWithDuplicates", "ScreenOverlay", "TimedCache", "ISetAndGet", "ToJava", "JFFMPEGVideoPlayer", "AbstractSSI", "RSyntaxTextAreaWithSearch", "InterpolatedDoubleArray", "QuickException", "SynchronizedSet", "DialogHandler", "JObjectTable", "ProbabilisticList", "Steppable", "G2Drawable", "UIURLSystem", "ImageSurfaceMouseHandler", "Pair", "Swingable", "FastDownscale2x2", "SingleThreadProfiler", "Percent", "RSTADummyParser", "ProbabilisticListAdapter", "LineAndColumn", "UniqueString", "ICharPred", "ILongQueue", "ChangeTriggerable", "GrabbableIntPixels", "IIVirtualClip", "IBackgroundProcesses", "DynamicHStack", "MetaWithChangeListeners", "ReverseChain", "BresenhamLineDrawer", "ConceptCreate", "CheckerBoard2", "TokenRange", "Seconds", "SynchronizedSortedMap", "ScaledBWImageFromBWIntegralImage", "HInitWebSocket", "PtSet", "MultiSetMap", "Var", "ClassNameResolver", "Best_comparable", "Scorer", "ITokCondition", "PopupMenuMaker", "CountingOutputStream", "INumberOfPixels", "Matrix", "SynchronizedRandomAccessList", "PrecisePolygon", "RunResultWithTimestamps", "ConceptChange", "AbstractProfiler", "CompactAbstractMap", "ExpNot", "TripletLSFR", "BitBuffer", "Fail", "WeakIdentityHashSet", "FunctionTimings", "ISetter", "DoneFlag", "RSTOverQ", "AIStrategy", "IResolvableClass", "SubMatrix", "ScannedBot", "ByteIO", "SimplyLinkedList", "AIStrategy_RandomWithVariation", "WebServable", "FPSCounter", "MechMode", "NotifyingStringBuffer", "IF2_Int", "VolatileImageMakerForComponent", "CompactHashMap", "IProbabilistic", "JVolatileImageSurface", "Complex", "RasterBars", "MultiMap", "RSTVar", "ProbabilisticScheduler", "CriticalAction", "JImageSwitch", "IResourceLoader", "WeakHasherMap", "Either", "Ratio", "FunctionCall", "PosterizeBufferedImage", "NotifyingSet", "CompilerBot", "JMenuScroller", "CharInToken", "ImageFileFilter", "ScalingImageOpResult", "MRUCache", "Angle", "Scored", "IIBWVirtualClip", "HashBWImage", "PadImageToAspectRatio", "VF1", "VF2", "JE_RepElement", "SynchronizedFloatBufferPresentingAsDoubles", "ICachedJavaXExpr", "IStackWithOptions", "RightAlignedLine", "GlobalID", "FastRegions_Hi15Image", "findCodeTokens_Matcher", "Unstructurer", "IntSize", "tempAdd_undo", "FieldVar", "JFastLogView_noWrap", "SimpleLeftToRightParser", "WebSocketFrame", "TimeoutException", "JEInstantCompressor_AnyType", "IRef", "ByteHead", "NotifyingStringBufferRotator", "Flag", "generalizedCIComparator_C", "IRecognizedRegion", "UniquifyUsingHasher", "BijectiveMap", "VStackComputableWithStep", "Producer", "Gazelle22_ImageToRegions", "CountHolesInRegion", "SourceTriggeredStream", "IProgressShower", "tempRememberListener_c", "talkTo_IO", "FlexibleVarContext", "ButtonImageLoader", "RollingAverage", "Timed", "ECJError", "UpdateTrigger", "NanoHTTPD", "ImageStreamFromVideoFile", "IContentsIndexedList", "IMakeEmptyClone", "LetterLayout", "StringIO", "BlockDiffer", "DeQ", "IF1_ObjectToDouble", "SynchronizedMap", "Decolorizer", "CompressionSearch_AnyType", "InstantNeverHideToolTip", "AbstractBufferedImageOp", "WebSocketHTTPD", "Test_ImageInfiller", "WrappedMap", "LongBuffer", "IBStack", "ListCellRendererWithToolTip", "ImageSurfaceDragger", "AbstractBorderTracer", "JavaXPeepholeShortener", "JavaXClassLoaderWithParent", "Transformable", "ClearForAutoRun", "ExplodedLine", "SurfaceShowingAutoZoomedImage", "FitImageInComponentRenderable", "ScaledBufferedImageFromIntegralImage", "Android3", "ComponentDragger", "OnePath", "IBackgroundProcess");
static public List myInnerClasses() {
return myInnerClasses_list;
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public void _handleError(Error e) {
}
static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != l(args)) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(Object... objects) {
throw new Fail(objects);
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null)
mm.put(key, value);
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public int isAndroid_flag;
static public boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
static public Boolean isHeadless_cache;
static public boolean isHeadless() {
if (isHeadless_cache != null)
return isHeadless_cache;
if (isAndroid())
return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless())
return isHeadless_cache = true;
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) {
return isHeadless_cache = true;
}
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return strOrEmpty(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(strOrEmpty(i.next()));
while (i.hasNext()) buf.append(glue).append(strOrEmpty(i.next()));
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(Object... c) {
return join(" ", c);
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public 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);
}
}
static public A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
static public Object get(Object o, String field) {
try {
if (o == null)
return null;
if (o instanceof Class)
return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return getOptDynOnly(((DynamicObject) o), field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static public Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static public Object get_raw(Object o, String field) {
try {
if (o == null)
return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field get_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());
}
static public Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Object get(String field, Object o) {
return get(o, field);
}
static public boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static public Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static public Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static public Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field getOpt_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);
return null;
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public 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());
}
static public 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());
}
static public void set(BitSet bs, int idx) {
{
if (bs != null)
bs.set(idx);
}
}
static public Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static public void setOpt(Object o, String field, Object value) {
try {
if (o == null)
return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c);
else
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null) {
smartSet(f, o, value);
return;
}
if (o instanceof DynamicObject) {
setDyn(((DynamicObject) o), field, value);
return;
}
if (o instanceof IMeta)
setDyn(((IMeta) o), field, value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field setOpt_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) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public void setOpt_raw(Object o, String field, Object value) {
try {
if (o == null)
return;
if (o instanceof Class)
setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
smartSet(f, o, value);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt_raw(Class c, String field, Object value) {
try {
if (c == null)
return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
makeAccessible(f);
smartSet(f, null, value);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field setOpt_raw_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);
return null;
}
static public Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Map> callF_cache = newDangerousWeakHashMap();
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(A a, IF1 f) {
return f == null ? null : f.get(a);
}
static public C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public void callF(A a, IVF1 f) {
if (f != null)
f.get(a);
}
static public void callF(IVF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callF(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF(Object f, Object... args) {
return safeCallF(f, args);
}
static public Object safeCallF(Object f, Object... args) {
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
if (f instanceof String)
throw fail("Legacy call: " + f);
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
}
static public ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public Object callOpt(Object o) {
return callF(o);
}
static public Object callOpt(Object o, String method, Object... args) {
return callOpt_withVarargs(o, method, args);
}
static public 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();
}
static public Map uniqueString_map = weakHashMap();
static public UniqueString uniqueString(String s) {
if (s == null)
return null;
synchronized (uniqueString_map) {
UniqueString us = uniqueString_map.get(s);
if (us == null)
uniqueString_map.put(s, us = new UniqueString(s, true));
return us;
}
}
static public UniqueString uniqueString(CharSequence s) {
return s == null ? null : uniqueString(str(s));
}
static public FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static public java.util.Timer doLater(long delay, final Object r) {
ping();
final java.util.Timer timer = new java.util.Timer();
timer.schedule(timerTask(r, timer), delay);
return vmBus_timerStarted(timer);
}
static public java.util.Timer doLater(double delaySeconds, final Object r) {
return doLater(toMS(delaySeconds), r);
}
static public boolean hasBot(String searchPattern) {
try {
DialogIO io = findBot(searchPattern);
if (io != null) {
io.close();
return true;
} else
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public JTextArea newTypeWriterTextArea() {
return newTypeWriterTextArea("");
}
static public JTextArea newTypeWriterTextArea(String text) {
return withTypeWriterFont(jTextArea(text));
}
static public String struct(Object o) {
return structure(o);
}
static public String struct(Object o, structure_Data data) {
return structure(o, data);
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public String loadPageSilentlyWithTimeout(double timeoutSeconds, String url) {
return loadPageSilentlyWithTimeout(url, toMS_int(timeoutSeconds));
}
static public String loadPageSilentlyWithTimeout(int timeout, String url) {
return loadPageSilentlyWithTimeout(url, timeout);
}
static public String loadPageSilentlyWithTimeout(String url, int timeout) {
try {
url = loadPage_preprocess(url);
URL _url = new URL(url);
return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean loadPageWithUserAgent_verbose = false;
static public String loadPageWithUserAgent(String url, String userAgent) {
try {
URL tURL = new URL(url);
URLConnection conn = tURL.openConnection();
conn.setRequestProperty("User-Agent", userAgent);
loadPage_anonymous = true;
if (loadPageWithUserAgent_verbose)
print("Loading as " + userAgent + ": " + hideCredentials(url));
return loadPage(conn, tURL);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void db() {
conceptsAndBot();
}
static public void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static public Object cget(Object c, String field) {
c = derefRef(c);
Object o = getOpt(c, field);
return derefRef(o);
}
static public Object cget(String field, Object c) {
return cget(c, field);
}
static public int cset(Concept c, Object... values) {
try {
if (c == null)
return 0;
warnIfOddCount(values = expandParams(c.getClass(), values));
int changes = 0;
for (int i = 0; i + 1 < l(values); i += 2) if (_csetField(c, (String) values[i], values[i + 1]))
++changes;
return changes;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int cset(Iterable extends Concept> l, Object... values) {
int changes = 0;
for (Concept c : unnullForIteration(l)) changes += cset(c, values);
return changes;
}
static public int cset(Concept.Ref c, Object... values) {
return cset(getVar(c), values);
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
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;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public 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);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public List> _threadInfo_makers = synchroList();
static public Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static public List> _threadInheritInfo_retrievers = synchroList();
static public void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static public void _threadInfo_addMakerAndRetriever(VF1 maker, VF1 retriever) {
_threadInfo_makers.add(maker);
_threadInheritInfo_retrievers.add(retriever);
}
static public boolean match(String pat, String s) {
return match3(pat, s);
}
static public boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static public boolean match(String pat, List toks, Matches matches) {
return match3(pat, toks, matches);
}
static public Field getField(Object o, String field) {
if (o == null)
return null;
return setOpt_findField(_getClass(o), field);
}
static public Object getField(Field field, Object o) {
return fieldGet(field, o);
}
static public Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static public String format3(String pat, Object... args) {
if (args.length == 0)
return pat;
List tok = javaTokPlusPeriod(pat);
int argidx = 0;
for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*"))
tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null"));
return join(tok);
}
static public String format3_formatArg(Object arg) {
if (arg == null)
return "null";
if (arg instanceof String) {
String s = (String) arg;
return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s);
}
if (arg instanceof Integer || arg instanceof Long)
return String.valueOf(arg);
return quote(structure(arg));
}
static public Set vm_generalIdentityHashSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
static public Map vm_generalHashMap(Object name) {
synchronized (vm_generalMap()) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
static public Map vm_generalWeakSubMap(Object name) {
synchronized (vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static public A bindToComponent(A component, Runnable onShow, Runnable onUnShow) {
{
swing(() -> {
final Var flag = new Var<>(false);
component.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
if (flag.get())
print("Warning: bindToComponent logic failure");
flag.set(true);
pcallF(onShow);
}
public void ancestorRemoved(AncestorEvent event) {
if (!flag.get())
print("Warning: bindToComponent logic failure");
flag.set(false);
pcallF(onUnShow);
}
public void ancestorMoved(AncestorEvent event) {
}
});
if (component.isShowing()) {
flag.set(true);
pcallF(onShow);
}
});
}
return component;
}
static public A bindToComponent(A component, Runnable onShow) {
return bindToComponent(component, onShow, null);
}
static public A bindToComponent(A component, IF0 onShow, IVF1 onUnShow) {
Var b = new Var();
return bindToComponent(component, () -> b.set(onShow.get()), () -> {
try {
onUnShow.get(b.get());
} finally {
b.set(null);
}
});
}
static public int loadPage_defaultTimeout = 60000;
static public ThreadLocal loadPage_charset = new ThreadLocal();
static public boolean loadPage_allowGzip = true, loadPage_debug;
static public boolean loadPage_anonymous = false;
static public int loadPage_verboseness = 100000;
static public int loadPage_retries = 1;
static public ThreadLocal loadPage_silent = new ThreadLocal();
static volatile public int loadPage_forcedTimeout;
static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static public ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static public String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static public String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static public String loadPage(URLConnection con, URL url, boolean addHeaders) {
try {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
return loadPage(con);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URLConnection con) {
try {
Long limit = optPar(loadPage_sizeLimit);
URL url = con.getURL();
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
static public URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static public String loadPage_utf8(URL url) {
return loadPage_utf8(url.toString());
}
static public String loadPage_utf8(String url) {
AutoCloseable __1 = tempSetTL(loadPage_charset, "UTF-8");
try {
return loadPage(url);
} finally {
_close(__1);
}
}
static public String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException {
AutoCloseable __2 = tempSetTL(loadPage_charset, "UTF-8");
try {
return loadPage(con, url, addHeaders);
} finally {
_close(__2);
}
}
static public boolean preferCached = false;
static public boolean loadSnippet_debug = false;
static public ThreadLocal loadSnippet_silent = new ThreadLocal();
static public ThreadLocal loadSnippet_publicOnly = new ThreadLocal();
static public int loadSnippet_timeout = 30000;
static public String loadSnippet(Snippet s) {
return loadSnippet(s.id);
}
static public String loadSnippet(String snippetID) {
try {
if (snippetID == null)
return null;
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
static public IF1 loadSnippet;
static public String loadSnippet(long snippetID) {
return loadSnippet != null ? loadSnippet.get(snippetID) : loadSnippet_base(snippetID);
}
final static public String loadSnippet_fallback(IF1 _f, long snippetID) {
return _f != null ? _f.get(snippetID) : loadSnippet_base(snippetID);
}
static public String loadSnippet_base(long snippetID) {
try {
return loadSnippet(snippetID, preferCached);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadSnippet(long snippetID, boolean preferCached) throws IOException {
if (isLocalSnippetID(snippetID))
return loadLocalSnippet(snippetID);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadSnippet(fsI(snippetID));
return loadSnippet_noResourceLoader(snippetID, preferCached);
}
static public String loadSnippet_noResourceLoader(long snippetID, boolean preferCached) throws IOException {
String text;
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (loadSnippet_debug && text != null)
System.err.println("md5: " + md5(text));
String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1";
if (nempty(text))
url += "&md5=" + md5(text);
if (!isTrue(loadSnippet_publicOnly.get()))
url += standardCredentials();
String text2 = loadSnippet_loadFromServer(url);
boolean same = eq(text2, "==*#*==");
if (loadSnippet_debug)
print("loadSnippet: same=" + same);
if (!same)
text = text2;
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static public File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(getGlobalCache());
}
static public String loadSnippet_loadFromServer(String url) {
Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout);
try {
return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url);
} finally {
loadPage_forcedTimeout_byThread.set(oldTimeout);
}
}
static public String loadSnippetQuietly(Snippet s) {
return loadSnippetQuietly(s.id);
}
static public String loadSnippetQuietly(String snippetID) {
loadSnippet_silent.set(true);
try {
return loadSnippet(snippetID);
} finally {
loadSnippet_silent.set(null);
}
}
static public String sendToLocalBot(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = findBot(bot);
try {
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
print(bot + "> " + shorten(text, 80));
channel.sendLine(text);
String s = channel.readLine();
print(bot + "< " + shorten(s, 80));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBot(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
try {
channel.readLine();
print(port + "> " + shorten(text, 80));
channel.sendLine(text);
String s = channel.readLine();
print(port + "< " + shorten(s, 80));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotOpt(String bot, String text, Object... args) {
if (bot == null)
return null;
text = format(text, args);
DialogIO channel = findBot(bot);
try {
if (channel == null) {
print(quote(bot) + " not found, skipping send: " + quote(text));
return null;
}
try {
channel.readLine();
print(shorten(bot + "> " + text, 200));
channel.sendLine(text);
String s = channel.readLine();
print(shorten(bot + "< " + s, 200));
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotQuietly(String bot, String text, Object... args) {
text = format3(text, args);
DialogIO channel = newFindBot2(bot);
try {
if (channel == null)
throw fail(quote(bot) + " not found");
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public String sendToLocalBotQuietly(int port, String text, Object... args) {
text = format3(text, args);
DialogIO channel = talkTo(port);
try {
try {
channel.readLine();
channel.sendLine(text);
String s = channel.readLine();
return s;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} finally {
_close(channel);
}
}
static public JTable sexyTableWithoutDrag() {
final JTable table = tableWithToolTips();
tablePopupMenu(table, sexyTableWithoutDrag_popupMenuMaker(table));
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
((InputMap) UIManager.get("Table.ancestorInputMap")).put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK), "none");
return table;
}
static public VF2 sexyTableWithoutDrag_popupMenuMaker(JTable t) {
final WeakReference ref = weakRef(t);
return new VF2() {
public void get(JPopupMenu menu, Integer row) {
try {
final JTable table = ref.get();
final String item = first(getTableLine(table, row));
MouseEvent e = tablePopupMenu_mouseEvent.get();
final int col = table.columnAtPoint(e.getPoint());
final Object value = table.getModel().getValueAt(row, col);
if (value instanceof ImageIcon) {
addMenuItem(menu, "Copy image to clipboard", new Runnable() {
public void run() {
try {
copyImageToClipboard(((ImageIcon) value).getImage());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyImageToClipboard(((ImageIcon) value).getImage());";
}
});
} else {
final String text = str(value);
addMenuItem(menu, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(text);
print("Copied text to clipboard: " + quote(text));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(text);\r\n print(\"Copied text to clipboard: \" + quot...";
}
});
}
addMenuItem(menu, "Set row height...", new Runnable() {
public void run() {
try {
final JTextField tf = jTextField(table.getRowHeight());
showTitledForm("Set row height", "Pixels", tf, new Runnable() {
public void run() {
try {
table.setRowHeight(parseInt(trim(tf.getText())));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "table.setRowHeight(parseInt(trim(tf.getText())))";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jTextField(table.getRowHeight());\r\n showTitledForm...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTable table = ref!;\r\n final S item = first(getTableLine(table, row)...";
}
};
}
static public class tablePopupMenu_Maker {
public List menuMakers = new ArrayList();
}
static public Map tablePopupMenu_map = newWeakHashMap();
static public ThreadLocal tablePopupMenu_mouseEvent = new ThreadLocal();
static public ThreadLocal tablePopupMenu_first = new ThreadLocal();
static public void tablePopupMenu(final JTable table, final Object menuMaker) {
final boolean first = isTrue(getAndClearThreadLocal(tablePopupMenu_first));
{
swing(() -> {
tablePopupMenu_Maker maker = tablePopupMenu_map.get(table);
if (maker == null) {
tablePopupMenu_map.put(table, maker = new tablePopupMenu_Maker());
final tablePopupMenu_Maker _maker = maker;
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
displayMenu(e);
}
public void mouseReleased(MouseEvent e) {
displayMenu(e);
}
public void displayMenu(MouseEvent e) {
if (!e.isPopupTrigger())
return;
JPopupMenu menu = new JPopupMenu();
int row = table.rowAtPoint(e.getPoint());
if (table.getSelectedRowCount() < 2)
table.setRowSelectionInterval(row, row);
int modelRow = convertTableRowToModel(table, row);
int emptyCount = menu.getComponentCount();
tablePopupMenu_mouseEvent.set(e);
for (Object menuMaker : _maker.menuMakers) pcallF(menuMaker, menu, modelRow);
vmBus_send("showingPopupMenu", table, menu);
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
if (first)
maker.menuMakers.add(0, menuMaker);
else
maker.menuMakers.add(menuMaker);
});
}
}
static public void tablePopupMenuFirst(JTable table, final Object menuMaker) {
tablePopupMenu_first.set(true);
tablePopupMenu(table, menuMaker);
}
static public void tablePopupMenuFirst(JTable table, IVF2 menuMaker) {
tablePopupMenuFirst(table, (Object) menuMaker);
}
static public ThreadLocal componentPopupMenu_mouseEvent;
static public void componentPopupMenu_init() {
{
swing(() -> {
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent");
if (componentPopupMenu_mouseEvent == null)
vm_generalMap_put("componentPopupMenu_mouseEvent", componentPopupMenu_mouseEvent = new ThreadLocal());
});
}
}
static public void componentPopupMenu(final JComponent component, IVF1 menuMaker) {
componentPopupMenu(component, (Object) menuMaker);
}
static public void componentPopupMenu(final JComponent component, final Object menuMaker) {
if (component == null || menuMaker == null)
return;
{
swing(() -> {
Object adapter = componentPopupMenu_initForComponent(component);
((List) _get(adapter, "maker")).add(menuMaker);
});
}
}
static public Object componentPopupMenu_initForComponent(final JComponent component) {
return component == null ? null : swing(new F0() {
public Object get() {
try {
componentPopupMenu_init();
Object adapter = findComponentPopupMenuListener_gen(component);
if (adapter == null) {
componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
component.addMouseListener(a);
adapter = a;
}
return adapter;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge...";
}
});
}
static public class componentPopupMenu_Adapter extends MouseAdapter {
public List maker = new ArrayList();
public boolean internalFrameLeftButtonMagic = false;
public boolean allowScrolling = true;
public Point pressedAt;
public void mousePressed(MouseEvent e) {
displayMenu(e);
pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
}
public void mouseReleased(MouseEvent e) {
if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
displayMenu2(e);
else
displayMenu(e);
}
public void displayMenu(MouseEvent e) {
if (e.getSource() instanceof JInternalFrame)
return;
if (e.isPopupTrigger())
displayMenu2(e);
}
public void populate(JPopupMenu menu, MouseEvent e) {
AutoCloseable __1 = tempSetTL(componentPopupMenu_mouseEvent, e);
try {
for (Object menuMaker : maker) pcallF(menuMaker, menu);
vmBus_send("showingPopupMenu", e.getComponent(), menu);
} finally {
_close(__1);
}
}
public void displayMenu2(MouseEvent e) {
new PopupMenuMaker(e, menu -> populate(menu, e)).allowScrolling(allowScrolling).run();
}
}
static public void componentPopupMenu_top(final JComponent component, final VF1 menuMaker) {
if (component != null && menuMaker != null) {
swing(() -> {
Object adapter = componentPopupMenu_initForComponent(component);
((List) get(adapter, "maker")).add(0, menuMaker);
});
}
}
static public MouseEvent componentPopupMenu_getEvent() {
return componentPopupMenu_mouseEvent.get();
}
static public Object dm_current_generic() {
return getWeakRef(dm_current_generic_tl().get());
}
static public Object dm_current_mandatory_generic() {
return assertNotNull("No module set", dm_current_generic());
}
static public Object withDBLock(Object r) {
Lock __0 = db_mainConcepts().lock;
lock(__0);
try {
return callF(r);
} finally {
unlock(__0);
}
}
static public A withDBLock(F0 r) {
return (A) withDBLock((Object) r);
}
static public Object withDBLock(Concepts concepts, Object r) {
Lock __1 = concepts.lock;
lock(__1);
try {
return callF(r);
} finally {
unlock(__1);
}
}
static public A withDBLock(Concepts concepts, F0 r) {
return (A) withDBLock(concepts, (Object) r);
}
static public A withDBLock(Concept concept, IF0 r) {
return (A) withDBLock(concept._concepts, r);
}
static public void makePopupMenuConditional(JComponent c, F0 condition) {
if (c != null && condition != null) {
swing(() -> {
componentPopupMenu_Adapter adapter = firstInstanceOf(c.getMouseListeners(), componentPopupMenu_Adapter.class);
c.removeMouseListener(adapter);
c.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (!callF(condition))
adapter.mousePressed(e);
}
public void mouseReleased(MouseEvent e) {
if (!callF(condition))
adapter.mouseReleased(e);
}
});
});
}
}
static public boolean dynamicObjectIsLoading() {
return isUnstructuring();
}
static public Object interceptPrintInThisThread(Object f) {
Object old = print_byThread().get();
print_byThread().set(f);
return old;
}
static public void rowSorter_setComparators(JTable table, final Object... params) {
setTableModel_fixSorter.put(table, new VF2() {
public void get(JTable table, RowSorter sorter) {
try {
if (sorter instanceof TableRowSorter) {
for (Pair p : (List>) (List) paramsToPairs(params)) ((TableRowSorter) sorter).setComparator(p.a, p.b);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "//print(\"Fixing table sorter\");\r\n if (sorter cast TableRowSorter) {\r\n ...";
}
});
}
static public String addPrefixOptIfNempty(String prefix, String s) {
return addPrefixIfNotEmpty2(prefix, s);
}
static public int year() {
return localYear();
}
static public int year(Timestamp now) {
return localYear(toLong(now));
}
static public int year(long now) {
return localYear(now);
}
static public int year(long now, TimeZone tz) {
return parseInt(simpleDateFormat("y", tz).format(now));
}
static public WithTimestamp withTimestamp(A value) {
return withTimestamp(now(), value);
}
static public WithTimestamp withTimestamp(long timestamp, A value) {
return new WithTimestamp(timestamp, value);
}
static public ICachedJavaXExpr javaObjectToIJavaExpr(Object o) {
if (isListOfElementType(Integer.class, o))
return javaExpr(functionCall("lInts", naiveQuote(intsToHex_withLineBreaks((List) o))), () -> o);
if (o instanceof List)
return javaExpr(functionCall("ll", map(__88 -> javaObjectToIJavaExpr(__88), (List) o)), () -> ((List) o));
Object code = toJavaOpt(o);
return javaExpr(code, () -> o);
}
static public List lambdaMapMethod(IF1 f, Iterable l) {
return lambdaMethodMap(f, l);
}
static public List lambdaMapMethod(IF1 f, A[] l) {
return lambdaMethodMap(f, l);
}
static public double negativeInfinity() {
return Double.NEGATIVE_INFINITY;
}
static public F1 mainFunctionToF1(final String fname) {
return new F1() {
public Object get(Object a) {
try {
return callMC(fname, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callMC(fname, a)";
}
};
}
static public float score(Scored s) {
return s == null ? 0 : s.score();
}
static public Set isThreadRunnable_x_exclude = lithashset("sun.nio.fs.WindowsNativeDispatcher.GetQueuedCompletionStatus0", "Java.lang.Thread.start0", "java.lang.Object.wait", "java.net.Inet6AddressImpl.lookupAllHostAddr", "java.io.FileInputStream.readBytes", "jdk.internal.misc.Unsafe.park", "sun.misc.Unsafe.park", "java.net.SocketInputStream.socketRead0", "java.net.PlainSocketImpl.socketConnect", "java.net.PlainSocketImpl.socketAccept", "sun.awt.X11.XToolkit.waitForEvents", "java.net.DualStackPlainSocketImpl.accept0", "org.jnativehook.GlobalScreen$NativeHookThread.enable", "java.lang.Thread.sleep", "sun.nio.ch.EPollArrayWrapper.epollWait", "com.ibm.lang.management.internal.MemoryNotificationThread.processNotificationLoop", "com.ibm.tools.attach.target.IPC.waitSemaphore", "sun.nio.ch.Net.poll", "sun.nio.ch.Net.accept", "sun.nio.ch.Net.connect0", "sun.nio.ch.EPoll.wait", "sun.nio.ch.SocketDispatcher.read0", "sun.nio.fs.LinuxWatchService.poll", "java.lang.ref.Reference.waitForReferencePendingList", "com.sun.java.accessibility.internal.AccessBridge.runDLL", "java.lang.ProcessHandleImpl.waitForProcessExit0");
static public boolean isThreadRunnable_x(StackTraceElement[] trace) {
StackTraceElement e = first(trace);
if (e == null)
return false;
String s = e.getClassName() + "." + e.getMethodName();
return !isThreadRunnable_x_exclude.contains(s);
}
static public boolean isThreadRunnable_x(Thread t, StackTraceElement[] trace) {
{
Boolean __1 = (Boolean) vmBus_query("isThreadRunnable_x", t, trace);
if (__1 != null)
return __1;
}
if (t.getState() != Thread.State.RUNNABLE)
return false;
return isThreadRunnable_x(trace);
}
static public RuntimeException asQuickException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new QuickException(t);
}
static public long stepAll(Steppable s) {
long steps = 0;
if (s != null) {
var pingSource = pingSource();
while (true) {
ping(pingSource);
if (s.step())
++steps;
else
break;
}
}
return steps;
}
static public void poorMansProfiling_stopAndPrintResults() {
poorMansProfiling_renderFullResults_backwards.set(true);
print(poorMansProfiling_stopAndRenderResults());
}
static public boolean isRunnableX(Object o) {
if (o == null)
return false;
if (o instanceof String)
return hasMethod(mc(), (String) o);
return o instanceof Runnable || hasMethod(o, "get");
}
static public String jreplaceExpandRefs(String s, List tokref) {
if (!contains(s, '$'))
return s;
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("$") && isInteger(t.substring(1))) {
String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
tok.set(i, x);
} else if (t.equals("\\")) {
tok.set(i, "");
i += 2;
}
}
return join(tok);
}
static public JTextArea wrappedTextArea(final JTextArea ta) {
enableWordWrapForTextArea(ta);
return ta;
}
static public JTextArea wrappedTextArea() {
return wrappedTextArea(jtextarea());
}
static public JTextArea wrappedTextArea(String text) {
JTextArea ta = wrappedTextArea();
setText(ta, text);
return ta;
}
static public boolean infoMessage_alwaysOnTop = true;
static public double infoMessage_defaultTime = 5.0;
static public JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static public JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
static public JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static public 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 {
JWindow window = makeWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
if (vmBus_noObjections("shouldShowInfoBox", window, text))
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize...";
}
});
}
static public JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static public int brightnessToRGBA(int brightness) {
return 0xFF000000 | clamp(brightness, 0, 255) * 0x010101;
}
static public JPanel withBorder(javax.swing.border.Border border, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(border);
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(border);\r\n p.add...";
}
});
}
static public Set getPlural_specials = litciset("sheep", "fish");
static public String getPlural(String s) {
if (contains(getPlural_specials, s))
return s;
if (ewic(s, "y"))
return dropSuffixIgnoreCase("y", s) + "ies";
if (ewicOneOf(s, "ss", "ch"))
return s + "es";
if (ewic(s, "s"))
return s;
return s + "s";
}
static public boolean hasLetters(String s) {
for (int i = 0; i < s.length(); i++) if (Character.isLetter(s.charAt(i)))
return true;
return false;
}
static public List sorted(Collection c, Object comparator) {
List l = cloneList(c);
sort(l, makeComparator(comparator));
return l;
}
static public List sorted(Collection c) {
List l = cloneList(c);
sort(l);
return l;
}
static public List sorted(Comparator comparator, Collection c) {
List l = cloneList(c);
sort(l, comparator);
return l;
}
static public Map loadFont_cached_cache = new HashMap();
static synchronized public Font loadFont_cached(String snippetID) {
try {
snippetID = formatSnippetID(snippetID);
Font f = loadFont_cached_cache.get(snippetID);
if (f == null)
loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static synchronized public Font loadFont_cached(String snippetID, float size) {
try {
return loadFont_cached(snippetID).deriveFont(size);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
static public Object rcallOpt(String method, Object o, Object... args) {
return callOpt_withVarargs(o, method, args);
}
static public void hideConsole() {
final JFrame frame = consoleFrame();
if (frame != null) {
autoVMExit();
swingLater(new Runnable() {
public void run() {
try {
frame.setVisible(false);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setVisible(false);";
}
});
}
}
static public String quickSubstring(String s, int i, int j) {
if (i >= j)
return "";
return s.substring(i, j);
}
static public boolean machineIsOffline() {
return isFalse(callF(vmGeneralMap_get("areWeOnline")));
}
static public Set getClassDeclarationName_skippables_cache;
static public Set getClassDeclarationName_skippables() {
if (getClassDeclarationName_skippables_cache == null)
getClassDeclarationName_skippables_cache = getClassDeclarationName_skippables_load();
return getClassDeclarationName_skippables_cache;
}
static public Set getClassDeclarationName_skippables_load() {
return litset("noeq", "mapMethodLike");
}
static public List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
static public List childrenOfType(Class theClass, Component c) {
return childrenOfType(c, theClass);
}
static public void dm_reloadModuleInBackground(Object module) {
dm_callOS("reloadModuleInBackground", dm_getStem(module));
}
static public void dm_reloadModuleInBackground() {
dm_reloadModuleInBackground(dm_current_mandatory_generic());
}
static public ThreadLocal poorMansProfiling_renderFullResults_backwards = new ThreadLocal();
static public String poorMansProfiling_renderFullResults(final MultiSet traces) {
int samples = poorMansProfiling_samples;
boolean backwards = isTrue(getAndClearThreadLocal(poorMansProfiling_renderFullResults_backwards));
final int n = traces.size();
int percent = ratioToIntPercent(l(traces), samples);
return (samples == 0 ? "Nothing sampled" : percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n" + joinMap(backwards ? traces.lowestFirst() : traces.highestFirst(), new F1() {
public Object get(String trace) {
try {
return traces.get(trace) + "/" + n + "\n" + trace + "\n\n";
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "traces.get(trace) + \"/\" + n + \"\\n\" + trace + \"\\n\\n\"";
}
});
}
static public String unCurlyBracket(String s) {
return tok_unCurlyBracket(s);
}
static public Pair compileSnippetThroughServer(String progID) {
String transpiledSrc = getServerTranspiled2(progID);
String md5 = md5(transpiledSrc + "\n" + progID);
File jar = CompilerBot.getJarFile(md5);
if (jar == null || jar.length() <= 22) {
byte[] jarData = null;
boolean dontLoad = false;
IResourceLoader rl = vm_getResourceLoader();
if (rl != null) {
dontLoad = true;
File jar2 = rl.getSnippetJar(progID, transpiledSrc);
if (jar2 != null)
return pair(jar2, transpiledSrc);
}
if (!dontLoad) {
try {
jarData = loadBinaryPage(jarBotURL() + psI(progID) + "?md5=" + md5(transpiledSrc));
} catch (Throwable __e) {
pcallFail(__e);
}
}
if (!isJAR(jarData)) {
if (jarData != null) {
print(bytesToHex(takeFirstOfByteArray(8, jarData)));
print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData)));
}
return CompilerBot.compileSnippet2(progID);
}
saveBinaryFile(jar, jarData);
}
return pair(jar, transpiledSrc);
}
static public String dropSpaceEtc(String s) {
if (empty(s))
return null;
int n = l(s), i = 0;
char c = s.charAt(i);
boolean totality = !isSpaceEtc(c);
for (++i; i < n; i++) {
c = s.charAt(i);
boolean b = !isSpaceEtc(c);
if (b != totality) {
StringBuilder buf = new StringBuilder();
if (totality)
buf.append(substring(s, 0, i));
while (true) {
ping();
if (b)
buf.append(c);
if (++i >= n)
break;
c = s.charAt(i);
b = !isSpaceEtc(c);
}
return buf.toString();
}
}
return totality ? s : "";
}
static public ClassLoader getVirtualParent(ClassLoader cl) {
return (ClassLoader) rcallOpt("getVirtualParent", cl);
}
static public boolean titlePopupMenu(final Component c, final Object menuMaker) {
JComponent titleBar = getTitlePaneComponent(getPossiblyInternalFrame(c));
if (titleBar == null) {
print("Can't add title right click!");
return false;
} else {
componentPopupMenu(titleBar, menuMaker);
return true;
}
}
static public boolean isA(Either e) {
return eitherIsA(e);
}
static public long nanoTime() {
return System.nanoTime();
}
static public int activateFrame_v3_delay = 100;
static public boolean activateFrame_v3(Component c, Object... __) {
return swing(() -> {
Frame f = getAWTFrame(c);
if (f == null)
return false;
if (!f.isVisible())
f.setVisible(true);
int state = f.getState();
boolean iconified = state == Frame.ICONIFIED;
boolean maximize = boolPar("maximize", __);
if (iconified)
f.setState(maximize ? Frame.MAXIMIZED_BOTH : Frame.NORMAL);
else {
f.setState(Frame.ICONIFIED);
print("Restoring frame in " + activateFrame_v3_delay + " ms");
doLater(activateFrame_v3_delay, new Runnable() {
public void run() {
try {
f.setState(state);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.setState(state)";
}
});
}
f.toFront();
return true;
});
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public Set vm_generalWeakSet(Object name) {
synchronized (vm_generalMap()) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static public File associatedInfosFile(File f) {
return replaceExtension(f, ".infos");
}
static public String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
static public boolean isCurlyBraced(String s) {
List tok = tok_combineCurlyBrackets_keep(javaTok(s));
return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}");
}
static public String b(Object contents, Object... params) {
return fulltag("b", contents, params);
}
static public File findCmdOnPATH(String cmd) {
String path = System.getenv("PATH");
List dirs = splitAt(path, File.pathSeparator);
String c = isWindows() ? addSuffix(cmd, ".exe") : cmd;
for (String dir : dirs) {
File f = new File(dir, c);
if (f.isFile())
return f;
}
return null;
}
static public File tempDirPossiblyInRAMDisk() {
File f = linux_fileInRamDisk(aGlobalID());
if (f != null) {
f.mkdirs();
return f;
}
return makeTempDir();
}
static public int javaxIncludeSnippetType() {
return 42;
}
static public boolean ewicOneOf(String s, String... l) {
if (s != null)
for (String x : l) if (ewic(s, x))
return true;
return false;
}
static public Pt bottomRightCorner(Rect r) {
return r == null ? null : pt(r.x2(), r.y2());
}
static public FixedRateTimer doEvery_daemon(long delay, final Object r) {
return doEvery_daemon(defaultTimerName(), delay, r);
}
static public FixedRateTimer doEvery_daemon(String timerName, long delay, final Object r) {
return doEvery_daemon(timerName, delay, delay, r);
}
static public FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) {
return doEvery_daemon(defaultTimerName(), delay, firstDelay, r);
}
static public FixedRateTimer doEvery_daemon(String timerName, long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(true);
timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay);
return timer;
}
static public FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) {
return doEvery_daemon(toMS(delaySeconds), r);
}
static public void pClose(AutoCloseable c) {
close_pcall(c);
}
static public void closeRandomAccessFile(RandomAccessFile f) {
if (f != null)
try {
f.close();
callJavaX("dropIO", f);
} catch (Throwable e) {
printStackTrace(e);
}
}
static public JPanel jCenteredSection(Component c) {
return jCenteredSection("", c);
}
static public JPanel jCenteredSection(String title, Swingable c) {
return jCenteredSection(title, wrap(c));
}
static public JPanel jCenteredSection(String title, 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...";
}
});
}
static public JPanel jCenteredSection(String title) {
return jCenteredSection(title, jpanel());
}
static public Comparator makeComparator(final Object f) {
if (f instanceof Comparator)
return (Comparator) f;
return new Comparator() {
public int compare(Object a, Object b) {
return (Integer) callF(f, a, b);
}
};
}
static public String manifestTextForMainClass(String mainClass) {
return "Manifest-Version: 1.0\n" + "Main-Class: " + mainClass + "\n\n";
}
static public JLabel dm_fieldLabel(String fieldName) {
return jLiveValueLabel(dm_fieldLiveValue(fieldName));
}
static public String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static public String n(Collection l, String name) {
return n(l(l), name);
}
static public String n(Map m, String name) {
return n(l(m), name);
}
static public String n(Object[] a, String name) {
return n(l(a), name);
}
static public String n(MultiSet ms, String name) {
return n(l(ms), name);
}
static public String htmlencode_noQuotes(String s) {
if (s == null)
return "";
int n = s.length();
StringBuilder out = null;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c == '<') {
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append("<");
} else if (c == '>') {
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append(">");
} else if (c > 127 || c == '&') {
int cp = s.codePointAt(i);
if (out == null)
out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s));
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else {
if (out != null)
out.append(c);
}
}
return out == null ? s : out.toString();
}
static public Window dm_window(Object module) {
return getWindow(dm_vis(module));
}
static public class IVF1WithToString implements IVF1 , IFieldsToList {
static final public String _fieldOrder = "toString f";
public String toString;
public IVF1 f;
public IVF1WithToString() {
}
public IVF1WithToString(String toString, IVF1 f) {
this.f = f;
this.toString = toString;
}
public boolean equals(Object o) {
if (!(o instanceof IVF1WithToString))
return false;
IVF1WithToString __1 = (IVF1WithToString) o;
return eq(toString, __1.toString) && eq(f, __1.f);
}
public int hashCode() {
int h = 574155786;
h = boostHashCombine(h, _hashCode(toString));
h = boostHashCombine(h, _hashCode(f));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { toString, f };
}
public void get(A a) {
f.get(a);
}
public String toString() {
return toString;
}
}
static public IVF1 ivf1WithToString(String toString, IVF1 f) {
return f == null ? null : new IVF1WithToString (toString, f);
}
static public int abs(int i) {
return Math.abs(i);
}
static public long abs(long i) {
return Math.abs(i);
}
static public float abs(float i) {
return Math.abs(i);
}
static public double abs(double i) {
return Math.abs(i);
}
static public double abs(Complex c) {
return c.abs();
}
static public void forEachWithPosition(Matrix m, IVF3 f) {
if (m == null || f == null)
return;
int w = m.getWidth(), h = m.getHeight();
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) f.get(x, y, m.get(x, y));
}
static public Map runnableThreadsWithStackTraces() {
Map map = filterMap((__154, __155) -> isThreadRunnable_x(__154, __155), Thread.getAllStackTraces());
map.remove(currentThread());
return map;
}
static public BufferedImage scaledBufferedImageFromBWIntegralImage(int w, BWIntegralImage img) {
return scaledBufferedImageFromBWIntegralImage(img, w);
}
static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w) {
return scaledBufferedImageFromBWIntegralImage(img, w, heightForWidth(img.w, img.h, w));
}
static public BufferedImage scaledBufferedImageFromBWIntegralImage(BWIntegralImage img, int w, int h) {
int w1 = img.w, h1 = img.h;
int[] pixels = new int[w * h];
int i = 0;
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
int x1 = x * w1 / w, x2 = max(x1 + 1, (x + 1) * w1 / w);
int y1 = y * h1 / h, y2 = max(y1 + 1, (y + 1) * h1 / h);
int pixel = iround(img.getPixelAverage(x1, y1, x2, y2));
pixels[i++] = brightnessToRGBA(pixel);
}
return bufferedImage(w, h, pixels);
}
public static String winQuote(String text) {
if (text == null)
return null;
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r") + "\"";
}
static public String winQuote(File f) {
return winQuote(f.getAbsolutePath());
}
static public Map stdFunctions_uncached() {
return stdFunctions_uncached(new HashMap());
}
static public Map stdFunctions_uncached(Map map) {
for (var snippetID : stdFunctionListSnippetIDs()) parseStdFunctionsList(loadSnippet(snippetID), map);
return map;
}
static public boolean isJavaxModuleSnippetType(int type) {
return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule();
}
static public int findEndOfBracketPart(List cnc, int i) {
int j = i + 2, level = 1;
while (j < cnc.size()) {
if (eqOneOf(cnc.get(j), "{", "("))
++level;
else if (eqOneOf(cnc.get(j), "}", ")"))
--level;
if (level == 0)
return j + 1;
++j;
}
return cnc.size();
}
static public File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static public File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static public boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
static public Set tok_returnTypesOfStaticFunction_uncleaned(List tok, String functionName) {
List> funcs = findFullFunctionDefs(tok, true);
TreeSet out = new TreeSet();
for (List tokF : funcs) {
int i = indexOfAny(tokF, 0, "(", "{");
if (i < 0)
continue;
String fname = get(tokF, i - 2);
if (!eq(fname, functionName))
continue;
out.add(joinSubList(tokF, 1, i - 3));
}
return out;
}
static public BufferedImage intMatrixToImage(Matrix m) {
return intMatrixToBufferedImage(m);
}
static public void interruptThreads(Collection threads) {
for (Thread t : unnull(threads)) interruptThread(t);
}
static public void interruptThreads(Class mainClass) {
interruptThreads(registeredThreads(mainClass));
}
static public List hotwire_collectJars(File jar) {
List libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar);
List files = ll(jar);
for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID));
return files;
}
static public A callMain(A c, String... args) {
callOpt(c, "main", new Object[] { args });
return c;
}
static public void callMain() {
callMain(mc());
}
static public Either eitherB(B b) {
return new Either(2, b);
}
static public String evalJava_prep(String code) {
return evalJava_prep(code, "calc");
}
static public String evalJava_prep(String code, String mainName) {
return evalJava_prep(code, mainName, "");
}
static public ThreadLocal evalJava_prep_args = new ThreadLocal();
static public String evalJava_prep(String code, String mainName, String preCode) {
EvalJavaPrep prep = new EvalJavaPrep();
List tok = evalJava_prePrep(code, prep);
code = tok_addReturn(tok);
String returnType = containsReturnWithArgument(code) ? "Object" : "void";
String main = lines(prep.global) + "static " + returnType + " " + mainName + "(" + unnull(evalJava_prep_args.get()) + ") throws Exception {\n" + preCode + code + "\n" + "}";
return main;
}
static public Either eitherA(A a) {
return new Either(1, a);
}
static public void markAsSrcLib(String snippetID) {
saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), "");
}
static public int lIntArray(int[] a) {
return a == null ? 0 : a.length;
}
static public ThreadLocal evalJava_myProgramID_main_time = new ThreadLocal();
static public ThreadLocal evalJava_myProgramID_main_mainClass = new ThreadLocal();
static public Object evalJava_myProgramID_main(String main, Object... args) {
Object obj = veryQuickJava(main);
setOpt(obj, "programID", programID());
makeDependent(obj);
if (evalJava_myProgramID_main_mainClass.get() != null)
evalJava_myProgramID_main_mainClass.set(obj);
return evalJava_myProgramID_main_2(obj, args);
}
static public Object evalJava_myProgramID_main_2(Object obj, Object... args) {
long time = sysNow();
try {
return callCalc(obj, args);
} finally {
evalJava_myProgramID_main_time.set(sysNow() - time);
}
}
static public void addMouseAndMotionListener(Component c, MouseAdapter ma) {
if (c != null && ma != null) {
swing(() -> {
c.addMouseListener(ma);
c.addMouseMotionListener(ma);
});
}
}
static public void containerAddFirst(Container c, Component... l) {
if (c != null) {
swing(() -> {
for (int i = 0; i < l(l); i++) c.add(l[i], i);
revalidate(c);
});
}
}
static public Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public File dropExtension(File f) {
return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
}
static public String dropExtension(String s) {
return takeFirst(s, smartLastIndexOf(s, '.'));
}
static public String asciiHeading2(String title) {
return asciiHeading(title) + "\n";
}
static public List getComponents(final Component c) {
return !(c instanceof Container) ? emptyList() : asList(swing(new F0() {
public Component[] get() {
try {
return ((Container) c).getComponents();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return ((Container) c).getComponents();";
}
}));
}
static public List> paramsToPairs(A... params) {
if (l(params) == 1 && params[0] instanceof Map)
return mapToPairs((Map) params[0]);
List> l = emptyList(l(params) / 2);
for (int i = 0; i + 1 < l(params); i += 2) l.add(pair(params[i], params[i + 1]));
return l;
}
static public String rep(int n, char c) {
return repeat(c, n);
}
static public String rep(char c, int n) {
return repeat(c, n);
}
static public List rep(A a, int n) {
return repeat(a, n);
}
static public List rep(int n, A a) {
return repeat(n, a);
}
static public int area(Rect r) {
return rectArea(r);
}
static public double area(DoubleRect r) {
return r == null ? 0 : r.w * r.h;
}
static public int area(WidthAndHeight img) {
return img == null ? 0 : img.getWidth() * img.getHeight();
}
static public int area(BufferedImage img) {
return img == null ? 0 : img.getWidth() * img.getHeight();
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public long add(AtomicLong l, long b) {
return l.addAndGet(b);
}
static public SingleComponentPanel singleComponentPanel() {
return singleComponentPanel(null);
}
static public SingleComponentPanel singleComponentPanel(final Component c) {
return swing(new F0() {
public SingleComponentPanel get() {
try {
return new SingleComponentPanel(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return new SingleComponentPanel(c);";
}
});
}
static public SimpleDateFormat simpleDateFormat_local(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTimeZone());
return sdf;
}
static public int withMargin_defaultWidth = 6;
static public JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static public JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static public JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static public 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 = marginPanel();
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 = marginPanel();\r\n p.setBorder(BorderFactory.createEmptyBorder(to...";
}
});
}
static public File getCodeProgramDir() {
return getCodeProgramDir(getProgramID());
}
static public File getCodeProgramDir(String snippetID) {
return new File(javaxCodeDir(), formatSnippetID(snippetID));
}
static public File getCodeProgramDir(long snippetID) {
return getCodeProgramDir(formatSnippetID(snippetID));
}
static public void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static public void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(() -> {
cb.addActionListener(actionListener(action));
});
}
}
static public void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(() -> {
b.addActionListener(actionListener(action));
});
}
}
static public Matrix imageToMatrix(MakesBufferedImage img) {
return imageToMatrix(toBufferedImage(img));
}
static public Matrix imageToMatrix(BufferedImage img) {
if (img == null)
return null;
int _w = img.getWidth(), _h = img.getHeight();
class ImageToMatrix extends AbstractMatrix {
public ImageToMatrix() {
super(_w, _h);
}
public Integer get(int x, int y) {
assertPointInBounds(x, y, w, h);
return img.getRGB(x, y);
}
public void set(int x, int y, Integer val) {
assertPointInBounds(x, y, w, h);
img.setRGB(x, y, val);
}
}
;
return new ImageToMatrix();
}
static public int hashAboutObjects(Object... l) {
int hash = 0, n = l(l);
for (int i = 0; i < n; i++) hash = boostHashCombine(hash, hashCode(l[i]));
return hash;
}
static public boolean hasMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args) != null;
}
static public void clearTokens(List tok) {
clearAllTokens(tok);
}
static public void clearTokens(List tok, int i, int j) {
clearAllTokens(tok, i, j);
}
static public void clearTokens(List tok, IntRange r) {
clearAllTokens(tok, r.start, r.end);
}
static public KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static public String poorMansProfiling_stopAndRenderResults() {
return poorMansProfiling_renderFullResults(poorMansProfiling_stopAndGetResults());
}
static public int areaFromPoints(int x1, int y1, int x2, int y2) {
return (x1 - x1) * (y2 - y1);
}
static public List countIteratorToList(int b) {
return countIteratorToList(0, b);
}
static public List countIteratorToList(int a, int b) {
return asList(countIterator(a, b));
}
static public List countIteratorToList(int b, IF1 f) {
return countIteratorToList(0, b, f);
}
static public List countIteratorToList(int a, int b, IF1 f) {
return asList(countIterator(a, b, f));
}
static public List countIteratorToList(int a, int b, int step) {
return asList(countIterator(a, b, step));
}
static public List countIteratorToList(double a, double b, double step, IF1 f) {
return asList(countIterator(a, b, step, f));
}
static public List countIteratorToList(double a, double b, double step) {
return asList(countIterator(a, b, step));
}
static public List countIteratorToList(IF1 f, double a, double b, double step) {
return asList(countIterator(f, a, b, step));
}
static public List countIteratorToList(IF1 f, int b) {
return countIteratorToList(f, 0, b);
}
static public List countIteratorToList(IF1 f, int a, int b) {
return asList(countIterator(f, a, b));
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
static public Object hotwire_onCompile;
static public boolean hotwire_serially = false;
static public Lock hotwire_overInternalBot_lock = lock();
static public boolean hotwire_compileOnServer = false;
static public Class> hotwire_overInternalBot(String progID) {
return hotwire_overInternalBot(progID, "main");
}
static public Class> hotwire_overInternalBot(String progID, String mainClass) {
return hotwire_overInternalBot(progID, __ -> mainClass);
}
static public Class> hotwire_overInternalBot(String progID, IF1 calculateMainClass) {
try {
Pair p;
try {
p = hotwire_compile(progID);
} catch (Throwable e) {
throw rethrow("Error hotwiring " + progID, e);
}
File jar = p.a;
assertTrue(jar.getAbsolutePath(), jar.isFile());
List files = hotwire_collectJars(jar);
JavaXClassLoader classLoader = hotwire_makeClassLoader(files);
classLoader.progID = progID;
String mainClass = calculateMainClass == null ? "main" : calculateMainClass.get(classLoader);
return hotwire_finish(classLoader, progID, p.b, mainClass);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Pair hotwire_compile(String progID) {
Pair p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID);
Lock __0 = hotwire_serially ? hotwire_overInternalBot_lock : null;
lock(__0);
try {
callF(hotwire_onCompile, p);
return p;
} finally {
unlock(__0);
}
}
static public A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static public A printStruct(A a) {
printStructure(a);
return a;
}
static public boolean containsOneOf(Collection l, A... x) {
if (l instanceof Set) {
if (x != null)
for (A a : x) if (l.contains(a))
return true;
} else {
for (A a : unnull(l)) if (eqOneOf(a, x))
return true;
}
return false;
}
static public boolean containsOneOf(Collection l, Set set) {
if (set == null)
return false;
for (A a : unnull(l)) if (set.contains(a))
return true;
return false;
}
static public boolean containsOneOf(String s, String... x) {
for (String o : x) if (contains(s, o))
return true;
return false;
}
static public AutoCloseable dm_registerAs_direct(String... msgs) {
return dm_registerAs_directLink(msgs);
}
static public JFrame setFrameIconLater(Component c, final String imageID) {
final JFrame frame = getFrame(c);
if (frame != null)
startThread("Loading Icon", new Runnable() {
public void run() {
try {
final Image i = imageIcon(or2(imageID, "#1005557")).getImage();
swingLater(new Runnable() {
public void run() {
try {
frame.setIconImage(i);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "frame.setIconImage(i);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final Image i = imageIcon(or2(imageID, \"#1005557\")).getImage();\r\n swingL...";
}
});
return frame;
}
static public 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);
}
static public Rect intersectRects(Rect a, int x1, int y1, int w, int h) {
if (a == null || a.x >= x1 && a.y >= y1 && a.x2() < x1 + w && a.y2() < y1 + h)
return a;
return rectFromPoints(max(a.x, x1), max(a.y, y1), min(a.x2(), x1 + w), min(a.y2(), y1 + h));
}
static public String loadCachedTranspilation(String id) {
try {
return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id));
} catch (Throwable __e) {
return null;
}
}
static public File infoBoxesLogFile() {
return new File(javaxDataDir(), "Logs/infoBoxes.txt");
}
static public boolean addToCollection(Collection c, A a) {
return c != null && c.add(a);
}
static public List dropFirstThreeAndLastThree(List l) {
return dropFirstAndLast(3, l);
}
static public double minusInfinity() {
return negativeInfinity();
}
static public boolean deleteFile(File file) {
return file != null && file.delete();
}
static public Matrix listOfListsToMatrix(List> data) {
if (data == null)
return null;
int _h = l(data);
if (_h == 0)
return null;
int _w = l(data.get(0));
class ListsToMatrix extends AbstractMatrix {
public ListsToMatrix() {
super(_w, _h);
}
public A get(int x, int y) {
return data.get(y).get(x);
}
public void set(int x, int y, A a) {
data.get(y).set(x, a);
}
}
;
return new ListsToMatrix();
}
static public String firstToken(String s) {
return firstJavaToken(s);
}
static public String firstToken(List tok) {
return get(tok, 1);
}
static public JPanel centerAndSouthWithMargins(Swingable c, Swingable s) {
return centerAndSouthWithMargins(c, toComponent(s));
}
static public JPanel centerAndSouthWithMargins(Swingable c, Component s) {
return centerAndSouthWithMargins(toComponent(c), s);
}
static public JPanel centerAndSouthWithMargins(Component c, Swingable s) {
return centerAndSouthWithMargins(c, toComponent(s));
}
static public JPanel centerAndSouthWithMargins(Component c, Component s) {
return applyDefaultMargin(centerAndSouth(c, withTopMargin(s)));
}
static public JPanel centerAndSouthWithMargins(int margin, Swingable c, Swingable s) {
return centerAndSouthWithMargins(margin, c, toComponent(s));
}
static public JPanel centerAndSouthWithMargins(int margin, Swingable c, Component s) {
return centerAndSouthWithMargins(margin, toComponent(c), s);
}
static public JPanel centerAndSouthWithMargins(int margin, Component c, Swingable s) {
return centerAndSouthWithMargins(margin, c, toComponent(s));
}
static public JPanel centerAndSouthWithMargins(int margin, Component c, Component s) {
return applyMargin(margin, centerAndSouth(c, withTopMargin(margin, s)));
}
static public void setSCPComponent(SingleComponentPanel scp, Component c) {
if (scp != null)
scp.setComponent(c);
}
static public void stopTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
static public Object dm_os() {
{
var __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public void hideWindow(final Component c) {
final Window w = getWindow(c);
if (w != null) {
swing(() -> {
w.setVisible(false);
});
}
}
static public A cyclicGet(List l, int i) {
return empty(l) ? null : get(l, mod(i, l(l)));
}
static public boolean cyclicGet(BitSet bs, int n, int i) {
return bs != null && bs.get(mod(i, n));
}
static public long cyclicGet(LongBuffer l, int i) {
return l.get(mod(i, l.size()));
}
static public String ymdMinusHMS() {
return ymdMinusHMS(now());
}
static public String ymdMinusHMS(long now) {
return ymd_minus_hms(now);
}
static public String addSlash(String s) {
return empty(s) || s.endsWith("/") ? s : s + "/";
}
static public int toIntPercent(double ratio) {
return roundToInt(ratio * 100);
}
static public int toIntPercent(float ratio) {
return toIntPercent((double) ratio);
}
static public boolean tok_classHasModifier(List classDecl, String modifier) {
if (classDecl == null)
return false;
int i = classDecl.indexOf("class");
return subList(classDecl, 0, i).contains(modifier);
}
static public String prependSquareBracketed(Object o) {
String s = strOrEmpty(o);
return empty(s) ? "" : squareBracketed(s) + " ";
}
static public int withLeftMargin_defaultWidth = 6;
static public JPanel withLeftMargin(Swingable c) {
return withLeftMargin(toComponent(c));
}
static public JPanel withLeftMargin(Component c) {
return withLeftMargin(withLeftMargin_defaultWidth, c);
}
static public JPanel withLeftMargin(int margin, Swingable c) {
return withLeftMargin(margin, toComponent(c));
}
static public JPanel withLeftMargin(int margin, Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, margin, 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...";
}
});
}
static public BetterThreadLocal pingSource_tl_var = new BetterThreadLocal() {
@Override
public PingSource initialValue() {
return ping_v3_pingSourceMaker().get();
}
};
static public BetterThreadLocal pingSource_tl() {
return pingSource_tl_var;
}
static public JPanel jSection(Component c) {
return jSection("", c);
}
static public 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...";
}
});
}
static public JPanel jSection(String title) {
return jSection(title, jpanel());
}
static public JPanel jSection(LiveValue> lv, Component c) {
return jLiveValueSection(lv, c);
}
static public JButton jPopDownButton_noText(final Object... menuParams) {
return toolTip("Additional commands", jPopDownButton("", menuParams));
}
static public java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
sdf.setTimeZone(timeZone);
return sdf;
}
static public List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
static public 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();
}
static public void swingLater(Object r) {
var runnable = toRunnable(r);
executingSwingCode(runnable);
SwingUtilities.invokeLater(runnable);
}
static public String tok_unCurlyBracket(String s) {
return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static public void copyListPart(List a, int i1, List b, int i2, int n) {
if (a == null || b == null)
return;
for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i));
}
static public boolean makeNotifyingStringBufferRotate_verbose = false;
static public class NotifyingStringBufferRotator implements Runnable {
public NotifyingStringBuffer buf;
public IF0 getMaxChars;
public boolean processing = false;
public NotifyingStringBufferRotator(NotifyingStringBuffer buf, IF0 getMaxChars) {
this.getMaxChars = getMaxChars;
this.buf = buf;
}
public void run() {
try {
if (processing)
return;
AutoCloseable __1 = tempSet(this, "processing", true);
try {
Integer max = callF(getMaxChars);
if (max == null || buf.length() <= max)
return;
if (makeNotifyingStringBufferRotate_verbose)
print("Rotating NotifyingStringBuffer (" + buf.length() + "/" + max + ")");
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public void makeNotifyingStringBufferRotate(NotifyingStringBuffer buf, IF0 getMaxChars) {
if (hasElementWithClassShortNamed("NotifyingStringBufferRotator", buf.onChange))
return;
buf.onChange(new NotifyingStringBufferRotator(buf, getMaxChars));
}
static public List matrixToList(Matrix m) {
if (m == null)
return null;
int w = m.getWidth(), h = m.getHeight(), n = w * h;
return new RandomAccessAbstractList () {
public int size() {
return n;
}
public A get(int i) {
return m.get(i % w, i / w);
}
public A set(int i, A val) {
A old = m.get(i % w, i % h);
m.set(i % w, i / w, val);
return old;
}
};
}
static public Object[] mapObjectArray(IF1 f, Object[] l) {
if (empty(l))
return l;
int n = l.length;
Object[] a2 = new Object[n];
for (int i = 0; i < n; i++) a2[i] = f.get(l[i]);
return a2;
}
static public String defaultTimerName_name;
static public String defaultTimerName() {
if (defaultTimerName_name == null)
defaultTimerName_name = "A timer by " + programID();
return defaultTimerName_name;
}
static public ThreadLocal currentImage_var = new ThreadLocal();
static public BufferedImage currentImage() {
return currentImage_var.get();
}
static public void currentImage(BufferedImage img) {
currentImage_var.set(img);
}
static public int imageMergeSpacing = 5;
static public int imageMergeSpacing() {
return imageMergeSpacing;
}
static public void imageMergeSpacing(int pixels) {
imageMergeSpacing = pixels;
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
static public boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
static public boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
static public boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
static public MultiSet poorMansProfiling_results = new MultiSet();
static public int poorMansProfiling_samples;
static public java.util.Timer poorMansProfiling_timer;
static public Lock poorMansProfiling_lock = lock();
static public Thread poorMansProfiling_threadToSample;
static public void poorMansProfiling() {
poorMansProfiling(poorMansProfiling_defaultInterval());
}
static public void poorMansProfiling(Thread thread) {
poorMansProfiling(poorMansProfiling_defaultInterval(), thread);
}
static public void poorMansProfiling(int interval) {
poorMansProfiling(interval, null);
}
static public void poorMansProfiling(int interval, Thread thread) {
Lock __0 = poorMansProfiling_lock;
lock(__0);
try {
poorMansProfiling_threadToSample = thread;
poorMansProfiling_stop();
poorMansProfiling_clear();
poorMansProfiling_timer = doEvery_daemon(interval, new Runnable() {
public void run() {
try {
Map map = poorMansProfiling_threadToSample != null ? litmap(poorMansProfiling_threadToSample, poorMansProfiling_threadToSample.getStackTrace()) : runnableThreadsWithStackTraces();
Lock __1 = poorMansProfiling_lock;
lock(__1);
try {
poorMansProfiling_samples++;
for (Thread t : keys(map)) {
{
if (isSystemThread(t))
continue;
}
StringBuilder buf = new StringBuilder();
for (StackTraceElement e : map.get(t)) buf.append(e).append("\n");
poorMansProfiling_results.add(str(buf));
}
} finally {
unlock(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Map map =\r\n poorMansProfiling_threadToSampl...";
}
});
} finally {
unlock(__0);
}
}
static public void poorMansProfiling_stop() {
Lock __2 = poorMansProfiling_lock;
lock(__2);
try {
if (poorMansProfiling_timer != null) {
stopTimer(poorMansProfiling_timer);
poorMansProfiling_timer = null;
}
} finally {
unlock(__2);
}
}
static public void poorMansProfiling_clear() {
Lock __3 = poorMansProfiling_lock;
lock(__3);
try {
poorMansProfiling_results.clear();
poorMansProfiling_samples = 0;
} finally {
unlock(__3);
}
}
static public MultiSet poorMansProfiling_results() {
return new MultiSet(poorMansProfiling_results);
}
static public MultiSet poorMansProfiling_stopAndGetResults() {
Lock __4 = poorMansProfiling_lock;
lock(__4);
try {
poorMansProfiling_stop();
return poorMansProfiling_results();
} finally {
unlock(__4);
}
}
static public Object getOptMC(String field) {
return getOpt(mc(), field);
}
static public JLabel setImage(final BufferedImage img, final JLabel lbl) {
if (lbl != null) {
swing(() -> {
lbl.setIcon(imageIcon(img));
});
}
return lbl;
}
static public JLabel setImage(JLabel lbl, BufferedImage img) {
return setImage(img, lbl);
}
static public JLabel setImage(final String imageID, final JLabel lbl) {
if (lbl != null) {
swing(() -> {
lbl.setIcon(imageIcon(imageID));
});
}
return lbl;
}
static public JLabel setImage(JLabel lbl, String imageID) {
return setImage(imageID, lbl);
}
static public A setImage(A is, BufferedImage img) {
{
if (is != null)
is.setImage(img);
}
return is;
}
static public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public Matcher regexp(String pat, String s) {
return regexp(compileRegexp(pat), unnull(s));
}
static public Matcher regexp(java.util.regex.Pattern pat, String s) {
return pat.matcher(unnull(s));
}
static public java.util.regex.Pattern regexp(String pat) {
return compileRegexp(pat);
}
static public void bindTimerToComponent(final Timer timer, JFrame f) {
bindTimerToComponent(timer, f.getRootPane());
}
static public void bindTimerToComponent(final Timer timer, JComponent c) {
if (c.isShowing())
timer.start();
c.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
timer.start();
}
public void ancestorRemoved(AncestorEvent event) {
timer.stop();
}
public void ancestorMoved(AncestorEvent event) {
}
});
}
static public IntegerIterator integerIterator(int[] l) {
return l == null ? null : new IntegerIterator() {
public int i = 0;
public boolean hasNext() {
return i < l.length;
}
public int next() {
return l[i++];
}
};
}
static public boolean containsRegexp(String s, String pat) {
return regexpFinds(pat, s);
}
static public int numLines(String s) {
return countLines(s);
}
static public String simpleQuote(String s) {
return s == null ? "null" : "\"" + s + "\"";
}
static public int indexOfAny(List l, int i, A... x) {
while (i < l(l)) if (eqOneOf(l.get(i), x))
return i;
else
++i;
return -1;
}
static public int indexOfAny(List l, Collection x) {
return indexOfAny(l, 0, x);
}
static public int indexOfAny(List l, int i, Collection x) {
if (nempty(x))
while (i < l(l)) if (x.contains(l.get(i)))
return i;
else
++i;
return -1;
}
static public int indexOfAny(String s, int i, String chars) {
for (; i < l(s); i++) if (chars.indexOf(s.charAt(i)) >= 0)
return i;
return -1;
}
static public int indexOfAny(String s, String chars) {
return indexOfAny(s, 0, chars);
}
static public BufferedImage gridLOLToImage(List cellWidths, List cellHeights, List> lol) {
List> lom = mapWithIndex(lol, (i, m) -> listToMatrix(cyclicGet(cellWidths, i), m));
Matrix> mom = listToMatrix_cols(l(cellWidths), lom);
List cellX1s = partialSums_firstIs0(cellWidths);
List cellY1s = partialSums_firstIs0(cellHeights);
int w = last(cellX1s), h = last(cellY1s);
BufferedImage restored = newBufferedImage(w, h);
forEachWithPosition(mom, (x, y, cell) -> drawIntMatrix(restored, cell, cyclicGet(cellX1s, x), cyclicGet(cellY1s, y)));
return restored;
}
static public Object html_valueLessParam_cache;
static public Object html_valueLessParam() {
if (html_valueLessParam_cache == null)
html_valueLessParam_cache = html_valueLessParam_load();
return html_valueLessParam_cache;
}
static public Object html_valueLessParam_load() {
return new Object();
}
static public Producer javaTokC_iterator(String s) {
return new Producer() {
final public int l = strL(s);
public int i = 0;
public String next() {
if (i >= l)
return null;
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l)
return null;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
static public String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public A alwaysOnTop(A c) {
return alwaysOnTop(c, true);
}
static public A alwaysOnTop(A c, boolean on) {
{
swing(() -> {
Window w = getWindow(c);
if (w != null && w.isAlwaysOnTop() != on)
w.setAlwaysOnTop(on);
});
}
return c;
}
static public A setFrameTitle(A c, final String title) {
final Frame f = getAWTFrame(c);
if (f != null) {
swing(() -> {
f.setTitle(title);
});
}
return c;
}
static public A setFrameTitle(String title, A c) {
return setFrameTitle(c, title);
}
static public JFrame setFrameTitle(String title) {
Object f = getOpt(mc(), "frame");
if (f instanceof JFrame)
return setFrameTitle((JFrame) f, title);
return null;
}
static public boolean _inCore() {
return false;
}
static public int getScreenWidth() {
return getScreenSize().width;
}
static public Set javaxVoidAliases_cache;
static public Set javaxVoidAliases() {
if (javaxVoidAliases_cache == null)
javaxVoidAliases_cache = javaxVoidAliases_load();
return javaxVoidAliases_cache;
}
static public Set javaxVoidAliases_load() {
return litset("void", "svoid");
}
static public ClassLoader myClassLoader() {
return _getClass(mc()).getClassLoader();
}
static public Timestamp tsNow() {
return new Timestamp();
}
static public Object makeDependent_postProcess;
static public void makeDependent(Object c) {
if (c == null)
return;
assertTrue("Not a class", c instanceof Class);
dependentClasses();
hotwire_classes.add(new WeakReference(c));
Object local_log = getOpt(mc(), "local_log");
if (local_log != null)
setOpt(c, "local_log", local_log);
Object print_byThread = getOpt(mc(), "print_byThread");
if (print_byThread != null)
setOpt(c, "print_byThread", print_byThread);
callF(makeDependent_postProcess, c);
}
static public Rectangle boundsOnScreen(Component c) {
if (c == null)
return null;
if (c.getParent() instanceof JViewport && c.getParent().getParent() instanceof JScrollPane)
c = c.getParent().getParent();
try {
return new Rectangle(c.getLocationOnScreen(), c.getSize());
} catch (IllegalComponentStateException e) {
return null;
}
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, (ITokCondition) null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, String in, IIntPred condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, IIntPred condition) {
return jfind(tok, startIndex, in, tokCondition(condition));
}
static public int jfind(List tok, String in, ITokCondition condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, (Object) condition);
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public String formatFunctionCall(String fname, Object... args) {
return formatFunctionCall((Object) fname, args);
}
static public String formatFunctionCall(Object fname, Object... args) {
return fname + "(" + joinWithComma(allToString(args)) + ")";
}
static public String formatFunctionCall(String fname, Iterable args) {
return formatFunctionCall((Object) fname, args);
}
static public String formatFunctionCall(Object fname, Iterable args) {
return formatFunctionCall(fname, toObjectArray(args));
}
static public 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);
}
static public void copyBufferedImage(BufferedImage src, BufferedImage dest, int destx, int desty) {
if (src != null)
copyBufferedImage(src, 0, 0, dest, destx, desty, src.getWidth(), src.getHeight());
}
static public void copyBufferedImage(BufferedImage src, BufferedImage dest, Pt destP) {
copyBufferedImage(src, dest, destP.x, destP.y);
}
static public List dependentClasses() {
return cleanUpAndGetWeakReferencesList(hotwire_classes);
}
static public Object dm_evalJava_veryQuickJava;
static public Object dm_evalJava_withModule(String expression, Object... args) {
Object m = dm_current_generic();
String code = evalJava_prep(expression) + "\r\n static new InheritableThreadLocal dm_currentModule_value;\r\n \r\n sO dm_current_mandatory_generic_value;\r\n \r\n sO dm_current_mandatory_generic() { ret dm_current_mandatory_generic_value; }\r\n sO dm_current_generic() { ret dm_current_mandatory_generic(); }\r\n ";
Object obj;
if (dm_evalJava_veryQuickJava != null)
obj = callF(dm_evalJava_veryQuickJava, code);
else
obj = veryQuickJava(code);
setOpt(obj, "programID", programID());
makeDependent(obj);
setOpt(obj, "creator_class", newWeakReference(dm_os()));
dm_pointSubmoduleToMe(obj, m);
return evalJava_myProgramID_main_2(obj, args);
}
static public String localDateWithSeconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss");
return format.format(time);
}
static public String localDateWithSeconds() {
return localDateWithSeconds(now());
}
static public void dm_reload() {
dm_reloadMe();
}
static public A foldl(F2 f, A seed, Iterable l) {
A a = seed;
if (l != null)
for (B b : l) a = callF(f, a, b);
return a;
}
static public A foldl(F2 f, A seed, B[] l) {
A a = seed;
if (l != null)
for (B b : l) a = callF(f, a, b);
return a;
}
static public A foldl(Object f, A seed, B[] l) {
A a = seed;
if (l != null)
for (B b : l) a = (A) callF(f, a, b);
return a;
}
static public String localSnippetTitle(String snippetID) {
if (!isLocalSnippetID(snippetID))
return null;
File f = localSnippetFile(snippetID);
if (!f.exists())
return null;
return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
}
static public int localMonth(long time) {
return parseInt(simpleDateFormat_local("MM").format(time));
}
static public int localMonth() {
return localMonth(now());
}
static public File fileInSameDir(File f, String newName) {
return newFile(parentFile(f), newName);
}
static public ImageSurface doubleBufferedImageSurface() {
ImageSurface is = imageSurface();
setDoubleBuffered(is, true);
return is;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public String renderFunctionCall(String fname, Object... args) {
return formatFunctionCall(fname, args);
}
static public A addMargin(final int top, final int left, final int bottom, final int right, final A c) {
if (c != null) {
swing(() -> {
Border margin = BorderFactory.createEmptyBorder(top, left, bottom, right);
c.setBorder(jCompoundBorder(c.getBorder(), margin));
});
}
return c;
}
static public A addMargin(int w, A c) {
return addMargin(w, w, w, w, c);
}
static public A dm_getOSOpt(String field) {
return (A) getOpt(dm_os(), field);
}
static public double[] subDoubleArray(double[] b, int start) {
return subDoubleArray(b, start, l(b));
}
static public double[] subDoubleArray(double[] b, int start, int end) {
start = max(start, 0);
end = min(end, l(b));
if (start == 0 && end == l(b))
return b;
if (start >= end)
return new double[0];
double[] x = new double[end - start];
System.arraycopy(b, start, x, 0, end - start);
return x;
}
static public boolean isJavaxCompilableSnippetTypeExceptInclude(int type) {
return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule();
}
static public A setFrameIcon(A c, String imageID) {
setFrameIconLater(c, imageID);
return c;
}
static public A setFrameIcon(String imageID, A c) {
return setFrameIcon(c, imageID);
}
static public JDesktopPane dm_desktopPane() {
return dm_getOSOpt("desktop");
}
static public boolean isListOfElementType(Object o, Class type) {
if (!(o instanceof List))
return false;
return allElementsAreOfType((List) o, type);
}
static public boolean isListOfElementType(Class type, Object o) {
return isListOfElementType(o, type);
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public String getSnippetTitle(String id) {
if (id == null)
return null;
if (!isSnippetID(id))
return "?";
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.getSnippetTitle(id);
return getSnippetTitle_noResourceLoader(id);
}
static public String getSnippetTitle_noResourceLoader(String id) {
try {
if (isLocalSnippetID(id))
return localSnippetTitle(id);
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
else if (isGeneralFileServerSnippet(parsedID))
url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
String title = trim(loadPageSilently(url));
if (title != null)
try {
saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
return or(title, "?");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
static public TimeZone getTimeZone(String name) {
return TimeZone.getTimeZone(name);
}
static public JPanel jFullCenter(final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;";
}
});
}
static public LiveValue dm_calculatedLiveValue(final DynModule module, final Class type, final F0 calc) {
Lock __0 = module.lock;
lock(__0);
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(__0);
}
}
static public LiveValue dm_calculatedLiveValue(Class type, F0 calc) {
return dm_calculatedLiveValue(dm_current_mandatory(), type, calc);
}
static public LiveValue dm_calculatedLiveValue(Class type, IF0 calc) {
return dm_calculatedLiveValue(type, if0ToF0(calc));
}
static public LiveValue dm_calculatedLiveValue(IF0> calc) {
return dm_calculatedLiveValue(Object.class, (F0) if0ToF0(calc));
}
static public MouseAdapter leftClickMouseAdapter_noPt(final Object r) {
return new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1)
pcallF(r);
}
};
}
static public List getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient", "default");
static public List getJavaModifiers() {
return getJavaModifiers_list;
}
static public boolean dm_setFlag(String flagName) {
return dm_setFlag(flagName, true);
}
static public boolean dm_setFlag(String flagName, boolean value) {
Object mod = dm_current_generic();
Object stem = dm_stem(mod);
Integer flagCode = (Integer) (getOpt("flagName", stem));
if (flagCode == null)
return false;
call(stem, value ? "setFlag" : "clearFlag", flagCode);
return true;
}
static public