Warning : session_start(): open(/var/lib/php/sessions/sess_fltfqvhhvl04gij5dj99mmbckj, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import 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 x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Q;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.awt.geom.*;
import java.text.*;
import java.text.NumberFormat;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import javax.swing.border.*;
class main {
static public class UltrafaST extends DynWebServee {
transient public SnippetInstaCache snippetCache;
transient public String microNewsSnippetID = "#1034192";
transient public String downloadURL = "https://botcompany.de/jar/1033860?withX30=1&withLibs=1&mainClassForManifest=Starter&name=Gazelle.jar";
public Set allowedWebhookClientIPs() {
return asSet(tlftj("\r\n // TradingView.com\r\n 52.89.214.238\r\n 34.212.75.30\r\n 54.218.53.128\r\n 52.32.178.7\r\n // Myself\r\n 127.0.0.1\r\n 161.97.120.94\r\n "));
}
public void start() {
try {
super.start();
snippetCache = new SnippetInstaCache(microNewsSnippetID);
print("cachedSnippetIDs", snippetCache.cachedSnippetIDs());
dm_registerAs("gazAiHomePage");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void cleanMeUp() {
{
cleanUp(snippetCache);
snippetCache = null;
}
}
@Override
public Object html(IWebRequest req) {
{
var __10 = redirectToHTTPS(req);
if (__10 != null)
return __10;
}
if (req.uriIs("/favicon.ico"))
return serveFavIcon(gazelleFavIconSnippet());
if (req.uriIsIC("/gazelle.jar"))
return subBot_serveRedirect(downloadURL, "application/octet-stream");
if (req.uriIsIC("/webhook")) {
String clientIP = req.clientIP();
if (!contains(allowedWebhookClientIPs(), clientIP))
return subBot_serve500("Not a registered client IP");
String content = mapGet(req.files(), "postData");
appendLineToFile(javaxDataDir("webhook.log"), jsonEncode(litorderedmap("clientIP", clientIP, "date", formatLocalDate(), "content", content)));
return "OK";
}
if (req.uriIs("/")) {
var newsParas = paragraphs(snippetCache.get(microNewsSnippetID));
List newsObjects = new ArrayList();
List newsItems = map(newsParas, item -> {
Pair p = splitAtFirstColon(item);
String date = pairA(p), text = pairB(p);
newsObjects.add(new NewsItem(date, text));
return text + " [" + date + "]";
});
addAll(newsItems, targetBlank("https://agi.topicbox.com/groups/agi/T419e8a952205967e", "News post") + " [2022/1/22]", targetBlank("https://agi.topicbox.com/groups/agi/T2dea42566ccf6693", "News post") + " [2022/1/7]", targetBlank("https://agi.topicbox.com/groups/agi/T8ca0db34fc106b16/image-recognizers-should-return-mathematical-proofs", "Image recognizers should return mathematical proofs") + " [2021/9/10]", targetBlank("https://agi.topicbox.com/groups/agi/T2771ec3238f217fa/gazelle-looks-at-its-own-logo-and-paints-it-red", "Gazelle looks at its own logo and paints it red") + " [2021/8/20]");
List headings = new ArrayList();
headings.add(ahref("https://Gaz.AI", "Gaz.AI"));
final class _C_11 {
public String heading(String text) {
return heading(text, "");
}
public String heading(String text, String extra) {
headings.add(text);
return aname(text, h3(hcombine(ahref("#top", himgsnippet("#1103033", "style", "height: .65em", "align", "absmiddle", "title", "Back to top")), text, extra)));
}
}
final _C_11 __12 = new _C_11();
String content = h1("Gazelle 22 - a new image recognizer") + (empty(newsObjects) ? "" : p(hcombine(joinNemptiesWithBR(first(newsObjects).date + ":", first(newsObjects).text), ahref("#News", "[More news]")))) + aname("Screenshots") + __12.heading("Latest Screenshots") + new Screenshot("#1103157", "2022/9/5", nlToBr_trim("\r\n Gazelle is learning to read. \r\n (All characters shown are drawn by Gazelle trying to mimic a screenshot.)\r\n Not all that bad already!\r\n And it wasn't even trained on Courier.\r\n And yes, that fancy artwork could be considered a bug.\r\n ")) + new Screenshot("#1103151", "2022/9/3", "Which shape is similar to a 5?") + new Screenshot("#1103149", "2022/9/3", "Gazelle's cheat sheet for all shapes in the extended latin alphabet") + new Screenshot("#1103138", "2022/6/30", "Working on a compressed image format (and the demo is a beautiful main program too)") + new Screenshot("#1103137", "2022/6/2", targetBlank("https://www.youtube.com/watch?v=PgZwlmF5epU&ab_channel=StefanReich", "Recognizing Toilet Paper [Video]")) + new Screenshot("#1103133", "2022/5/22", "A more evolved data graph") + new Screenshot("#1103132", "2022/5/17", "First data graph") + new Screenshot("#1103131", "2022/5/6", "Finding topological graph mappings") + new Screenshot("#1103128", "2022/4/28", "A nice, straight-forward motion detector") + new Screenshot("#1103123", "2022/4/17", "Segmenting an image by covering it with single color tiles (left: input, right: output scaled up)") + new Screenshot("#1103121", "2022/4/6", "Semi-automatic conversion of left-arrow scripts to Java(X)") + new Screenshot("#1103119", "2022/4/2", "Optimized script compilation time to below 1 ms (displayed value is rounded up!)") + new Screenshot("#1103118", "2022/4/1", "PDF Import (commercial feature)") + new Screenshot("#1103116", "2022/3/30", "Learning fonts!") + new Screenshot("#1103112", "2022/3/26", "Training the computer as a math student... :)") + new Screenshot("#1103111", "2022/3/23", "Finding junctions and line ends in the letter skeletons") + new Screenshot("#1103110", "2022/3/22", "Artifact-free reduction of letters to 1 pixel-wide skeletons!") + new Screenshot("#1103105", "2022/3/17", "Finding a polygon's corners (marked red)") + new Screenshot("#1103099", "2022/3/13", "A 5 point gradient is recognized!") + new Screenshot("#1103097", "2022/3/12", "Rendering some multi-point gradients [gradient detection coming up too]") + new Screenshot("#1103095", "2022/3/11", "Some recognition of... something!? LOL") + new Screenshot("#1103094", "2022/3/10", "Checking in how many fonts (out of 88) a letter is actually different. Turns out \"e\" has the most versions (83) and \"l\" (lowercase L) has the fewest (76).") + new Screenshot("#1103093", "2022/3/8", "Theoretical number of different images at 3*3 pixels and 3 colors") + new Screenshot("#1103092", "2022/3/8", "Each letter reduced to 3x3 pixels and 3 colors. Can you still tell them apart? (Each letter in the grid is an H, e, l or o.)") + new Screenshot("#1103090", "2022/3/8", "Each letter was padded into a square") + new Screenshot("#1103088", "2022/3/8", "Extracted letter matrix ready for learning") + new Screenshot("#1103087", "2022/3/8", "Segmenter usually finds 5 letters as expected (the word is 'Hello'), but a few fonts still confuse it.") + new Screenshot("#1103086", "2022/3/7", "Project story editor with hyperlinks & auto-run mechanism for user scripts") + new Screenshot("#1103083", "2022/3/7", "Gazelle has split a word into invididual letters.") + new Screenshot("#1103072", "This screenshot shows my cute new scripting language which is very flexible.") + new Screenshot("#1103059", "Here you see Gazelle's preprocessing filters applied to a screen cam.") + __12.heading("Quick start (Windows, Mac, Linux)") + p("1. Install " + targetBlank("https://adoptium.net", "Temurin 17") + " or any recent Java version." + " (Their smaller \"" + targetBlank("https://adoptium.net/releases.html", "JRE") + "\" version is fine too. If you already have Java, just go to step 2.)") + p("2. Save and double-click " + ahref(downloadURL, "Gazelle.jar") + " (it's under 30 MB).") + __12.heading("What it does") + p(joinWithBR("Gazelle 22 watches your screen and recognizes things.", "It is being developed right now by " + targetBlank("https://BotCompany.de", "Stefan Reich") + " at " + ahref("https://gazelle.rocks", "Gaz.AI") + ". " + ahref("mailto:info@botcompany.de", "Contact.") + " ")) + p(targetBlank("https://code.botcompany.de/1033860", "Source repository") + ". " + "Older releases on " + ahref("https://github.com/stefan-reich/gazelle-22", "GitHub") + ".") + __12.heading("Privacy statement") + p(joinWithBR("Gazelle 22 runs locally on your machine.", "It does not upload any data to any server.", "Server connections are made only for downloading program parts and checking for updates.", "All code is open source.")) + __12.heading("News") + mapToLines(__33 -> p(__33), newsItems) + p("Imprint: Stefan Reich, Dubenhorst 27, 25474 Ellerbek");
String nav = aname("top", p(hcombine(ahref("https://Gaz.AI", himgsnippet("#1102967", "style", "height: 1em; vertical-align: bottom", "title", "Gaz.AI Gazelle Logo")), joinWithVBar(map(s -> ahrefAnchor(s, s), headings)))));
return hhtml(hcombine(hhead(hcombine(htitle("Gazelle 22 - a new image recognizer"), hcss_linkColorInherit(), hsansserif(), hmobilefix())), hbody(hfullcenter(hcombine(nav, content)))));
}
if (req.uriIs("/carousel/")) {
HImageCarousel carousel = new HImageCarousel();
carousel.add(carousel.new Slide("#1103072", "Scriptable", "This screenshot shows my cute new scripting language which is very flexible."));
carousel.add(carousel.new Slide("#1103059", "Interactive Screen Cam", "Here you see Gazelle's preprocessing filters applied to a screen cam."));
return hhtml(hhead(carousel.headStuff()) + hbody(carousel.html()));
}
return subBot_serve404("Four oh four. Bad URL");
}
public class Screenshot implements IFieldsToList {
public String imageID;
public String date;
public String text;
public Screenshot() {
}
public Screenshot(String imageID, String date, String text) {
this.text = text;
this.date = date;
this.imageID = imageID;
}
public Object[] _fieldsToList() {
return new Object[] { imageID, date, text };
}
public Screenshot(String imageID, String text) {
this.text = text;
this.imageID = imageID;
}
public String toString() {
return hcombine(p(hsnippetimg_linkToSameImage(imageID, "width", 250, "title", "Gazelle 22 screenshot - click to enlarge")), pUnlessEmpty(joinNemptiesWithBR(text, squareBracketUnlessEmpty(date))), pNbsp());
}
}
static public class NewsItem implements IFieldsToList {
public String date;
public String text;
public NewsItem() {
}
public NewsItem(String date, String text) {
this.text = text;
this.date = date;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + date + ", " + text + ")";
}
public boolean equals(Object o) {
if (!(o instanceof NewsItem))
return false;
NewsItem __13 = (NewsItem) o;
return eq(date, __13.date) && eq(text, __13.text);
}
public int hashCode() {
int h = 1459174566;
h = boostHashCombine(h, _hashCode(date));
h = boostHashCombine(h, _hashCode(text));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { date, text };
}
}
}
static public boolean _moduleClass_UltrafaST = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
static public Set asSet(MultiSet ms) {
return ms == null ? null : ms.asSet();
}
static public List tlftj(String text) {
return toLinesFullTrim_java(text);
}
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 AutoCloseable dm_registerAs(String... msgs) {
F0 f = new F0() {
public String get() {
try {
return dm_moduleID();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "return dm_moduleID();";
}
};
return combineAutoCloseables(map(msgs, msg -> dm_vmBus_answerToMessage(msg, f)));
}
static public boolean cleanUp_interruptThreads = false;
static public void cleanUp(Object c) {
if (c == null)
return;
if (c instanceof AutoCloseable) {
close_pcall((AutoCloseable) c);
return;
}
if (c instanceof java.util.Timer) {
((java.util.Timer) c).cancel();
return;
}
if (c instanceof Collection) {
cleanUp((Collection) c);
return;
}
if (c instanceof Map) {
for (Object o : keysList((Map) c)) cleanUp(o);
for (Object o : valuesList((Map) c)) cleanUp(o);
syncClear((Map) c);
return;
}
try {
preCleanUp(c);
setOpt_raw(c, "ping_pauseAll", false);
innerCleanUp(c);
List androids = (List) getOpt(c, "record_list");
for (Object android : unnull(androids)) pcallOpt(android, "dispose");
List classes = (List) (getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) {
try {
cleanUp(cc.get());
} catch (Throwable __e) {
pcallFail(__e);
}
}
if (cleanUp_interruptThreads) {
List threads = registeredThreads(c);
if (nempty(threads)) {
print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
interruptThreads(threads);
}
}
} catch (Throwable __e) {
pcallFail(__e);
}
setOpt_raw(c, "cleaningUp_flag", false);
if (c instanceof Class && ((Class) c).getName().equals("main"))
retireClassLoader(((Class) c).getClassLoader());
}
static public void cleanUp(Collection l) {
if (l == null)
return;
for (Object c : l) cleanUp(c);
l.clear();
}
static public Object redirectToHTTPS(IWebRequest req) {
if (!req.isHttps())
return subBot_serveRedirect("https://" + req.domain() + req.uri() + htmlQuery(req.params()));
return null;
}
static public Object serveFavIcon(String icoSnippet) {
return serveFavIcon(loadLibrary(icoSnippet));
}
static public Object serveFavIcon(File icoFile) {
return favIconHeaders(subBot_serveFile(icoFile, faviconMimeType()));
}
static public String gazelleFavIconSnippet() {
return "#1400504";
}
static public Object subBot_serveRedirect(String url) {
return call(getMainBot(), "serveRedirect", url);
}
static public Object subBot_serveRedirect(String url, String contentType) {
return call(getMainBot(), "serveRedirect", url, contentType);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean contains(Rect r, Pt p) {
return rectContains(r, p);
}
static public Object subBot_serve500() {
return call(getMainBot(), "serve500");
}
static public Object subBot_serve500(String msg) {
return call(getMainBot(), "serve500", msg);
}
static public Object subBot_serve500(Throwable error) {
return subBot_serve500(renderStackTrace(error));
}
static public B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static public B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static public void appendLineToFile(File file, String s) {
appendToFile(file, unnull(s) + "\n");
}
static public File javaxDataDir_dir;
static public File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static public File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static public String jsonEncode(Object o) {
StringBuilder buf = new StringBuilder();
jsonEncode(o, buf);
return str(buf);
}
static public void jsonEncode(Object o, StringBuilder buf) {
if (o == null)
buf.append("null");
else if (o instanceof String)
buf.append(quote((String) o));
else if (o instanceof Number || o instanceof Boolean)
buf.append(o);
else if (o instanceof Map) {
Map map = (Map) o;
buf.append("{");
boolean first = true;
for (Object key : keys(map)) {
if (first)
first = false;
else
buf.append(",");
buf.append(quote((String) key));
buf.append(":");
jsonEncode(map.get(key), buf);
}
buf.append("}");
} else if (o instanceof Collection) {
Collection l = (Collection) o;
buf.append("[");
boolean first = true;
for (Object element : l) {
if (first)
first = false;
else
buf.append(",");
jsonEncode(element, buf);
}
buf.append("]");
} else
throw fail("Unknown object for JSON encoding: " + className(o));
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public String formatLocalDate(long time) {
return localDate(time);
}
static public String formatLocalDate() {
return localDate();
}
static public List paragraphs(String text) {
return paragraphsFromText(text);
}
static public String paragraphs(Iterable l) {
return joinWithEmptyLines(l);
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) {
var it = l.iterator();
if (it.hasNext()) {
var pingSource = pingSource();
do {
ping(pingSource);
x.add(f.get(it.next()));
} while (it.hasNext());
}
}
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(Map map, IF2 f) {
List x = new ArrayList();
if (map != null)
for (Map.Entry e : map.entrySet()) {
ping();
x.add(f.get(e.getKey(), e.getValue()));
}
return x;
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public Pair splitAtFirstColon(String s) {
int i = smartIndexOf(s, ':');
return pair(trimSubstring(s, 0, i), trimSubstring(s, i + 1));
}
static public A pairA(Pair p) {
return p == null ? null : p.a;
}
static public B pairB(Pair p) {
return p == null ? null : p.b;
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
static public A addAll(A c, Collection extends Component> components) {
return addComponents(c, components);
}
static public A addAll(A c, Component... components) {
return addComponents(c, components);
}
static public String targetBlank(String link, Object contents, Object... params) {
return hrefBlank(link, contents, params);
}
static public String ahref(String link, Object contents, Object... params) {
return link == null ? str(contents) : href(link, contents, params);
}
static public String aname(String anchor) {
return aname(anchor, "");
}
static public String aname(String anchor, Object contents, Object... params) {
return tag("a", contents, concatArrays(new Object[] { "name", anchor }, params));
}
static public String h3(String s, Object... params) {
return tag("h3", s, params) + "\n";
}
static public String hcombine(Object... l) {
return htmlCombine(l);
}
static public String himgsnippet(String imageID, Object... params) {
return hsnippetimg(imageID, params);
}
static public String h1(String s, Object... params) {
return hfulltag("h1", s, params);
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(BitSet bs) {
return bs == null || bs.isEmpty();
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(IMultiMap mm) {
return mm == null || mm.size() == 0;
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public boolean empty(Chain c) {
return c == null;
}
static public boolean empty(AppendableChain c) {
return c == null;
}
static public boolean empty(IntSize l) {
return l == null || l.size() == 0;
}
static public String p(Object contents, Object... params) {
return hfulltag("p", contents, params) + "\n";
}
static public String p() {
return p("");
}
static public String joinNemptiesWithBR(Iterable l) {
return joinNempties(" \n", l);
}
static public String joinNemptiesWithBR(String... l) {
return joinNemptiesWithBR(asList(l));
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public Double first(double[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public String nlToBr_trim(String s) {
return nlToBr(trim(s));
}
static public String joinWithBR(Iterable l) {
return join(" \n", l);
}
static public String joinWithBR(String... l) {
return joinWithBR(asList(l));
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public String joinWithVBar(Iterable l) {
return join(" | ", l);
}
static public String joinWithVBar(String... l) {
return joinWithVBar(asList(l));
}
static public String ahrefAnchor(String anchor, Object contents, Object... params) {
return ahref("#" + unnull(anchor), contents, params);
}
static public String hhtml(Object contents) {
return containerTag("html", contents);
}
static public String hhead(Object contents) {
return tag("head", contents);
}
static public String htitle(String title) {
return hfulltag("title", htmlencode_noQuotes(title));
}
static public String hcss_linkColorInherit() {
return hcss("a { color: inherit; }");
}
static public String hsansserif() {
return hcss("body { font-family: Sans-Serif; }");
}
static public String hmobilefix() {
return " ";
}
static public String hmobilefix(String html) {
return hAddToHead(html, hmobilefix());
}
static public String hbody(Object contents, Object... params) {
return tag("body", contents, params);
}
static public String hfullcenter(Object contents, Object... __) {
return tag("table", tr(td(contents, "align", "center")), paramsPlus(__, "width", "100%", "height", "100%"));
}
static public Object subBot_serve404() {
return call(getMainBot(), "serve404");
}
static public Object subBot_serve404(String msg) {
return call(getMainBot(), "serve404", msg);
}
static public String hsnippetimg_linkToSameImage(String imageID, Object... params) {
String url = snippetImageLink(imageID);
return ahref(url, himg(url, params));
}
static public String pUnlessEmpty(String s, Object... __) {
return empty(s) ? "" : p(s, __);
}
static public String squareBracketUnlessEmpty(String s) {
return empty(s) ? "" : squareBracket(s);
}
static public String pNbsp() {
return p(nbsp());
}
static public String shortClassName_dropNumberPrefix(Object o) {
return dropNumberPrefix(shortClassName(o));
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public Concepts newConceptsWithClassFinder(File conceptsFile) {
Concepts cc = new Concepts(assertNotNull(conceptsFile));
cc.classFinder = _defaultClassFinder();
return cc;
}
static public Concepts newConceptsWithClassFinder(File conceptsFile, IF1 classFinder) {
Concepts cc = new Concepts(assertNotNull(conceptsFile));
cc.classFinder = classFinder;
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public float[] unnull(float[] l) {
return l == null ? emptyFloatArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public List toLinesFullTrim_java(String text) {
return tlft(joinLines(map(__34 -> javaDropComments(__34), tlft(text))));
}
static public String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
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 void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
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 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 void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Class mc() {
return main.class;
}
static public String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
static public String dm_moduleID() {
return dm_moduleID(dm_current_mandatory_generic());
}
static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
return a == null ? b : b == null ? a : new AutoCloseable() {
public String toString() {
return "pClose(a); pClose(b);";
}
public void close() throws Exception {
pClose(a);
pClose(b);
}
};
}
static public AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) {
return combineAutoCloseables(concatLists(ll(a, b, c), asList(more)));
}
static public AutoCloseable combineAutoCloseables(Iterable l) {
return foldl(new F2() {
public AutoCloseable get(AutoCloseable a, AutoCloseable b) {
try {
return combineAutoCloseables(a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "combineAutoCloseables(a,b)";
}
}, null, l);
}
static public AutoCloseable dm_vmBus_answerToMessage(String msg, final IF0 f) {
final DynModule m = dm_current_mandatory();
return dm_ownResource(vmBus_addListener_basic(msg, new F2() {
public Object get(String _msg, Object arg) {
try {
AutoCloseable __1 = m.enter();
try {
return callF(f);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n ret callF(f);";
}
}));
}
static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) {
final DynModule m = dm_current_mandatory();
return dm_ownResource(vmBus_addListener_basic(msg, new F2() {
public Object get(String _msg, Object arg) {
try {
AutoCloseable __2 = m.enter();
try {
return callF(f);
} finally {
_close(__2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n ret callF(f);";
}
}));
}
static public AutoCloseable dm_vmBus_answerToMessage(String msg, final F1 f) {
final DynModule m = dm_current_mandatory();
return dm_ownResource(vmBus_addListener_basic(msg, new F2() {
public Object get(String _msg, Object arg) {
try {
AutoCloseable __3 = m.enter();
try {
return callF(f, arg);
} finally {
_close(__3);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp m.enter();\r\n ret callF(f, arg);";
}
}));
}
static public AutoCloseable dm_vmBus_answerToMessage(String msg, F2 f) {
final DynModule m = dm_current_mandatory();
return dm_ownResource(vmBus_addListener_basic(msg, new F2() {
public Object get(String _msg, Object arg) {
try {
if (arg instanceof Object[]) {
if (((Object[]) arg).length != 2)
return null;
AutoCloseable __4 = m.enter();
try {
return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1]);
} finally {
_close(__4);
}
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (arg cast O[]) {\r\n if (arg.length != 2) null;\r\n temp m.enter();\r...";
}
}));
}
static public AutoCloseable dm_vmBus_answerToMessage(String msg, F3 f) {
final DynModule m = dm_current_mandatory();
return dm_ownResource(vmBus_addListener_basic(msg, new F2() {
public Object get(String _msg, Object arg) {
try {
if (arg instanceof Object[]) {
if (((Object[]) arg).length != 3)
return null;
AutoCloseable __5 = m.enter();
try {
return callF(f, ((Object[]) arg)[0], ((Object[]) arg)[1], ((Object[]) arg)[2]);
} finally {
_close(__5);
}
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (arg cast O[]) {\r\n if (arg.length != 3) null;\r\n temp m.enter();\r...";
}
}));
}
static public void close_pcall(AutoCloseable c) {
if (c != null) {
try {
c.close();
} catch (Throwable __e) {
pcallFail(__e);
}
}
}
static public List keysList(Map map) {
return cloneListSynchronizingOn(keys(map), map);
}
static public List keysList(MultiSet ms) {
return ms == null ? null : keysList(ms.map);
}
static public List valuesList(Map map) {
return cloneListSynchronizingOn(values(map), map);
}
static public List valuesList(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public void syncClear(Collection c) {
if (c != null)
synchronized (collectionMutex(c)) {
c.clear();
}
}
static public void syncClear(Map map) {
if (map != null)
synchronized (collectionMutex(map)) {
map.clear();
}
}
static public void preCleanUp(Object c) {
if (c instanceof Collection) {
for (Object o : ((Collection) c)) preCleanUp(o);
return;
}
callOpt(c, "licensed_off");
setOpt_raw(c, "ping_anyActions", true);
setOpt_raw(c, "cleaningUp_flag", true);
}
static public void innerCleanUp(Object c) {
if (!isFalse(pcallOpt(c, "cleanMeUp")))
for (String name : sorted(methodsStartingWith(c, "cleanMeUp_"))) try {
callOpt(c, name);
} catch (Throwable e) {
print("Error cleaning up: " + programID(c));
_handleException(e);
}
}
static public void innerCleanUp() {
innerCleanUp(mc());
}
static public Object pcallOpt(Object o, String method, Object... args) {
try {
return callOpt(o, method, args);
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public void pcallFail(Throwable e) {
pcallPolicyForThread().handlePcallFail(e);
}
static public void pcallFail(String msg) {
pcallFail(new Throwable(msg));
}
static public List registeredThreads(Object o) {
Map map = (Map) (getOpt(o, "_registerThread_threads"));
if (map == null)
return ll();
map.size();
synchronized (map) {
return asList(keys(map));
}
}
static public List registeredThreads() {
_registerThread_threads.size();
return asList(keys(_registerThread_threads));
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(BitSet bs) {
return !empty(bs);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(IMultiMap mm) {
return mm != null && mm.size() != 0;
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean nempty(MultiSet ms) {
return ms != null && !ms.isEmpty();
}
static public boolean nempty(IntSize l) {
return l != null && l.size() != 0;
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(AtomicLong l) {
return n2(l.get());
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2_getPlural(String singular) {
return plural(singular);
}
static public String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, n2_getPlural(singular));
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return empty(singular) ? n2(l) : n_fancy2(l, singular, n2_getPlural(singular));
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(long[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular) {
return n2(ms, singular, n2_getPlural(singular));
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public String n2(IMultiMap mm, String singular) {
return n2(mm, singular, n2_getPlural(singular));
}
static public String n2(IMultiMap mm, String singular, String plural) {
return n_fancy2(l(mm), singular, plural);
}
static public String joinWithComma(Iterable c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List allToString(Iterable c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static public void interruptThreads(Collection threads) {
for (Thread t : unnull(threads)) interruptThread(t);
}
static public void interruptThreads(Class mainClass) {
interruptThreads(registeredThreads(mainClass));
}
static public void retireClassLoader(ClassLoader cl) {
try {
if (isJavaXClassLoader(cl))
setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader());
} catch (Throwable __e) {
pcallFail(__e);
}
}
static public String htmlQuery(Map params) {
return empty(params) ? "" : "?" + makePostData(params);
}
static public String htmlQuery(Object... data) {
return empty(data) ? "" : "?" + makePostData(data);
}
static public File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static public Object favIconHeaders(Object response) {
call(response, "addHeader", "Cache-Control", "public, max-age=" + iround(hoursToSeconds(favIconCacheHours())));
return response;
}
static public Object subBot_serveFile(File file) {
return call(getMainBot(), "serveFile", file);
}
static public Object subBot_serveFile(File file, String mimeType) {
return call(getMainBot(), "serveFile", file, mimeType);
}
static public String faviconMimeType() {
return "image/x-icon";
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public boolean rectContains(int x1, int y1, int w, int h, Pt p) {
return p.x >= x1 && p.y >= y1 && p.x < x1 + w && p.y < y1 + h;
}
static public boolean rectContains(Rect a, Rect b) {
return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2();
}
static public boolean rectContains(Rect a, Rectangle b) {
return rectContains(a, toRect(b));
}
static public boolean rectContains(Rect a, int x, int y) {
return a != null && a.contains(x, y);
}
static public boolean rectContains(Rect a, Pt p) {
return a != null && p != null && a.contains(p);
}
static public String renderStackTrace(StackTraceElement[] st) {
return stackTraceToString(st);
}
static public String renderStackTrace(Throwable e) {
return stackTraceToString(e);
}
static public String renderStackTrace(String msg) {
return renderStackTrace(new Throwable(msg));
}
static public Lock appendToFile_lock = lock();
static public boolean appendToFile_keepOpen = false;
static public HashMap appendToFile_writers = new HashMap();
static public void appendToFile(String path, String s) {
try {
Lock __0 = appendToFile_lock;
lock(__0);
try {
mkdirsForFile(new File(path));
path = getCanonicalPath(path);
Writer writer = appendToFile_writers.get(path);
if (writer == null) {
writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8"));
if (appendToFile_keepOpen)
appendToFile_writers.put(path, writer);
}
writer.write(s);
if (!appendToFile_keepOpen)
writer.close();
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void appendToFile(File path, String s) {
if (path != null)
appendToFile(path.getPath(), s);
}
static public void cleanMeUp_appendToFile() {
AutoCloseable __3 = tempCleaningUp();
try {
Lock __1 = appendToFile_lock;
lock(__1);
try {
closeAllWriters(values(appendToFile_writers));
appendToFile_writers.clear();
} finally {
unlock(__1);
}
} finally {
_close(__3);
}
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return c == null ? "null" : new String(c);
}
static public String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(IMultiMap mm) {
return mm.keySet();
}
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 String className(Object o) {
return getClassName(o);
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public String localDate(long time) {
return simpleDateFormat_local("yyyy/MM/dd").format(time);
}
static public String localDate() {
return localDate(now());
}
static public List paragraphsFromText(String text) {
List lines = toLinesTrim2(text);
List> paragraphs = paragraphsFromText_groupParagraphs(lines);
return lmap(__35 -> fromLines(__35), paragraphs);
}
static public List> paragraphsFromText_groupParagraphs(List lines) {
return groupNonEmpty(lines, new F1() {
public Object get(String line) {
try {
return empty(line);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "empty(line)";
}
});
}
static public String joinWithEmptyLines(Iterable l) {
return join("\n\n", map(__36 -> rtrim(__36), l));
}
static public String joinWithEmptyLines(String... l) {
return joinWithEmptyLines(asList(l));
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping(PingSource pingSource) {
return ping();
}
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(char[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(byte[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public PingSource pingSource() {
return pingSource_tl().get();
}
static public PingSource pingSource(Thread thread) {
return pingSource_tl().get(thread);
}
static public int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static public int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static public int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static public int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static public int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static public int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public String trimSubstring(String s, int x) {
return trim(substring(s, x));
}
static public String trimSubstring(String s, int x, int y) {
return trim(substring(s, x, y));
}
static public String trimSubstring(int x, String s) {
return trimSubstring(s, x);
}
static public A addComponents(A c, Collection extends Component> components) {
if (nempty(components)) {
swing(() -> {
for (Component comp : components) if (comp != null)
c.add(comp);
revalidate(c);
});
}
return c;
}
static public A addComponents(A c, Component... components) {
return addComponents(c, asList(components));
}
static public String hrefBlank(String link, Object contents, Object... params) {
return empty(link) ? strOrEmpty(contents) : tag("a", contents, concatArrays(new Object[] { "href", link, "target", "_blank" }, params));
}
static public String href(String link, Object contents, Object... params) {
if (link == null)
return str(contents);
return hfulltag("a", contents, arrayPlus(params, "href", link));
}
static public String tag(String tag) {
return htag(tag);
}
static public String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static public String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static public String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static public Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
static public String htmlCombine(Object... l) {
return nemptyLines_extractLists(l);
}
static public String hsnippetimg(String imageID, Object... params) {
return himg(snippetImageLink(imageID), params);
}
static public String hfulltag(String tag) {
return hfulltag(tag, "");
}
static public String hfulltag(String tag, Object contents, Object... params) {
return hopeningTag(tag, params) + str(contents) + "" + tag + ">";
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public String joinNempties(String sep, Object... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Iterable strings) {
return joinStrings(sep, strings);
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public String nlToBr(String s) {
return s.replace("\n", " \n");
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
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 lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String lines(Iterable l, IF1 f) {
return mapToLines(l, f);
}
static public String containerTag(String tag) {
return containerTag(tag, "");
}
static public String containerTag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
return openingTag + s + "" + tag + ">";
}
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 String hcss(Object contents) {
if (contents instanceof String && isRelativeOrAbsoluteURL((String) contents))
return hstylesheetsrc((String) contents);
else
return htag("style", contents);
}
static public String hAddToHead(String html, String tag) {
List tok = htmlTok(html);
List head = first(findContainerTag(tok, "head"));
if (head == null)
return tag + html;
head.set(2, addLineBreak(tag) + head.get(2));
return join(tok);
}
static public String tr(Object contents) {
return tag("tr", contents);
}
static public String td(Object contents, Object... params) {
return hfulltag("td", contents, params);
}
static public String td() {
return td("");
}
static public Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], a2) };
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
static public Object[] paramsPlus(Map a1, Object... a2) {
return paramsPlus(new Object[] { a1 }, a2);
}
static public String snippetImageLink(String snippetID) {
return snippetImageURL(snippetID);
}
static public String himg(String src, Object... params) {
return tag("img", "", arrayPlus(params, "src", isSnippetID(src) ? snippetImageLink(src) : src));
}
static public String himg(BufferedImage img, Object... params) {
return himg(dataURL(jpegMimeType(), toJPEG(img)), params);
}
static public String squareBracket(String s) {
return "[" + s + "]";
}
static public String nbsp() {
return " ";
}
static public String dropNumberPrefix(String s) {
return dropFirst(s, indexOfNonDigit(s));
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void __setJavaX(Class j) {
__javax = j;
_onJavaXSet();
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
name = replacePrefix("main$main$", "main$", name);
Class c = get2(name);
return c;
}
public Class get2(String name) {
if (eq(name, ""))
return mc();
{
Class c = findClass_fullName(name);
if (c != null)
return c;
}
if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
String newName = pkg + afterDollar(name);
{
Class c = findClass_fullName(newName);
if (c != null)
return c;
}
}
return null;
}
};
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public float[] emptyFloatArray = new float[0];
static public float[] emptyFloatArray() {
return emptyFloatArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
static public String joinLines(List lines) {
return fromLines(lines);
}
static public String joinLines(String glue, String text) {
return join(glue, toLines(text));
}
static public String javaDropComments(String s) {
return javaDropAllComments(s);
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public Object call_withVarargs(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(methodName, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(methodName);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public int indexOf(List l, A a, int startIndex) {
if (l == null)
return -1;
int n = l(l);
for (int i = startIndex; i < n; i++) if (eq(l.get(i), a))
return i;
return -1;
}
static public int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static public int indexOf(List l, A a) {
if (l == null)
return -1;
return l.indexOf(a);
}
static public int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static public int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static public int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static public int indexOf(A[] x, A a) {
int n = l(x);
for (int i = 0; i < n; i++) if (eq(x[i], a))
return i;
return -1;
}
static public int indexOf(Iterable l, A a) {
if (l == null)
return -1;
int i = 0;
for (A x : l) {
if (eq(x, a))
return i;
i++;
}
return -1;
}
static public void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public Object dm_getStem(Object moduleOrID) {
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
moduleOrID = dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static public void pClose(AutoCloseable c) {
close_pcall(c);
}
static public List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
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 A dm_ownResource(A resource) {
dm_currentModuleMandatory().ownResource(resource);
return resource;
}
static public AutoCloseable vmBus_addListener_basic(String msg, Object listener) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, listener);
}
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public ArrayList cloneListSynchronizingOn(Collection l, Object mutex) {
if (l == null)
return new ArrayList();
synchronized (mutex) {
return new ArrayList (l);
}
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
return o;
}
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 List methodsStartingWith(Object o, final String prefix) {
return filter(allMethodNames(o), new F1() {
public Object get(String s) {
try {
return startsWith(s, prefix);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startsWith(s, prefix)";
}
});
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll((IVF1) (__1 -> printStackTrace2(__1))));
static public boolean _handleException_showThreadCancellations = false;
static public void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
if (_handleException_showThreadCancellations)
System.out.println(getStackTrace_noRecord(e2));
return;
}
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
try {
printStackTrace2(e3);
} catch (Throwable e4) {
System.out.println(getStackTrace(e3));
System.out.println(getStackTrace(e4));
}
}
}
static public PCallPolicy pcallPolicyForThread() {
var policy = pcallPolicyForThread_tl().get();
if (policy != null)
return policy;
return defaultPCallPolicy();
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public String plural(String s) {
return getPlural(s);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public boolean interruptThread_verbose = false;
static public void interruptThread(Thread t) {
if (t == null)
return;
if (interruptThread_verbose)
print("Interrupting thread " + t);
vm_threadInterruptionReasonsMap().put(t, getStackTrace());
t.interrupt();
URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t));
if (c != null) {
try {
print("Closing URLConnection of interrupted thread.");
call(c, "disconnect");
} catch (Throwable __e) {
pcallFail(__e);
}
}
}
static public boolean isJavaXClassLoader(ClassLoader cl) {
return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader");
}
static public void setOptAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) setOpt(o, field, fields.get(field));
}
static public void setOptAll(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
setOpt(o, field, value);
}
}
static public String makePostData(Map map) {
StringBuilder buf = new StringBuilder();
for (Map.Entry e : castMapToMapO(map).entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public String makePostData(Object... params) {
StringBuilder buf = new StringBuilder();
int n = l(params);
for (int i = 0; i + 1 < n; i += 2) {
String key = (String) (params[i]);
Object val = params[i + 1];
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public File loadBinarySnippet(String snippetID) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadBinarySnippet_noResourceLoader(snippetID);
}
static public File loadBinarySnippet_noResourceLoader(String snippetID) {
try {
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile_noResourceLoader(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
static public double hoursToSeconds(double hours) {
return hours * 60 * 60;
}
static public double favIconCacheHours() {
return 24;
}
static public Rect toRect(Rectangle r) {
return r == null ? null : new Rect(r);
}
static public Rect toRect(RectangularShape r) {
return r == null ? null : toRect(r.getBounds());
}
static public Rect toRect(Rect r) {
return r;
}
static public String stackTraceToString(StackTraceElement[] st) {
return lines(st);
}
static public String stackTraceToString(Throwable e) {
return getStackTrace_noRecord(e);
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
vmBus_send("locking", lock, "thread", currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread", currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static public String getCanonicalPath(File f) {
try {
return f == null ? null : f.getCanonicalPath();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String getCanonicalPath(String path) {
return getCanonicalPath(newFile(path));
}
static public FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static public FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
}
static public AutoCloseable tempCleaningUp() {
AutoCloseable result = null;
result = tempSetTL(ping_isCleanUpThread, true);
return result;
}
static public void closeAllWriters(Collection extends Writer> l) {
for (Writer w : unnull(l)) {
try {
w.close();
} catch (Throwable __e) {
pcallFail(__e);
}
}
}
static public String actualUserHome_value;
static public String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
static public File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public SimpleDateFormat simpleDateFormat_local(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTimeZone());
return sdf;
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public List toLinesTrim2(String s) {
return map(__37 -> trim(__37), toLinesTrim(s));
}
static public List lmap(IF1 f, Iterable l) {
return lambdaMap(f, l);
}
static public List lmap(IF1 f, A[] l) {
return lambdaMap(f, l);
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public List> groupNonEmpty(List l, Object isSep) {
List> out = new ArrayList();
int j = 0;
for (int i = 0; i < l(l); i++) {
boolean sep = isTrue(callF(isSep, l.get(i)));
if (sep) {
if (i > j)
out.add(newSubList(l, j, i));
j = i + 1;
}
}
if (l(l) > j)
out.add(newSubList(l, j));
return out;
}
public static String rtrim(String s) {
if (s == null)
return null;
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
return i < s.length() ? s.substring(0, i) : s;
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public > A max(Iterable l) {
A max = null;
var it = iterator(l);
if (it.hasNext()) {
max = it.next();
while (it.hasNext()) {
A a = it.next();
if (cmp(a, max) > 0)
max = a;
}
}
return max;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
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 failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
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 int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public > A min(A a, A b) {
return cmp(a, b) <= 0 ? a : b;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(() -> {
c.revalidate();
c.repaint();
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public String a(String noun) {
if (eq(noun, ""))
return "?";
return ("aeiou".indexOf(noun.charAt(0)) >= 0 ? "an " : "a ") + noun;
}
static public String a(String contents, Object... params) {
return hfulltag("a", contents, params);
}
static public Object[] arrayPlus(Object[] a1, Object... a2) {
return concatArrays(a1, a2);
}
static public String htag(String tag) {
return htag(tag, "");
}
static public String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
static public String nemptyLines_extractLists(Object... l) {
return nemptyLines(flattenCollectionsAndArrays(ll(l)));
}
static public String hopeningTag(String tag, Map params) {
return hopeningTag(tag, mapToParams(params));
}
static public String hopeningTag(String tag, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
params = unrollParams(params);
for (int i = 0; i < l(params); i += 2) {
String name = (String) get(params, i);
Object val = get(params, i + 1);
if (nempty(name) && val != null) {
if (eqOneOf(val, html_valueLessParam(), true))
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
static public String joinStrings(String sep, Object... strings) {
return joinStrings(sep, Arrays.asList(strings));
}
static public String joinStrings(String sep, Iterable strings) {
StringBuilder buf = new StringBuilder();
for (Object o : unnull(strings)) {
String s = strOrNull(o);
if (nempty(s)) {
if (nempty(buf))
buf.append(sep);
buf.append(s);
}
}
return str(buf);
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public byte[] unnullForIteration(byte[] l) {
return l == null ? emptyByteArray() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static public List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static public String takeFirst(int n, String s) {
return substring(s, 0, n);
}
static public String takeFirst(String s, int n) {
return substring(s, 0, n);
}
static public CharSequence takeFirst(int n, CharSequence s) {
return subCharSequence(s, 0, n);
}
static public List takeFirst(int n, Iterator it) {
if (it == null)
return null;
List l = new ArrayList();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public List takeFirst(int n, Iterable i) {
if (i == null)
return null;
return i == null ? null : takeFirst(n, i.iterator());
}
static public List takeFirst(int n, IterableIterator i) {
return takeFirst(n, (Iterator ) i);
}
static public int[] takeFirst(int n, int[] a) {
return takeFirstOfIntArray(n, a);
}
static public short[] takeFirst(int n, short[] a) {
return takeFirstOfShortArray(n, a);
}
static public byte[] takeFirst(int n, byte[] a) {
return takeFirstOfByteArray(n, a);
}
static public byte[] takeFirst(byte[] a, int n) {
return takeFirstOfByteArray(n, a);
}
static public double[] takeFirst(int n, double[] a) {
return takeFirstOfDoubleArray(n, a);
}
static public double[] takeFirst(double[] a, int n) {
return takeFirstOfDoubleArray(n, a);
}
static public String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public boolean isRelativeOrAbsoluteURL(String s) {
return isAbsoluteURL(s) || isRelativeURL(s);
}
static public String hstylesheetsrc(String src) {
return tag("link", "", "rel", "stylesheet", "href", src);
}
static public List htmlTok(String s) {
return htmlcoarsetok(s);
}
static public List> findContainerTag(List tok, String tag) {
List> l = new ArrayList();
for (int i = 1; i < l(tok); i += 2) if (isOpeningTag(tok.get(i), tag)) {
int j, level = 1;
for (j = i + 2; j < tok.size(); j += 2) if (isOpeningTag(tok.get(j), tag))
++level;
else if (isTag(tok.get(j), "/" + tag)) {
--level;
if (level == 0) {
l.add(subList(tok, i - 1, j + 2));
break;
}
}
i = j;
}
return l;
}
static public List> findContainerTag(String html, String tag) {
return findContainerTag(htmlTok(html), tag);
}
static public String addLineBreak(String s) {
return addSuffix(s, "\n");
}
static public Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
static public Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
static public LinkedHashMap paramsToOrderedMap(Object... params) {
return asLinkedHashMap(paramsToMap(params));
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static public String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
static public String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static public String snippetImageURL(String snippetID, String contentType) {
if (snippetID == null || isURL(snippetID))
return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (isImageServerSnippet(id))
url = imageServerLink(id);
else
url = "https://botcompany.de/img/" + id;
return url;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static public String dataURL(String mimeType, byte[] data) {
return "data:" + mimeType + ";base64," + base64(data);
}
static public String jpegMimeType() {
return "image/jpeg";
}
static public byte[] toJPEG(BufferedImage img) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(dropAlphaChannelFromBufferedImage(img), "jpeg", stream);
return stream.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] toJPEG(File f) {
return toJPEG(loadImage2(f));
}
static public String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static public String[] dropFirst(String[] a) {
return drop(1, a);
}
static public Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static public List dropFirst(List l) {
return dropFirst(1, l);
}
static public List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
static public List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static public List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static public List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static public String dropFirst(int n, String s) {
return substring(s, n);
}
static public String dropFirst(String s, int n) {
return substring(s, n);
}
static public String dropFirst(String s) {
return substring(s, 1);
}
static public Chain dropFirst(Chain c) {
return c == null ? null : c.next;
}
static public int indexOfNonDigit(String s) {
int n = l(s);
for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i)))
return i;
return -1;
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public void _onJavaXSet() {
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
static public Object get2(Object o, String field1, String field2) {
return get(get(o, field1), field2);
}
static public boolean startsWithAny(String a, Collection b) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, String... b) {
if (b != null)
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, Collection b, Matches m) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m))
return true;
return false;
}
static public String mcDollar() {
return mcName() + "$";
}
static public String afterDollar(String s) {
return substring(s, smartIndexOf(s, '$') + 1);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() {
public int hashCode(Symbol symbol) {
return symbol.text.hashCode();
}
public boolean equals(Symbol a, Symbol b) {
if (a == null)
return b == null;
return b != null && eq(a.text, b.text);
}
});
static public Symbol symbol(String s) {
if (s == null)
return null;
synchronized (symbol_map) {
Symbol symbol = new Symbol(s, true);
Symbol existingSymbol = symbol_map.findKey(symbol);
if (existingSymbol == null)
symbol_map.put(existingSymbol = symbol, true);
return existingSymbol;
}
}
static public Symbol symbol(CharSequence s) {
if (s == null)
return null;
if (s instanceof Symbol)
return (Symbol) s;
if (s instanceof String)
return symbol((String) s);
return symbol(str(s));
}
static public Symbol symbol(Object o) {
return symbol((CharSequence) o);
}
static public List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public String javaDropAllComments(String s) {
return join(javaDropAllComments(javaTok(s)));
}
static public List javaDropAllComments(List tok) {
for (int i = 0; i < l(tok); i += 2) tok.set(i, tok_javaDropCommentsFromWhitespace(tok.get(i)));
return tok;
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Executable m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = l(args);
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
int nVarArgs = nArgs - n;
Object varArgs = Array.newInstance(varArgType, nVarArgs);
for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n + i]);
newArgs[n] = varArgs;
return newArgs;
}
static public String formatArgumentClasses(Object[] args) {
return joinWithComma(map(__38 -> getClassName(__38), args));
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public Object pcallF_minimalExceptionHandling(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable e) {
System.out.println(getStackTrace(e));
_storeException(e);
}
return null;
}
static public boolean isString(Object o) {
return o instanceof String;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static public boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static public DynModule dm_currentModuleMandatory() {
return dm_current_mandatory();
}
static public Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static public AutoCloseable tempAdd(Collection l, A a) {
if (l == null || l.contains(a))
return null;
l.add(a);
return new tempAdd_undo(l, a);
}
static public class tempAdd_undo implements AutoCloseable, IFieldsToList {
public Collection l;
public A a;
public tempAdd_undo() {
}
public tempAdd_undo(Collection l, A a) {
this.a = a;
this.l = l;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + l + ", " + a + ")";
}
public Object[] _fieldsToList() {
return new Object[] { l, a };
}
public void close() {
try {
l.remove(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public AutoCloseable tempAdd(Container a, Component b) {
if (a == null || b == null)
return null;
{
return swing(() -> {
if (b.getParent() == a)
return null;
a.add(b);
return () -> {
swing(() -> {
if (b.getParent() == a)
removeFromParent(b);
});
};
});
}
}
static public void sort(T[] a, Comparator super T> c) {
if (a != null)
Arrays.sort(a, c);
}
static public void sort(T[] a) {
if (a != null)
Arrays.sort(a);
}
static public void sort(int[] a) {
if (a != null)
Arrays.sort(a);
}
static public void sort(List a, Comparator super T> c) {
if (a != null)
Collections.sort(a, c);
}
static public void sort(List a) {
if (a != null)
Collections.sort(a);
}
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 List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
static public List allMethodNames(Object o) {
Class c = _getClass(o);
TreeSet names = new TreeSet();
while (c != null) {
for (Method m : c.getDeclaredMethods()) names.add(m.getName());
c = c.getSuperclass();
}
return asList(names);
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public String getProgramID() {
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 List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public Throwable innerException(Throwable e) {
return getInnerException(e);
}
static public ThreadLocal pcallPolicyForThread_tl_tl = new ThreadLocal();
static public ThreadLocal pcallPolicyForThread_tl() {
return pcallPolicyForThread_tl_tl;
}
static public PCallPolicy defaultPCallPolicy = __1 -> printStackTrace(__1);
static public PCallPolicy defaultPCallPolicy() {
return defaultPCallPolicy;
}
static public void defaultPCallPolicy_set(PCallPolicy policy) {
defaultPCallPolicy = policy;
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
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 Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public Map vm_generalSubMap(Object name) {
synchronized (vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
static public Map castMapToMapO(Map map) {
return map;
}
static public String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
static public IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static public File loadImageAsFile(String snippetIDOrURL) {
try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL))
throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0)
return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static File DiskSnippetCache_getLibrary(String snippetID) {
try {
return DiskSnippetCache_getLibrary(psI(snippetID));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
static public byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
static public long fileSize(String path) {
return getFileSize(path);
}
static public long fileSize(File f) {
return getFileSize(f);
}
static public File loadDataSnippetToFile(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File loadDataSnippetToFile_noResourceLoader(String snippetID) {
try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null)
return 0.0;
throw fail(o);
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public void _registerIO(Object object, String path, boolean opened) {
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public AutoCloseable tempSetTL(BetterThreadLocal tl, A a) {
return tempSetThreadLocalIfNecessary(tl, a);
}
static public void _handleError(Error e) {
}
static public TimeZone localTimeZone() {
return getTimeZone(standardTimeZone());
}
public static List toLinesTrim(String s) {
List lines = new ArrayList();
int start = 0;
while (true) {
int i = toLinesTrim_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(rtrim(s.substring(start)));
break;
}
lines.add(rtrim(s.substring(start, i)));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
private static int toLinesTrim_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static public List lambdaMap(IF1 f, A[] l) {
return map(l, f);
}
static public List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static public List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static public int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(int a, int b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(long a, long b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> {
Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread")));
var tl = new x30_pkg.x30_util.BetterThreadLocal();
tl.set(value);
return tl;
});
return newPing_actionTL;
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public IF0 ping_v3_pingSourceMaker_cache;
static public IF0 ping_v3_pingSourceMaker() {
if (ping_v3_pingSourceMaker_cache == null)
ping_v3_pingSourceMaker_cache = ping_v3_pingSourceMaker_load();
return ping_v3_pingSourceMaker_cache;
}
static public IF0 ping_v3_pingSourceMaker_load() {
return or((IF0) vm_generalMap_get("ping_v3_pingSourceMaker"), () -> null);
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else {
r = addThreadInfoToRunnable(r);
executingSwingCode(r);
EventQueue.invokeAndWait(r);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(Object f) {
if (isAWTThread())
return callF(f);
else {
Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public boolean neqic(String a, String b) {
return !eqic(a, b);
}
static public boolean neqic(char a, char b) {
return !eqic(a, b);
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public String nemptyLines(Iterable l) {
return lines(nempties(allToStrOrNull(l)));
}
static public String nemptyLines(Object... l) {
return nemptyLinesLL(l);
}
static public List flattenCollectionsAndArrays(Iterable a) {
List l = new ArrayList();
for (Object x : a) if (x instanceof Collection)
l.addAll(flattenCollectionsAndArrays((Collection) x));
else if (x instanceof Object[])
l.addAll(flattenCollectionsAndArrays(asList((Object[]) x)));
else
l.add(x);
return l;
}
static public List flattenCollectionsAndArrays(Object... whatever) {
return flattenCollectionsAndArrays(ll(whatever));
}
static public Object[] unrollParams(Object[] params) {
if (l(params) == 1 && params[0] instanceof Map)
return mapToParams((Map) params[0]);
return params;
}
static public boolean eqOneOf(Object o, Object... l) {
if (l != null)
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public List immutableEmptyList() {
return Collections.emptyList();
}
static public byte[] emptyByteArray_a = new byte[0];
static public byte[] emptyByteArray() {
return emptyByteArray_a;
}
static public short[] emptyShortArray = new short[0];
static public short[] emptyShortArray() {
return emptyShortArray;
}
static public Map immutableEmptyMap() {
return Collections.emptyMap();
}
static public CloseableIterableIterator linesFromFile(File f) {
return linesFromFile(f, null);
}
static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) {
try {
if (!fileExists(f))
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(path, null);
}
static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) {
return linesFromFile(newFile(path), resourceHolder);
}
static public List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static public List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
static public CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static public CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.subSequence(x, y);
}
static public int[] takeFirstOfIntArray(int[] b, int n) {
return subIntArray(b, 0, n);
}
static public int[] takeFirstOfIntArray(int n, int[] b) {
return takeFirstOfIntArray(b, n);
}
static public short[] takeFirstOfShortArray(short[] b, int n) {
return subShortArray(b, 0, n);
}
static public short[] takeFirstOfShortArray(int n, short[] b) {
return takeFirstOfShortArray(b, n);
}
static public byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static public byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static public double[] takeFirstOfDoubleArray(double[] b, int n) {
return subDoubleArray(b, 0, n);
}
static public double[] takeFirstOfDoubleArray(int n, double[] b) {
return takeFirstOfDoubleArray(b, n);
}
static public boolean isAbsoluteURL(String s) {
return isURL(s);
}
static public boolean isRelativeURL(String s) {
return startsWithOneOf(s, "/", "./", "../");
}
static public List htmlcoarsetok(String s) {
List tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c;
while (j < l) {
if (s.charAt(j) != '<')
++j;
else if (s.substring(j, Math.min(j + 4, l)).equals(""));
j = Math.min(j + 3, l);
} else {
char d = charAt(s, j + 1);
if (d == '/' || isLetter(d))
break;
else
++j;
}
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
if (c == '<') {
++j;
while (j < l && s.charAt(j) != '>') ++j;
if (j < l)
++j;
}
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() & 1) == 0)
tok.add("");
return tok;
}
static public boolean isOpeningTag(String token, String tag) {
return isTag(token, tag) && !token.endsWith("/>");
}
static public boolean isOpeningTag(String token) {
return token.startsWith("<") && token.endsWith(">") && !token.endsWith("/>") && isLetter(token.charAt(1));
}
static public boolean isTag(String token, String tag) {
return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length() + 2) || token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length() + 2);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, List l) {
return subList(l, startIndex);
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex > endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public String addSuffix(String s, String suffix) {
return s == null || s.endsWith(suffix) ? s : s + suffix;
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public boolean even(int i) {
return (i & 1) == 0;
}
static public boolean even(long i) {
return (i & 1) == 0;
}
static public boolean even(BigInteger n) {
return even(n.intValue());
}
static public LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
static public Map paramsToMap(Object... params) {
int n = l(params);
if (l(params) == 1 && params[0] instanceof Map)
return (Map) params[0];
LinkedHashMap map = new LinkedHashMap();
for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]);
return map;
}
static public Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static public Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
return array;
}
static public Object[] mapToObjectArray(Collection l, IF1 f) {
return mapToObjectArray(f, l);
}
static public Object[] mapToObjectArray(A[] l, IF1 f) {
return mapToObjectArray(f, l);
}
static public Object[] mapToObjectArray(IF1 f, A[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = f.get(l[i]);
return array;
}
static public Object[] mapToObjectArray(IF1 f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public String fsI(String id) {
return formatSnippetID(id);
}
static public String fsI(long id) {
return formatSnippetID(id);
}
static public boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static public String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static public String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static public String base64(byte[] a) {
return base64encode(a);
}
static public BufferedImage dropAlphaChannelFromBufferedImage(BufferedImage img) {
if (img == null || img.getType() == BufferedImage.TYPE_INT_RGB)
return img;
int w = img.getWidth(), h = img.getHeight();
BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
int[] rgb = img.getRGB(0, 0, w, h, null, 0, w);
newImage.setRGB(0, 0, w, h, rgb, 0, w);
return newImage;
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
static public String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static public Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
static public List drop(Iterable c, Object pred) {
return antiFilter(c, pred);
}
static public List drop(Object pred, Iterable c) {
return antiFilter(pred, c);
}
static public List drop(Object pred, Object[] c) {
return antiFilter(pred, c);
}
static public List drop(Iterable c, F1 pred) {
return antiFilter(c, pred);
}
static public List drop(F1 pred, Iterable c) {
return antiFilter(pred, c);
}
static public List drop(Iterable c, IF1 pred) {
return antiFilter(c, pred);
}
static public List drop(IF1 pred, Iterable c) {
return antiFilter(pred, c);
}
static public ArrayList toList(A[] a) {
return asList(a);
}
static public ArrayList toList(int[] a) {
return asList(a);
}
static public ArrayList toList(short[] a) {
return asList(a);
}
static public ArrayList