Warning : session_start(): open(/var/lib/php/sessions/sess_5f3pga68kulqkk3l17c965sbtt, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.text.NumberFormat;
import java.util.*;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.net.ssl.*;
import java.text.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
class main {
static public class StandardScript extends Concept {
public String scriptID;
}
static public class Cruddie extends DynPrintLogAndEnabled {
static public boolean _switchableField_httpPort = true;
public int httpPort = 80;
static public boolean _switchableField_httpsPort = true;
public int httpsPort = 443;
public void cleanMeUp_httpServer() {
{
cleanUp(httpServer);
httpServer = null;
}
}
transient public MyHTTPD httpServer;
public void cleanMeUp_httpsServer() {
{
cleanUp(httpsServer);
httpsServer = null;
}
}
transient public MyHTTPD httpsServer;
transient public boolean redirectHttpToHttps = false;
public void start_webServers(File keyStore, String passphrase) {
start_webServers(serveHttps_makeSSLSocketFactory(keyStore, passphrase));
}
public void start_webServers(SSLServerSocketFactory sslSocketFactory) {
try {
httpServer = new MyHTTPD(httpPort);
httpServer.enter = () -> enter();
httpServer.serveFunction = new F2, Object>() {
public Object get(String uri, Map parms) {
try {
return redirectHttpToHttps ? serveRedirect("https://" + serveHttp_domainName() + (httpsPort == 443 ? "" : ":" + httpsPort) + uri) : webServe(uri, parms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "redirectHttpToHttps\r\n ? serveRedirect(\"https://\" + serveHttp_domainName(...";
}
};
httpServer.start();
print("HTTP server started on port " + httpServer.getPort());
if (httpsPort == 0 || sslSocketFactory == null)
return;
httpsServer = new MyHTTPD(httpsPort);
httpsServer.enter = () -> enter();
httpsServer.makeSecure(sslSocketFactory);
httpsServer.serveFunction = new F2, Object>() {
public Object get(String uri, Map parms) {
try {
return webServe(uri, parms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "webServe(uri, parms)";
}
};
httpsServer.start();
print("HTTPS server started on port " + httpsServer.getPort());
} catch (Exception __e) {
throw rethrow(__e);
}
}
transient public String salt;
transient public WebChatBot chatBot;
transient public CRUD standardScriptsCRUD;
transient public CRUD conversationsCRUD;
public String myLink() {
return "https://cruddie.site/";
}
public String botLink() {
return "bot";
}
static public boolean _switchableField_frontendModuleLibID = true;
public String frontendModuleLibID = "#1027675/ChatBotFrontend";
static public boolean _switchableField_backendModuleLibID = true;
public String backendModuleLibID = "#1027591/DynamicClassesMultiCRUD";
transient public String cmdsSnippetID = "#1027616";
public void start() {
try {
super.start();
standardScriptsCRUD = new CRUD(StandardScript.class);
conversationsCRUD = new CRUD(Conversation.class);
{
startThread(new Runnable() {
public void run() {
try {
File saltFile = secretProgramFile("salt.txt");
String salt = trimLoadTextFile(saltFile);
if (empty(salt)) {
saveTextFile(saltFile, salt = randomID());
print("Made salt");
}
dm_restartOnFieldChange("enabled");
if (!enabled)
return;
chatBot = new WebChatBot();
chatBot.preprocess = s -> {
String s2 = googleDecensor(s);
print("Preprocessing: " + s + " => " + s2);
return s2;
};
chatBot.templateID = "#1027690";
chatBot.baseLink = botLink();
chatBot.thoughtBot = new ThoughtBot();
chatBot.jsOnMsgHTML = "window.processNewStuff(src);";
chatBot.onBotShown = " {\r\n var input = $(\"#status_message\")[0];\r\n console.log(\"input: \" + input);\r\n if (input)\r\n new Awesomplete(input, {\r\n minChars: 1,\r\n list: [\r\n \"I call you Fido\",\r\n \"What is your name?\",\r\n 'add script \"#1027704/SomeCruddieScripts/RepeatAfterMe\"',\r\n 'add script \"#1027704/SomeCruddieScripts/GoPublic\"',\r\n 'clear scripts'\r\n ]\r\n });\r\n } ";
chatBot.afterHeading = "` + ('webkitSpeechRecognition' in window ? ` " + tag("button", "...", "onclick", "startOrStop(); if (bigOn) startVAD(); else stopVAD();", "type", "button", "class", "speechOnBtn", "disabled", "disabled", "display", "inline") + "` : ``) + `" + hdiv(hsnippetimg("#1102908", "width", 24, "height", 24, "title", "Someone is speaking (either me or you)"), "style", "display: inline; visibility: hidden; margin-left: 10px", "class", "vadStatus") + hdiv(hsnippetimg("#1102909", "width", 24, "height", 24, "title", "Listening"), "style", "display: inline; visibility: hidden; margin-left: 10px", "class", "listenStatus") + hdiv(small("Note: All conversations are public rn " + targetBlank("https://www.youtube.com/watch?v=StxQerL0D-o", "(why)")));
chatBot.moreStuff = "window.srUpdate();";
chatBot.start();
redirectHttpToHttps = true;
start_webServers(javaxSecretDir("cruddie.site/keystore.p12"), "botcompany");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "File saltFile = secretProgramFile(\"salt.txt\");\r\n String salt = trimLoadT...";
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Object webServe(String uri, Map params) {
printVars("webServe", "uri", uri);
Matches m = new Matches();
String uri2 = appendSlash(uri);
if (startsWith(uri2, "/bot/", m))
return chatBot.html("/" + m.rest(), params);
if (eq(uri, "/awesomplete.css"))
return serveWithContentType(loadSnippet("#2000595"), "text/css");
if (eq(uri, "/awesomplete.js"))
return serveText(loadSnippet("#2000594"));
String jsOnSpeech = "if (transcript != 'stop listening') window.submitAMsg(transcript);";
String sayBotMsgsScript = "\r\n window.processNewStuff = function(src) {\r\n " + (eq(params.get("quiet"), "1") ? "" : "\r\n if ($(\"#speechResults\") == null) return; // no speech\r\n // we assume that webkit speech synthesis is present\r\n // when there is webkit speech recognition\r\n if (!bigOn) return; // not enabled\r\n console.log(\"Got speech\");\r\n var match = src.match(/\\d+/);\r\n if (match == null) return;\r\n if (src.match(/NEW DIALOG -->/)) return;\r\n console.log(\"Got incremental\");\r\n var re = /bot-utterance\">(.*?)") + hbody(hOnBottom(p(hsnippetimage("#1102905")) + p("Chat bot is doing basic stuff. Documentation coming up.") + stats() + hjavascript("\r\n var srPause;\r\n \r\n function say(text) {\r\n console.log(\"Saying: \" + text);\r\n var u = new SpeechSynthesisUtterance(text);\r\n u.onstart = function() { console.log(\"speech start\"); srPause = true; srUpdate(); };\r\n u.onend = function() { srPause = false; srUpdate(); };\r\n window.speechSynthesis.speak(u);\r\n }\r\n " + sayBotMsgsScript) + hSpeechRecognition(jsOnSpeech, true, "en-US", false, "noWebKit", p("Use Chrome if you want speech recognition"), "speechUI", speechUI) + hjs((String) chatBot.html("/", litmap(), "returnJS", true)) + hVAD("console.log(\"voice start\"); $(\".vadStatus\").css(\"visibility\", \"visible\");", "console.log(\"voice stop\"); $(\".vadStatus\").css(\"visibility\", \"hidden\");", false))));
}
public String cookieToCaseID(String cookie) {
return md5(cookie + salt);
}
public class Request {
public String cookie, caseID;
public String frontend, backend;
public Request(String cookie) {
this.cookie = cookie;
caseID = cookieToCaseID(cookie);
frontend = dm_makeModuleWithParams_systemQ(frontendModuleLibID, "caseID", caseID);
backend = dm_makeModuleWithParams_systemQ(backendModuleLibID, "caseID", caseID);
dm_call(frontend, "connectToBackend", backend);
dm_call(frontend, "importCmdsFromSnippetIfEmpty", cmdsSnippetID);
dm_call(frontend, "addScripts", collect("scriptID", list(StandardScript.class)));
Conversation conv = uniq(Conversation.class, "cookie", cookie);
forwardSwappableFunctionToObject(dm_mod(frontend), "chatLog_userMessagesOnly", new F0>() {
public List get() {
try {
return map(m -> m.text, filter(conv.allMsgs(), m -> m.fromUser));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret map(m -> m.text, filter(conv.allMsgs(), m -> m.fromUser));";
}
}, "get");
printVars("caseID", caseID, "backend", backend);
}
}
public class ThoughtBot {
public ThreadLocal request = new ThreadLocal();
public void setSession(String cookie, Map params) {
request.set(new Request(cookie));
}
public String initialMessage() {
return (String) dm_call(request.get().backend, "answer", "stats");
}
public String answer(String s) {
return (String) dm_call(request.get().frontend, "answer", s);
}
}
public String stats() {
return p(joinWithBR("Server temperature is " + dm_cpuTemperature(), n2(numberOfCruddies(), "cruddie") + ", " + n2(vmBus_countResponses("chatBotFrontend")) + " loaded"));
}
public int numberOfCruddies() {
return countDirsInDir(getProgramDir(beforeSlash(frontendModuleLibID)));
}
public JComponent visualize() {
return jtabs("Main", super.visualize(), "Standard Scripts", standardScriptsCRUD.visualize(), "Conversations", conversationsCRUD.visualize());
}
}
static public boolean _moduleClass_Cruddie = 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 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 : keys((Map) c)) cleanUp(o);
for (Object o : values((Map) c)) cleanUp(o);
((Map) c).clear();
return;
}
try {
preCleanUp(c);
setOpt(c, "ping_pauseAll", false);
innerCleanUp(c);
List androids = (List) getOpt(c, "record_list");
for (Object android : unnull(androids)) pcallOpt(android, "dispose");
List classes = (List) (getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) {
try {
cleanUp(cc.get());
} catch (Throwable __e) {
_handleException(__e);
}
}
if (cleanUp_interruptThreads) {
List threads = registeredThreads(c);
if (nempty(threads)) {
print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
interruptThreads(threads);
}
}
} catch (Throwable __e) {
_handleException(__e);
}
setOpt(c, "cleaningUp_flag", false);
if (c instanceof Class && ((Class) c).getName().equals("main"))
retireClassLoader(((Class) c).getClassLoader());
}
static public void cleanUp(Collection l) {
if (l == null)
return;
for (Object c : l) cleanUp(c);
l.clear();
}
static public MyHTTPD serveHttps_server;
static public int serveHttps_port = 8889;
static public void serveHttps(int port, SSLServerSocketFactory socketFactory) {
try {
serveHttps_port = port;
serveHttps_server = new MyHTTPD(port);
serveHttps_server.makeSecure(socketFactory);
serveHttps_server.start();
print("HTTPS server started (socket factory: " + socketFactory + ", listening on port " + port + "!)");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void serveHttps(int port, File keystore, String pass) {
try {
serveHttps(port, serveHttps_makeSSLSocketFactory(keystore, pass));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void serveHttps(int port) {
try {
serveHttps_port = port;
serveHttps_server = new MyHTTPD(port);
serveHttps_server.makeSecure((SSLServerSocketFactory) SSLServerSocketFactory.getDefault());
serveHttps_server.start();
print("HTTPS server started with default socket factory (listening on port " + port + "!)");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public SSLServerSocketFactory serveHttps_makeSSLSocketFactory(File keystoreFile, String passphrase) {
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = new FileInputStream(keystoreFile);
try {
keystore.load(keystoreStream, passphrase.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase.toCharArray());
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
return ctx.getServerSocketFactory();
} finally {
_close(keystoreStream);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void cleanMeUp_serveHttps() {
if (serveHttps_server != null) {
serveHttps_server.stop();
serveHttps_server = null;
}
}
static public NanoHTTPD.Response serveRedirect(String url) {
NanoHTTPD.IStatus status = new NanoHTTPD.IStatus() {
public String getDescription() {
return "302 Moved temporarily";
}
public int getRequestStatus() {
return 302;
}
};
NanoHTTPD.Response r = NanoHTTPD.newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, "");
r.addHeader("Location", url);
return r;
}
static public String serveHttp_domainName() {
NanoHTTPD.IHTTPSession session = NanoHTTPD.currentSession.get();
if (session == null)
return null;
return session.getHeaders().get("host");
}
static volatile public StringBuffer local_log = new StringBuffer();
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((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
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);
System.out.print(s);
}
static public void print_autoRotate() {
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public File secretProgramFile(String progID, String fileName) {
return new File(getSecretProgramDir(progID), fileName);
}
static public File secretProgramFile(String fileName) {
return secretProgramFile(getProgramID(), fileName);
}
static public String trimLoadTextFile(String fileName) {
return loadTextFile_trim(fileName);
}
static public String trimLoadTextFile(File f, String defaultContents) {
return loadTextFile_trim(f, defaultContents);
}
static public String trimLoadTextFile(File fileName) {
return loadTextFile_trim(fileName);
}
static public String trimLoadTextFile(String fileName, String defaultContents) {
return loadTextFile_trim(fileName, defaultContents);
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
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(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(File f) {
return getFileSize(f) == 0;
}
static public File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static public File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int randomID_defaultLength = 12;
static public String randomID(int length) {
return makeRandomID(length);
}
static public String randomID(Random r, int length) {
return makeRandomID(r, length);
}
static public String randomID() {
return randomID(randomID_defaultLength);
}
static public String randomID(Random r) {
return randomID(r, randomID_defaultLength);
}
static public void dm_restartOnFieldChange(String field) {
dm_reloadOnFieldChange(field);
}
static public String googleDecensor(String s) {
return translateUsingMechPhraseList("Google speech recognition de-censor phrases", s);
}
static public String botLink() {
return botLink(programID());
}
static public String botLink(String botID) {
return "https://botcompany.de/" + parseSnippetID(botID);
}
static public String botLink(String botID, String uri) {
return "https://botcompany.de/" + parseSnippetID(botID) + addPrefix("/", uri);
}
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 String hdiv(Object contents, Object... params) {
return div(contents, params);
}
static public String hsnippetimg(String imageID, Object... params) {
return himg(snippetImageLink(imageID), params);
}
static public String small(Object contents, Object... params) {
return tag("small", contents, params);
}
static public String targetBlank(String link, Object contents, Object... params) {
return hrefBlank(link, contents, params);
}
static public File javaxSecretDir_dir;
static public File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
static public File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
static public void printVars(Object... params) {
String s = "";
if (odd(l(params))) {
s = str(first(params));
if (endsWithLetter(s))
s += ": ";
params = dropFirst(params);
}
print(s + renderVars(params));
}
static public String appendSlash(String s) {
return addSlash(s);
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(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;
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 boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static public Object serveWithContentType(String text, String contentType) {
return serveByteArray(toUtf8(text), contentType);
}
static public Object serveText(Object s) {
if (getMainBot() == null)
return serveText_direct(str(s));
return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8");
}
static public String hhtml(Object contents) {
return containerTag("html", contents);
}
static public String hmobilefix() {
return " ";
}
static public String hmobilefix(String html) {
return hAddToHead(html, hmobilefix());
}
static public String hhead(Object contents) {
return tag("head", contents);
}
static public String htitle(String title) {
return tag("title", htmlencode_noQuotes(title));
}
static public String hLoadJQuery2() {
return loadJQuery2();
}
static public String hJsMakeCookie() {
return hjavascript("\r\n var cookie = localStorage.getItem('cookie');\r\n var urlParams = new URLSearchParams(window.location.search);\r\n console.log(\"cookie 1: \" + cookie);\r\n if (!cookie) {\r\n cookie = Math.random().toString(36).substr(2, 9);\r\n localStorage.setItem('cookie', cookie);\r\n console.log(\"cookie 2: \" + cookie);\r\n }\r\n ");
}
static public String hbody(Object contents, Object... params) {
return tag("body", contents, params);
}
static public String hOnBottom(Object contents) {
return tag("table", tr(td(contents, "align", "center", "valign", "bottom")), "width", "100%", "height", "100%");
}
static public String p(Object contents, Object... params) {
return tag("p", contents, params) + "\n";
}
static public String hsnippetimage(String imageID, Object... params) {
return hsnippetimg(imageID, params);
}
static public String hjavascript(String script) {
return tag("script", script, "type", "text/javascript");
}
static public String hSpeechRecognition(String jsOnSpeech, boolean autoStart) {
return hSpeechRecognition(jsOnSpeech, autoStart, "de-DE", true);
}
static public String hSpeechRecognition(String jsOnSpeech, boolean autoStart, String language, boolean autoTurnOn, Object... __) {
String noWebKit = optPar("noWebKit", __, "No webkit");
String speechUI = optPar("speechUI", __, "");
return hjavascript(("\r\n var bigOn = #BIGON#, srPause = false, listening = false;\r\n var recognition;\r\n var firstStart = true;\r\n\r\n function resultHTML(html) {\r\n if ($(\"#speechResults\")) $(\"#speechResults\").html(html);\r\n }\r\n\r\n function srUpdate() {\r\n var btn = $(\"#speechOnBtn, .speechOnBtn\");\r\n //console.log(\"srUpdate: btn=\" + btn.length);\r\n btn.prop('disabled', false);\r\n btn.html(bigOn ? \"Stop listening\" : \"Listen\");\r\n console.log(\"srUpdate: bigOn=\" + bigOn + \", srPause=\" + srPause);\r\n\r\n var should = bigOn && !srPause;\r\n $(\".listenStatus\").css(\"visibility\", should ? \"visible\" : \"hidden\");\r\n if (should && !listening) startRecognition();\r\n else if (!should && listening) stopRecognition();\r\n }\r\n \r\n function stopRecognition() {\r\n listening = false;\r\n recognition.stop();\r\n srUpdate();\r\n }\r\n \r\n function isMobile() {\r\n return /mobile/i.test(navigator.userAgent);\r\n }\r\n \r\n function startRecognition() {\r\n listening = true;\r\n recognition.start();\r\n if (firstStart) {\r\n firstStart = false;\r\n resultHTML(isMobile() ? \"Please talk after the blip\" : \"You can talk now\");\r\n }\r\n srUpdate();\r\n }\r\n \r\n function startSpeechRecog() {\r\n resultHTML(\"Starting\");\r\n console.log(\"startSpeechRecog\");\r\n \r\n if (!('webkitSpeechRecognition' in window)) {\r\n console.log(\"No webkit\");\r\n document.writeln(" + jsQuote(noWebKit) + ");\r\n return;\r\n }\r\n \r\n console.log(\"Have webkit\");\r\n document.writeln(" + jsQuote(speechUI) + ");\r\n \r\n recognition = new webkitSpeechRecognition();\r\n resultHTML(\"Speech recognition available.\");\r\n recognition.lang = \"#LANGUAGE#\";\r\n \r\n recognition.onerror = function(event) { \r\n var s = \" \";\r\n if (event.error != \"no-speech\") s = \"Error: \" + event.error;\r\n resultHTML(s);\r\n }\r\n \r\n recognition.onresult = function(event) { \r\n var result = event.results[0];\r\n var transcript = result[0].transcript;\r\n resultHTML(\"You said: \\\"\" + transcript + \"\\\"\");\r\n #ONSPEECH#\r\n if (transcript == \"stop listening\") {\r\n bigOn = false;\r\n srUpdate();\r\n }\r\n }\r\n \r\n recognition.onnomatch = function(event) { \r\n resultHTML(\"-\");\r\n }\r\n \r\n recognition.onend = function(event) { \r\n listening = false; setTimeout(srUpdate, 100);\r\n }\r\n \r\n srUpdate();\r\n }\r\n \r\n function startOrStop() {\r\n bigOn = !bigOn;\r\n srUpdate();\r\n }\r\n \r\n window.srUpdate = srUpdate;\r\n " + (autoStart ? "startSpeechRecog();" : "")).replace("#BIGON#", str(autoTurnOn)).replace("#LANGUAGE#", language).replace("#ONSPEECH#", jsOnSpeech));
}
static public String hjs(String script) {
return hjavascript(script);
}
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 hVAD(String onVoiceStart, String onVoiceStop, boolean autoStart) {
return "\r\n\r\n\r\n ";
}
static public String md5(String text) {
try {
if (text == null)
return "-";
return bytesToHex(md5_impl(toUtf8(text)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(byte[] data) {
if (data == null)
return "-";
return bytesToHex(md5_impl(data));
}
static public byte[] md5_impl(byte[] data) {
try {
return MessageDigest.getInstance("MD5").digest(data);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String md5(File file) {
return md5OfFile(file);
}
static public String dm_makeModuleWithParams_systemQ(String moduleLibID, Object... params) {
return dm_evalInSystemQ(() -> dm_makeModuleWithParams(moduleLibID, params));
}
static public Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __1 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__1);
}
}
static public List collect(Iterable c, String field) {
return collectField(c, field);
}
static public List collect(String field, Iterable c) {
return collectField(c, field);
}
static public List list(Class type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public A uniq(Class c, Object... params) {
return uniqueConcept(c, params);
}
static public A uniq(Concepts cc, Class c, Object... params) {
return uniqueConcept(cc, c, params);
}
static public void forwardSwappableFunctionToObject(Object o, String swappableMethodName, Object target) {
forwardSwappableFunctionToObject(o, swappableMethodName, target, swappableMethodName);
}
static public void forwardSwappableFunctionToObject(Object o, String swappableMethodName, Object target, String methodNameOnTarget) {
if (o == null || target == null)
return;
Class type = fieldType(o, swappableMethodName);
if (type == null)
return;
String proxyMethodName = type == Runnable.class ? "run" : "get";
set(o, swappableMethodName, singleObjectMethodProxy2(type, target, proxyMethodName, methodNameOnTarget));
}
static public Object dm_mod(Object moduleOrID) {
return dm_getModule(moduleOrID);
}
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) x.add(callF(f, o));
return x;
}
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) 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)
for (A o : l) x.add(f.get(o));
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) x.add(f.get(o));
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(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
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 String joinWithBR(Iterable l) {
return join(" ", l);
}
static public String joinWithBR(String... l) {
return joinWithBR(asList(l));
}
static public String dm_cpuTemperature() {
return (String) dm_rcall("getValue", dm_require("#1018430/CPUTemp"));
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
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 n_fancy2(l, singular, singular + "s");
}
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(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, String plural) {
return n_fancy2(ms, singular, plural);
}
static public int vmBus_countResponses(String msg, Object... args) {
return l(vmBus_queryAll(msg, args));
}
static public int countDirsInDir(File dir) {
return l(listDirs(dir));
}
static public File getProgramDir() {
return programDir();
}
static public File getProgramDir(String snippetID) {
return programDir(snippetID);
}
static public String beforeSlash(String s) {
return takeFirst(indexOf(s, '/'), s);
}
static public JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
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 void close_pcall(AutoCloseable c) {
if (c != null) {
try {
c.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
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 Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public void preCleanUp(Object c) {
if (c instanceof Collection) {
for (Object o : ((Collection) c)) preCleanUp(o);
return;
}
callOpt(c, "licensed_off");
setOpt(c, "ping_anyActions", true);
setOpt(c, "cleaningUp_flag", true);
}
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 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 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 Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public Object pcallOpt(Object o, String method, Object... args) {
try {
return callOpt(o, method, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll("printStackTrace2"));
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)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
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(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public String joinWithComma(Collection 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)) t.interrupt();
}
static public void interruptThreads(Class mainClass) {
interruptThreads(registeredThreads(mainClass));
}
static public void retireClassLoader(ClassLoader cl) {
if (isJavaXClassLoader(cl))
setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader());
}
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 boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
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 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 String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
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 File getSecretProgramDir() {
return getSecretProgramDir(getProgramID());
}
static public File getSecretProgramDir(String snippetID) {
if (empty(snippetID))
return javaxSecretDir();
return newFile(javaxSecretDir(), formatSnippetID(snippetID));
}
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 String loadTextFile_trim(String fileName) {
return trim(loadTextFile(fileName));
}
static public String loadTextFile_trim(File f, String defaultContents) {
return trim(loadTextFile(f, defaultContents));
}
static public String loadTextFile_trim(File fileName) {
return trim(loadTextFile(fileName));
}
static public String loadTextFile_trim(String fileName, String defaultContents) {
return trim(loadTextFile(fileName, defaultContents));
}
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 List beginCriticalAction_inFlight = synchroList();
static public class CriticalAction {
public String description;
public CriticalAction() {
}
public CriticalAction(String description) {
this.description = description;
}
public void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static public CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static public void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) {
_handleException(__e);
}
}
sleepInCleanUp(10);
}
}
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 long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public File copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
return dest;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A printStackTrace(A e) {
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 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 vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public void dm_reloadOnFieldChange(String field) {
dm_onFieldChange(field, new Runnable() {
public void run() {
try {
dm_reloadModule();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_reloadModule();";
}
});
}
static public String translateUsingMechPhraseList(String listName, String s) {
return translateUsingPhraseMap(s, mechCIMap(listName));
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
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 String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
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 str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public String div(Object contents, Object... params) {
return hfulltag("div", contents, params);
}
static public BigInteger div(BigInteger a, BigInteger b) {
return a.divide(b);
}
static public BigInteger div(BigInteger a, int b) {
return a.divide(bigint(b));
}
static public String himg(String src, Object... params) {
return tag("img", "", arrayPlus(params, "src", isSnippetID(src) ? snippetImageLink(src) : src));
}
static public String snippetImageLink(String snippetID) {
return snippetImageURL(snippetID);
}
static public String hrefBlank(String link, Object contents, Object... params) {
return tag("a", contents, concatArrays(new Object[] { "href", link, "target", "_blank" }, params));
}
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 boolean odd(int i) {
return (i & 1) != 0;
}
static public boolean odd(long i) {
return (i & 1) != 0;
}
static public boolean odd(BigInteger i) {
return odd(toInt(i));
}
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 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 A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
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 String renderVars(Object... params) {
List l = new ArrayList();
for (int i = 0; i + 1 < l(params); i += 2) l.add(params[i] + "=" + struct(params[i + 1]) + ". ");
return trim(join(l));
}
static public String addSlash(String s) {
return empty(s) || s.endsWith("/") ? s : s + "/";
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
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;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public NanoHTTPD.Response serveByteArray(byte[] data, String mimeType) {
try {
return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Status.OK, mimeType, new ByteArrayInputStream(data), l(data));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public byte[] toUtf8(String s) {
try {
return s.getBytes("UTF-8");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public NanoHTTPD.Response serveText_direct(String s) {
return serveByteArray(toUtf8(s), "text/plain; charset=utf8");
}
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 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 htmlencode_noQuotes(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<')
out.append("<");
else if (c == '>')
out.append(">");
else if (c > 127 || c == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else
out.append(c);
}
return out.toString();
}
static public String loadJQuery2() {
return "";
}
static public String tr(Object contents) {
return tag("tr", contents);
}
static public String td(Object contents, Object... params) {
return tag("td", contents, params);
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public String jsQuote(String s) {
return javascriptQuote(s);
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs + i]);
stringBuilder.append(s.substring(s.length() - 2, s.length()));
}
return stringBuilder.toString();
}
static public boolean md5OfFile_verbose = false;
static public String md5OfFile(String path) {
return md5OfFile(newFile(path));
}
static public String md5OfFile(File f) {
try {
if (!f.exists())
return "-";
if (md5OfFile_verbose)
print("Getting MD5 of " + f);
MessageDigest md5 = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(f);
try {
byte[] buf = new byte[65536];
int l;
while (true) {
l = in.read(buf);
if (l <= 0)
break;
md5.update(buf, 0, l);
}
return bytesToHex(md5.digest());
} finally {
_close(in);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A dm_evalInSystemQ(IF0 f) {
return (A) dm_callOS("evalInSystemQ_gen", f);
}
static public String dm_makeModuleWithParams(String moduleLibID, Object... params) {
String mod = dm_findModuleWithParams(moduleLibID, params);
if (mod != null)
return mod;
return dm_makeNewModuleWithParams(moduleLibID, params);
}
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 AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
static public Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public A uniqueConcept(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqueConcept(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhere(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
}
return x;
} finally {
_close(__1);
}
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public A singleObjectMethodProxy2(Class intrface, Object object, String invokedMethodName, String targetMethodName) {
return proxyFromInvocationHandler(intrface, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
String mname = method.getName();
if (mname.equals(invokedMethodName))
return call(object, targetMethodName, unnull(args));
if (mname.equals("toString"))
return "proxy for method " + targetMethodName;
return null;
}
});
}
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 public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
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(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(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(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) 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;
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
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 Object dm_rcall(String method, Object moduleOrID, Object... args) {
return dm_call(moduleOrID, method, args);
}
static public String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
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 List vmBus_queryAll(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
List out = new ArrayList();
for (Object o : unnull(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg));
for (Object o : unnull(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg));
return out;
}
static public List listDirs(File dir) {
if (dir == null)
return emptyList();
File[] files = dir.listFiles();
List l = new ArrayList();
if (files != null)
for (File f : files) if (f.isDirectory())
l.add(f);
return l;
}
static public List listDirs(String dir) {
return listDirs(newFile(dir));
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
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 List takeFirst(int n, Iterable i) {
if (i == null)
return null;
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
clearTabs(tabs);
Object[] x = flattenArray2(_x);
int idx = 0;
if (get(x, 0) instanceof Integer) {
idx = asInt(get(x, 0));
x = dropFirst(x);
if (empty(x)) {
x = arrayrep(null, idx);
idx = 0;
}
}
int n = 0;
for (int i = 0; i < l(x); i++) {
++n;
if (x[i] instanceof Component)
tabs.addTab("Tab " + n, wrap((Component) x[i]));
else {
String name = str(or(x[i], "Tab " + n));
Component c;
if (get(x, i + 1) instanceof Component)
c = (Component) get(x, ++i);
else
c = new JPanel();
tabs.addTab(name, wrap(c));
}
}
if (idx != 0)
tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clearTabs(tabs);\r\n Object[] x = flattenArray2(_x);\r\n ifdef fillJTabs_de...";
}
});
}
return tabs;
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("loadableUtils.utils$"))
return findClass_fullName("main" + name.substring(19));
return null;
}
};
}
static public List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List sorted(Collection c, final 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 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 Class mc() {
return main.class;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(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 PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public Throwable innerException(Throwable e) {
return getInnerException(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 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 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() {
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 A or(A a, A b) {
return a != null ? a : b;
}
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 Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
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();
}
static public String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static public String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public void sleepInCleanUp(long ms) {
try {
if (ms < 0)
return;
Thread.sleep(ms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 copyStream(InputStream in, OutputStream out) {
try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 void _registerIO(Object object, String path, boolean opened) {
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(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 Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static public void dm_onFieldChange(String field, Runnable onChange) {
dm_watchField(field, onChange);
}
static public void dm_reloadModule(Object module) {
dm_reloadModuleInBackground(module);
}
static public void dm_reloadModule() {
dm_reloadModuleInBackground();
}
static public String translateUsingPhraseMap(String s, Map map) {
return translateUsingWordTree(s, mapToWordTree(map));
}
static public Map mechCIMap(String listName) {
return mechMapCI(listName);
}
static public String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
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);
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 (val == html_valueLessParam())
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
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 String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
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 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 BigInteger bigint(String s) {
return new BigInteger(s);
}
static public BigInteger bigint(long l) {
return BigInteger.valueOf(l);
}
static public Object[] arrayPlus(Object[] a1, Object... a2) {
return concatArrays(a1, a2);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
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 (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;
}
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 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 int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt(((String) o));
if (o instanceof Boolean)
return boolToInt(((Boolean) o));
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public boolean isLetter(char c) {
return Character.isLetter(c);
}
static public A last(List l) {
return empty(l) ? null : l.get(l.size() - 1);
}
static public char last(String s) {
return empty(s) ? '#' : s.charAt(l(s) - 1);
}
static public int last(int[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public double last(double[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public A last(A[] a) {
return l(a) != 0 ? a[l(a) - 1] : null;
}
static public A last(Iterator it) {
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
static public A last(Collection l) {
if (l == null)
return null;
Iterator it = iterator(l);
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
static public A last(SortedSet l) {
return l == null ? null : l.last();
}
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 ArrayList toList(A[] a) {
return asList(a);
}
static public ArrayList toList(int[] a) {
return asList(a);
}
static public ArrayList toList(Set s) {
return asList(s);
}
static public ArrayList toList(Iterable s) {
return asList(s);
}
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(tok.subList(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 String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static public String javascriptQuote(String s) {
return quote(s);
}
static public Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
static public String dm_findModuleWithParams(String moduleLibID, Object... params) {
return firstThat(dm_modulesWithLibID(moduleLibID), mod -> checkFields(dm_mod(mod), params));
}
static public String dm_makeNewModuleWithParams(String moduleLibID, Object... params) {
return (String) dm_callOS("makeNewModule", moduleLibID, false, "beforeStart", new VF1() {
public void get(Object mod) {
try {
print("Got module: " + dm_mod(mod));
dm_call(mod, "setFields", params);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Got module: \" + dm_mod(mod));\r\n dm_call(mod, 'setFields, params);";
}
});
}
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_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
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) {
synchronized (callOpt_cache) {
_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(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public AutoCloseable tempDBLock(Concepts concepts) {
return tempLock(concepts.lock);
}
static public AutoCloseable tempDBLock() {
return tempDBLock(db_mainConcepts());
}
static public Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static public A findConceptWhere(Class c, Object... params) {
return findConceptWhere(db_mainConcepts(), c, params);
}
static public A findConceptWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i + 1])) if (checkConceptFields(x, params))
return x;
return null;
}
}
for (A x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
static public Concept findConceptWhere(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) if (checkConceptFields(x, params))
return x;
return null;
}
static public A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static public int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static public int csetAll(Iterable extends Concept> l, Object... values) {
int n = 0;
for (Concept c : unnull(l)) n += cset(c, values);
return n;
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
static public A proxyFromInvocationHandler(Class intrface, InvocationHandler handler) {
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, handler);
}
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 int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
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 String dm_makeModule(String moduleLibID) {
return (String) dm_callOS("makeModule", moduleLibID);
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public void addIfNotNull(Collection l, A a) {
if (a != null && l != null)
l.add(a);
}
static public void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null)
ms.add(a);
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
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 volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
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 Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.removeAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.removeAll();";
}
});
}
}
static public Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static public int asInt(Object o) {
return toInt(o);
}
static public Object[] arrayrep(Object a, int n) {
return asArray(repeat(a, n));
}
static public JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static public JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
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 swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
static public void sort(T[] a) {
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) {
Collections.sort(a, c);
}
static public void sort(List a) {
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 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 Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
static public Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
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 String className(Object o) {
return getClassName(o);
}
static public void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
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 WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static public void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
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 void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public void dm_reloadModuleInBackground(Object module) {
dm_callOS("reloadModuleInBackground", dm_getStem(module));
}
static public void dm_reloadModuleInBackground() {
dm_reloadModuleInBackground(dm_current_mandatory_generic());
}
static public boolean translateUsingWordTree_debug = false;
static public boolean translateUsingWordTree_printReplacements = false;
static public String translateUsingWordTree(String input, Map tree) {
return empty(input) ? input : join(translateUsingWordTree(javaTok(input), tree));
}
static public List translateUsingWordTree(List tok, Map tree) {
for (int i = 1; i < l(tok); ) i = translateUsingWordTree_scanFrom(tok, i, tree);
return tok;
}
static public int translateUsingWordTree_scanFrom(List tok, int i, Map tree) {
int j = i;
String best = null;
int bestIndex = 0;
while (true) {
if (j > i) {
String def = (String) (tree.get(""));
if (def != null) {
best = def;
bestIndex = j;
}
}
if (j >= l(tok))
break;
Object t = tree.get(tok.get(j));
if (translateUsingWordTree_debug)
print(i + "-" + j + " / " + joinSubList(tok, i, j + 1) + " => " + sfu(t));
if (t == null)
break;
if (t instanceof String) {
int k = j + 2;
if (translateUsingWordTree_printReplacements)
print("translateUsingWordTree: replacing " + sfu(subList(tok, i, k - 1) + " with " + quote(t)));
replaceTokens(tok, i, k - 1, (String) t);
return k;
}
tree = (Map) t;
j += 2;
}
if (best != null) {
int k = bestIndex;
replaceTokens(tok, i, k - 1, best);
return k;
}
return i + 2;
}
static public String translateUsingWordTree(Map tree, String input) {
return translateUsingWordTree(input, tree);
}
static public Map mapToWordTree(Map map) {
Map tree = ciMap();
{
final Map __0 = unnull(map);
for (String key : keys(__0)) {
String value = __0.get(key);
wordTreeAdd(tree, javaTokC(key), value);
}
}
return simplifyWordTree(tree);
}
static public Map>> mechMapCI_cache = synchroMap();
static public Map mechMapCI(String listName) {
Pair> p = mechMapCI_cache.get(listName);
String text = mechList_raw(listName);
if (p != null && eq(p.a, text))
return p.b;
String parsing = first(mechList_opt(listName + " | Parsing"));
Map map;
if (parsing == null)
map = parseDoubleArrowMapCI(tlft(text));
else
map = asCIMap((Map) callMC(parsing, text));
p = pair(text, map);
mechMapCI_cache.put(listName, p);
return p.b;
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
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 boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
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 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 boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
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 int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
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
break;
}
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() % 2) == 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 String addSuffix(String s, String suffix) {
return s == null || s.endsWith(suffix) ? s : s + suffix;
}
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 boolean even(int i) {
return (i & 1) == 0;
}
static public boolean even(long i) {
return (i & 1) == 0;
}
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 == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public Object dm_os() {
{
Object __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public A firstThat(Iterable l, Object pred) {
if (l != null)
for (A a : l) if (checkCondition(pred, a))
return a;
return null;
}
static public A firstThat(Iterable l, IF1 pred) {
return firstThat(l, (Object) pred);
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public List dm_modulesWithLibID(final String moduleLibID) {
return filter(dm_moduleIDs(), new F1() {
public Boolean get(String m) {
try {
return eq(dm_moduleLibID(m), moduleLibID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "eq(dm_moduleLibID(m), moduleLibID)";
}
});
}
static public boolean checkFields(Object x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i + 1]))
return false;
return true;
}
static public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__1 != null)
return __1;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
static public String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static public String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Collection c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public AutoCloseable tempLock(final Lock lock) {
if (lock == null)
return null;
lock(lock);
return new AutoCloseable() {
public String toString() {
return "unlock(lock);";
}
public void close() throws Exception {
unlock(lock);
}
};
}
static public String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static public boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2) if (neq(cget(x, (String) data[i]), deref(data[i + 1])))
return false;
return true;
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
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 Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public Object[] asObjectArray(Collection l) {
return toObjectArray(l);
}
static public Object[] asArray(List l) {
return toObjectArray(l);
}
static public A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static public String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++) chars[i] = c;
return new String(chars);
}
static public List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++) l.add(a);
return l;
}
static public List repeat(int n, A a) {
return repeat(a, n);
}
static public A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
static public JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public Map parseDoubleLeftArrowMapCI_tlft(String s) {
return parseDoubleLeftArrowMapCI(tlft(s));
}
static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
static public String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
static public Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public void replaceTokens(List tok, int i, int j, String s) {
clearAllTokens(tok, i + 1, j);
tok.set(i, s);
}
static public void replaceTokens(List tok, String s) {
clearAllTokens(tok, 1, l(tok));
tok.set(0, s);
}
static public TreeMap ciMap() {
return caseInsensitiveMap();
}
static public void wordTreeAdd(Map tree, List words, String value) {
for (String word : words) {
Object child = tree.get(word);
Map subTree;
if (child instanceof Map)
tree = (Map) child;
else {
tree.put(word, subTree = ciMap());
if (child != null)
subTree.put("", child);
tree = subTree;
}
}
tree.put("", value);
}
static public List javaTokC(String s) {
if (s == null)
return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
return tok;
}
static public Map simplifyWordTree(Map tree) {
if (tree == null)
return null;
return (Map) simplifyWordTree_impl(tree, true);
}
static public Object simplifyWordTree_impl(Object tree, boolean keepAsMap) {
if (tree instanceof String)
return tree;
Map m = (Map) tree;
if (!keepAsMap && l(m) == 1 && eq(firstKey(m), ""))
return (String) firstValue(m);
Map map = similarEmptyMap(m);
for (String key : keys(m)) {
Object value = m.get(key);
map.put(key, simplifyWordTree_impl(value, false));
}
return map;
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap());
static public Lock mechList_raw_lock = lock();
static public int mechList_raw_timeout = 60000;
static public String mechList_raw(String name) {
try {
Lock __0 = mechList_raw_lock;
lock(__0);
try {
if (empty(name))
return "";
String src = mechList_raw_cache.get(name);
if (src != null)
return src;
src = mechList_raw_fresh(name);
if (src != null)
mechList_raw_cache.put(name, src);
return src;
} finally {
unlock(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public VF2 mechList_raw_listener = new VF2() {
public void get(String msg, Object arg) {
try {
if (eq(msg, "mechChange") && arg instanceof String) {
mechList_raw_cache.remove((String) arg);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti...";
}
};
static public void _onLoad_mechList_raw() {
add(vm_busListeners_live(), mechList_raw_listener);
}
static public void cleanMeUp_mechList_raw() {
remove(vm_busListeners_live(), mechList_raw_listener);
}
static public List mechList_opt(String name) {
return mechList_opt_tlft(name);
}
static public Map parseDoubleArrowMapCI(List l) {
return parseDoubleArrowMap((Map) ciMap(), l);
}
static public List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
static public TreeMap asCIMap(Map map) {
return asCaseInsensitiveMap(map);
}
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 dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
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 String htmlencode_forParams(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public boolean possibleMD5(String s) {
return isMD5(s);
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static public boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static public boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static public List dm_moduleIDs() {
return dm_listModuleIDs();
}
static public String dm_moduleLibID() {
return programID() + "/" + shortClassName(dm_current_mandatory_generic());
}
static public String dm_moduleLibID(Object mod) {
if (mod == null)
return null;
mod = dm_getModule(mod);
if (hasSuperclassShortNamed(mod, "DynModule"))
return programID(mod) + "/" + shortClassName(mod);
return null;
}
static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __1 = pcallF(f, args);
if (__1 != null)
return __1;
}
return null;
}
static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __2 = pcallF(it.next(), args);
if (__2 != null)
return __2;
}
return null;
}
static public String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static public String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
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();
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
static public Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName());
return fields;
}
static public String n(long l, String name) {
return l + " " + trim(l == 1 ? singular(name) : getPlural(name));
}
static public String n(Collection l, String name) {
return n(l(l), name);
}
static public String n(Map m, String name) {
return n(l(m), name);
}
static public String n(Object[] a, String name) {
return n(l(a), name);
}
static public String n(MultiSet ms, String name) {
return n(l(ms), name);
}
static public A cget(Object c, String field) {
Object o = getOpt(c, field);
if (o instanceof Concept.Ref)
return (A) ((Concept.Ref) o).get();
return (A) o;
}
static public A cget(String field, Object c) {
return cget(c, field);
}
static public Object deref(Object o) {
if (o instanceof Derefable)
o = ((Derefable) o).get();
return o;
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static public Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
static public Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public Map parseDoubleLeftArrowMapCI(List l) {
return parseDoubleLeftArrowMap((Map) ciMap(), l);
}
static public Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static public Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static public String theAGIBlueDomain() {
return "agi.blue";
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
static public String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
static public String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
static public void clearAllTokens(List tok) {
for (int i = 0; i < tok.size(); i++) tok.set(i, "");
}
static public void clearAllTokens(List tok, int i, int j) {
for (; i < j; i++) tok.set(i, "");
}
static public TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static public A firstKey(Map map) {
return first(keys(map));
}
static public B firstValue(Map map) {
return first(values(map));
}
static public Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public String mechList_raw_fresh(String name) {
return mechList_opt_raw_fresh(name);
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public List mechList_opt_tlft(String name) {
return mechList_opt_tlft_cached(name);
}
static public Map parseDoubleArrowMap(Map map, List l) {
for (String s : l) {
List x = splitAtDoubleArrow_bothDirections(s);
if (l(x) == 2)
map.put(first(x), second(x));
}
return map;
}
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 TreeMap asCaseInsensitiveMap(Map map) {
if (isCIMap(map))
return (TreeMap) map;
TreeMap m = ciMap();
m.putAll(map);
return m;
}
static public boolean isMD5(String s) {
return l(s) == 32 && isLowerHexString(s);
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public List dm_listModuleIDs() {
return map("dm_moduleID", dm_listStems());
}
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 boolean hasSuperclassShortNamed(Object o, String name) {
Class c = _getClass(o);
while (c != null) if (shortClassNameIs(c, name))
return true;
else
c = c.getSuperclass();
return false;
}
static public String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess");
static public Set singular_specials2 = litciset("time", "machine", "line", "rule");
static public String singular(String s) {
if (s == null)
return null;
{
String __1 = singular_specials.get(s);
if (!empty(__1))
return __1;
}
if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s))))
return dropSuffix("s", s);
if (s.endsWith("ness"))
return s;
if (s.endsWith("ges"))
return dropSuffix("s", s);
if (endsWith(s, "bases"))
return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static public List getPlural_specials = ll("sheep", "fish");
static public String getPlural(String s) {
if (containsIgnoreCase(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 Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public Map parseDoubleLeftArrowMap(Map map, List l) {
for (String s : l) {
List x = splitAtDoubleLeftArrow(s);
if (l(x) == 2)
map.put(second(x), first(x));
}
return map;
}
static public boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static public boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static public String beautifyStructure(String s) {
List tok = javaTokForStructure(s);
structure_addTokenMarkers(tok);
jreplace(tok, "lhm", "");
return join(tok);
}
static public String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
static public Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public String mechList_opt_raw_fresh(String name) {
Object readMode = mechMode().readMode;
if (readMode instanceof File) {
String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name));
return loadTextFileFromZipFile((File) readMode, md5Name);
}
boolean useLocal = false, useRemote = true;
if (eq(readMode, "mergeLocalAndRemote"))
useLocal = true;
else if (eq(readMode, "local")) {
useLocal = true;
useRemote = false;
}
String s = "";
if (useRemote) {
if (eq(mechMode().readMode, "localCopies"))
s = unnull(loadTextFile(remoteMechListMirrorFile(name)));
else
s = serverMechList_raw_fresh(name, true);
}
if (useLocal)
s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name);
return s;
}
static public void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
static public Map>> mechList_opt_tlft_cached_cache = ciMap();
static public Lock mechList_opt_tlft_cached_lock = lock();
static public List mechList_opt_tlft_cached(String name) {
MechListDependentCache> listCache;
{
Lock __0 = mechList_opt_tlft_cached_lock;
lock(__0);
try {
listCache = mechList_opt_tlft_cached_cache.get(name);
if (listCache == null)
mechList_opt_tlft_cached_cache.put(name, listCache = new MechListDependentCache(name, new F1>() {
public List get(String x) {
try {
return tlft(x);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tlft(x)";
}
}));
} finally {
unlock(__0);
}
}
return listCache.get();
}
static public List splitAtDoubleArrow_bothDirections(String s) {
return splitAtDoubleArrow_bothDirections(javaTok(s));
}
static public List splitAtDoubleArrow_bothDirections(List tok) {
List l = splitAtDoubleArrow(tok);
if (l(l) != 2)
l = reversedList(splitAtDoubleLeftArrow(tok));
return l;
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
static public char second(String s) {
return charAt(s, 1);
}
static public IterableIterator